Fix minor compile warnings

This commit is contained in:
Dmitry Gridin
2019-04-17 17:48:26 +07:00
parent 79793a4bda
commit 37c856290f
226 changed files with 618 additions and 479 deletions
@@ -97,7 +97,7 @@ open class FrameMapBase<T : Any> {
val descriptors = Lists.newArrayList<Trinity<T, Int, Int>>()
for (descriptor0 in myVarIndex.keys()) {
val descriptor = descriptor0 as T
@Suppress("UNCHECKED_CAST") val descriptor = descriptor0 as T
val varIndex = myVarIndex.get(descriptor)
val varSize = myVarSizes.get(descriptor)
descriptors.add(Trinity.create(descriptor, varIndex, varSize))
@@ -234,7 +234,7 @@ class ScriptCodegen private constructor(
hasMain = true
}
}
is KtProperty, is KtNamedFunction, is KtTypeAlias -> genSimpleMember(declaration)
is KtProperty, is KtTypeAlias -> genSimpleMember(declaration)
is KtClassOrObject -> genClassOrObject(declaration)
is KtDestructuringDeclaration -> for (entry in declaration.entries) {
genSimpleMember(entry)
@@ -135,10 +135,9 @@ internal fun performRefinedTypeAnalysis(methodNode: MethodNode, thisName: String
override fun use(frame: VarExpectedTypeFrame, insn: AbstractInsnNode) {
val (expectedType, sources) = expectedTypeAndSourcesByInsnIndex[insn.index()] ?: return
sources.flatMap(SourceValue::insns).forEach {
insn ->
if (insn.isIntLoad()) {
frame.updateExpectedType((insn as VarInsnNode).`var`, expectedType)
sources.flatMap(SourceValue::insns).forEach { insnNode ->
if (insnNode.isIntLoad()) {
frame.updateExpectedType((insnNode as VarInsnNode).`var`, expectedType)
}
}
}
@@ -168,12 +168,12 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
}
}
@Suppress("UNREACHABLE_CODE")
private fun canSkipStackSpillingOnInline(methodNode: MethodNode): Boolean {
// Temporary disable this optimization until
// TODO: Temporary disable this optimization until
// https://issuetracker.google.com/issues/68796377 is fixed
// or until d8 substitute dex
return false
// Stack spilling before inline function 'f' call is required if:
// - 'f' is a suspend function
// - 'f' has try-catch blocks
@@ -96,19 +96,19 @@ class LocalVarRemapper(private val params: Parameters, private val additionalShi
}
fun visitVarInsn(opcode: Int, `var`: Int, mv: InstructionAdapter) {
var opcode = opcode
val remapInfo = remap(`var`)
val value = remapInfo.value
if (value is StackValue.Local) {
val isStore = isStoreInstruction(opcode)
if (remapInfo.parameterInfo != null) {
val localOpcode = if (remapInfo.parameterInfo != null) {
//All remapped value parameters can't be rewritten except case of default ones.
//On remapping default parameter to actual value there is only one instruction that writes to it according to mask value
//but if such parameter remapped then it passed and this mask branch code never executed
//TODO add assertion about parameter default value: descriptor is required
opcode = value.type.getOpcode(if (isStore) Opcodes.ISTORE else Opcodes.ILOAD)
}
mv.visitVarInsn(opcode, value.index)
value.type.getOpcode(if (isStore) Opcodes.ISTORE else Opcodes.ILOAD)
} else opcode
mv.visitVarInsn(localOpcode, value.index)
if (remapInfo.parameterInfo != null && !isStore) {
StackValue.coerce(value.type, remapInfo.parameterInfo.type, mv)
}
@@ -58,7 +58,7 @@ class InFloatingPointRangeLiteralExpressionGenerator(
// goto jumpLabel
// exitLabel:
frameMap.useTmpVar(operandType) { argVar ->
frameMap.useTmpVar(operandType) { _ ->
val exitLabel = Label()
genJumpIfFalse(v, exitLabel)
v.goTo(jumpLabel)
@@ -278,8 +278,8 @@ class GenerationState private constructor(
?.let { destination -> SignatureDumpingBuilderFactory(it, File(destination)) } ?: it
}
)
.wrapWith(ClassBuilderInterceptorExtension.getInstances(project)) { builderFactory, extension ->
extension.interceptClassBuilderFactory(builderFactory, bindingContext, diagnostics)
.wrapWith(ClassBuilderInterceptorExtension.getInstances(project)) { classBuilderFactory, extension ->
extension.interceptClassBuilderFactory(classBuilderFactory, bindingContext, diagnostics)
}
this.factory = ClassFileFactory(this, interceptedBuilderFactory)
@@ -59,7 +59,7 @@ class LanguageSettingsParser : AbstractInternalArgumentParser<ManualLanguageFeat
return null
}
val colon = tail.getOrNull(0) ?: return reportAndReturnNull("Incorrect internal argument syntax, missing colon: $wholeArgument")
tail.getOrNull(0) ?: return reportAndReturnNull("Incorrect internal argument syntax, missing colon: $wholeArgument")
val modificator = tail.getOrNull(1)
val languageFeatureState = when (modificator) {
@@ -86,11 +86,12 @@ open class AggregatedReplStageState<T1, T2>(val state1: IReplStageState<T1>, val
override val history: IReplStageHistory<Pair<T1, T2>> = AggregatedReplStateHistory(state1.history, state2.history, lock)
override fun <StateT : IReplStageState<*>> asState(target: Class<out StateT>): StateT =
when {
target.isAssignableFrom(state1::class.java) -> state1 as StateT
target.isAssignableFrom(state2::class.java) -> state2 as StateT
else -> super.asState(target)
}
@Suppress("UNCHECKED_CAST")
when {
target.isAssignableFrom(state1::class.java) -> state1 as StateT
target.isAssignableFrom(state2::class.java) -> state2 as StateT
else -> super.asState(target)
}
override fun getNextLineNo() = state1.getNextLineNo()
@@ -57,9 +57,10 @@ interface IReplStageState<T> {
fun getNextLineNo(): Int = history.peek()?.id?.no?.let { it + 1 } ?: REPL_CODE_LINE_FIRST_NO // TODO: it should be more robust downstream (e.g. use atomic)
@Suppress("UNCHECKED_CAST")
fun <StateT : IReplStageState<*>> asState(target: Class<out StateT>): StateT =
if (target.isAssignableFrom(this::class.java)) this as StateT
else throw IllegalArgumentException("$this is not an expected instance of IReplStageState")
if (target.isAssignableFrom(this::class.java)) this as StateT
else throw IllegalArgumentException("$this is not an expected instance of IReplStageState")
}
@@ -53,7 +53,7 @@ abstract class CLICompiler<A : CommonCompilerArguments> : CLITool<A>() {
return exec(errStream, Services.EMPTY, MessageRenderer.PLAIN_FULL_PATHS, args)
}
public override fun execImpl(baseMessageCollector: MessageCollector, services: Services, arguments: A): ExitCode {
public override fun execImpl(messageCollector: MessageCollector, services: Services, arguments: A): ExitCode {
val performanceManager = performanceManager
if (arguments.reportPerf || arguments.dumpPerf != null) {
performanceManager.enableCollectingPerformanceStatistics()
@@ -61,7 +61,7 @@ abstract class CLICompiler<A : CommonCompilerArguments> : CLITool<A>() {
val configuration = CompilerConfiguration()
val messageCollector = GroupingMessageCollector(baseMessageCollector, arguments.allWarningsAsErrors).also {
val collector = GroupingMessageCollector(messageCollector, arguments.allWarningsAsErrors).also {
configuration.put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, it)
}
@@ -69,8 +69,8 @@ abstract class CLICompiler<A : CommonCompilerArguments> : CLITool<A>() {
try {
setupCommonArguments(configuration, arguments)
setupPlatformSpecificArgumentsAndServices(configuration, arguments, services)
val paths = computeKotlinPaths(messageCollector, arguments)
if (messageCollector.hasErrors()) {
val paths = computeKotlinPaths(collector, arguments)
if (collector.hasErrors()) {
return ExitCode.COMPILATION_ERROR
}
@@ -93,14 +93,14 @@ abstract class CLICompiler<A : CommonCompilerArguments> : CLITool<A>() {
performanceManager.dumpPerformanceReport(File(arguments.dumpPerf!!))
}
return if (messageCollector.hasErrors()) COMPILATION_ERROR else code
return if (collector.hasErrors()) COMPILATION_ERROR else code
} catch (e: CompilationCanceledException) {
messageCollector.report(INFO, "Compilation was canceled", null)
collector.report(INFO, "Compilation was canceled", null)
return ExitCode.OK
} catch (e: RuntimeException) {
val cause = e.cause
if (cause is CompilationCanceledException) {
messageCollector.report(INFO, "Compilation was canceled", null)
collector.report(INFO, "Compilation was canceled", null)
return ExitCode.OK
} else {
throw e
@@ -111,10 +111,10 @@ abstract class CLICompiler<A : CommonCompilerArguments> : CLITool<A>() {
} catch (e: AnalysisResult.CompilationErrorException) {
return COMPILATION_ERROR
} catch (t: Throwable) {
MessageCollectorUtil.reportException(messageCollector, t)
MessageCollectorUtil.reportException(collector, t)
return INTERNAL_ERROR
} finally {
messageCollector.flush()
collector.flush()
}
}
@@ -134,7 +134,8 @@ class DummyProfiler : Profiler {
override fun getCounters(): Map<Any?, PerfCounters> = mapOf(null to SimplePerfCounters())
override fun getTotalCounters(): PerfCounters = SimplePerfCounters()
override final inline fun <R> withMeasure(obj: Any?, body: () -> R): R = body()
@Suppress("OVERRIDE_BY_INLINE")
override inline fun <R> withMeasure(obj: Any?, body: () -> R): R = body()
}
@@ -149,17 +150,20 @@ abstract class TotalProfiler : Profiler {
class WallTotalProfiler : TotalProfiler() {
override final inline fun <R> withMeasure(obj: Any?, body: () -> R): R = withMeasureWallTime(total, body)
@Suppress("OVERRIDE_BY_INLINE")
override inline fun <R> withMeasure(obj: Any?, body: () -> R): R = withMeasureWallTime(total, body)
}
class WallAndThreadTotalProfiler : TotalProfiler() {
override final inline fun <R> withMeasure(obj: Any?, body: () -> R): R = withMeasureWallAndThreadTimes(total, threadMXBean, body)
@Suppress("OVERRIDE_BY_INLINE")
override inline fun <R> withMeasure(obj: Any?, body: () -> R): R = withMeasureWallAndThreadTimes(total, threadMXBean, body)
}
class WallAndThreadAndMemoryTotalProfiler(val withGC: Boolean) : TotalProfiler() {
override final inline fun <R> withMeasure(obj: Any?, body: () -> R): R = withMeasureWallAndThreadTimesAndMemory(total, withGC, threadMXBean, body)
@Suppress("OVERRIDE_BY_INLINE")
override inline fun <R> withMeasure(obj: Any?, body: () -> R): R = withMeasureWallAndThreadTimesAndMemory(total, withGC, threadMXBean, body)
}
@@ -169,6 +173,7 @@ class WallAndThreadByClassProfiler() : TotalProfiler() {
override fun getCounters(): Map<Any?, PerfCounters> = counters
override final inline fun <R> withMeasure(obj: Any?, body: () -> R): R =
withMeasureWallAndThreadTimes(counters.getOrPut(obj?.javaClass?.name, { SimplePerfCountersWithTotal(total) }), threadMXBean, body)
@Suppress("OVERRIDE_BY_INLINE")
override inline fun <R> withMeasure(obj: Any?, body: () -> R): R =
withMeasureWallAndThreadTimes(counters.getOrPut(obj?.javaClass?.name, { SimplePerfCountersWithTotal(total) }), threadMXBean, body)
}
@@ -81,10 +81,9 @@ class JavaClassImpl(psiClass: PsiClass) : JavaClassifierImpl<PsiClass>(psiClass)
override val fields: Collection<JavaField>
get() {
assertNotLightClass()
return fields(psi.fields.filter { field ->
val name = field.name
return fields(psi.fields.filter {
// ex. Android plugin generates LightFields for resources started from '.' (.DS_Store file etc)
name != null && Name.isValidIdentifier(name)
Name.isValidIdentifier(it.name)
})
}
@@ -52,6 +52,7 @@ object JvmArrayVariableInLoopAssignmentChecker : AdditionalTypeChecker {
val resolvedCall = lhsExpression.getResolvedCall(c.trace.bindingContext) ?: return
val variableDescriptor = resolvedCall.resultingDescriptor as? LocalVariableDescriptor ?: return
if (variableDescriptor is SyntheticFieldDescriptor) return
@Suppress("DEPRECATION")
if (variableDescriptor.isDelegated) return
val variableType = variableDescriptor.returnType
@@ -20,7 +20,8 @@ class JvmDefaultSuperCallChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val jvmDefaultMode = context.languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
if (jvmDefaultMode.isEnabled) return
val superExpression = getSuperCallExpression(resolvedCall.call) ?: return
if (getSuperCallExpression(resolvedCall.call) == null) return
val resultingDescriptor = resolvedCall.resultingDescriptor as? CallableMemberDescriptor ?: return
if (!resultingDescriptor.hasJvmDefaultAnnotation()) return
@@ -385,14 +385,14 @@ class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val l
}
}
override fun substitute(originalSubstitutor: TypeSubstitutor): PropertyDescriptor? {
val descriptor = super.substitute(originalSubstitutor) as MyPropertyDescriptor? ?: return null
override fun substitute(substitutor: TypeSubstitutor): PropertyDescriptor? {
val descriptor = super.substitute(substitutor) as MyPropertyDescriptor? ?: return null
if (descriptor == this) return descriptor
val classTypeParameters = (getMethod.containingDeclaration as ClassDescriptor).typeConstructor.parameters
val substitutionMap = HashMap<TypeConstructor, TypeProjection>()
for ((typeParameter, classTypeParameter) in typeParameters.zip(classTypeParameters)) {
val typeProjection = originalSubstitutor.substitution[typeParameter.defaultType] ?: continue
val typeProjection = substitutor.substitution[typeParameter.defaultType] ?: continue
substitutionMap[classTypeParameter.typeConstructor] = typeProjection
}
@@ -121,6 +121,7 @@ class ResolverForProjectImpl<M : ModuleInfo>(
// Protected by ("projectContext.storageManager.lock")
private val moduleInfoByDescriptor = mutableMapOf<ModuleDescriptorImpl, M>()
@Suppress("UNCHECKED_CAST")
private val moduleInfoToResolvableInfo: Map<M, M> =
modules.flatMap { module -> module.flatten().map { modulePart -> modulePart to module } }.toMap() as Map<M, M>
@@ -326,6 +327,7 @@ class LazyModuleDependencies<M : ModuleInfo>(
yield(moduleDescriptor.builtIns.builtInsModule)
}
for (dependency in module.dependencies()) {
@Suppress("UNCHECKED_CAST")
yield(resolverForProject.descriptorForModule(dependency as M))
}
if (module.dependencyOnBuiltIns() == ModuleInfo.DependencyOnBuiltIns.LAST) {
@@ -337,12 +339,16 @@ class LazyModuleDependencies<M : ModuleInfo>(
override val allDependencies: List<ModuleDescriptorImpl> get() = dependencies()
override val expectedByDependencies by storageManager.createLazyValue {
module.expectedBy.map { resolverForProject.descriptorForModule(it as M) }
module.expectedBy.map {
@Suppress("UNCHECKED_CAST")
resolverForProject.descriptorForModule(it as M)
}
}
override val modulesWhoseInternalsAreVisible: Set<ModuleDescriptorImpl>
get() =
module.modulesWhoseInternalsAreVisible().mapTo(LinkedHashSet()) {
@Suppress("UNCHECKED_CAST")
resolverForProject.descriptorForModule(it as M)
}
@@ -166,6 +166,7 @@ class SyntheticClassOrObjectDescriptor(
override fun getPsiOrParent() = _parent.psiOrParent
override fun getParent() = _parent.psiOrParent
@Suppress("USELESS_ELVIS")
override fun getContainingKtFile() =
// in theory `containingKtFile` is `@NotNull` but in practice EA-114080
_parent.containingKtFile ?: throw IllegalStateException("containingKtFile was null for $_parent of ${_parent.javaClass}")
@@ -439,11 +439,11 @@ class CallCompleter(
}
var shouldBeMadeNullable = false
expressions.asReversed().forEach { expression ->
if (!(expression is KtParenthesizedExpression || expression is KtLabeledExpression || expression is KtAnnotatedExpression)) {
shouldBeMadeNullable = hasNecessarySafeCall(expression, trace)
expressions.asReversed().forEach { ktExpression ->
if (!(ktExpression is KtParenthesizedExpression || ktExpression is KtLabeledExpression || ktExpression is KtAnnotatedExpression)) {
shouldBeMadeNullable = hasNecessarySafeCall(ktExpression, trace)
}
BindingContextUtils.updateRecordedType(updatedType, expression, trace, shouldBeMadeNullable)
BindingContextUtils.updateRecordedType(updatedType, ktExpression, trace, shouldBeMadeNullable)
}
return trace.getType(argumentExpression)
}
@@ -360,7 +360,7 @@ class CallExpressionResolver(
initialDataFlowInfoForArguments = initialDataFlowInfoForArguments.disequate(
receiverDataFlowValue, DataFlowValue.nullValue(builtIns), languageVersionSettings
)
} else if (receiver is ReceiverValue) {
} else {
reportUnnecessarySafeCall(context.trace, receiver.type, callOperationNode, receiver)
}
}
@@ -145,7 +145,7 @@ fun isBinaryRemOperator(call: Call): Boolean {
val operator = callElement.operationToken
if (operator !is KtToken) return false
val name = OperatorConventions.getNameForOperationSymbol(operator, true, true)
val name = OperatorConventions.getNameForOperationSymbol(operator, true, true) ?: return false
return name in OperatorConventions.REM_TO_MOD_OPERATION_NAMES.keys
}
@@ -41,6 +41,7 @@ internal fun VariableDescriptor.variableKind(
return propertyKind(usageModule)
}
@Suppress("DEPRECATION")
if (this is LocalVariableDescriptor && this.isDelegated) {
// Local delegated property: normally unstable, but can be treated as stable in legacy mode
return if (languageVersionSettings.supportsFeature(LanguageFeature.ProhibitSmartcastsOnLocalDelegatedProperty))
@@ -117,6 +117,7 @@ class KotlinToResolvedCallTransformer(
forwardCallToInferenceSession(baseResolvedCall, context, stub, tracingStrategy)
@Suppress("UNCHECKED_CAST")
return stub as ResolvedCall<D>
}
@@ -131,7 +132,8 @@ class KotlinToResolvedCallTransformer(
}
}
val resolvedCall = ktPrimitiveCompleter.completeResolvedCall(candidate, baseResolvedCall.diagnostics) as ResolvedCall<D>
@Suppress("UNCHECKED_CAST") val resolvedCall =
ktPrimitiveCompleter.completeResolvedCall(candidate, baseResolvedCall.diagnostics) as ResolvedCall<D>
forwardCallToInferenceSession(baseResolvedCall, context, resolvedCall, tracingStrategy)
resolvedCall
@@ -580,6 +582,7 @@ class NewResolvedCallImpl<D : CallableDescriptor>(
override val argumentMappingByOriginal: Map<ValueParameterDescriptor, ResolvedCallArgument>
get() = resolvedCallAtom.argumentMappingByOriginal
@Suppress("UNCHECKED_CAST")
override fun getCandidateDescriptor(): D = resolvedCallAtom.candidateDescriptor as D
override fun getResultingDescriptor(): D = resultingDescriptor
override fun getExtensionReceiver(): ReceiverValue? = extensionReceiver
@@ -639,6 +642,7 @@ class NewResolvedCallImpl<D : CallableDescriptor>(
}
}
@Suppress("UNCHECKED_CAST")
resultingDescriptor = run {
val candidateDescriptor = resolvedCallAtom.candidateDescriptor
val containsCapturedTypes = resolvedCallAtom.candidateDescriptor.returnType?.contains { it is NewCapturedType } ?: false
@@ -53,6 +53,7 @@ abstract class ManyCandidatesResolver<D : CallableDescriptor>(
if (callInfo !is PSIErrorCallInfo<*>) {
throw AssertionError("Error call info for $callInfo should be instance of PSIErrorCallInfo")
}
@Suppress("UNCHECKED_CAST")
errorCallsInfo.add(callInfo as PSIErrorCallInfo<D>)
}
@@ -260,7 +260,10 @@ class NewResolutionOldInference(
private fun <D : CallableDescriptor> allCandidatesResult(allCandidates: Collection<MyCandidate>) =
OverloadResolutionResultsImpl.nameNotFound<D>().apply {
this.allCandidates = allCandidates.map { it.resolvedCall as MutableResolvedCall<D> }
this.allCandidates = allCandidates.map {
@Suppress("UNCHECKED_CAST")
it.resolvedCall as MutableResolvedCall<D>
}
}
private fun <D : CallableDescriptor> convertToOverloadResults(
@@ -315,6 +318,7 @@ class NewResolutionOldInference(
}
}
@Suppress("UNCHECKED_CAST")
resolvedCall as MutableResolvedCall<D>
}
@@ -475,7 +479,7 @@ class NewResolutionOldInference(
variable: MyCandidate,
invoke: MyCandidate
): MyCandidate {
val resolvedCallImpl = VariableAsFunctionResolvedCallImpl(
@Suppress("UNCHECKED_CAST") val resolvedCallImpl = VariableAsFunctionResolvedCallImpl(
invoke.resolvedCall as MutableResolvedCall<FunctionDescriptor>,
variable.resolvedCall as MutableResolvedCall<VariableDescriptor>
)
@@ -25,7 +25,6 @@ import org.jetbrains.kotlin.resolve.calls.components.CallableReferenceResolver
import org.jetbrains.kotlin.resolve.calls.components.InferenceSession
import org.jetbrains.kotlin.resolve.calls.components.PostponedArgumentsAnalyzer
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.context.CheckArgumentTypesMode
import org.jetbrains.kotlin.resolve.calls.context.ContextDependency
import org.jetbrains.kotlin.resolve.calls.inference.buildResultingSubstitutor
import org.jetbrains.kotlin.resolve.calls.inference.components.KotlinConstraintSystemCompleter
@@ -551,8 +550,7 @@ class PSICallResolver(
require(oldCall is CallTransformer.CallForImplicitInvoke) { "Call should be CallForImplicitInvoke, but it is: $oldCall" }
val dispatchReceiver = oldCall.dispatchReceiver!! // dispatch receiver from CallForImplicitInvoke is always not null
return resolveReceiver(context, dispatchReceiver, isSafeCall = false, isForImplicitInvoke = true)
return resolveReceiver(context, oldCall.dispatchReceiver, isSafeCall = false, isForImplicitInvoke = true)
}
private fun resolveReceiver(
@@ -39,6 +39,7 @@ val KotlinCall.psiKotlinCall: PSIKotlinCall
return this as PSIKotlinCall
}
@Suppress("UNCHECKED_CAST")
fun <D : CallableDescriptor> KotlinCall.getResolvedPsiKotlinCall(trace: BindingTrace): NewResolvedCallImpl<D>? =
psiKotlinCall.psiCall.getResolvedCall(trace.bindingContext) as? NewResolvedCallImpl<D>
@@ -30,7 +30,7 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.storage.LockBasedLazyResolveStorageManager
import javax.inject.Inject
open class LazyDeclarationResolver @Deprecated("") constructor(
open class LazyDeclarationResolver constructor(
globalContext: GlobalContext,
delegationTrace: BindingTrace,
private val topLevelDescriptorProvider: TopLevelDescriptorProvider,
@@ -464,8 +464,8 @@ open class LazyClassMemberScope(
descriptor.returnType = c.wrappedTypeFactory.createDeferredType(trace, { thisDescriptor.defaultType })
}
override fun recordLookup(name: Name, from: LookupLocation) {
c.lookupTracker.record(from, thisDescriptor, name)
override fun recordLookup(name: Name, location: LookupLocation) {
c.lookupTracker.record(location, thisDescriptor, name)
}
// Do not add details here, they may compromise the laziness during debugging
@@ -62,8 +62,8 @@ class LazyPackageMemberScope(
// No extra properties
}
override fun recordLookup(name: Name, from: LookupLocation) {
c.lookupTracker.record(from, thisDescriptor, name)
override fun recordLookup(name: Name, location: LookupLocation) {
c.lookupTracker.record(location, thisDescriptor, name)
}
override fun getClassifierNames(): Set<Name>? = declarationProvider.getDeclarationNames()
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
@@ -163,7 +164,7 @@ object CastDiagnosticsUtil {
val supertypeWithVariables = TypeCheckingProcedure.findCorrespondingSupertype(subtypeWithVariables, supertype)
val variables = subtypeWithVariables.constructor.parameters
val variableConstructors = variables.map { descriptor -> descriptor.typeConstructor }.toSet()
val variableConstructors = variables.map(TypeParameterDescriptor::getTypeConstructor).toSet()
val substitution: MutableMap<TypeConstructor, TypeProjection> = if (supertypeWithVariables != null) {
// Now, let's try to unify Collection<T> and Collection<Foo> solution is a map from T to Foo
@@ -53,9 +53,8 @@ abstract class ModulesApiHistoryBase(protected val modulesInfo: IncrementalModul
}
val classFileDirs = classFiles.groupBy { it.parentFile }
for ((dir, files) in classFileDirs) {
val historyEither = getBuildHistoryForDir(dir)
when (historyEither) {
for (dir in classFileDirs.keys) {
when (val historyEither = getBuildHistoryForDir(dir)) {
is Either.Success<Set<File>> -> result.addAll(historyEither.value)
is Either.Error -> return historyEither
}
@@ -107,13 +106,13 @@ class ModulesApiHistoryJvm(modulesInfo: IncrementalModuleInfo) : ModulesApiHisto
val classFileDirs = classFiles.filter { it.exists() && it.parentFile != null }.groupBy { it.parentFile }
val result = HashSet<File>()
for ((dir, files) in classFileDirs) {
val historyEither = getBuildHistoryForDir(dir)
when (historyEither) {
for (dir in classFileDirs.keys) {
when (val historyEither = getBuildHistoryForDir(dir)) {
is Either.Success<Set<File>> -> result.addAll(historyEither.value)
is Either.Error -> return historyEither
}
}
return Either.Success(result)
}
}
@@ -121,7 +121,7 @@ abstract class IrElementVisitorVoidWithContext : IrElementVisitorVoid {
}
override final fun visitField(declaration: IrField) {
val isDelegated = declaration.descriptor.isDelegated
@Suppress("DEPRECATION") val isDelegated = declaration.descriptor.isDelegated
if (isDelegated) scopeStack.push(ScopeWithIr(Scope(declaration.symbol), declaration))
visitFieldNew(declaration)
if (isDelegated) scopeStack.pop()
@@ -19,7 +19,9 @@ package org.jetbrains.kotlin.backend.common.ir
import org.jetbrains.kotlin.backend.common.DumpIrTreeWithDescriptorsVisitor
import org.jetbrains.kotlin.backend.common.deepCopyWithVariables
import org.jetbrains.kotlin.backend.common.descriptors.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.builders.Scope
@@ -43,7 +45,6 @@ import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeImpl
import org.jetbrains.kotlin.ir.types.impl.makeTypeProjection
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import java.io.StringWriter
@@ -160,7 +161,6 @@ fun IrTypeParameter.copyToWithoutSuperTypes(
shift: Int = 0,
origin: IrDeclarationOrigin = this.origin
): IrTypeParameter {
val source = parent as IrTypeParametersContainer
val descriptor = WrappedTypeParameterDescriptor(symbol.descriptor.annotations, symbol.descriptor.source)
val symbol = IrTypeParameterSymbolImpl(descriptor)
return IrTypeParameterImpl(startOffset, endOffset, origin, symbol, name, shift + index, isReified, variance).also { copied ->
@@ -240,7 +240,8 @@ fun IrFunction.copyValueParametersToStatic(
)
)
}
source.valueParameters.forEachIndexed { i, oldValueParameter ->
for (oldValueParameter in source.valueParameters) {
target.valueParameters.add(
oldValueParameter.copyTo(
target,
@@ -345,6 +346,7 @@ fun IrClass.createImplicitParameterDeclarationWithWrappedDescriptor() {
assert(descriptor.declaredTypeParameters.isEmpty())
}
@Suppress("UNCHECKED_CAST")
fun isElseBranch(branch: IrBranch) = branch is IrElseBranch || ((branch.condition as? IrConst<Boolean>)?.value == true)
fun IrSimpleFunction.isMethodOfAny() =
@@ -183,31 +183,35 @@ class InlineClassLowering(val context: BackendContext) {
override fun lower(irFile: IrFile) {
irFile.transformChildrenVoid(object : IrElementTransformerVoid() {
override fun visitCall(call: IrCall): IrExpression {
call.transformChildrenVoid(this)
val function = call.symbol.owner
override fun visitCall(expression: IrCall): IrExpression {
expression.transformChildrenVoid(this)
val function = expression.symbol.owner
if (function.parent !is IrClass ||
function.isStaticMethodOfClass ||
!function.parentAsClass.isInline ||
(function is IrSimpleFunction && !function.isReal) ||
(function is IrConstructor && function.isPrimary)
) {
return call
return expression
}
return irCall(call, getOrCreateStaticMethod(function), dispatchReceiverAsFirstArgument = (function is IrSimpleFunction))
return irCall(
expression,
getOrCreateStaticMethod(function),
dispatchReceiverAsFirstArgument = (function is IrSimpleFunction)
)
}
override fun visitDelegatingConstructorCall(call: IrDelegatingConstructorCall): IrExpression {
call.transformChildrenVoid(this)
val function = call.symbol.owner
override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall): IrExpression {
expression.transformChildrenVoid(this)
val function = expression.symbol.owner
val klass = function.parentAsClass
return when {
!klass.isInline -> call
function.isPrimary -> irCall(call, function)
else -> irCall(call, getOrCreateStaticMethod(function)).apply {
(0 until call.valueArgumentsCount).forEach {
putValueArgument(it, call.getValueArgument(it)!!)
!klass.isInline -> expression
function.isPrimary -> irCall(expression, function)
else -> irCall(expression, getOrCreateStaticMethod(function)).apply {
(0 until expression.valueArgumentsCount).forEach {
putValueArgument(it, expression.getValueArgument(it)!!)
}
}
}
@@ -78,6 +78,7 @@ abstract class AbstractNamedPhaseWrapper<in Context : CommonBackendContext, Inpu
if (this is SameTypeCompilerPhase<*, *> &&
this !in phaseConfig.enabled
) {
@Suppress("UNCHECKED_CAST")
return input as Output
}
@@ -121,7 +122,7 @@ abstract class AbstractNamedPhaseWrapper<in Context : CommonBackendContext, Inpu
for (post in postconditions) post(output)
for (post in stickyPostconditions) post(output)
if (phaseConfig.checkStickyConditions && this is SameTypeCompilerPhase<*, *>) {
val phaserStateO = phaserState as PhaserState<Output>
@Suppress("UNCHECKED_CAST") val phaserStateO = phaserState as PhaserState<Output>
for (post in phaserStateO.stickyPostconditions) post(output)
}
}
@@ -17,7 +17,7 @@ private class CompositePhase<Context : CommonBackendContext, Input, Output>(
) : CompilerPhase<Context, Input, Output> {
override fun invoke(phaseConfig: PhaseConfig, phaserState: PhaserState<Input>, context: Context, input: Input): Output {
var currentState = phaserState as PhaserState<Any?>
@Suppress("UNCHECKED_CAST") var currentState = phaserState as PhaserState<Any?>
var result = phases.first().invoke(phaseConfig, currentState, context, input)
for ((previous, next) in phases.zip(phases.drop(1))) {
if (next !is SameTypeCompilerPhase<*, *>) {
@@ -27,6 +27,7 @@ private class CompositePhase<Context : CommonBackendContext, Input, Output>(
currentState.stickyPostconditions.addAll(previous.stickyPostconditions)
result = next.invoke(phaseConfig, currentState, context, result)
}
@Suppress("UNCHECKED_CAST")
return result as Output
}
@@ -36,6 +37,7 @@ private class CompositePhase<Context : CommonBackendContext, Input, Output>(
override val stickyPostconditions get() = phases.last().stickyPostconditions
}
@Suppress("UNCHECKED_CAST")
infix fun <Context : CommonBackendContext, Input, Mid, Output> CompilerPhase<Context, Input, Mid>.then(
other: CompilerPhase<Context, Mid, Output>
): CompilerPhase<Context, Input, Output> {
@@ -176,8 +176,6 @@ internal class FunctionInlining(val context: Context): IrElementTransformerVoidW
}
}
val sourceFile = callee.file
val transformer = ParameterSubstitutor()
statements.transform { it.transform(transformer, data = null) }
statements.addAll(0, evaluationStatements)
@@ -12,8 +12,8 @@ import org.jetbrains.kotlin.js.backend.ast.JsDeclarationScope
import org.jetbrains.kotlin.js.backend.ast.JsStatement
class IrFileToJsTransformer : BaseIrElementToJsNodeTransformer<JsStatement, JsGenerationContext> {
override fun visitFile(declaration: IrFile, context: JsGenerationContext): JsStatement {
val fileContext = context.newDeclaration(JsDeclarationScope(context.currentScope, "scope for file ${declaration.path}"))
override fun visitFile(declaration: IrFile, data: JsGenerationContext): JsStatement {
val fileContext = data.newDeclaration(JsDeclarationScope(data.currentScope, "scope for file ${declaration.path}"))
val block = fileContext.currentBlock
declaration.declarations.forEach {
@@ -10,7 +10,9 @@ import org.jetbrains.kotlin.backend.common.ir.isElseBranch
import org.jetbrains.kotlin.ir.backend.js.utils.JsGenerationContext
import org.jetbrains.kotlin.ir.backend.js.utils.Namer
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrMemberAccessExpression
import org.jetbrains.kotlin.ir.expressions.IrWhen
import org.jetbrains.kotlin.js.backend.ast.*
fun jsVar(name: JsName, initializer: IrExpression?, context: JsGenerationContext): JsVars {
@@ -18,12 +20,12 @@ fun jsVar(name: JsName, initializer: IrExpression?, context: JsGenerationContext
return JsVars(JsVars.JsVar(name, jsInitializer))
}
fun <T : JsNode, D : JsGenerationContext> IrWhen.toJsNode(
tr: BaseIrElementToJsNodeTransformer<T, D>,
data: D,
fun <T : JsNode> IrWhen.toJsNode(
tr: BaseIrElementToJsNodeTransformer<T, JsGenerationContext>,
data: JsGenerationContext,
node: (JsExpression, T, T?) -> T
): T? =
branches.foldRight<IrBranch, T?>(null) { br, n ->
branches.foldRight(null) { br, n ->
val body = br.result.accept(tr, data)
if (isElseBranch(br)) body
else {
@@ -118,9 +120,7 @@ object JsAstUtils {
thenStatement: JsStatement,
elseStatement: JsStatement? = null
): JsIf {
var elseStatement = elseStatement
elseStatement = if (elseStatement != null) deBlockIfPossible(elseStatement) else null
return JsIf(ifExpression, deBlockIfPossible(thenStatement), elseStatement)
return JsIf(ifExpression, deBlockIfPossible(thenStatement), elseStatement?.let { deBlockIfPossible(it) })
}
fun and(op1: JsExpression, op2: JsExpression): JsBinaryOperation {
@@ -21,6 +21,7 @@ object JsAnnotations {
val jsQualifierFqn = FqName("kotlin.js.JsQualifier")
}
@Suppress("UNCHECKED_CAST")
private fun IrCall.getSingleConstStringArgument() =
(getValueArgument(0) as IrConst<String>).value
@@ -31,7 +31,7 @@ class JvmIrCodegenFactory(private val phaseConfig: PhaseConfig) : CodegenFactory
val psi2ir = Psi2IrTranslator(state.languageVersionSettings)
val psi2irContext = psi2ir.createGeneratorContext(state.module, state.bindingContext, extensions = JvmGeneratorExtensions)
val irModuleFragment = psi2ir.generateModuleFragment(psi2irContext, files as Collection<KtFile>)
@Suppress("UNCHECKED_CAST") val irModuleFragment = psi2ir.generateModuleFragment(psi2irContext, files as Collection<KtFile>)
JvmBackendFacade.doGenerateFilesInternal(state, errorHandler, irModuleFragment, psi2irContext, phaseConfig)
}
@@ -96,7 +96,7 @@ class IrInlineCodegen(
private fun rememberClosure(irReference: IrFunctionReference, type: Type, parameter: ValueParameterDescriptor): LambdaInfo {
//assert(InlineUtil.isInlinableParameterExpression(ktLambda)) { "Couldn't find inline expression in ${expression.text}" }
val expression = irReference.symbol.owner as IrFunction
val expression = irReference.symbol.owner
return IrExpressionLambdaImpl(
irReference, expression, typeMapper, parameter.isCrossinline, false/*TODO*/,
parameter.type.isExtensionFunctionType
@@ -177,7 +177,7 @@ class JvmSharedVariablesManager(
typeArgumentsCount = typeArgumentsCount,
origin = SHARED_VARIABLE_CONSTRUCTOR_CALL_ORIGIN
).apply {
refConstructor.parentAsClass.typeParameters.mapIndexed { i, param ->
List(refConstructor.parentAsClass.typeParameters.size) { i ->
putTypeArgument(i, valueType)
}
}
@@ -212,10 +212,10 @@ private class FieldReplacer(val replacementMap: Map<IrFieldSymbol, IrFieldSymbol
} ?: super.visitGetField(expression)
override fun visitSetField(expression: IrSetField): IrExpression =
replacementMap[expression.symbol]?.let { newSymbol ->
replacementMap[expression.symbol]?.let { _ ->
IrSetFieldImpl(
expression.startOffset, expression.endOffset,
replacementMap[expression.symbol]!!,
replacementMap.getValue(expression.symbol),
/* receiver = */ null,
visitExpression(expression.value),
expression.type,
@@ -106,7 +106,6 @@ class BranchingExpressionGenerator(statementGenerator: StatementGenerator) : Sta
// TODO relies on ControlFlowInformationProvider, get rid of it
val isUsedAsExpression = get(BindingContext.USED_AS_EXPRESSION, expression) ?: false
val isExhaustive = expression.isExhaustiveWhen()
val resultType = when {
isUsedAsExpression -> inferredType.toIrType()
@@ -172,7 +172,7 @@ class CallGenerator(statementGenerator: StatementGenerator) : StatementGenerator
val irType = descriptor.type.toIrType()
return if (getMethodDescriptor == null) {
call.callReceiver.call { dispatchReceiverValue, extensionReceiverValue ->
call.callReceiver.call { dispatchReceiverValue, _ ->
val fieldSymbol = context.symbolTable.referenceField(descriptor.original)
IrGetFieldImpl(
startOffset, endOffset,
@@ -156,6 +156,7 @@ class ReflectionReferencesGenerator(statementGenerator: StatementGenerator) : St
private fun getFieldForPropertyReference(originalProperty: PropertyDescriptor) =
// NB this is a hack, we really don't know if an arbitrary property has a backing field or not
when {
@Suppress("DEPRECATION")
originalProperty.isDelegated -> null
originalProperty.getter != null -> null
else -> context.symbolTable.referenceField(originalProperty)
@@ -85,6 +85,7 @@ class IrLocalDelegatedPropertyImpl(
descriptor.name, type, descriptor.isVar
)
@Suppress("DEPRECATION")
@Deprecated("Creates unbound symbol")
constructor(
startOffset: Int,
@@ -39,7 +39,7 @@ class IrPropertyImpl(
override val isVar: Boolean = symbol.descriptor.isVar,
override val isConst: Boolean = symbol.descriptor.isConst,
override val isLateinit: Boolean = symbol.descriptor.isLateInit,
override val isDelegated: Boolean = symbol.descriptor.isDelegated,
@Suppress("DEPRECATION") override val isDelegated: Boolean = symbol.descriptor.isDelegated,
override val isExternal: Boolean = symbol.descriptor.isEffectivelyExternal()
) : IrDeclarationBase(startOffset, endOffset, origin),
IrProperty {
@@ -69,6 +69,7 @@ class IrPropertyImpl(
isExternal = isExternal
)
@Suppress("DEPRECATION")
@Deprecated(message = "Don't use descriptor-based API for IrProperty", level = DeprecationLevel.WARNING)
constructor(
startOffset: Int,
@@ -86,6 +87,7 @@ class IrPropertyImpl(
isExternal = descriptor.isEffectivelyExternal()
)
@Suppress("DEPRECATION")
@Deprecated(message = "Don't use descriptor-based API for IrProperty", level = DeprecationLevel.WARNING)
constructor(
startOffset: Int,
@@ -94,6 +96,7 @@ class IrPropertyImpl(
descriptor: PropertyDescriptor
) : this(startOffset, endOffset, origin, descriptor.isDelegated, descriptor)
@Suppress("DEPRECATION")
@Deprecated(message = "Don't use descriptor-based API for IrProperty", level = DeprecationLevel.WARNING)
constructor(
startOffset: Int,
@@ -106,6 +109,7 @@ class IrPropertyImpl(
this.backingField = backingField
}
@Suppress("DEPRECATION")
@Deprecated(message = "Don't use descriptor-based API for IrProperty", level = DeprecationLevel.WARNING)
constructor(
startOffset: Int,
@@ -57,7 +57,7 @@ class IrLazyProperty(
isVar = symbol.descriptor.isVar,
isConst = symbol.descriptor.isConst,
isLateinit = symbol.descriptor.isLateInit,
isDelegated = symbol.descriptor.isDelegated,
isDelegated = @Suppress("DEPRECATION") symbol.descriptor.isDelegated,
isExternal = symbol.descriptor.isEffectivelyExternal(),
stubGenerator = stubGenerator,
typeTranslator = typeTranslator,
@@ -33,6 +33,6 @@ class LazyScopedTypeParametersResolver(private val symbolTable: ReferenceSymbolT
parent.typeParameters.firstOrNull {
it.descriptor == typeParameterDescriptor
}?.symbol
} ?: null
}
}
}
@@ -93,7 +93,7 @@ class DeclarationStubGenerator(
val origin = computeOrigin(descriptor)
return symbolTable.declareProperty(
UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, descriptor.original,
isDelegated = descriptor.isDelegated
isDelegated = @Suppress("DEPRECATION") descriptor.isDelegated
) {
deserializer?.findDeserializedDeclaration(descriptor)
?: IrLazyProperty(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator, bindingContext)
@@ -62,7 +62,7 @@ fun IrMemberAccessExpression.getArguments(): List<Pair<ParameterDescriptor, IrEx
*/
fun IrFunctionAccessExpression.getArgumentsWithSymbols(): List<Pair<IrValueParameterSymbol, IrExpression>> {
val res = mutableListOf<Pair<IrValueParameterSymbol, IrExpression>>()
val irFunction = symbol.owner as IrFunction
val irFunction = symbol.owner
dispatchReceiver?.let {
res += (irFunction.dispatchReceiverParameter!!.symbol to it)
@@ -347,6 +347,7 @@ fun IrDeclaration.isEffectivelyExternal(): Boolean {
inline fun <reified T : IrDeclaration> IrDeclarationContainer.findDeclaration(predicate: (T) -> Boolean): T? =
declarations.find { it is T && predicate(it) } as? T
@Suppress("UNCHECKED_CAST")
inline fun <reified T : IrDeclaration> IrDeclarationContainer.filterDeclarations(predicate: (T) -> Boolean): List<T> =
declarations.filter { it is T && predicate(it) } as List<T>
@@ -334,7 +334,7 @@ open class SymbolTable : ReferenceSymbolTable {
endOffset: Int,
origin: IrDeclarationOrigin,
descriptor: PropertyDescriptor,
isDelegated: Boolean = descriptor.isDelegated,
@Suppress("DEPRECATION") isDelegated: Boolean = descriptor.isDelegated,
propertyFactory: (IrPropertySymbol) -> IrProperty = { symbol ->
IrPropertyImpl(startOffset, endOffset, origin, symbol, isDelegated = isDelegated).apply {
metadata = MetadataSource.Property(symbol.descriptor)
@@ -166,7 +166,7 @@ abstract class IrModuleDeserializer(
}
private fun deserializeSyntheticBody(proto: KotlinIr.IrSyntheticBody, start: Int, end: Int): IrSyntheticBody {
val kind = when (proto.kind) {
val kind = when (proto.kind!!) {
KotlinIr.IrSyntheticBodyKind.ENUM_VALUES -> IrSyntheticBodyKind.ENUM_VALUES
KotlinIr.IrSyntheticBodyKind.ENUM_VALUEOF -> IrSyntheticBodyKind.ENUM_VALUEOF
}
@@ -652,7 +652,7 @@ abstract class IrModuleDeserializer(
}
private fun deserializeConst(proto: KotlinIr.IrConst, start: Int, end: Int, type: IrType): IrExpression =
when (proto.valueCase) {
when (proto.valueCase!!) {
NULL
-> IrConstImpl.constNull(start, end, type)
BOOLEAN
@@ -678,7 +678,7 @@ abstract class IrModuleDeserializer(
}
private fun deserializeOperation(proto: KotlinIr.IrOperation, start: Int, end: Int, type: IrType): IrExpression =
when (proto.operationCase) {
when (proto.operationCase!!) {
BLOCK
-> deserializeBlock(proto.block, start, end, type)
BREAK
@@ -766,11 +766,12 @@ abstract class IrModuleDeserializer(
val name = deserializeName(proto.name)
val variance = deserializeIrTypeVariance(proto.variance)
val parameter = symbolTable.declareGlobalTypeParameter(UNDEFINED_OFFSET, UNDEFINED_OFFSET, irrelevantOrigin,
symbol.descriptor, { symbol ->
IrTypeParameterImpl(start, end, origin, symbol, name, proto.index, proto.isReified, variance)
}
)
val parameter = symbolTable.declareGlobalTypeParameter(
UNDEFINED_OFFSET, UNDEFINED_OFFSET, irrelevantOrigin,
symbol.descriptor
) {
IrTypeParameterImpl(start, end, origin, it, name, proto.index, proto.isReified, variance)
}
val superTypes = proto.superTypeList.map { deserializeIrType(it) }
parameter.superTypes.addAll(superTypes)
@@ -1162,7 +1163,7 @@ abstract class IrModuleDeserializer(
val declarator = proto.declarator
val declaration: IrDeclaration = when (declarator.declaratorCase) {
val declaration: IrDeclaration = when (declarator.declaratorCase!!) {
IR_ANONYMOUS_INIT
-> deserializeIrAnonymousInit(declarator.irAnonymousInit, start, end, origin)
IR_CONSTRUCTOR
@@ -967,7 +967,7 @@ open class IrModuleSerializer(
}
private fun serializeIrProperty(property: IrProperty): KotlinIr.IrProperty {
val index = declarationTable.uniqIdByDeclaration(property)
declarationTable.uniqIdByDeclaration(property)
val proto = KotlinIr.IrProperty.newBuilder()
.setIsDelegated(property.isDelegated)
@@ -133,7 +133,6 @@ object LightClassUtil {
.filter { it.kotlinOrigin === declaration }
private fun getWrappingClass(declaration: KtDeclaration): PsiClass? {
var declaration = declaration
if (declaration is KtParameter) {
val constructorClass = KtPsiUtil.getClassIfParameterIsProperty(declaration)
if (constructorClass != null) {
@@ -141,15 +140,16 @@ object LightClassUtil {
}
}
if (declaration is KtPropertyAccessor) {
declaration = declaration.property
var ktDeclaration = declaration
if (ktDeclaration is KtPropertyAccessor) {
ktDeclaration = ktDeclaration.property
}
if (declaration is KtConstructor<*>) {
return declaration.getContainingClassOrObject().toLightClass()
if (ktDeclaration is KtConstructor<*>) {
return ktDeclaration.getContainingClassOrObject().toLightClass()
}
val parent = declaration.parent
val parent = ktDeclaration.parent
if (parent is KtFile) {
// top-level declaration
@@ -474,7 +474,7 @@ open class KtUltraLightClass(classOrObject: KtClassOrObject, internal val suppor
}
private fun addReceiverParameter(callable: KtCallableDeclaration, method: KtUltraLightMethod) {
val receiver = callable.receiverTypeReference ?: return
if (callable.receiverTypeReference == null) return
method.delegate.addParameter(KtUltraLightReceiverParameter(callable, support, method))
}
@@ -103,8 +103,7 @@ class KtLightAnnotationForSourceEntry(
}
private fun getAttributeValue(name: String?, useDefault: Boolean): PsiAnnotationMemberValue? {
val name = name ?: "value"
val callEntry = getCallEntry(name) ?: return null
val callEntry = getCallEntry(name ?: "value") ?: return null
val valueArgument = callEntry.value.arguments.firstOrNull()
if (valueArgument != null) {
@@ -341,7 +340,7 @@ private fun KtElement.getResolvedCall(): ResolvedCall<out CallableDescriptor>? {
}
fun convertToLightAnnotationMemberValue(lightParent: PsiElement, argument: KtExpression): PsiAnnotationMemberValue {
val argument = unwrapCall(argument)
@Suppress("NAME_SHADOWING") val argument = unwrapCall(argument)
when (argument) {
is KtClassLiteralExpression -> {
return KtLightPsiClassObjectAccessExpression(argument, lightParent)
@@ -395,7 +394,7 @@ private fun unwrapCall(callee: KtExpression): KtExpression = when (callee) {
}
private fun getAnnotationName(callee: KtExpression): String? {
val callee = unwrapCall(callee)
@Suppress("NAME_SHADOWING") val callee = unwrapCall(callee)
val resultingDescriptor = callee.getResolvedCall()?.resultingDescriptor
if (resultingDescriptor is ClassConstructorDescriptor) {
val ktClass = resultingDescriptor.constructedClass.source.getPsi() as? KtClass
@@ -16,8 +16,6 @@
package org.jetbrains.kotlin.kdoc.parser
import com.intellij.openapi.util.text.StringUtil
enum class KDocKnownTag(val isReferenceRequired: Boolean, val isSectionStart: Boolean) {
AUTHOR(false, false),
THROWS(true, false),
@@ -35,12 +33,11 @@ enum class KDocKnownTag(val isReferenceRequired: Boolean, val isSectionStart: Bo
companion object {
fun findByTagName(tagName: CharSequence): KDocKnownTag? {
var tagName = tagName
if (StringUtil.startsWith(tagName, "@")) {
tagName = tagName.subSequence(1, tagName.length)
}
val name = if (tagName.startsWith('@')) {
tagName.subSequence(1, tagName.length)
} else tagName
try {
return valueOf(tagName.toString().toUpperCase())
return valueOf(name.toString().toUpperCase())
} catch (ignored: IllegalArgumentException) {
}
@@ -28,6 +28,7 @@ object EditCommaSeparatedListHelper {
return addItemBefore(list, allItems, item, null, prefix)
}
@Suppress("UNCHECKED_CAST")
@JvmOverloads
fun <TItem : KtElement> addItemAfter(
list: KtElement,
@@ -292,6 +292,7 @@ class KtPsiFactory @JvmOverloads constructor(private val project: Project, val m
val file = createFile(text)
val declarations = file.declarations
assert(declarations.size == 1) { "${declarations.size} declarations in $text" }
@Suppress("UNCHECKED_CAST")
return declarations.first() as TDeclaration
}
@@ -8,7 +8,6 @@ package org.jetbrains.kotlin.resolve.calls.inference.components
import org.jetbrains.kotlin.types.AbstractNullabilityChecker
import org.jetbrains.kotlin.types.AbstractTypeChecker
import org.jetbrains.kotlin.types.AbstractTypeCheckerContext
import org.jetbrains.kotlin.types.checker.*
import org.jetbrains.kotlin.types.model.*
abstract class AbstractTypeCheckerContextForConstraintSystem : AbstractTypeCheckerContext(), TypeSystemInferenceExtensionContext {
@@ -86,9 +85,9 @@ abstract class AbstractTypeCheckerContextForConstraintSystem : AbstractTypeCheck
// extract type variable only from type like Captured(out T)
private fun extractTypeVariableForSubtype(type: KotlinTypeMarker): KotlinTypeMarker? {
val type = type.asSimpleType()?.asCapturedType() ?: return null
val typeMarker = type.asSimpleType()?.asCapturedType() ?: return null
val projection = type.typeConstructorProjection()
val projection = typeMarker.typeConstructorProjection()
return if (projection.getVariance() == TypeVariance.OUT)
projection.getType().takeIf { it is SimpleTypeMarker && isMyTypeVariable(it) }?.asSimpleType()
else
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.resolve.calls.components.ClassicTypeSystemContextForCS
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilder
import org.jetbrains.kotlin.resolve.calls.inference.model.NewConstraintSystemImpl
import org.jetbrains.kotlin.resolve.calls.inference.model.SimpleConstraintSystemConstraintPosition
import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableFromCallableDescriptor
import org.jetbrains.kotlin.resolve.calls.inference.substitute
import org.jetbrains.kotlin.resolve.calls.results.SimpleConstraintSystem
@@ -52,7 +51,12 @@ class SimpleConstraintSystemImpl(constraintInjector: ConstraintInjector, builtIn
}
override fun addSubtypeConstraint(subType: UnwrappedType, superType: UnwrappedType) {
csBuilder.addSubtypeConstraint(subType, superType, SimpleConstraintSystemConstraintPosition)
csBuilder.addSubtypeConstraint(
subType,
superType,
@Suppress("DEPRECATION")
org.jetbrains.kotlin.resolve.calls.inference.model.SimpleConstraintSystemConstraintPosition
)
}
override fun hasContradiction() = csBuilder.hasContradiction
@@ -216,7 +216,7 @@ open class OverloadingConflictResolver<C : Any>(
}
}
if (result == null) return null
if (any { it != result && isNotWorse(it, result!!) }) {
if (any { it != result && isNotWorse(it, result) }) {
return null
}
return result
@@ -121,6 +121,7 @@ abstract class LexicalScopeStorage(
val result = ArrayList<TDescriptor>(1)
var rest: IntList? = this
do {
@Suppress("UNCHECKED_CAST")
result.add(rest!!.last.descriptorByIndex() as TDescriptor)
rest = rest.prev
} while (rest != null)
@@ -48,7 +48,7 @@ abstract class AbstractCheckLocalVariablesTableTest : CodegenTestCase() {
val pathsString = outputFiles.joinToString { it.relativePath }
assertNotNull("Couldn't find class file for pattern $classFileRegex in: $pathsString", outputFile)
val actualLocalVariables = readLocalVariable(ClassReader(outputFile!!.asByteArray()), methodName)
val actualLocalVariables = readLocalVariable(ClassReader(outputFile.asByteArray()), methodName)
doCompare(wholeFile, files.single().content, actualLocalVariables)
} catch (e: Throwable) {
@@ -59,10 +59,8 @@ class AdditionalBuiltInsMembersSignatureListsTest : KotlinTestWithEnvironment()
val lateJdkSignatures = LATE_JDK_SIGNATURES[internalName] ?: emptySet()
jvmDescriptors.forEach {
jvmDescriptor ->
if (jvmDescriptor in lateJdkSignatures) return@forEach
for (jvmDescriptor in jvmDescriptors) {
if (jvmDescriptor in lateJdkSignatures) continue
val stringName = jvmDescriptor.split("(")[0]
val functions =
@@ -78,9 +78,11 @@ class CustomScriptCodegenTest : CodegenTestCase() {
}
@Suppress("UNCHECKED_CAST")
private fun Class<*>.safeGetAnnotation(ann: KClass<out Annotation>): Annotation? =
getAnnotation(classLoader.loadClass(ann.qualifiedName) as Class<Annotation>)
@Suppress("UNCHECKED_CAST")
private fun java.lang.reflect.Constructor<*>.safeGetAnnotation(ann: KClass<out Annotation>): Annotation? =
getAnnotation(this.declaringClass.classLoader.loadClass(ann.qualifiedName) as Class<Annotation>)
@@ -579,11 +579,11 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
ParallelStartParams.performCompilation -> {
val jar = tmpdir.absolutePath + File.separator + "hello.$threadNo.jar"
KotlinCompilerClient.compile(
compileServiceSession!!.compileService,
compileServiceSession.sessionId,
CompileService.TargetPlatform.JVM,
arrayOf(File(getHelloAppBaseDir(), "hello.kt").absolutePath, "-d", jar),
PrintingMessageCollector(PrintStream(outStreams[threadNo]), MessageRenderer.WITHOUT_PATHS, true))
compileServiceSession.compileService,
compileServiceSession.sessionId,
CompileService.TargetPlatform.JVM,
arrayOf(File(getHelloAppBaseDir(), "hello.kt").absolutePath, "-d", jar),
PrintingMessageCollector(PrintStream(outStreams[threadNo]), MessageRenderer.WITHOUT_PATHS, true))
}
else -> 0 // compilation skipped, assuming - successful
}
@@ -60,10 +60,10 @@ class KotlinClassFinderTest : KotlinTestWithEnvironmentManagement() {
assertNotNull(psiClass, "Psi class not found for $className")
assertTrue(psiClass !is KtLightClass, "Kotlin light classes are not not expected")
val binaryClass = VirtualFileFinder.SERVICE.getInstance(project).findKotlinClass(JavaClassImpl(psiClass!!))
val binaryClass = VirtualFileFinder.SERVICE.getInstance(project).findKotlinClass(JavaClassImpl(psiClass))
assertNotNull(binaryClass, "No binary class for $className")
assertEquals("test/A.B.C", binaryClass?.classId?.toString())
assertEquals("test/A.B.C", binaryClass.classId.toString())
}
private fun createEnvironment(tmpdir: File?): KotlinCoreEnvironment {
@@ -66,10 +66,10 @@ class KotlinJavacBasedClassFinderTest : KotlinTestWithEnvironmentManagement() {
val found = classFinder.findClass(classId)
assertNotNull(found, "Class not found for $className")
val binaryClass = VirtualFileFinder.SERVICE.getInstance(project).findKotlinClass(found!!)
val binaryClass = VirtualFileFinder.SERVICE.getInstance(project).findKotlinClass(found)
assertNotNull(binaryClass, "No binary class for $className")
assertEquals("test/A.B.C", binaryClass?.classId?.toString())
assertEquals("test/A.B.C", binaryClass.classId.toString())
}
private fun createClassFinder(project: Project) = JavacBasedClassFinder().apply {
@@ -37,8 +37,8 @@ abstract class AbstractVersionRequirementTest : TestCaseWithTmpdir() {
val descriptor = module.findUnambiguousDescriptorByFqName(fqName)
val requirement = when (descriptor) {
is DeserializedMemberDescriptor -> descriptor.versionRequirements.single()
is DeserializedClassDescriptor -> descriptor.versionRequirements.single()
is DeserializedMemberDescriptor -> descriptor.versionRequirements.singleOrNull()
is DeserializedClassDescriptor -> descriptor.versionRequirements.singleOrNull()
else -> throw AssertionError("Unknown descriptor: $descriptor")
} ?: throw AssertionError("No VersionRequirement for $descriptor")
@@ -40,7 +40,7 @@ abstract class AbstractTypeBindingTest : KotlinTestWithEnvironment() {
val analyzeResult = JvmResolveUtil.analyze(testKtFile, environment)
val testDeclaration = testKtFile.declarations.last()!! as KtCallableDeclaration
val testDeclaration = testKtFile.declarations.last() as KtCallableDeclaration
val typeBinding = testDeclaration.createTypeBindingForReturnType(analyzeResult.bindingContext)
@@ -31,6 +31,7 @@ class ReflectJavaTypeParameter(
return bounds
}
@Suppress("USELESS_CAST")
override val element: AnnotatedElement?
// TypeVariable is AnnotatedElement only in JDK8
get() = typeVariable as? AnnotatedElement
@@ -404,6 +404,7 @@ interface ClassicTypeSystemContext : TypeSystemInferenceExtensionContext {
override fun SimpleTypeMarker.replaceArguments(newArguments: List<TypeArgumentMarker>): SimpleTypeMarker {
require(this is SimpleType, this::errorMessage)
@Suppress("UNCHECKED_CAST")
return this.replace(newArguments as List<TypeProjection>)
}
@@ -137,6 +137,7 @@ object NewKotlinTypeChecker : KotlinTypeChecker {
constructor: TypeConstructor
): List<SimpleType> {
return AbstractTypeChecker.run {
@Suppress("UNCHECKED_CAST")
findCorrespondingSupertypes(baseType, constructor) as List<SimpleType>
}
}
@@ -21,5 +21,5 @@ enum class ScriptExpectedLocation {
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class ScriptExpectedLocations(
val value: Array<ScriptExpectedLocation> = [ScriptExpectedLocation.SourcesOnly, ScriptExpectedLocation.TestsOnly]
@Suppress("DEPRECATION") val value: Array<ScriptExpectedLocation> = [ScriptExpectedLocation.SourcesOnly, ScriptExpectedLocation.TestsOnly]
)
@@ -19,5 +19,5 @@ open class ScriptTemplateAdditionalCompilerArgumentsProvider(val arguments: Iter
@Retention(AnnotationRetention.RUNTIME)
annotation class ScriptTemplateAdditionalCompilerArguments(
val arguments: Array<String> = [],
val provider: KClass<out ScriptTemplateAdditionalCompilerArgumentsProvider> = ScriptTemplateAdditionalCompilerArgumentsProvider::class
@Suppress("DEPRECATION") val provider: KClass<out ScriptTemplateAdditionalCompilerArgumentsProvider> = ScriptTemplateAdditionalCompilerArgumentsProvider::class
)
-1
View File
@@ -47,7 +47,6 @@ class GenerateProgressions(out: PrintWriter) : BuiltInsSourceGenerator(out) {
" if (isEmpty()) -1 else (31 * (31 * first + last) + step)"
LONG ->
" if (isEmpty()) -1 else (31 * (31 * ${hashLong("first")} + ${hashLong("last")}) + ${hashLong("step")}).toInt()"
else -> throw IllegalArgumentException()
}
out.println(
-1
View File
@@ -371,7 +371,6 @@ class UnsignedTypeGenerator(val type: UnsignedType, out: PrintWriter) : BuiltIns
UnsignedType.UBYTE, UnsignedType.USHORT -> out.println("toInt().toString()")
UnsignedType.UINT -> out.println("toLong().toString()")
UnsignedType.ULONG -> out.println("ulongToString(data)")
else -> error(type)
}
out.println()
@@ -60,13 +60,11 @@ class SyntheticKotlinBlock(
}
val textRange = getTextRange()
if (treeNode != null) {
val psi = treeNode.psi
if (psi != null) {
val file = psi.containingFile
if (file != null) {
return file.text!!.subSequence(textRange.startOffset, textRange.endOffset).toString() + " " + textRange
}
val psi = treeNode.psi
if (psi != null) {
val file = psi.containingFile
if (file != null) {
return file.text!!.subSequence(textRange.startOffset, textRange.endOffset).toString() + " " + textRange
}
}
@@ -199,8 +199,8 @@ class KotlinPsiUnifier(
s and when {
arg1 == arg2 -> MATCHED
arg1 == null || arg2 == null -> UNMATCHED
else -> (arg1.arguments.asSequence().zip(arg2.arguments.asSequence())).fold(MATCHED) { s, p ->
s and matchArguments(p.first, p.second)
else -> (arg1.arguments.asSequence().zip(arg2.arguments.asSequence())).fold(MATCHED) { status, pair ->
status and matchArguments(pair.first, pair.second)
}
}
}
@@ -711,7 +711,7 @@ class KotlinPsiUnifier(
null
}
if (status == UNMATCHED) {
declarationPatternsToTargets.removeValue(desc1, desc2)
declarationPatternsToTargets.remove(desc1, desc2)
}
return status
@@ -110,7 +110,7 @@ sealed class LazyLightClassDataHolder(
return dummyDelegate!!.fields.map { dummyField ->
val fieldOrigin = KtLightFieldImpl.getOrigin(dummyField)
val fieldName = dummyField.name!!
val fieldName = dummyField.name
KtLightFieldImpl.lazy(dummyField, fieldOrigin, containingClass) {
clsDelegate.findFieldByName(fieldName, false).assertMatches(dummyField, containingClass)
}
@@ -60,7 +60,7 @@ data class LightMemberOriginForCompiledField(val psiField: PsiField, val file: K
override val originalElement: KtDeclaration? by lazyPub {
val desc = MapPsiToAsmDesc.typeDesc(psiField.type)
val signature = MemberSignature.fromFieldNameAndDesc(psiField.name!!, desc)
val signature = MemberSignature.fromFieldNameAndDesc(psiField.name, desc)
findDeclarationInCompiledFile(file, psiField, signature)
}
}
@@ -33,6 +33,7 @@ abstract class AbstractApplicabilityBasedInspection<TElement: KtElement>(
super.visitKtElement(element)
if (!elementType.isInstance(element) || element.textLength == 0) return
@Suppress("UNCHECKED_CAST")
visitTargetElement(element as TElement, holder, isOnTheFly)
}
}
@@ -175,7 +175,11 @@ abstract class IntentionBasedInspection<TElement : PsiElement> private construct
override fun isAvailable(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement): Boolean {
assert(startElement == endElement)
return intention.applicabilityRange(startElement as TElement) != null && additionalChecker(startElement, this@IntentionBasedInspection)
@Suppress("UNCHECKED_CAST")
return intention.applicabilityRange(startElement as TElement) != null && additionalChecker(
startElement,
this@IntentionBasedInspection
)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
@@ -190,6 +194,7 @@ abstract class IntentionBasedInspection<TElement : PsiElement> private construct
val editor = startElement.findExistingEditor()
editor?.caretModel?.moveToOffset(startElement.textOffset)
@Suppress("UNCHECKED_CAST")
intention.applyTo(startElement as TElement, editor)
}
}
@@ -22,6 +22,7 @@ import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
interface KotlinUniversalQuickFix : IntentionAction, LocalQuickFix {
@JvmDefault
override fun getName() = text
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
@@ -136,7 +136,7 @@ sealed class SyntheticPropertyAccessorReference(expression: KtNameReferenceExpre
val fullExpression = expression.getQualifiedExpressionForSelectorOrThis()
fullExpression.getAssignmentByLHS()?.let { assignment ->
val rhs = assignment.right ?: return expression
val operationToken = assignment.operationToken as? KtSingleValueToken
val operationToken = assignment.operationToken as? KtSingleValueToken ?: return expression
val counterpartOp = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[operationToken]
val setterArgument = if (counterpartOp != null) {
val getterCall = if (getter) fullExpression.createCall(psiFactory, newGetterName) else fullExpression
@@ -121,4 +121,4 @@ fun indexInternals(stub: KotlinCallableStubBase<*>, sink: IndexSink) {
}
private val KotlinStubWithFqName<*>.modifierList: KotlinModifierListStub?
get() = findChildStubByType(KtStubElementTypes.MODIFIER_LIST) as? KotlinModifierListStub
get() = findChildStubByType(KtStubElementTypes.MODIFIER_LIST)
@@ -27,7 +27,7 @@ class KotlinTypeAliasByExpansionShortNameIndex : StringStubIndexExtension<KtType
override fun getKey(): StubIndexKey<String, KtTypeAlias> = KEY
override fun get(key: String, project: Project, scope: GlobalSearchScope) =
StubIndex.getElements(KEY, key, project, scope, KtTypeAlias::class.java)!!
StubIndex.getElements(KEY, key, project, scope, KtTypeAlias::class.java)
companion object {
val KEY = KotlinIndexUtil.createIndexKey(KotlinTypeAliasByExpansionShortNameIndex::class.java)
@@ -40,7 +40,7 @@ fun <T> Project.executeWriteCommand(name: String, groupId: Any? = null, command:
}
fun <T> Project.executeCommand(name: String, groupId: Any? = null, command: () -> T): T {
var result: T = null as T
@Suppress("UNCHECKED_CAST") var result: T = null as T
CommandProcessor.getInstance().executeCommand(this, { result = command() }, name, groupId)
@Suppress("USELESS_CAST")
return result as T
@@ -26,7 +26,7 @@ fun <T> Project.runReadActionInSmartMode(action: () -> T): T {
}
fun <T> Project.runWithAlternativeResolveEnabled(action: () -> T): T {
var result: T = null as T
@Suppress("UNCHECKED_CAST") var result: T = null as T
DumbService.getInstance(this).withAlternativeResolveEnabled { result = action() }
@Suppress("USELESS_CAST")
return result as T
@@ -57,8 +57,8 @@ fun parse(lineText: String, reader: OutputLineReader, messages: MutableList<Mess
val column = if (matcher.groupCount() >= 2) matcher.group(2)?.toInt() ?: 1 else 1
if (line != null) {
val position = SourceFilePosition(file, SourcePosition(line, column, column))
return addMessage(Message(getMessageKind(severity), message.trim(), position), messages)
val filePosition = SourceFilePosition(file, SourcePosition(line, column, column))
return addMessage(Message(getMessageKind(severity), message.trim(), filePosition), messages)
}
}
@@ -33,7 +33,7 @@ class AndroidGradleModelFacade : KotlinGradleModelFacade {
}
override fun getDependencyModules(ideModule: DataNode<ModuleData>, gradleIdeaProject: IdeaProject): Collection<DataNode<ModuleData>> {
val ideProject = ideModule.parent as DataNode<ProjectData>
@Suppress("UNCHECKED_CAST") val ideProject = ideModule.parent as DataNode<ProjectData>
ExternalSystemApiUtil.find(ideModule, AndroidProjectKeys.JAVA_MODULE_MODEL)?.let { javaModuleModel ->
val moduleNames = javaModuleModel.data.javaModuleDependencies.map { it.moduleName }.toHashSet()
return findModulesByNames(moduleNames, gradleIdeaProject, ideProject)
@@ -43,6 +43,7 @@ class AndroidGradleModelFacade : KotlinGradleModelFacade {
val projects = androidModel.data.mainArtifact.dependencies.projects
val projectIds = libraries.mapNotNull { it.projectSafe } + projects
return projectIds.mapNotNullTo(LinkedHashSet()) { projectId ->
@Suppress("UNCHECKED_CAST")
ExternalSystemApiUtil.findFirstRecursively(ideProject) {
(it.data as? ModuleData)?.id == projectId
} as DataNode<ModuleData>?
@@ -46,7 +46,7 @@ object PackageDirectiveCompletion {
val prefixLength = parameters.offset - expression.textOffset
val prefix = expression.text!!
val prefixMatcher = PlainPrefixMatcher(prefix.substring(0, prefixLength))
val result = result.withPrefixMatcher(prefixMatcher)
val resultSet = result.withPrefixMatcher(prefixMatcher)
val resolutionFacade = expression.getResolutionFacade()
@@ -57,7 +57,7 @@ object PackageDirectiveCompletion {
for (variant in variants) {
val lookupElement = lookupElementFactory.createLookupElement(variant)
if (!lookupElement.lookupString.contains(DUMMY_IDENTIFIER)) {
result.addElement(lookupElement)
resultSet.addElement(lookupElement)
}
}
@@ -123,8 +123,8 @@ class VariableOrParameterNameWithTypeCompletion(
val parameterType = descriptor.type
if (parameterType.isVisible(visibilityFilter)) {
val lookupElement = MyLookupElement.create(name, ArbitraryType(parameterType), withType, lookupElementFactory)!!
val (count, name) = lookupElementToCount[lookupElement] ?: Pair(0, name)
lookupElementToCount[lookupElement] = Pair(count + 1, name)
val (count, s) = lookupElementToCount[lookupElement] ?: Pair(0, name)
lookupElementToCount[lookupElement] = Pair(count + 1, s)
}
}
}
@@ -84,22 +84,28 @@ object LambdaItems {
}
private fun createLookupElement(
functionType: KotlinType,
functionExpectedInfos: List<ExpectedInfo>,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
functionType: KotlinType,
functionExpectedInfos: List<ExpectedInfo>,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
): LookupElement {
val lookupString = LambdaSignatureTemplates.lambdaPresentation(functionType, signaturePresentation)
return LookupElementBuilder.create(lookupString)
.withInsertHandler({ context, lookupElement ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
val placeholderRange = TextRange(offset, offset + placeholder.length)
LambdaSignatureTemplates.insertTemplate(context, placeholderRange, functionType, explicitParameterTypes, signatureOnly = false)
})
.suppressAutoInsertion()
.assignSmartCompletionPriority(SmartCompletionItemPriority.LAMBDA)
.addTailAndNameSimilarity(functionExpectedInfos.filter { it.fuzzyType?.type == functionType })
.withInsertHandler { context, _ ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
val placeholderRange = TextRange(offset, offset + placeholder.length)
LambdaSignatureTemplates.insertTemplate(
context,
placeholderRange,
functionType,
explicitParameterTypes,
signatureOnly = false
)
}
.suppressAutoInsertion()
.assignSmartCompletionPriority(SmartCompletionItemPriority.LAMBDA)
.addTailAndNameSimilarity(functionExpectedInfos.filter { it.fuzzyType?.type == functionType })
}
}
@@ -64,9 +64,9 @@ object LambdaSignatureItems {
}
private fun createLookupElement(
functionType: KotlinType,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
functionType: KotlinType,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
): LookupElement {
val lookupString = LambdaSignatureTemplates.signaturePresentation(functionType, signaturePresentation)
val priority = if (explicitParameterTypes)
@@ -74,13 +74,19 @@ object LambdaSignatureItems {
else
SmartCompletionItemPriority.LAMBDA_SIGNATURE
return LookupElementBuilder.create(lookupString)
.withInsertHandler({ context, lookupElement ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
LambdaSignatureTemplates.insertTemplate(context, TextRange(offset, offset + placeholder.length), functionType, explicitParameterTypes, signatureOnly = true)
})
.suppressAutoInsertion()
.assignSmartCompletionPriority(priority)
.withInsertHandler { context, _ ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
LambdaSignatureTemplates.insertTemplate(
context,
TextRange(offset, offset + placeholder.length),
functionType,
explicitParameterTypes,
signatureOnly = true
)
}
.suppressAutoInsertion()
.assignSmartCompletionPriority(priority)
}
}

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