@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . lastOrNull ( ) : E ?

= <EOL> consume { <EOL> val iterator = iterator ( ) <EOL> if ( ! iterator . hasNext ( ) ) <EOL> return null <EOL> var last = iterator . next ( ) <EOL> while ( iterator . hasNext ( ) ) <EOL> last = iterator . next ( ) <EOL> return last <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . single ( ) : E

= <EOL> consume { <EOL> val iterator = iterator ( ) <EOL> if ( ! iterator . hasNext ( ) ) <EOL> throw NoSuchElementException ( "<STR_LIT>" ) <EOL> val single = iterator . next ( ) <EOL> if ( iterator . hasNext ( ) ) <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> return single <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . singleOrNull ( ) : E ?

= <EOL> consume { <EOL> val iterator = iterator ( ) <EOL> if ( ! iterator . hasNext ( ) ) <EOL> return null <EOL> val single = iterator . next ( ) <EOL> if ( iterator . hasNext ( ) ) <EOL> return null <EOL> return single <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E > ReceiveChannel < E > . drop ( n : Int , context : CoroutineContext = Dispatchers . Unconfined ) : ReceiveChannel < E >

= <EOL> GlobalScope . produce ( context , onCompletion = consumes ( ) ) { <EOL> require ( n >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> var remaining : Int = n <EOL> if ( remaining > <NUM_LIT:0> ) <EOL> for ( e in this @ drop ) { <EOL> remaining -- <EOL> if ( remaining == <NUM_LIT:0> ) <EOL> break <EOL> } <EOL> for ( e in this @ drop ) { <EOL> send ( e ) <EOL> } <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E > ReceiveChannel < E > . dropWhile ( context : CoroutineContext = Dispatchers . Unconfined , predicate : suspend ( E ) -> Boolean ) : ReceiveChannel < E >

= <EOL> GlobalScope . produce ( context , onCompletion = consumes ( ) ) { <EOL> for ( e in this @ dropWhile ) { <EOL> if ( ! predicate ( e ) ) { <EOL> send ( e ) <EOL> break <EOL> } <EOL> } <EOL> for ( e in this @ dropWhile ) { <EOL> send ( e ) <EOL> } <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E > ReceiveChannel < E > . filterIndexed ( context : CoroutineContext = Dispatchers . Unconfined , predicate : suspend ( index : Int , E ) -> Boolean ) : ReceiveChannel < E >

= <EOL> GlobalScope . produce ( context , onCompletion = consumes ( ) ) { <EOL> var index = <NUM_LIT:0> <EOL> for ( e in this @ filterIndexed ) { <EOL> if ( predicate ( index ++ , e ) ) send ( e ) <EOL> } <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E > ReceiveChannel < E > . filterNot ( context : CoroutineContext = Dispatchers . Unconfined , predicate : suspend ( E ) -> Boolean ) : ReceiveChannel < E >

= <EOL> filter ( context ) { ! predicate ( it ) }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E : Any , C : MutableCollection < in E > > ReceiveChannel < E ? > . filterNotNullTo ( destination : C ) : C

{ <EOL> consumeEach { <EOL> if ( it != null ) destination . add ( it ) <EOL> } <EOL> return destination <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E : Any , C : SendChannel < E > > ReceiveChannel < E ? > . filterNotNullTo ( destination : C ) : C

{ <EOL> consumeEach { <EOL> if ( it != null ) destination . send ( it ) <EOL> } <EOL> return destination <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E > ReceiveChannel < E > . take ( n : Int , context : CoroutineContext = Dispatchers . Unconfined ) : ReceiveChannel < E >

= <EOL> GlobalScope . produce ( context , onCompletion = consumes ( ) ) { <EOL> if ( n == <NUM_LIT:0> ) return@produce <EOL> require ( n >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> var remaining : Int = n <EOL> for ( e in this @ take ) { <EOL> send ( e ) <EOL> remaining -- <EOL> if ( remaining == <NUM_LIT:0> ) <EOL> return@produce <EOL> } <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E > ReceiveChannel < E > . takeWhile ( context : CoroutineContext = Dispatchers . Unconfined , predicate : suspend ( E ) -> Boolean ) : ReceiveChannel < E >

= <EOL> GlobalScope . produce ( context , onCompletion = consumes ( ) ) { <EOL> for ( e in this @ takeWhile ) { <EOL> if ( ! predicate ( e ) ) return@produce <EOL> send ( e ) <EOL> } <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < K , V > ReceiveChannel < Pair < K , V > > . toMap ( ) : Map < K , V >

= <EOL> toMap ( LinkedHashMap ( ) )


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . toMutableList ( ) : MutableList < E >

= <EOL> toCollection ( ArrayList ( ) )


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . toSet ( ) : Set < E >

= <EOL> this . toMutableSet ( )


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E , R > ReceiveChannel < E > . flatMap ( context : CoroutineContext = Dispatchers . Unconfined , transform : suspend ( E ) -> ReceiveChannel < R > ) : ReceiveChannel < R >

= <EOL> GlobalScope . produce ( context , onCompletion = consumes ( ) ) { <EOL> for ( e in this @ flatMap ) { <EOL> transform ( e ) . toChannel ( this ) <EOL> } <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E , R : Any > ReceiveChannel < E > . mapIndexedNotNull ( context : CoroutineContext = Dispatchers . Unconfined , transform : suspend ( index : Int , E ) -> R ? <EOL> ) : ReceiveChannel < R >

= <EOL> mapIndexed ( context , transform ) . filterNotNull ( )


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E , R : Any > ReceiveChannel < E > . mapNotNull ( context : CoroutineContext = Dispatchers . Unconfined , transform : suspend ( E ) -> R ? <EOL> ) : ReceiveChannel < R >

= <EOL> map ( context , transform ) . filterNotNull ( )


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E > ReceiveChannel < E > . withIndex ( context : CoroutineContext = Dispatchers . Unconfined ) : ReceiveChannel < IndexedValue < E > >

= <EOL> GlobalScope . produce ( context , onCompletion = consumes ( ) ) { <EOL> var index = <NUM_LIT:0> <EOL> for ( e in this @ withIndex ) { <EOL> send ( IndexedValue ( index ++ , e ) ) <EOL> } <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E > ReceiveChannel < E > . distinct ( ) : ReceiveChannel < E >

= <EOL> this . distinctBy { it }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . any ( ) : Boolean

= <EOL> consume { <EOL> return iterator ( ) . hasNext ( ) <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . count ( ) : Int

{ <EOL> var count = <NUM_LIT:0> <EOL> consumeEach { count ++ } <EOL> return count <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . maxWith ( comparator : Comparator < in E > ) : E ?

= <EOL> consume { <EOL> val iterator = iterator ( ) <EOL> if ( ! iterator . hasNext ( ) ) return null <EOL> var max = iterator . next ( ) <EOL> while ( iterator . hasNext ( ) ) { <EOL> val e = iterator . next ( ) <EOL> if ( comparator . compare ( max , e ) < <NUM_LIT:0> ) max = e <EOL> } <EOL> return max <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . minWith ( comparator : Comparator < in E > ) : E ?

= <EOL> consume { <EOL> val iterator = iterator ( ) <EOL> if ( ! iterator . hasNext ( ) ) return null <EOL> var min = iterator . next ( ) <EOL> while ( iterator . hasNext ( ) ) { <EOL> val e = iterator . next ( ) <EOL> if ( comparator . compare ( min , e ) > <NUM_LIT:0> ) min = e <EOL> } <EOL> return min <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public suspend fun < E > ReceiveChannel < E > . none ( ) : Boolean

= <EOL> consume { <EOL> return ! iterator ( ) . hasNext ( ) <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < E : Any > ReceiveChannel < E ? > . requireNoNulls ( ) : ReceiveChannel < E >

= <EOL> map { it ? : throw IllegalArgumentException ( "<STR_LIT>" ) }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public infix fun < E , R > ReceiveChannel < E > . zip ( other : ReceiveChannel < R > ) : ReceiveChannel < Pair < E , R > >

= <EOL> zip ( other ) { t1 , t2 -> t1 to t2 }


{ <EOL> _builder . clearGroup ( ) <EOL> }


{ <EOL> return _builder . hasGroup ( ) <EOL> }

/**
 * optional string group = 1;
 * @return Whether the group field is set.
 */


{ <EOL> _builder . clearModule ( ) <EOL> }


{ <EOL> return _builder . hasModule ( ) <EOL> }

/**
 * optional string module = 2;
 * @return Whether the module field is set.
 */


{ <EOL> _builder . clearVersion ( ) <EOL> }


{ <EOL> return _builder . hasVersion ( ) <EOL> }

/**
 * optional string version = 3;
 * @return Whether the version field is set.
 */


{ <EOL> _builder . clearSourceSetName ( ) <EOL> }

/**
 * optional string source_set_name = 4;
 */


fun hasSourceSetName ( ) : kotlin . Boolean

{ <EOL> return _builder . hasSourceSetName ( ) <EOL> }

/**
 * optional string source_set_name = 4;
 * @return Whether the sourceSetName field is set.
 */


@ kotlin . jvm . JvmSynthetic <EOL> @ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> fun com . google . protobuf . kotlin . DslList < org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto , CapabilitiesProxy > . add ( value : org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto )

{ <EOL> _builder . addCapabilities ( value ) <EOL> }

/**
 * repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;
 * @param value The capabilities to add.
 */


@ kotlin . jvm . JvmSynthetic <EOL> @ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> @ Suppress ( "<STR_LIT:NOTHING_TO_INLINE>" ) <EOL> inline operator fun com . google . protobuf . kotlin . DslList < org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto , CapabilitiesProxy > . plusAssign ( value : org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto )

{ <EOL> add ( value ) <EOL> }


@ kotlin . jvm . JvmSynthetic <EOL> @ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> fun com . google . protobuf . kotlin . DslList < org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto , CapabilitiesProxy > . addAll ( values : kotlin . collections . Iterable < org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto > )

{ <EOL> _builder . addAllCapabilities ( values ) <EOL> }

/**
 * repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;
 * @param values The capabilities to add.
 */


@ kotlin . jvm . JvmSynthetic <EOL> @ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> @ Suppress ( "<STR_LIT:NOTHING_TO_INLINE>" ) <EOL> inline operator fun com . google . protobuf . kotlin . DslList < org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto , CapabilitiesProxy > . plusAssign ( values : kotlin . collections . Iterable < org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto > )

{ <EOL> addAll ( values ) <EOL> }


@ kotlin . jvm . JvmSynthetic <EOL> @ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> operator fun com . google . protobuf . kotlin . DslList < org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto , CapabilitiesProxy > . set ( index : kotlin . Int , value : org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto )

{ <EOL> _builder . setCapabilities ( index , value ) <EOL> }

/**
 * repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;
 * @param index The index to set the value at.
 * @param value The capabilities to set.
 */


@ kotlin . jvm . JvmSynthetic <EOL> @ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> fun com . google . protobuf . kotlin . DslList < org . jetbrains . kotlin . gradle . idea . proto . generated . tcs . IdeaKotlinBinaryCapabilityProto , CapabilitiesProxy > . clear ( )

{ <EOL> _builder . clearCapabilities ( ) <EOL> }

/**
 * repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;
 */


{ <EOL> _builder . clearAttributes ( ) <EOL> }

/**
 * optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryAttributesProto attributes = 6;
 */


fun hasAttributes ( ) : kotlin . Boolean

{ <EOL> return _builder . hasAttributes ( ) <EOL> }

/**
 * optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryAttributesProto attributes = 6;
 * @return Whether the attributes field is set.
 */


@ JsName ( "<STR_LIT>" ) <EOL> protected open fun toArray ( ) : Array < Any ? >

= collectionToArray ( this )

/**
 * Returns new array of type `Array<Any?>` with the elements of this collection.
 */


protected open fun < T > toArray ( array : Array < T > ) : Array < T >

= collectionToArray ( this , array )

/**
 * Fills the provided [array] or creates new array of the same type
 * and fills it with the elements of this collection.
 *
 * If this collection doesn't fit in the provided [array],
 * a new array is created with the same array type and the size of this collection,
 * and filled with this collection elements.
 * Otherwise, the specified [array] is filled starting from index 0.
 * The value of the elements following the collection elements is unspecified.
 *
 * @return An array containing all elements of this collection.
 */


fun resolveExtrasSerialized ( owner : Any ) : ByteArray ?

/**
 * @param owner: Should implement [HasMutableExtras]. Passing [Any] is fine to make it easier to cross
 * ClassLoader boundaries. Passing some non [HasMutableExtras] will just return null
 */


fun < T : Any > serialize ( key : Extras . Key < T > , value : T ) : ByteArray ?

/**
 * Will try to serialise the [value] for IDE import.
 * Returns `null` if there is no [IdeaKotlinExtrasSerializationExtension] provided that can handle the particular [key],
 * or if the registered serializer fails with an exception.
 * See [registerExtrasSerializationExtension] for 'how to register a serializer for extra values'
 */


@ ExternalKotlinTargetApi <EOL> fun registerDependencyResolver ( resolver : IdeDependencyResolver , constraint : SourceSetConstraint , phase : DependencyResolutionPhase , priority : Priority = Priority . normal , )

/**
 * Registers a given [resolver] to run during Gradle import:
 * The given resolver will only run if the [constraint] matches a given SourceSet and if not overwritten by another
 * resolver registered in the same [phase] and higher [Priority]
 */


@ ExternalKotlinTargetApi <EOL> fun registerAdditionalArtifactResolver ( resolver : IdeAdditionalArtifactResolver , constraint : SourceSetConstraint , phase : AdditionalArtifactResolutionPhase , priority : Priority = Priority . normal , )


@ ExternalKotlinTargetApi <EOL> fun registerDependencyTransformer ( transformer : IdeDependencyTransformer , constraint : SourceSetConstraint , phase : DependencyTransformationPhase , )

/**
 * Registers a given [transformer] to run during Gradle import:
 * The resolver will only run if the [constraint] matches the SourceSet
 */


@ ExternalKotlinTargetApi <EOL> fun registerDependencyEffect ( effect : IdeDependencyEffect , constraint : SourceSetConstraint , )

/**
 * Registers a given [effect] to run during Gradle import:
 * The effect will only run for SourceSets matching the given [constraint]
 */


@ ExternalKotlinTargetApi <EOL> fun registerExtrasSerializationExtension ( extension : IdeaKotlinExtrasSerializationExtension , )

/**
 * Registers a [IdeaKotlinExtrasSerializationExtension] for transporting generic/external data into the
 * IDE process using the [Extras]. Entities that implement [HasMutableExtras] which are imported to the IDE
 * (like KotlinTarget, KotlinCompilation and KotlinSourceSet) will automatically retain their attached extras using
 * the serializers registered as [extension].
 *
 * Note 1: In order to access the extras in the IDE during (or after) Gradle import, a similar
 * extension needs to be registered in the IDE plugin to deserialize the payload.
 * Note 2: Extras that do not have a serializer attached will not be transported into the IDE process
 * Note 3: This transport mechanism will only act as transport mechanics of data. Keeping serializers and deserializers compatible
 * shall be handled by the implementers of the [extension]
 */


@ ExternalKotlinTargetApi <EOL> fun registerImportAction ( action : IdeMultiplatformImportAction )

/**
 * Registers a [IdeMultiplatformImportAction] which will be invoked only if an IDE/Gradle sync (import) is running.
 * This action is guaranteed to run before the Kotlin Multiplatform Model is being built.
 * There is no 'guarantee' whether this action will be running during configuration phase or as a first step
 * of model building. This is considered an implementation detail.
 * For further details please read [IdeMultiplatformImportAction]
 */


@ Suppress ( "<STR_LIT:unused>" ) <EOL> @ ExternalKotlinTargetApi <EOL> fun IdeMultiplatformImport . registerExtrasSerializationExtension ( builder : IdeaKotlinExtrasSerializationExtensionBuilder . ( ) -> Unit , )

{ <EOL> registerExtrasSerializationExtension ( IdeaKotlinExtrasSerializationExtension ( builder ) ) <EOL> }

/**
 * Convenience shortcut method for
 * `registerExtrasSerializationExtension(IdeaKotlinExtrasSerializationExtension(builder))`
 * see [IdeMultiplatformImport.registerExtrasSerializationExtension]
 */


@ ExternalKotlinTargetApi <EOL> infix fun SourceSetConstraint . or ( other : SourceSetConstraint , )

= SourceSetConstraint { sourceSet -> <EOL> this@or ( sourceSet ) || other ( sourceSet ) <EOL> }

/**
 * Combines two given [SourceSetConstraint] using a logical 'or':
 * The resulting constraint will match any SourceSet that matches at least one of the specified constraints
 */


@ ExternalKotlinTargetApi <EOL> infix fun SourceSetConstraint . and ( other : SourceSetConstraint , )

= SourceSetConstraint { sourceSet -> <EOL> this@and ( sourceSet ) && other ( sourceSet ) <EOL> }

/**
 * Combines two given [SourceSetConstraint] using a logical 'and':
 * The resulting constraint will match only SourceSets that matches both of the specified constraints
 */


@ ExternalKotlinTargetApi <EOL> operator fun SourceSetConstraint . not ( )

= SourceSetConstraint { sourceSet -> <EOL> this@not ( sourceSet ) . not ( ) <EOL> }

/**
 * Negates a given [SourceSetConstraint]:
 * The resulting constraint will match only SourceSets that would *not* have been matched by the source constraint
 */


{ <EOL> val testProject = kotlinJvmTestProject { <EOL> dokkaConfiguration { <EOL> moduleName = "<STR_LIT>" <EOL> kotlinSourceSet { <EOL> } <EOL> } <EOL> ktFile ( pathFromSrc = "<STR_LIT>" ) { <EOL> + "<STR_LIT>" <EOL> } <EOL> } <EOL> val module = testProject . parse ( ) <EOL> assertEquals ( "<STR_LIT>" , module . name ) <EOL> assertEquals ( <NUM_LIT:1> , module . packages . size ) <EOL> val pckg = module . packages [ <NUM_LIT:0> ] <EOL> assertEquals ( "<STR_LIT>" , pckg . name ) <EOL> assertEquals ( <NUM_LIT:1> , pckg . classlikes . size ) <EOL> val fooClass = pckg . classlikes [ <NUM_LIT:0> ] <EOL> assertEquals ( "<STR_LIT:Foo>" , fooClass . name ) <EOL> }

/**
 * Used as a sample for [kotlinJvmTestProject]
 */


fun < T > JavaSparkContext . rddOf ( vararg elements : T , numSlices : Int = defaultParallelism ( ) , ) : JavaRDD < T >

= parallelize ( elements . toList ( ) , numSlices )

/**
 * Utility method to create an RDD from a list.
 * NOTE: [T] must be [Serializable].
 */


fun < T > JavaSparkContext . toRDD ( elements : List < T > , numSlices : Int = defaultParallelism ( ) , ) : JavaRDD < T >

= parallelize ( elements , numSlices )


fun < T : Comparable < T > > JavaRDD < T > . min ( ) : T

= min ( object : Comparator < T > , Serializable { <EOL> override fun compare ( o1 : T , o2 : T ) : Int = o1 . compareTo ( o2 ) <EOL> } )

/**
 * Returns the minimum element from this RDD as defined by the specified
 * [Comparator].
 *
 * @return the minimum of the RDD
 */


fun < T : Comparable < T > > JavaRDD < T > . max ( ) : T

= max ( object : Comparator < T > , Serializable { <EOL> override fun compare ( o1 : T , o2 : T ) : Int = o1 . compareTo ( o2 ) <EOL> } )

/**
 * Returns the maximum element from this RDD as defined by the specified
 * [Comparator].
 *
 * @return the maximum of the RDD
 */


@ Test <EOL> fun testClosingNotDroppingTasks ( )

{ <EOL> repeat ( <NUM_LIT:7> ) { <EOL> shared . value = <NUM_LIT:0> <EOL> val nThreads = it + <NUM_LIT:1> <EOL> val dispatcher = newFixedThreadPoolContext ( nThreads , "<STR_LIT>" ) <EOL> repeat ( <NUM_LIT> ) { <EOL> dispatcher . dispatch ( EmptyCoroutineContext , Runnable { <EOL> shared . incrementAndGet ( ) <EOL> } ) <EOL> } <EOL> dispatcher . close ( ) <EOL> while ( shared . value < <NUM_LIT> ) { <EOL> } <EOL> } <EOL> }

/**
 * Tests that [newFixedThreadPoolContext] will not drop tasks when closed.
 */


override fun iterator ( ) : Iterator < File >

= FileTreeWalkIterator ( )

/** Returns an iterator walking through files. */


public abstract fun step ( ) : File ?

/** Call of this function proceeds to a next file for visiting and returns it */


{ <EOL> if ( ! failed && fileList == null ) { <EOL> if ( onEnter ? . invoke ( root ) == false ) { <EOL> return null <EOL> } <EOL> fileList = root . listFiles ( ) <EOL> if ( fileList == null ) { <EOL> onFail ? . invoke ( root , AccessDeniedException ( file = root , reason = "<STR_LIT>" ) ) <EOL> failed = true <EOL> } <EOL> } <EOL> if ( fileList != null && fileIndex < fileList ! ! . size ) { <EOL> return fileList ! ! [ fileIndex ++ ] <EOL> } else if ( ! rootVisited ) { <EOL> rootVisited = true <EOL> return root <EOL> } else { <EOL> onLeave ? . invoke ( root ) <EOL> return null <EOL> } <EOL> }

/** First all children, then root directory */


{ <EOL> if ( ! rootVisited ) { <EOL> if ( onEnter ? . invoke ( root ) == false ) { <EOL> return null <EOL> } <EOL> rootVisited = true <EOL> return root <EOL> } else if ( fileList == null || fileIndex < fileList ! ! . size ) { <EOL> if ( fileList == null ) { <EOL> fileList = root . listFiles ( ) <EOL> if ( fileList == null ) { <EOL> onFail ? . invoke ( root , AccessDeniedException ( file = root , reason = "<STR_LIT>" ) ) <EOL> } <EOL> if ( fileList == null || fileList ! ! . size == <NUM_LIT:0> ) { <EOL> onLeave ? . invoke ( root ) <EOL> return null <EOL> } <EOL> } <EOL> return fileList ! ! [ fileIndex ++ ] <EOL> } else { <EOL> onLeave ? . invoke ( root ) <EOL> return null <EOL> } <EOL> }


{ <EOL> if ( visited ) return null <EOL> visited = true <EOL> return root <EOL> }


public fun onEnter ( function : ( File ) -> Boolean ) : FileTreeWalk

{ <EOL> return FileTreeWalk ( start , direction , onEnter = function , onLeave = onLeave , onFail = onFail , maxDepth = maxDepth ) <EOL> }

/**
 * Sets a predicate [function], that is called on any entered directory before its files are visited
 * and before it is visited itself.
 *
 * If the [function] returns `false` the directory is not entered and neither it nor its files are visited.
 */


public fun onLeave ( function : ( File ) -> Unit ) : FileTreeWalk

{ <EOL> return FileTreeWalk ( start , direction , onEnter = onEnter , onLeave = function , onFail = onFail , maxDepth = maxDepth ) <EOL> }

/**
 * Sets a callback [function], that is called on any left directory after its files are visited and after it is visited itself.
 */


public fun onFail ( function : ( File , IOException ) -> Unit ) : FileTreeWalk

{ <EOL> return FileTreeWalk ( start , direction , onEnter = onEnter , onLeave = onLeave , onFail = function , maxDepth = maxDepth ) <EOL> }

/**
 * Set a callback [function], that is called on a directory when it's impossible to get its file list.
 *
 * [onEnter] and [onLeave] callback functions are called even in this case.
 */


public fun maxDepth ( depth : Int ) : FileTreeWalk

{ <EOL> if ( depth <= <NUM_LIT:0> ) <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> return FileTreeWalk ( start , direction , onEnter , onLeave , onFail , depth ) <EOL> }

/**
 * Sets the maximum [depth] of a directory tree to traverse. By default there is no limit.
 *
 * The value must be positive and [Int.MAX_VALUE] is used to specify an unlimited depth.
 *
 * With a value of 1, walker visits only the origin directory and all its immediate children,
 * with a value of 2 also grandchildren, etc.
 */


public fun File . walk ( direction : FileWalkDirection = FileWalkDirection . TOP_DOWN ) : FileTreeWalk

= <EOL> FileTreeWalk ( this , direction )

/**
 * Gets a sequence for visiting this directory and all its content.
 *
 * @param direction walk direction, top-down (by default) or bottom-up.
 */


public fun File . walkTopDown ( ) : FileTreeWalk

= walk ( FileWalkDirection . TOP_DOWN )

/**
 * Gets a sequence for visiting this directory and all its content in top-down order.
 * Depth-first search is used and directories are visited before all their files.
 */


public fun File . walkBottomUp ( ) : FileTreeWalk

= walk ( FileWalkDirection . BOTTOM_UP )

/**
 * Gets a sequence for visiting this directory and all its content in bottom-up order.
 * Depth-first search is used and directories are visited after all their files.
 */


private fun DProperty . isAlsoParameter ( sourceSet : DokkaSourceSet ) : Boolean

{ <EOL> return this . extra [ IsAlsoParameter ] <EOL> ? . inSourceSets <EOL> ? . any { it . sourceSetID == sourceSet . sourceSetID } <EOL> ? : false <EOL> }

/**
 * An example would be a primary constructor `class A(val s: String)`,
 * where `s` is both a function parameter and a property
 */


internal fun prepareTargets ( graph : KGraph , weights : List < Variable < Float > > , tf : Ops , loss : Operand < Float > ) : List < Operand < Float > >

{ <EOL> slots = mutableMapOf ( ) <EOL> val gradients : Gradients = computeGradients ( tf , loss , weights ) <EOL> val variableOutputs = variablesToOutputs ( weights ) <EOL> createSlots ( graph , tf , variableOutputs ) <EOL> return applyGradients ( graph , tf , weights , gradients ) <EOL> }

/**
 * Prepares targets for optimization process.
 *
 * NOTE: Developer API.
 *
 * @param [graph] KGraph to be updated.
 * @param [tf] TensorFlow graph API for building operations.
 * @param [loss] Loss function.
 * @return List of optimizer operands to update variables.
 */


protected abstract fun applyGradients ( graph : KGraph , tf : Ops , weights : List < Variable < Float > > , gradients : Gradients ) : List < Operand < Float > >

/**
 * Applies gradients to weights.
 *
 * NOTE: Developer API. Override this method in each optimizer.
 *
 * @param [graph] KGraph to be updated.
 * @param [tf] TensorFlow graph API for building operations.
 * @param [weights] Variables to update in optimizer.
 * @param [gradients] See [Gradients] for more information.
 */


protected open fun createSlots ( graph : KGraph , tf : Ops , variables : List < Output < Float > > )

{ <EOL> }

/**
 * No-op slot creation method.
 *
 * @param variables The variables to create slots for.
 */


protected open fun createSlot ( graph : KGraph , tf : Ops , variable : Output < Float > , slotName : String , initializer : Operand < Float > )

{ <EOL> val createName : String = createName ( variable , slotName ) <EOL> val slot : Variable < Float > = tf . withName ( createName ) . variable ( variable . shape ( ) , getDType ( ) ) <EOL> val assignName = defaultAssignOpName ( createName ( variable , slotName ) ) <EOL> val slotInit : Assign < Float > = tf . withName ( assignName ) . assign ( slot , initializer ) <EOL> graph . addOptimizerVariableInitializer ( slotInit ) <EOL> graph . addOptimizerVariable ( slot ) <EOL> val varName = variable . op ( ) . name ( ) <EOL> val variables : MutableMap < String , Variable < Float > > = slots . computeIfAbsent ( slotName ) { mutableMapOf ( ) } <EOL> variables [ varName ] = slot <EOL> }

/**
 * Creates a slot in the graph for the specified variable with the specified name. Adds the slot's
 * initializer to the graph's initializers, and the slot to the optimiser's slot map.
 *
 * @param [graph] KGraph to be updated.
 * @param [tf] TensorFlow graph API for building operations.
 * @param [variable] The variable to create the slot for.
 * @param [slotName] The name of the slot.
 * @param [initializer] The initializer for the slot.
 */


protected fun getSlot ( varName : String , slotName : String ) : Variable < Float >

{ <EOL> val variables : MutableMap < String , Variable < Float > > = slots [ slotName ] ! ! <EOL> return variables [ varName ] ! ! <EOL> }

/**
 * Gets the slot associated with the specified variable and slot name.
 *
 * @param [varName] The variable to lookup.
 * @param [slotName] The slot name.
 * @return The slot.
 */


internal open fun createName ( variable : Output < Float > , slotName : String ) : String

{ <EOL> return defaultOptimizerVariableName ( variable . op ( ) . name ( ) + "<STR_LIT:->" + slotName ) <EOL> }

/**
 * Creates name for [variable] used in slot with name [slotName].
 */


open fun < T > runInCoroutineContext ( block : suspend ( ) -> T ) : T

= <EOL> @ Suppress ( "<STR_LIT:DEPRECATION_ERROR>" ) <EOL> internalScriptingRunSuspend { block ( ) }

/**
 * The overridable wrapper for executing evaluation in a desired coroutines context
 */


open fun eval ( script : SourceCode , compilationConfiguration : ScriptCompilationConfiguration , evaluationConfiguration : ScriptEvaluationConfiguration ? <EOL> ) : ResultWithDiagnostics < EvaluationResult >

= <EOL> runInCoroutineContext { <EOL> compiler ( script , compilationConfiguration ) . onSuccess { <EOL> evaluator ( it , evaluationConfiguration ? : ScriptEvaluationConfiguration . Default ) <EOL> } <EOL> }

/**
 * The default implementation of the evaluation function
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public expect fun Trace ( size : Int = <NUM_LIT> , format : TraceFormat = traceFormatDefault ) : TraceBase

/**
 * Creates `Trace` object for tracing atomic operations.
 *
 * To use a trace create a separate field for `Trace`:
 *
 * ```
 * val trace = Trace(size)
 * ```
 *
 * Using it to add trace messages:
 *
 * ```
 * trace { "Doing something" }
 * ```
 * or you can do multi-append in a garbage-free manner
 * ```
 * // Before queue.send(element) invocation
 * trace.append("Adding element to the queue", element, Thread.currentThread())
 * ```
 *
 * Pass it to `atomic` constructor to automatically trace all modifications of the corresponding field:
 *
 * ```
 * val state = atomic(initialValue, trace)
 * ```
 * An optional [named][TraceBase.named] call can be used to name all the messages related to this specific instance:
 *
 * ```
 * val state = atomic(initialValue, trace.named("state"))
 * ```
 *
 * An optional [format] parameter can be specified to add context-specific information to each trace.
 * The default format is [traceFormatDefault].
 */


public expect fun TraceBase . named ( name : String ) : TraceBase

/**
 * Adds a name to the trace. For example:
 *
 * ```
 * val state = atomic(initialValue, trace.named("state"))
 * ```
 */


@ OptionalJsName ( TRACE_APPEND_1 ) <EOL> public open fun append ( event : Any )

/**
 * Accepts the logging [event] and appends it to the trace.
 */


@ OptionalJsName ( TRACE_APPEND_2 ) <EOL> public open fun append ( event1 : Any , event2 : Any )

/**
 * Accepts the logging events [event1], [event2] and appends them to the trace.
 */


@ OptionalJsName ( TRACE_APPEND_3 ) <EOL> public open fun append ( event1 : Any , event2 : Any , event3 : Any )

/**
 * Accepts the logging events [event1], [event2], [event3] and appends them to the trace.
 */


@ OptionalJsName ( TRACE_APPEND_4 ) <EOL> public open fun append ( event1 : Any , event2 : Any , event3 : Any , event4 : Any )

/**
 * Accepts the logging events [event1], [event2], [event3], [event4] and appends them to the trace.
 */


@ InlineOnly <EOL> public inline operator fun invoke ( event : ( ) -> Any )

{ <EOL> append ( event ( ) ) <EOL> }


public fun < T > xMin ( column : ColumnReference < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( X_MIN , column . name ( ) , null ) <EOL> }

/**
 * Maps the `xMin` aesthetic to a data column specified by a [ColumnReference].
 *
 * @param column the data column to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > xMin ( column : KProperty < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( X_MIN , column . name , null ) <EOL> }

/**
 * Maps the `xMin` aesthetic to a data column specified by a [KProperty].
 *
 * @param column the data column to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun xMin ( column : String ) : PositionalMapping < Any ? >

{ <EOL> return addPositionalMapping ( X_MIN , column , null ) <EOL> }

/**
 * Maps the `xMin` aesthetic to a data column specified by a [String].
 *
 * @param column the data column to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > xMin ( values : Iterable < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( X_MIN , values . toList ( ) , null , null ) <EOL> }

/**
 * Maps the `xMin` aesthetic to iterable of values.
 *
 * @param values the iterable of values to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > xMin ( values : DataColumn < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( X_MIN , values , null ) <EOL> }

/**
 * Maps the `xMin` aesthetic to a data column.
 *
 * @param values the data column to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T : Any > rxObservable ( context : CoroutineContext = EmptyCoroutineContext , @ BuilderInference block : suspend ProducerScope < T > . ( ) -> Unit ) : Observable < T >

{ <EOL> require ( context [ Job ] === null ) { "<STR_LIT>" + <EOL> "<STR_LIT>" } <EOL> return rxObservableInternal ( GlobalScope , context , block ) <EOL> }

/**
 * Creates cold [observable][Observable] that will run a given [block] in a coroutine.
 * Every time the returned observable is subscribed, it starts a new coroutine.
 *
 * Coroutine emits ([ObservableEmitter.onNext]) values with `send`, completes ([ObservableEmitter.onComplete])
 * when the coroutine completes or channel is explicitly closed and emits error ([ObservableEmitter.onError])
 * if coroutine throws an exception or closes channel with a cause.
 * Unsubscribing cancels running coroutine.
 *
 * Invocations of `send` are suspended appropriately to ensure that `onNext` is not invoked concurrently.
 * Note that Rx 2.x [Observable] **does not support backpressure**.
 *
 * Coroutine context can be specified with [context] argument.
 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
 * Method throws [IllegalArgumentException] if provided [context] contains a [Job] instance.
 */


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN , replaceWith = ReplaceWith ( "<STR_LIT>" ) ) <EOL> public fun < T : Any > CoroutineScope . rxObservable ( context : CoroutineContext = EmptyCoroutineContext , @ BuilderInference block : suspend ProducerScope < T > . ( ) -> Unit ) : Observable < T >

= rxObservableInternal ( this , context , block )


public fun FloatArray . set3D ( rowIndex : Int , columnIndex : Int , channelIndex : Int , width : Int , channels : Int , value : Float )

{ <EOL> this [ width * rowIndex * channels + columnIndex * channels + channelIndex ] = value <EOL> }


public fun FloatArray . get3D ( rowIndex : Int , columnIndex : Int , channelIndex : Int , width : Int , channels : Int ) : Float

{ <EOL> return this [ width * rowIndex * channels + columnIndex * channels + channelIndex ] <EOL> }


public fun FloatArray . set2D ( rowIndex : Int , columnIndex : Int , width : Int , value : Float )

{ <EOL> this [ width * rowIndex + columnIndex ] = value <EOL> }


public fun FloatArray . get2D ( rowIndex : Int , columnIndex : Int , width : Int ) : Float

{ <EOL> return this [ width * rowIndex + columnIndex ] <EOL> }


public fun FloatArray . argmax ( ) : Int

= <EOL> maxOrNull ( ) ? . let { max -> indexOfFirst { it == max } } ? : - <NUM_LIT:1>

/**
 * Returns the index of the maximum element in the given FloatArray.
 * TODO: Should be replaced with Multik in future.
 */


fun get ( key : K , compute : ( K ) -> V ? ) : V ?

= cache . get ( key ) { compute ( it ) ? : NullValue } ? . nullValueToNull ( )

/**
 * Returns the value for the given [key] if it's contained in the cache, or computes the value with [compute] and adds it to the cache.
 */


internal fun prepare ( project : Project ) : KoverContext

{ <EOL> val koverBucketConfiguration = project . configurations . create ( KOVER_DEPENDENCY_NAME ) { <EOL> asBucket ( ) <EOL> } <EOL> val projectExtension = project . extensions . create < KoverProjectExtensionImpl > ( KOVER_PROJECT_EXTENSION_NAME , project . objects , project . layout , project . path ) <EOL> val toolProvider = CoverageToolFactory . get ( projectExtension ) <EOL> val agentClasspath = project . configurations . create ( JVM_AGENT_CONFIGURATION_NAME ) { <EOL> asTransitiveDependencies ( ) <EOL> } <EOL> project . dependencies . add ( JVM_AGENT_CONFIGURATION_NAME , toolProvider . map { tool -> tool . jvmAgentDependency } ) <EOL> project . configurations . register ( "<STR_LIT>" ) { <EOL> isVisible = false <EOL> asProducer ( ) <EOL> attributes { <EOL> attribute ( VariantNameAttr . ATTRIBUTE , project . objects . named ( "<STR_LIT>" ) ) <EOL> attribute ( ProjectPathAttr . ATTRIBUTE , project . objects . named ( project . path ) ) <EOL> } <EOL> } <EOL> val findAgentJarTask = project . tasks . register < KoverAgentJarTask > ( FIND_JAR_TASK ) <EOL> findAgentJarTask . configure { <EOL> dependsOn ( agentClasspath ) <EOL> this . tool . convention ( toolProvider ) <EOL> this . koverDisabled . convention ( projectExtension . koverDisabled ) <EOL> this . agentJar . set ( project . layout . buildDirectory . map { dir -> dir . file ( agentFilePath ( toolProvider . get ( ) . variant ) ) } ) <EOL> this . agentClasspath . from ( agentClasspath ) <EOL> } <EOL> val reporterClasspath = project . configurations . create ( JVM_REPORTER_CONFIGURATION_NAME ) { <EOL> asTransitiveDependencies ( ) <EOL> } <EOL> project . dependencies . add ( JVM_REPORTER_CONFIGURATION_NAME , toolProvider . map { tool -> tool . jvmReporterDependency } ) <EOL> project . dependencies . add ( JVM_REPORTER_CONFIGURATION_NAME , toolProvider . map { tool -> tool . jvmReporterExtraDependency } ) <EOL> val totalReports = VariantReportsSet ( project , TOTAL_VARIANT_NAME , ReportVariantType . TOTAL , toolProvider , projectExtension . reports . total , reporterClasspath , projectExtension . koverDisabled ) <EOL> return KoverContext ( project , projectExtension , toolProvider , findAgentJarTask , koverBucketConfiguration , agentClasspath , reporterClasspath , totalReports ) <EOL> }

/**
 * The first stage of applying the Kover plugin.
 * Objects are created that will be available in user build scripts during the evaluation step.
 */


public suspend fun delay ( duration : Duration ) : Unit

= delay ( duration . coerceToMillis ( ) )

/**
 * "java.time" adapter method for [kotlinx.coroutines.delay].
 */


@ FlowPreview <EOL> public fun < T > Flow < T > . debounce ( timeout : Duration ) : Flow < T >

= debounce ( timeout . coerceToMillis ( ) )

/**
 * "java.time" adapter method for [kotlinx.coroutines.flow.debounce].
 */


@ FlowPreview <EOL> public fun < T > Flow < T > . sample ( period : Duration ) : Flow < T >

= sample ( period . coerceToMillis ( ) )

/**
 * "java.time" adapter method for [kotlinx.coroutines.flow.sample].
 */


public fun < R > SelectBuilder < R > . onTimeout ( duration : Duration , block : suspend ( ) -> R ) : Unit

= <EOL> onTimeout ( duration . coerceToMillis ( ) , block )

/**
 * "java.time" adapter method for [SelectBuilder.onTimeout].
 */


public suspend fun < T > withTimeout ( duration : Duration , block : suspend CoroutineScope . ( ) -> T ) : T

{ <EOL> contract { <EOL> callsInPlace ( block , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> return kotlinx . coroutines . withTimeout ( duration . coerceToMillis ( ) , block ) <EOL> }

/**
 * "java.time" adapter method for [kotlinx.coroutines.withTimeout].
 */


public suspend fun < T > withTimeoutOrNull ( duration : Duration , block : suspend CoroutineScope . ( ) -> T ) : T ?

= <EOL> kotlinx . coroutines . withTimeoutOrNull ( duration . coerceToMillis ( ) , block )

/**
 * "java.time" adapter method for [kotlinx.coroutines.withTimeoutOrNull].
 */


private fun Duration . coerceToMillis ( ) : Long

{ <EOL> if ( this <= Duration . ZERO ) return <NUM_LIT:0> <EOL> if ( this <= ChronoUnit . MILLIS . duration ) return <NUM_LIT:1> <EOL> val maxSeconds = <NUM_LIT> <EOL> val maxNanos = <NUM_LIT> <EOL> return if ( seconds < maxSeconds || seconds == maxSeconds && nano < maxNanos ) toMillis ( ) <EOL> else Long . MAX_VALUE <EOL> }

/**
 * Coerces the given [Duration] to a millisecond delay.
 * Negative values are coerced to zero, values that cannot
 * be represented in milliseconds as long ("infinite" duration) are coerced to [Long.MAX_VALUE]
 * and durations lesser than a millisecond are coerced to 1 millisecond.
 *
 * The rationale of coercion:
 * 1) Too large durations typically indicate infinity and Long.MAX_VALUE is the
 * best approximation of infinity we can provide.
 * 2) Coercing too small durations to 1 instead of 0 is crucial for two patterns:
 * - Programming with deadlines and delays
 * - Non-suspending fast-paths (e.g. `withTimeout(1 nanosecond) { 42 }` should not throw)
 */


internal fun CallableDescriptor . unwrapFakeOverrideIfNeeded ( ) : CallableDescriptor

{ <EOL> val useSiteUnwrapped = unwrapUseSiteSubstitutionOverride ( ) <EOL> if ( useSiteUnwrapped !is CallableMemberDescriptor ) return useSiteUnwrapped <EOL> if ( useSiteUnwrapped . kind . isReal ) return useSiteUnwrapped <EOL> val overriddenDescriptor = useSiteUnwrapped . overriddenDescriptors . singleOrNull ( ) ? . unwrapUseSiteSubstitutionOverride ( ) <EOL> ? : return useSiteUnwrapped <EOL> if ( hasTypeReferenceAffectingSignature ( useSiteUnwrapped , overriddenDescriptor ) ) { <EOL> return useSiteUnwrapped <EOL> } <EOL> return overriddenDescriptor . unwrapFakeOverrideIfNeeded ( ) <EOL> }

/**
 * This logic should be equivalent to
 * [org.jetbrains.kotlin.analysis.api.fir.KtSymbolByFirBuilder.unwrapSubstitutionOverrideIfNeeded]. But this method unwrap all fake
 * overrides that do not change the signature.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> private fun < T : CallableDescriptor > T . unwrapUseSiteSubstitutionOverride ( ) : T

{ <EOL> var current : CallableDescriptor = this <EOL> while ( original != current ) { <EOL> current = current . original <EOL> } <EOL> return current as T <EOL> }

/**
 * Use-site substitution override are tracked through [CallableDescriptor.getOriginal]. Note that overridden symbols are accessed through
 * [CallableDescriptor.getOverriddenDescriptors] instead, which is separate from [CallableDescriptor.getOriginal].
 */


public fun addEngine ( type : EngineType )

{ <EOL> if ( ! _engines . containsKey ( type . name ) ) { <EOL> _engines [ type . name ] = type <EOL> } <EOL> }


public fun setEngine ( type : EngineType )

{ <EOL> if ( type . name in engines ) <EOL> Engine . setDefaultEngine ( type ) <EOL> }

/**
 * Sets the engine of type [type] as the current implementation.
 */


public operator fun < T > get ( vararg elements : T ) : List < T >

= elements . toList ( )

/**
 * Returns a list of [elements]. Sugar for easy array creation.
 */


@ FirSymbolProviderInternals <EOL> abstract fun getClassLikeSymbolByClassId ( classId : ClassId , classLikeDeclaration : KtClassLikeDeclaration ) : FirClassLikeSymbol < * > ?

/**
 * This function is optimized for a known [classLikeDeclaration].
 */


@ FirSymbolProviderInternals <EOL> abstract fun getTopLevelCallableSymbolsTo ( destination : MutableList < FirCallableSymbol < * > > , callableId : CallableId , callables : Collection < KtCallableDeclaration > , )

/**
 * This function is optimized for known [callables].
 */


@ FirSymbolProviderInternals <EOL> abstract fun getTopLevelFunctionSymbolsTo ( destination : MutableList < FirNamedFunctionSymbol > , callableId : CallableId , functions : Collection < KtNamedFunction > , )

/**
 * This function is optimized for known [functions].
 */


@ FirSymbolProviderInternals <EOL> abstract fun getTopLevelPropertySymbolsTo ( destination : MutableList < FirPropertySymbol > , callableId : CallableId , properties : Collection < KtProperty > , )

/**
 * This function is optimized for known [properties].
 */


private fun validFileOrNull ( path : String ) : File ?

= <EOL> try { <EOL> File ( Paths . get ( path ) ) <EOL> } catch ( _ : InvalidPathException ) { <EOL> null <EOL> }

/**
 * Returns a [File] instance if the [path] is valid on the current file system and null otherwise.
 * Doesn't check whether the file denoted by [path] really exists.
 */


private fun directLibsSequence ( givenName : String ) : Sequence < File >

{ <EOL> return directLibraries . asSequence ( ) . filter { <EOL> it . uniqueName == givenName <EOL> } . map { <EOL> it . libraryFile <EOL> } <EOL> }

/**
 * Returns a sequence of libraries passed to the compiler directly for which unique_name == [givenName].
 */


abstract operator fun contains ( ch : Int ) : Boolean

/** Returns true if this char class contains character specified. */


fun classWithSurrogates ( ) : AbstractCharClass

{ <EOL> surrogates_ . value ? . let { <EOL> return it <EOL> } <EOL> val surrogates = lowHighSurrogates <EOL> val result = object : AbstractCharClass ( ) { <EOL> override fun contains ( ch : Int ) : Boolean { <EOL> val index = ch - Char . MIN_SURROGATE . toInt ( ) <EOL> return if ( index >= <NUM_LIT:0> && index < AbstractCharClass . SURROGATE_CARDINALITY ) { <EOL> this . altSurrogates xor surrogates [ index ] <EOL> } else { <EOL> false <EOL> } <EOL> } <EOL> } <EOL> result . alt = this . alt <EOL> result . altSurrogates = this . altSurrogates <EOL> result . mayContainSupplCodepoints = this . mayContainSupplCodepoints <EOL> surrogates_ . compareAndSet ( null , result . freeze ( ) ) <EOL> return surrogates_ . value ! ! <EOL> }

/**
 * Returns a char class that contains only unpaired surrogate chars from this char class.
 *
 * Consider the following char class: `[a\uD801\uDC00\uD800]`.
 * This function returns a char class that contains only `\uD800`: `[\uD800]`.
 * [classWithoutSurrogates] returns a char class that does not contain `\uD800`: `[a\uD801\uDC00]`.
 *
 * The returned char class is used to create [SurrogateRangeSet] node
 * that matches any unpaired surrogate from this char class. [SurrogateRangeSet]
 * doesn't match a surrogate that is paired with the char before or after it.
 * The result of [classWithoutSurrogates] is used to create [SupplementaryRangeSet]
 * or [RangeSet] depending on [mayContainSupplCodepoints].
 * The two nodes are then combined in [CompositeRangeSet] node to fully represent this char class.
 */


fun classWithoutSurrogates ( ) : AbstractCharClass

{ <EOL> val result = object : AbstractCharClass ( ) { <EOL> override fun contains ( ch : Int ) : Boolean { <EOL> val index = ch - Char . MIN_SURROGATE . toInt ( ) <EOL> val containslHS = if ( index >= <NUM_LIT:0> && index < AbstractCharClass . SURROGATE_CARDINALITY ) <EOL> this . altSurrogates xor this@AbstractCharClass . lowHighSurrogates . get ( index ) <EOL> else <EOL> false <EOL> return this@AbstractCharClass . contains ( ch ) && ! containslHS <EOL> } <EOL> } <EOL> result . alt = this . alt <EOL> result . altSurrogates = this . altSurrogates <EOL> result . mayContainSupplCodepoints = this . mayContainSupplCodepoints <EOL> return result <EOL> }

/**
 * Returns a char class that contains all chars from this char class excluding the unpaired surrogate chars.
 *
 * See [classWithSurrogates] for details.
 */


fun setNegative ( value : Boolean ) : AbstractCharClass

{ <EOL> if ( alt xor value ) { <EOL> alt = ! alt <EOL> altSurrogates = ! altSurrogates <EOL> if ( ! mayContainSupplCodepoints ) { <EOL> mayContainSupplCodepoints = true <EOL> } <EOL> } <EOL> return this <EOL> }

/**
 * Sets this CharClass to negative form, i.e. if they will add some characters and after that set this
 * class to negative it will accept all the characters except previously set ones.
 *
 * Although this method will not alternate all the already set characters,
 * just overall meaning of the class.
 */


@ ExternalKotlinTargetApi <EOL> fun < T : DecoratedExternalKotlinTarget > KotlinMultiplatformExtension . createExternalKotlinTarget ( descriptor : ExternalKotlinTargetDescriptor < T > , ) : T

{ <EOL> val apiElementsConfiguration = project . configurations <EOL> . maybeCreateConsumable ( lowerCamelCaseName ( descriptor . targetName , "<STR_LIT>" ) ) <EOL> val runtimeElementsConfiguration = project . configurations <EOL> . maybeCreateConsumable ( lowerCamelCaseName ( descriptor . targetName , "<STR_LIT>" ) ) <EOL> val sourcesElementsConfiguration = project . configurations <EOL> . maybeCreateConsumable ( lowerCamelCaseName ( descriptor . targetName , "<STR_LIT>" ) ) <EOL> fun Configuration . notVisible ( ) = apply { isVisible = false } <EOL> val apiElementsPublishedConfiguration = project . configurations <EOL> . maybeCreateDependencyScope ( lowerCamelCaseName ( descriptor . targetName , "<STR_LIT>" ) ) <EOL> . notVisible ( ) <EOL> val runtimeElementsPublishedConfiguration = project . configurations <EOL> . maybeCreateDependencyScope ( lowerCamelCaseName ( descriptor . targetName , "<STR_LIT>" ) ) <EOL> . notVisible ( ) <EOL> val sourcesElementsPublishedConfiguration = project . configurations <EOL> . maybeCreateDependencyScope ( lowerCamelCaseName ( descriptor . targetName , "<STR_LIT>" ) ) <EOL> . notVisible ( ) <EOL> val resourcesElementsPublishedConfiguration = project . configurations <EOL> . maybeCreateDependencyScope ( lowerCamelCaseName ( descriptor . targetName , "<STR_LIT>" ) ) <EOL> . notVisible ( ) <EOL> val kotlinTargetComponent = ExternalKotlinTargetComponent ( ExternalKotlinTargetComponent . TargetProvider . byTargetName ( this , descriptor . targetName ) ) <EOL> val artifactsTaskLocator = ExternalKotlinTargetImpl . ArtifactsTaskLocator { target -> <EOL> target . project . locateOrRegisterTask < Jar > ( lowerCamelCaseName ( descriptor . targetName , "<STR_LIT>" ) ) <EOL> } <EOL> val compilerOptions = when ( descriptor . platformType ) { <EOL> KotlinPlatformType . androidJvm , <EOL> KotlinPlatformType . jvm -> project . objects . newInstance < KotlinJvmCompilerOptionsDefault > ( ) <EOL> KotlinPlatformType . wasm , <EOL> KotlinPlatformType . js -> project . objects . newInstance < KotlinJsCompilerOptionsDefault > ( ) <EOL> KotlinPlatformType . common -> project . objects . newInstance < KotlinCommonCompilerOptionsDefault > ( ) <EOL> KotlinPlatformType . native -> project . objects . newInstance < KotlinNativeCompilerOptionsDefault > ( ) <EOL> } <EOL> val target = ExternalKotlinTargetImpl ( project = project , targetName = descriptor . targetName , platformType = descriptor . platformType , publishable = true , compilerOptions = compilerOptions , apiElementsConfiguration = apiElementsConfiguration , runtimeElementsConfiguration = runtimeElementsConfiguration , sourcesElementsConfiguration = sourcesElementsConfiguration , apiElementsPublishedConfiguration = apiElementsPublishedConfiguration , runtimeElementsPublishedConfiguration = runtimeElementsPublishedConfiguration , sourcesElementsPublishedConfiguration = sourcesElementsPublishedConfiguration , resourcesElementsPublishedConfiguration = resourcesElementsPublishedConfiguration , kotlinTargetComponent = kotlinTargetComponent , artifactsTaskLocator = artifactsTaskLocator ) <EOL> target . setupApiElements ( apiElementsConfiguration ) <EOL> target . setupApiElements ( apiElementsPublishedConfiguration ) <EOL> target . setupRuntimeElements ( runtimeElementsConfiguration ) <EOL> target . setupRuntimeElements ( runtimeElementsPublishedConfiguration ) <EOL> target . setupSourcesElements ( sourcesElementsConfiguration ) <EOL> target . setupSourcesElements ( sourcesElementsPublishedConfiguration ) <EOL> val decorated = descriptor . targetFactory . create ( DecoratedExternalKotlinTarget . Delegate ( target ) ) <EOL> target . onCreated ( ) <EOL> descriptor . configure ? . invoke ( decorated ) <EOL> descriptor . apiElements . configure ? . invoke ( decorated , apiElementsConfiguration ) <EOL> descriptor . runtimeElements . configure ? . invoke ( decorated , runtimeElementsConfiguration ) <EOL> descriptor . sourcesElements . configure ? . invoke ( decorated , sourcesElementsConfiguration ) <EOL> descriptor . apiElementsPublished . configure ? . invoke ( decorated , apiElementsPublishedConfiguration ) <EOL> descriptor . runtimeElementsPublished . configure ? . invoke ( decorated , runtimeElementsPublishedConfiguration ) <EOL> descriptor . sourcesElementsPublished . configure ? . invoke ( decorated , sourcesElementsPublishedConfiguration ) <EOL> descriptor . configureIdeImport ? . invoke ( project . kotlinIdeMultiplatformImport ) <EOL> targets . add ( decorated ) <EOL> decorated . logger . info ( "<STR_LIT>" ) <EOL> return decorated <EOL> }

/**
 * Creates an adhoc/external Kotlin Target which can be maintained and evolved outside the kotlin.git repository.
 * The target will be created adhering to the configuration provided by the [descriptor].
 * The instance will be backed by an internal implementation of [KotlinTarget]
 * The instance will be created using the [ExternalKotlinTargetDescriptor.targetFactory] which will have to inject the backing
 * internal implementation using the [DecoratedExternalKotlinTarget.Delegate] into [DecoratedExternalKotlinTarget]
 */


@ ExternalKotlinTargetApi <EOL> fun < T : DecoratedExternalKotlinTarget > KotlinMultiplatformExtension . createExternalKotlinTarget ( descriptor : ExternalKotlinTargetDescriptorBuilder < T > . ( ) -> Unit , ) : T

{ <EOL> return createExternalKotlinTarget ( ExternalKotlinTargetDescriptor ( descriptor ) ) <EOL> }

/**
 * @see createExternalKotlinTarget
 */


@ HtmlTagMarker <EOL> inline fun HGROUP . h1 ( classes : String ? = null , crossinline block : H1 . ( ) -> Unit = { } ) : Unit

= H1 ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun HGROUP . h2 ( classes : String ? = null , crossinline block : H2 . ( ) -> Unit = { } ) : Unit

= H2 ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun HGROUP . h3 ( classes : String ? = null , crossinline block : H3 . ( ) -> Unit = { } ) : Unit

= H3 ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun HGROUP . h4 ( classes : String ? = null , crossinline block : H4 . ( ) -> Unit = { } ) : Unit

= H4 ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun HGROUP . h5 ( classes : String ? = null , crossinline block : H5 . ( ) -> Unit = { } ) : Unit

= H5 ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun HGROUP . h6 ( classes : String ? = null , crossinline block : H6 . ( ) -> Unit = { } ) : Unit

= H6 ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun HTML . body ( classes : String ? = null , crossinline block : BODY . ( ) -> Unit = { } ) : Unit

= BODY ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun HTML . head ( crossinline block : HEAD . ( ) -> Unit = { } ) : Unit

= HEAD ( emptyMap , consumer ) . visit ( block )


@ ObsoleteCoroutinesApi <EOL> public fun < E > CoroutineScope . actor ( context : CoroutineContext = EmptyCoroutineContext , capacity : Int = <NUM_LIT:0> , start : CoroutineStart = CoroutineStart . DEFAULT , onCompletion : CompletionHandler ? = null , block : suspend ActorScope < E > . ( ) -> Unit ) : SendChannel < E >

{ <EOL> val newContext = newCoroutineContext ( context ) <EOL> val channel = Channel < E > ( capacity ) <EOL> val coroutine = if ( start . isLazy ) <EOL> LazyActorCoroutine ( newContext , channel , block ) else <EOL> ActorCoroutine ( newContext , channel , active = true ) <EOL> if ( onCompletion != null ) coroutine . invokeOnCompletion ( handler = onCompletion ) <EOL> coroutine . start ( start , coroutine , block ) <EOL> return coroutine <EOL> }

/**
 * Launches new coroutine that is receiving messages from its mailbox channel
 * and returns a reference to its mailbox channel as a [SendChannel]. The resulting
 * object can be used to [send][SendChannel.send] messages to this coroutine.
 *
 * The scope of the coroutine contains [ActorScope] interface, which implements
 * both [CoroutineScope] and [ReceiveChannel], so that coroutine can invoke
 * [receive][ReceiveChannel.receive] directly. The channel is [closed][SendChannel.close]
 * when the coroutine completes.
 *
 * Coroutine context is inherited from a [CoroutineScope], additional context elements can be specified with [context] argument.
 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
 * The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden
 * with corresponding [context] element.
 *
 * By default, the coroutine is immediately scheduled for execution.
 * Other options can be specified via `start` parameter. See [CoroutineStart] for details.
 * An optional [start] parameter can be set to [CoroutineStart.LAZY] to start coroutine _lazily_. In this case,
 * it will be started implicitly on the first message
 * [sent][SendChannel.send] to this actors's mailbox channel.
 *
 * Uncaught exceptions in this coroutine close the channel with this exception as a cause and
 * the resulting channel becomes _failed_, so that any attempt to send to such a channel throws exception.
 *
 * The kind of the resulting channel depends on the specified [capacity] parameter.
 * See [Channel] interface documentation for details.
 *
 * See [newCoroutineContext][CoroutineScope.newCoroutineContext] for a description of debugging facilities that are available for newly created coroutine.
 *
 * ### Using actors
 *
 * A typical usage of the actor builder looks like this:
 *
 * ```
 * val c = actor {
 * // initialize actor's state
 * for (msg in channel) {
 * // process message here
 * }
 * }
 * // send messages to the actor
 * c.send(...)
 * ...
 * // stop the actor when it is no longer needed
 * c.close()
 * ```
 *
 * ### Stopping and cancelling actors
 *
 * When the inbox channel of the actor is [closed][SendChannel.close] it sends a special "close token" to the actor.
 * The actor still processes all the messages that were already sent and then "`for (msg in channel)`" loop terminates
 * and the actor completes.
 *
 * If the actor needs to be aborted without processing all the messages that were already sent to it, then
 * it shall be created with a parent job:
 *
 * ```
 * val job = Job()
 * val c = actor(context = job) { ... }
 * ...
 * // abort the actor
 * job.cancel()
 * ```
 *
 * When actor's parent job is [cancelled][Job.cancel], then actor's job becomes cancelled. It means that
 * "`for (msg in channel)`" and other cancellable suspending functions throw [CancellationException] and actor
 * completes without processing remaining messages.
 *
 * **Note: This API will become obsolete in future updates with introduction of complex actors.**
 * See [issue #87](https://github.com/Kotlin/kotlinx.coroutines/issues/87).
 *
 * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine.
 * @param capacity capacity of the channel's buffer (no buffer by default).
 * @param start coroutine start option. The default value is [CoroutineStart.DEFAULT].
 * @param onCompletion optional completion handler for the actor coroutine (see [Job.invokeOnCompletion])
 * @param block the coroutine code.
 */


public fun readCodeForGeneration ( stream : InputStream , name : String , generateHelperCompanionObject : Boolean = false , ) : Code

/**
 * @param stream where to read the schema from
 * @param name the name of the top-level interface to generate
 * @param generateHelperCompanionObject whether to generate a helper companion object (only needed for Jupyter)
 */


public fun readCodeForGeneration ( file : File , name : String , generateHelperCompanionObject : Boolean = false , ) : Code

/**
 * @param file where to read the schema from
 * @param name the name of the top-level interface to generate
 * @param generateHelperCompanionObject whether to generate a helper companion object (only needed for Jupyter)
 */


internal fun readCodeForGeneration ( stream : InputStream , name : String , format : SupportedCodeGenerationFormat ? = null , generateHelperCompanionObject : Boolean = false , formats : List < SupportedCodeGenerationFormat > = supportedFormats . filterIsInstance < SupportedCodeGenerationFormat > ( ) , ) : GeneratedCode

{ <EOL> if ( format != null ) return format to format . readCodeForGeneration ( stream , name , generateHelperCompanionObject ) <EOL> val input = NotCloseableStream ( if ( stream . markSupported ( ) ) stream else BufferedInputStream ( stream ) ) <EOL> try { <EOL> val readLimit = <NUM_LIT> <EOL> input . mark ( readLimit ) <EOL> formats . sortedBy { it . testOrder } . forEach { <EOL> try { <EOL> input . reset ( ) <EOL> return it to it . readCodeForGeneration ( input , name , generateHelperCompanionObject ) <EOL> } catch ( _ : Exception ) { <EOL> } <EOL> } <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } finally { <EOL> input . doClose ( ) <EOL> } <EOL> }

/**
 * @param stream where to read the schema from
 * @param name the name of the top-level interface to generate
 * @param format the format to use
 * @param generateHelperCompanionObject whether to generate a helper companion object (only needed for Jupyter)
 * @param formats Optional list of supported formats to use. If not specified, all formats will be used.
 *
 * @return [GeneratedCode] with generated code
 */


private fun FirQualifiedAccessExpression . findIrDynamicReceiver ( explicitReceiverExpression : IrExpression ? , ) : IrExpression

{ <EOL> return explicitReceiverExpression <EOL> ? : ( dispatchReceiver as? FirThisReceiverExpression ) ? . let ( visitor :: convertToIrExpression ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> }

/**
 * A dynamic call has either an explicit receiver or an implicit this dispatch receiver.
 */


private fun wrapWithImplicitCastForAssignment ( assignment : FirVariableAssignment , value : IrExpression ) : IrExpression

{ <EOL> if ( value is IrTypeOperatorCall ) return value <EOL> val rValue = assignment . rValue <EOL> if ( rValue !is FirSmartCastExpression ) return value <EOL> val originalType = rValue . originalExpression . resolvedType . withNullability ( ConeNullability . NOT_NULL , session . typeContext ) <EOL> val assignmentType = assignment . lValue . resolvedType <EOL> if ( originalType . isSubtypeOf ( assignmentType , session ) ) return value <EOL> return implicitCast ( value , assignmentType . toIrType ( ) , IrTypeOperator . IMPLICIT_CAST ) <EOL> }

/** Wrap an assignment - as needed - with an implicit cast to the left-hard side type. */


private fun extractDispatchReceiverOfAssignment ( variableAssignment : FirVariableAssignment ) : FirExpression ?

{ <EOL> val receiver = variableAssignment . dispatchReceiver ? : return null <EOL> if ( receiver !is FirSmartCastExpression ) return receiver <EOL> val thisReceiver = receiver . originalExpression as? FirThisReceiverExpression ? : return receiver <EOL> val thisClass = thisReceiver . calleeReference . boundSymbol as? FirClassSymbol < * > ? : return receiver <EOL> val propertySymbol = variableAssignment . calleeReference ? . toResolvedPropertySymbol ( ) ? : return receiver <EOL> val propertyDispatchReceiverType = propertySymbol . dispatchReceiverType ? : return receiver <EOL> return when ( thisClass . defaultType ( ) . isSubtypeOf ( propertyDispatchReceiverType , session ) ) { <EOL> true -> thisReceiver <EOL> false -> receiver <EOL> } <EOL> }

/**
 * If we have assignment like `this.x = ...` and this `this` is a dispatch this of some class, then we should unwrap
 * smartcast if possible to generate SetField instead of setter call
 *
 * See KT-57105
 */


private fun List < FirTypeProjection > . toExpandedTypeArguments ( typeAliasSymbol : FirTypeAliasSymbol ) : List < FirTypeProjection >

{ <EOL> return typeAliasSymbol <EOL> . constructType ( map { it . toConeTypeProjection ( ) } . toTypedArray ( ) , false ) <EOL> . fullyExpandedType ( session ) <EOL> . typeArguments <EOL> . map { typeProjection -> <EOL> buildTypeProjectionWithVariance { <EOL> variance = when ( typeProjection ) { <EOL> is ConeKotlinTypeProjectionIn -> Variance . IN_VARIANCE <EOL> is ConeKotlinTypeProjectionOut -> Variance . OUT_VARIANCE <EOL> else -> Variance . INVARIANT <EOL> } <EOL> typeRef = ( typeProjection as? ConeKotlinType ) ? . let { <EOL> buildResolvedTypeRef { type = it } <EOL> } ? : buildErrorTypeRef { <EOL> diagnostic = ConeSimpleDiagnostic ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Applies the list of type arguments to the given type alias, expands it fully and returns the list of type arguments for the
 * resulting type.
 */


private fun getDefaultJdkModuleRoots ( javaModuleFinder : CliJavaModuleFinder , javaModuleGraph : JavaModuleGraph ) : List < JavaRoot >

{ <EOL> return javaModuleGraph . getAllDependencies ( javaModuleFinder . computeDefaultRootModules ( ) ) . flatMap { moduleName -> <EOL> val module = javaModuleFinder . findModule ( moduleName ) ? : return@flatMap emptyList < JavaRoot > ( ) <EOL> val result = module . getJavaModuleRoots ( ) <EOL> result <EOL> } <EOL> }

/**
 * Computes the [JavaRoot]s of the JDK's default modules.
 *
 * @see ClasspathRootsResolver.addModularRoots
 */


fun findJvmRootsForJavaFiles ( files : List < PsiJavaFile > ) : List < PsiDirectory >

{ <EOL> if ( files . isEmpty ( ) ) return emptyList ( ) <EOL> val result = mutableSetOf < PsiDirectory > ( ) <EOL> for ( file in files ) { <EOL> val packageParts = file . packageName . takeIf { it . isNotEmpty ( ) } ? . split ( '<CHAR_LIT:.>' ) ? : emptyList ( ) <EOL> var javaDir : PsiDirectory ? = file . parent <EOL> for ( part in packageParts . reversed ( ) ) { <EOL> if ( javaDir ? . name == part ) { <EOL> javaDir = javaDir . parent <EOL> } else { <EOL> break <EOL> } <EOL> } <EOL> javaDir ? . let { result += it } <EOL> } <EOL> return result . toList ( ) <EOL> }

/**
 * Note that [findJvmRootsForJavaFiles] parses the given [files] because it needs access to each file's package name. To avoid parsing
 * errors, [registerJavaPsiFacade] ensures that the Java language level is configured before [findJvmRootsForJavaFiles] is called.
 */


{ <EOL> taskHolders . forEach { holder -> <EOL> if ( framework . buildType == holder . buildType ) { <EOL> holder . task . configure { task -> task . from ( framework ) } <EOL> AppleTarget . values ( ) <EOL> . firstOrNull { it . targets . contains ( framework . konanTarget ) } <EOL> ? . also { appleTarget -> <EOL> holder . fatTasks [ appleTarget ] ? . configure { fatTask -> <EOL> fatTask . baseName = framework . baseName <EOL> fatTask . from ( framework ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Adds the specified frameworks in this XCFramework.
 */


fun from ( vararg frameworks : Framework )

{ <EOL> frameworks . forEach { framework -> <EOL> require ( framework . konanTarget . family . isAppleFamily ) { <EOL> "<STR_LIT>" <EOL> } <EOL> dependsOn ( framework . linkTask ) <EOL> } <EOL> fromFrameworkDescriptors ( frameworks . map { FrameworkDescriptor ( it ) } ) <EOL> }


fun suggest ( descriptor : DeclarationDescriptor , bindingContext : BindingContext )

= <EOL> cache . getOrPut ( descriptor ) { generate ( descriptor . original , bindingContext ) }

/**
 * Generates names for declarations. Name consists of the following parts:
 *
 * * Aliasing declaration, if the given `descriptor` does not have its own entity in JS.
 * * Scoping declaration. Declarations are usually compiled to the hierarchy of nested JS objects,
 * this attribute allows to find out where to put the declaration.
 * * Simple name, which is a name that object must (or may) get on the generated JS.
 * * Whether the name is stable. Stable names are visible to other modules and to native JS.
 * Unstable names do not require particular name, so the code generator can invent any name
 * which does not clash with anything; however, it may derive the name from the suggested name to
 * improve readability and debugging experience.
 *
 * This method returns `null` for root declarations (modules and root packages).
 * It's guaranteed that a particular name is returned for any other declarations.
 *
 * Since packages in Kotlin do not always form hierarchy, suggested name is a list of strings. This
 * list consists of exactly one string for any declaration except for package. Package name lists
 * have at least one string.
 */


public fun Buffer . transferFrom ( input : InputStream ) : Buffer

{ <EOL> write ( input , Long . MAX_VALUE , true ) <EOL> return this <EOL> }

/**
 * Read and exhaust bytes from [input] into this buffer. Stops reading data on [input] exhaustion.
 *
 * @param input the stream to read data from.
 *
 * @sample kotlinx.io.samples.KotlinxIoSamplesJvm.bufferTransferToStream
 */


public fun Buffer . write ( input : InputStream , byteCount : Long ) : Buffer

{ <EOL> checkByteCount ( byteCount ) <EOL> write ( input , byteCount , false ) <EOL> return this <EOL> }

/**
 * Read [byteCount] bytes from [input] into this buffer. Throws an exception when [input] is
 * exhausted before reading [byteCount] bytes.
 *
 * @param input the stream to read data from.
 * @param byteCount the number of bytes read from [input].
 *
 * @throws IOException when [input] exhausted before reading [byteCount] bytes from it.
 * @throws IllegalArgumentException when [byteCount] is negative.
 *
 * @sample kotlinx.io.samples.KotlinxIoSamplesJvm.writeInputStreamToBuffer
 */


public fun Buffer . readTo ( out : OutputStream , byteCount : Long = size )

{ <EOL> checkOffsetAndCount ( size , <NUM_LIT:0> , byteCount ) <EOL> var remainingByteCount = byteCount <EOL> var s = head <EOL> while ( remainingByteCount > <NUM_LIT:0L> ) { <EOL> val toCopy = minOf ( remainingByteCount , s ! ! . limit - s . pos ) . toInt ( ) <EOL> out . write ( s . data , s . pos , toCopy ) <EOL> s . pos += toCopy <EOL> size -= toCopy . toLong ( ) <EOL> remainingByteCount -= toCopy . toLong ( ) <EOL> if ( s . pos == s . limit ) { <EOL> val toRecycle = s <EOL> s = toRecycle . pop ( ) <EOL> head = s <EOL> SegmentPool . recycle ( toRecycle ) <EOL> } <EOL> } <EOL> }

/**
 * Consumes [byteCount] bytes from this buffer and writes it to [out].
 *
 * @param out the [OutputStream] to write to.
 * @param byteCount the number of bytes to be written, [Buffer.size] by default.
 *
 * @throws IllegalArgumentException when [byteCount] is negative or exceeds the buffer size.
 *
 * @sample kotlinx.io.samples.KotlinxIoSamplesJvm.bufferTransferToStream
 */


public fun Buffer . copyTo ( out : OutputStream , startIndex : Long = <NUM_LIT:0L> , endIndex : Long = size )

{ <EOL> checkBounds ( size , startIndex , endIndex ) <EOL> if ( startIndex == endIndex ) return <EOL> var currentOffset = startIndex <EOL> var remainingByteCount = endIndex - startIndex <EOL> var s = head <EOL> while ( currentOffset >= s ! ! . limit - s . pos ) { <EOL> currentOffset -= ( s . limit - s . pos ) . toLong ( ) <EOL> s = s . next <EOL> } <EOL> while ( remainingByteCount > <NUM_LIT:0L> ) { <EOL> val pos = ( s ! ! . pos + currentOffset ) . toInt ( ) <EOL> val toCopy = minOf ( s . limit - pos , remainingByteCount ) . toInt ( ) <EOL> out . write ( s . data , pos , toCopy ) <EOL> remainingByteCount -= toCopy . toLong ( ) <EOL> currentOffset = <NUM_LIT:0L> <EOL> s = s . next <EOL> } <EOL> }

/**
 * Copy bytes from this buffer's subrange, starting at [startIndex] and ending at [endIndex], to [out]. This method
 * does not consume data from the buffer.
 *
 * @param out the destination to copy data into.
 * @param startIndex the index (inclusive) of the first byte to copy, `0` by default.
 * @param endIndex the index (exclusive) of the last byte to copy, `buffer.size` by default.
 *
 * @throws IndexOutOfBoundsException when [startIndex] or [endIndex] is out of this buffer bounds (`[0..buffer.size)`).
 * @throws IllegalArgumentException when `startIndex > endIndex`.
 *
 * @sample kotlinx.io.samples.KotlinxIoSamplesJvm.copyBufferToOutputStream
 */


public fun Buffer . readAtMostTo ( sink : ByteBuffer ) : Int

{ <EOL> val s = head ? : return - <NUM_LIT:1> <EOL> val toCopy = minOf ( sink . remaining ( ) , s . limit - s . pos ) <EOL> sink . put ( s . data , s . pos , toCopy ) <EOL> s . pos += toCopy <EOL> size -= toCopy . toLong ( ) <EOL> if ( s . pos == s . limit ) { <EOL> head = s . pop ( ) <EOL> SegmentPool . recycle ( s ) <EOL> } <EOL> return toCopy <EOL> }

/**
 * Writes up to [ByteBuffer.remaining] bytes from this buffer to the sink.
 * Return the number of bytes written.
 *
 * @param sink the sink to write data to.
 *
 * @sample kotlinx.io.samples.KotlinxIoSamplesJvm.readWriteByteBuffer
 */


public fun Buffer . transferFrom ( source : ByteBuffer ) : Buffer

{ <EOL> val byteCount = source . remaining ( ) <EOL> var remaining = byteCount <EOL> while ( remaining > <NUM_LIT:0> ) { <EOL> val tail = writableSegment ( <NUM_LIT:1> ) <EOL> val toCopy = minOf ( remaining , Segment . SIZE - tail . limit ) <EOL> source . get ( tail . data , tail . limit , toCopy ) <EOL> remaining -= toCopy <EOL> tail . limit += toCopy <EOL> } <EOL> size += byteCount . toLong ( ) <EOL> return this <EOL> }

/**
 * Reads all data from [source] into this buffer.
 *
 * @sample kotlinx.io.samples.KotlinxIoSamplesJvm.transferBufferFromByteBuffer
 */


public fun Buffer . asByteChannel ( ) : ByteChannel

= object : ByteChannel { <EOL> override fun read ( sink : ByteBuffer ) : Int = readAtMostTo ( sink ) <EOL> override fun write ( source : ByteBuffer ) : Int { <EOL> val sizeBefore = size <EOL> transferFrom ( source ) <EOL> return ( size - sizeBefore ) . toInt ( ) <EOL> } <EOL> override fun close ( ) { } <EOL> override fun isOpen ( ) : Boolean = true <EOL> }

/**
 * Returns a new [ByteChannel] instance representing this buffer.
 */


@ HtmlTagMarker <EOL> inline fun COLGROUP . col ( classes : String ? = null , crossinline block : COL . ( ) -> Unit = { } ) : Unit

= COL ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ Test <EOL> fun `it should be possible to replace compilation output classes` ( )

{ <EOL> fun Project . addClassesTransformationTask ( target : KotlinTarget ) { <EOL> val compilation = target . compilations . getByName ( KotlinCompilation . MAIN_COMPILATION_NAME ) <EOL> val classesDirs = compilation . output . classesDirs <EOL> val originalClassesDirs : FileCollection = <EOL> project . files ( classesDirs . from . toTypedArray ( ) ) <EOL> val transformedClassesDir = project . layout . buildDirectory . dir ( "<STR_LIT>" ) <EOL> val transformTask = project . tasks . create ( "<STR_LIT>" ) { <EOL> it . dependsOn ( compilation . compileAllTaskName ) <EOL> it . inputs . files ( originalClassesDirs ) <EOL> it . outputs . files ( transformedClassesDir ) <EOL> } <EOL> classesDirs . setFrom ( transformedClassesDir ) <EOL> classesDirs . builtBy ( transformTask ) <EOL> } <EOL> val project = buildProjectWithMPP { <EOL> kotlin { <EOL> val target = jvm { } <EOL> addClassesTransformationTask ( target ) <EOL> } <EOL> } <EOL> project . evaluate ( ) <EOL> val jvmMainClasses = project . tasks . getByName ( "<STR_LIT>" ) <EOL> jvmMainClasses . assertNoCircularTaskDependencies ( ) <EOL> }

/**
 * This mechanism used by `kotlinx-atomicfu` gradle plugin. It replaces compilation classes to transformed classes dir
 */


fun configure ( target : KotlinAndroidTarget , kotlinSourceSet : KotlinSourceSet , @ Suppress ( "<STR_LIT:TYPEALIAS_EXPANSION_DEPRECATION>" ) androidSourceSet : DeprecatedAndroidSourceSet )

= Unit

/**
 * Called once, when the corresponding KotlinSourceSet is created for a given [DeprecatedAndroidSourceSet].
 * Note, this can also be called in 'afterEvaluate', when Android is finalizing its variants.
 */


fun configureWithVariant ( target : KotlinAndroidTarget , kotlinSourceSet : KotlinSourceSet , @ Suppress ( "<STR_LIT:TYPEALIAS_EXPANSION_DEPRECATION>" ) variant : DeprecatedAndroidBaseVariant )

= Unit

/**
 * Called every time, when a given [KotlinSourceSet] participates in a given Android variant.
 */


@ Test <EOL> fun testStressReleaseCancelRace ( )

= runTest { <EOL> val n = iterations <EOL> val semaphore = Semaphore ( <NUM_LIT:1> , <NUM_LIT:1> ) <EOL> newSingleThreadContext ( "<STR_LIT>" ) . use { pool -> <EOL> repeat ( n ) { <EOL> assertEquals ( <NUM_LIT:0> , semaphore . availablePermits ) <EOL> var job1EnteredCriticalSection = false <EOL> val job1 = launch ( start = CoroutineStart . UNDISPATCHED ) { <EOL> semaphore . acquire ( ) <EOL> job1EnteredCriticalSection = true <EOL> semaphore . release ( ) <EOL> } <EOL> assertEquals ( false , job1EnteredCriticalSection ) <EOL> val job2 = launch ( pool ) { <EOL> semaphore . release ( ) <EOL> } <EOL> job1 . cancelAndJoin ( ) <EOL> job2 . join ( ) <EOL> assertEquals ( <NUM_LIT:1> , semaphore . availablePermits ) <EOL> semaphore . acquire ( ) <EOL> } <EOL> } <EOL> }

/**
 * This checks if repeated releases that race with cancellations put
 * the semaphore into an incorrect state where permits are leaked.
 */


fun trySetWithoutReassigning ( container : Object , newValue : Type ) : Type ?

/**
 * If the field is not set, sets it to the given value.
 * If the field is set to the given value, does nothing.
 * If the field is set to a different value, throws [IllegalArgumentException].
 *
 * This function is used to ensure internal consistency during parsing.
 * There exist formats where the same data is repeated several times in the same object, for example,
 * "14:15 (02:15 PM)". In such cases, we want to ensure that the values are consistent.
 */


private fun transformInMemoryResults ( rendered : InMemoryMimeTypedResult , evalData : EvalRequestData , ) : MimeTypedResultEx

{ <EOL> val id = evalData . jupyterId . toString ( ) <EOL> val inMemoryValue = rendered . inMemoryOutput . result <EOL> inMemoryReplResultsHolder . setReplResult ( id , inMemoryValue ) <EOL> val mimeData = rendered . fallbackResult + Pair ( rendered . inMemoryOutput . mimeType , JsonPrimitive ( id ) ) <EOL> return MimeTypedResultEx ( Json . encodeToJsonElement ( mimeData ) , null , standardMetadataModifiers ( ) ) <EOL> }

/**
 * If the render result is an in-memory value, we need to extract it from
 * the mimetype and put it into the `InMemoryReplResultsHolder`. Then we
 * construct a new DisplayResult where the in-memory value is replaced by
 * its `jupyterId`. This allows us to re-use the existing Jupyter protocol
 * infrastructure to send display results, but also allows a custom UI
 * component on the Client side to find the in-memory value
 * again by asking for it in the `InMemoryReplResultsHolder`.
 */


private fun updateClasspath ( ) : Classpath

{ <EOL> val resolvedClasspath = resolver . popAddedClasspath ( ) . map { it . canonicalPath } <EOL> if ( resolvedClasspath . isEmpty ( ) ) return emptyList ( ) <EOL> val ( oldClasspath , newClasspath ) = resolvedClasspath . partition { it in currentClasspath } <EOL> currentClasspath . addAll ( newClasspath ) <EOL> if ( options . trackClasspath ) { <EOL> val sb = StringBuilder ( ) <EOL> if ( newClasspath . isNotEmpty ( ) ) { <EOL> sb . appendLine ( "<STR_LIT>" ) <EOL> newClasspath . sortedBy { it } . forEach { sb . appendLine ( it ) } <EOL> } <EOL> if ( oldClasspath . isNotEmpty ( ) ) { <EOL> sb . appendLine ( "<STR_LIT>" ) <EOL> oldClasspath . sortedBy { it } . forEach { sb . appendLine ( it ) } <EOL> } <EOL> sb . appendLine ( "<STR_LIT>" ) <EOL> println ( sb . toString ( ) ) <EOL> } <EOL> return newClasspath <EOL> }

/**
 * Updates current classpath with newly resolved libraries paths
 * Also, prints information about resolved libraries to stdout if [ReplOptions.trackClasspath] is true
 *
 * @return Newly resolved classpath
 */


internal fun FirBasedSymbol < * > . cannotResolveAnnotationsOnDemand ( ) : Boolean

{ <EOL> return this is FirCallableSymbol < * > && isLocalForLazyResolutionPurposes <EOL> }

/**
 * Some symbols shouldn't be processed as a regular annotation owner and should be just skipped.
 * Example:
 * ```kotlin
 * fun foo() {
 * class Local {
 * fun localMemberWithoutType() = localMember()
 * fun localMember(): @Anno Int = 0
 * }
 * }
 * ```
 * Here `localMember` is the owner of `Anno`, but we shouldn't process it as a usual non-local declaration, because
 * this annotation cannot be leaked out of the body in not fully resolved state.
 *
 * @return true if this symbol shouldn't be processed as the owner of an annotation call
 */


internal fun FirDeclaration . forEachDeclarationWhichCanHavePostponedSymbols ( action : ( FirCallableDeclaration ) -> Unit )

{ <EOL> when ( this ) { <EOL> is FirCallableDeclaration -> action ( this ) <EOL> else -> { } <EOL> } <EOL> }

/**
 * Invoke [action] on each callable declaration that can have postponed symbols
 *
 * @see postponedSymbolsForAnnotationResolution
 */


internal fun FirBasedSymbol < * > . unwrapSymbolToPostpone ( ) : FirBasedSymbol < * >

= when ( this ) { <EOL> is FirValueParameterSymbol -> containingFunctionSymbol <EOL> else -> this <EOL> }

/**
 * @return a symbol which should be used as a member of [postponedSymbolsForAnnotationResolution] collection
 *
 * @see postponedSymbolsForAnnotationResolution
 */


internal fun FirBasedSymbol < * > . symbolToPostponeIfCanBeResolvedOnDemand ( ) : FirBasedSymbol < * > ?

{ <EOL> return unwrapSymbolToPostpone ( ) . takeUnless { it . cannotResolveAnnotationsOnDemand ( ) } <EOL> }

/**
 * @return an [unwrapped][unwrapSymbolToPostpone] symbol which [can][cannotResolveAnnotationsOnDemand] be resolved on demand
 *
 * @see unwrapSymbolToPostpone
 * @see cannotResolveAnnotationsOnDemand
 */


fun shrinkClasspath ( allClasses : List < AccessibleClassSnapshot > , lookupStorage : LookupStorage , metrics : MetricsReporter = MetricsReporter ( ) ) : List < AccessibleClassSnapshot >

{ <EOL> val lookupSymbols = metrics . getLookupSymbols { <EOL> lookupStorage . lookupSymbols <EOL> } <EOL> return shrinkClasses ( allClasses , lookupSymbols , metrics ) <EOL> }

/**
 * Shrinks the given classes by retaining only classes that are referenced by the lookup symbols stored in the given [LookupStorage].
 */


fun shrinkClasses ( allClasses : List < AccessibleClassSnapshot > , lookupSymbols : Collection < LookupSymbolKey > , metrics : MetricsReporter = MetricsReporter ( ) ) : List < AccessibleClassSnapshot >

{ <EOL> val referencedClasses = metrics . findReferencedClasses { <EOL> findReferencedClasses ( allClasses , lookupSymbols ) <EOL> } <EOL> return metrics . findTransitivelyReferencedClasses { <EOL> findTransitivelyReferencedClasses ( allClasses , referencedClasses ) <EOL> } <EOL> }

/**
 * Shrinks the given classes by retaining only classes that are referenced by the given lookup symbols.
 *
 * Note: We need to retain both directly and transitively referenced classes to compute the impact of classpath changes correctly (see
 * [ClasspathChangesComputer.computeChangedAndImpactedSet]).
 */


private fun findReferencedClasses ( allClasses : List < AccessibleClassSnapshot > , lookupSymbolKeys : Collection < LookupSymbolKey > ) : List < AccessibleClassSnapshot >

{ <EOL> val lookupSymbols = <EOL> LookupSymbolSet ( lookupSymbolKeys . asSequence ( ) . map { LookupSymbol ( name = it . name , scope = it . scope ) } . asIterable ( ) ) <EOL> val referencedClasses = allClasses . filter { clazz -> <EOL> when ( clazz ) { <EOL> is RegularKotlinClassSnapshot , is JavaClassSnapshot -> { <EOL> ClassSymbol ( clazz . classId ) . toLookupSymbol ( ) in lookupSymbols <EOL> || lookupSymbols . getLookupNamesInScope ( clazz . classId . asSingleFqName ( ) ) . isNotEmpty ( ) <EOL> } <EOL> is PackageFacadeKotlinClassSnapshot , is MultifileClassKotlinClassSnapshot -> { <EOL> val lookupNamesInScope = lookupSymbols . getLookupNamesInScope ( clazz . classId . packageFqName ) <EOL> if ( lookupNamesInScope . isEmpty ( ) ) return@filter false <EOL> val packageMemberNames = when ( clazz ) { <EOL> is PackageFacadeKotlinClassSnapshot -> clazz . packageMemberNames <EOL> else -> ( clazz as MultifileClassKotlinClassSnapshot ) . constantNames <EOL> } <EOL> packageMemberNames . any { it in lookupNamesInScope } <EOL> } <EOL> } <EOL> } <EOL> return referencedClasses <EOL> }

/**
 * Finds classes that are *directly* referenced by the given lookup symbols.
 *
 * Note: It's okay to over-approximate the result.
 */


private fun findTransitivelyReferencedClasses ( allClasses : List < AccessibleClassSnapshot > , referencedClasses : List < AccessibleClassSnapshot > ) : List < AccessibleClassSnapshot >

{ <EOL> val referencedClassIds = referencedClasses . map { it . classId } <EOL> val impactingClassesResolver = AllImpacts . getReverseResolver ( allClasses ) <EOL> val transitivelyReferencedClassIds : Set < ClassId > = <EOL> findReachableNodes ( referencedClassIds , impactingClassesResolver :: getImpactingClasses ) <EOL> return allClasses . filter { it . classId in transitivelyReferencedClassIds } <EOL> }

/**
 * Finds classes that are *transitively* referenced from the given classes. For example, if a subclass is referenced, its supertypes
 * will be transitively referenced.
 *
 * The returned list is *inclusive* (it contains the given list + the transitively referenced ones).
 */


internal fun ClasspathSnapshot . removeDuplicateAndInaccessibleClasses ( ) : List < AccessibleClassSnapshot >

{ <EOL> return getNonDuplicateClassSnapshots ( ) . filterIsInstance < AccessibleClassSnapshot > ( ) <EOL> }

/**
 * Removes duplicate classes and [InaccessibleClassSnapshot]s from the given [ClasspathSnapshot].
 *
 * To see why removing duplicate classes is important, consider this example:
 * - Current classpath: (Unchanged) jar2!/com/example/A.class containing A.foo, (Added) jar3!/com/example/A.class containing A.bar
 * - Previous classpath: (Removed) jar1!/com/example/A.class containing A.bar, (Unchanged) jar2!/com/example/A.class containing A.foo
 * Without removing duplicates, we might report that there are no changes (both the current classpath and previous classpath have A.foo and
 * A.bar). However, the correct report should be that A.bar is removed and A.foo is added because the second A class on each classpath does
 * not have any effect.
 *
 * It's also important to remove duplicate classes first before removing [InaccessibleClassSnapshot]s. For example, if
 * jar1!/com/example/A.class is inaccessible and jar2!/com/example/A.class is accessible, removing inaccessible classes first would mean
 * that jar2!/com/example/A.class would be kept whereas it shouldn't be since it is a duplicate class (keeping a duplicate class can
 * lead to incorrect change reports as shown in the previous example).
 *
 * That is also why we cannot remove inaccessible classes from each classpath entry in isolation (i.e., during classpath entry
 * snapshotting), even though it seems more efficient to do so. For correctness, we need to look at the entire classpath first, remove
 * duplicate classes, and then remove inaccessible classes.
 */


private fun ClasspathSnapshot . getNonDuplicateClassSnapshots ( ) : List < ClassSnapshot >

{ <EOL> val classSnapshots = LinkedHashMap < String , ClassSnapshot > ( classpathEntrySnapshots . sumOf { it . classSnapshots . size } ) <EOL> for ( classpathEntrySnapshot in classpathEntrySnapshots ) { <EOL> for ( ( unixStyleRelativePath , classSnapshot ) in classpathEntrySnapshot . classSnapshots ) { <EOL> classSnapshots . putIfAbsent ( unixStyleRelativePath , classSnapshot ) <EOL> } <EOL> } <EOL> return classSnapshots . values . toList ( ) <EOL> }

/**
 * Returns all [ClassSnapshot]s in this [ClasspathSnapshot].
 *
 * If there are duplicate classes on the classpath, retain only the first one to match the compiler's behavior.
 */


@ Test <EOL> fun `when compileOnly dependency is defined in commonTest, expect no warning` ( )

{ <EOL> val project = setupKmpProject { <EOL> kotlin { <EOL> sourceSets . apply { <EOL> commonTest { <EOL> dependencies { <EOL> compileOnly ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> project . runLifecycleAwareTest { <EOL> val diagnostics = kotlinToolingDiagnosticsCollector . getDiagnosticsForProject ( this ) <EOL> diagnostics . assertNoDiagnostics ( IncorrectCompileOnlyDependencyWarning ) <EOL> } <EOL> }

/**
 * The `compileOnly()` warning is only relevant for 'published' compilations.
 *
 * Verify `compileOnly()` dependencies in test sources do not trigger the warning.
 */


{ <EOL> }


@ OptIn ( InternalKotlinGradlePluginApi :: class ) <EOL> @ Deprecated ( message = KOTLIN_OPTIONS_DEPRECATION_MESSAGE ) <EOL> fun kotlinOptions ( fn : T . ( ) -> Unit )

{ <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> kotlinOptions . fn ( ) <EOL> }

/**
 * Configures the [kotlinOptions] with the provided configuration.
 */


@ OptIn ( InternalKotlinGradlePluginApi :: class ) <EOL> @ Deprecated ( message = KOTLIN_OPTIONS_DEPRECATION_MESSAGE ) <EOL> fun kotlinOptions ( fn : Action < in T > )

{ <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> fn . execute ( kotlinOptions ) <EOL> }


suspend fun compile ( snippets : Iterable < SourceCode > , configuration : ScriptCompilationConfiguration ) : ResultWithDiagnostics < LinkedSnippet < CompiledSnippetT > >

/**
 * Compiles snippet chain and returns compilation result for the *last* snippet in the chain.
 * Generally <b>changes</b> the internal state of implementing object.
 * @param snippets Chain of snippets to compile
 * @param configuration Compilation configuration which is used
 * @return Compilation result with the last compiled snippet in chain
 */


suspend fun compile ( snippet : SourceCode , configuration : ScriptCompilationConfiguration ) : ResultWithDiagnostics < LinkedSnippet < CompiledSnippetT > >

= compile ( listOf ( snippet ) , configuration )

/**
 * Compiles snippet and returns compilation result for it.
 * Generally <b>changes</b> the internal state of implementing object.
 * @param snippet Snippet to compile
 * @param configuration Compilation configuration which is used
 * @return Compilation result
 */


public fun < T > injectCoroutineContext ( publisher : Publisher < T > , coroutineContext : CoroutineContext ) : Publisher < T >

/**
 * Injects `ReactorContext` element from the given context into the `SubscriberContext` of the publisher.
 * This API used as an indirection layer between `reactive` and `reactor` modules.
 */


@ ExperimentalForeignApi <EOL> @ TypedIntrinsic ( IntrinsicType . IDENTITY ) <EOL> public external fun < T : NativePointed > interpretNullablePointed ( ptr : NativePtr ) : T ?

/**
 * Performs type cast of the native pointer to given interop type, including null values.
 *
 * @param T must not be abstract
 */


@ ExperimentalForeignApi <EOL> @ TypedIntrinsic ( IntrinsicType . IDENTITY ) <EOL> public external fun < T : CPointed > interpretCPointer ( rawValue : NativePtr ) : CPointer < T > ?

/**
 * Performs type cast of the [CPointer] from the given raw pointer.
 */


@ ExperimentalForeignApi <EOL> @ TypedIntrinsic ( IntrinsicType . INTEROP_STATIC_C_FUNCTION ) <EOL> public external fun < R > staticCFunction ( @ VolatileLambda function : ( ) -> R ) : CPointer < CFunction < ( ) -> R > >

/**
 * Returns a pointer to C function which calls given Kotlin *static* function.
 *
 * @param function must be *static*, i.e. an (unbound) reference to a Kotlin function or
 * a closure which doesn't capture any variable
 */


private fun createSampleBody ( imports : List < String > , body : String )

= <EOL> """<STR_LIT>""" . trimMargin ( )

/**
 * If both [imports] and [body] are present, it should return
 *
 * ```kotlin
 * import com.example.One
 * import com.example.Two
 *
 * fun main() {
 * //sampleStart
 * println("Sample function body")
 * println("Another line")
 * //sampleEnd
 * }
 * ```
 *
 * If [imports] are empty, it should return:
 *
 * ```kotlin
 * fun main() {
 * //sampleStart
 * println("Sample function body")
 * println("Another line")
 * //sampleEnd
 * }
 * ```
 *
 * Notice the presence/absence of the new line before the body.
 */


private fun addKotlinDependenciesToAndroidSourceSets ( project : Project )

{ <EOL> fun addDependenciesToAndroidSourceSet ( @ Suppress ( "<STR_LIT:TYPEALIAS_EXPANSION_DEPRECATION>" ) androidSourceSet : DeprecatedAndroidSourceSet , apiConfigurationName : String , implementationConfigurationName : String , compileOnlyConfigurationName : String , runtimeOnlyConfigurationName : String ) { <EOL> if ( project . configurations . findByName ( androidSourceSet . apiConfigurationName ) != null ) { <EOL> project . addExtendsFromRelation ( androidSourceSet . apiConfigurationName , apiConfigurationName ) <EOL> } else { <EOL> project . configurations . getByName ( apiConfigurationName ) . dependencies . all { <EOL> throw InvalidUserCodeException ( "<STR_LIT>" + "<STR_LIT>" ) <EOL> } <EOL> } <EOL> project . addExtendsFromRelation ( androidSourceSet . implementationConfigurationName , implementationConfigurationName ) <EOL> project . addExtendsFromRelation ( androidSourceSet . compileOnlyConfigurationName , compileOnlyConfigurationName ) <EOL> project . addExtendsFromRelation ( androidSourceSet . runtimeOnlyConfigurationName , runtimeOnlyConfigurationName ) <EOL> } <EOL> ( project . extensions . getByName ( "<STR_LIT>" ) as BaseExtension ) . sourceSets . forEach { androidSourceSet -> <EOL> project . findKotlinSourceSet ( androidSourceSet ) ? . let { kotlinSourceSet -> <EOL> addDependenciesToAndroidSourceSet ( androidSourceSet , kotlinSourceSet . apiConfigurationName , kotlinSourceSet . implementationConfigurationName , kotlinSourceSet . compileOnlyConfigurationName , kotlinSourceSet . runtimeOnlyConfigurationName ) <EOL> } <EOL> } <EOL> }

/**
 * The Android variants have their configurations extendsFrom relation set up in a way that only some of the configurations of the
 * variants propagate the dependencies from production variants to test ones. To make this dependency propagation work for the Kotlin
 * source set dependencies as well, we need to add them to the Android source sets' api/implementation-like configurations,
 * not just the classpath-like configurations of the variants.
 */


private fun MemberScope . collectClasses ( collector : MutableCollection < ClassDescriptor > )

{ <EOL> getContributedDescriptors ( ) <EOL> . asSequence ( ) <EOL> . filterIsInstance < ClassDescriptor > ( ) <EOL> . forEach { <EOL> collector += it <EOL> if ( mapper . shouldBeExposed ( it ) ) { <EOL> it . unsubstitutedMemberScope . collectClasses ( collector ) <EOL> } <EOL> } <EOL> }

/**
 * Recursively collect classes into [collector].
 * We need to do so because we want to make the order of declarations stable.
 */


{ <EOL> while ( extraClassesToTranslate . isNotEmpty ( ) ) { <EOL> val descriptor = extraClassesToTranslate . first ( ) <EOL> extraClassesToTranslate -= descriptor <EOL> assert ( shouldTranslateExtraClass ( descriptor ) ) { "<STR_LIT>" } <EOL> if ( descriptor . isInterface ) { <EOL> generateInterface ( descriptor ) <EOL> } else { <EOL> generateClass ( descriptor ) <EOL> } <EOL> } <EOL> }

/**
 * Translates additional classes referenced from the module's declarations, such as parameter types, return types,
 * thrown exception types, and underlying enum types.
 *
 * This is required for classes from dependencies to be exported correctly. However, we also currently rely on this
 * for a few edge cases, such as some inner classes. Sub classes may reject certain descriptors to be translated.
 * Some referenced descriptors may be translated early for ordering reasons.
 * @see shouldTranslateExtraClass
 * @see generateExtraClassEarly
 * @see generateExtraInterfaceEarly
 */


private fun writeUtf8CodePoint ( codePoint : Int )

{ <EOL> when { <EOL> codePoint < <NUM_LIT> -> { <EOL> ensure ( <NUM_LIT:1> ) <EOL> write ( codePoint ) <EOL> } <EOL> codePoint < <NUM_LIT> -> { <EOL> ensure ( <NUM_LIT:2> ) <EOL> write ( codePoint shr <NUM_LIT:6> or <NUM_LIT> ) <EOL> write ( codePoint and <NUM_LIT> or <NUM_LIT> ) <EOL> } <EOL> codePoint in <NUM_LIT> .. <NUM_LIT> -> { <EOL> ensure ( <NUM_LIT:1> ) <EOL> write ( '<CHAR_LIT>' . code ) <EOL> } <EOL> codePoint < <NUM_LIT> -> { <EOL> ensure ( <NUM_LIT:3> ) <EOL> write ( codePoint shr <NUM_LIT:12> or <NUM_LIT> ) <EOL> write ( codePoint shr <NUM_LIT:6> and <NUM_LIT> or <NUM_LIT> ) <EOL> write ( codePoint and <NUM_LIT> or <NUM_LIT> ) <EOL> } <EOL> codePoint <= <NUM_LIT> -> { <EOL> ensure ( <NUM_LIT:4> ) <EOL> write ( codePoint shr <NUM_LIT> or <NUM_LIT> ) <EOL> write ( codePoint shr <NUM_LIT:12> and <NUM_LIT> or <NUM_LIT> ) <EOL> write ( codePoint shr <NUM_LIT:6> and <NUM_LIT> or <NUM_LIT> ) <EOL> write ( codePoint and <NUM_LIT> or <NUM_LIT> ) <EOL> } <EOL> else -> { <EOL> throw JsonEncodingException ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * Sources taken from okio library with minor changes, see https://github.com/square/okio
 */