@ ExperimentalSerializationApi <EOL> public fun ProtoBuf ( from : ProtoBuf = ProtoBuf , builderAction : ProtoBufBuilder . ( ) -> Unit ) : ProtoBuf

{ <EOL> val b = ProtoBufBuilder ( from ) <EOL> b . builderAction ( ) <EOL> return ProtoBufImpl ( b . encodeDefaults , b . serializersModule ) <EOL> }

/**
 * Creates an instance of [ProtoBuf] configured from the optionally given [ProtoBuf instance][from]
 * and adjusted with [builderAction].
 */


inline fun < T , R > Collection < T > . memoryOptimizedMap ( transform : ( T ) -> R ) : List < R >

{ <EOL> return mapTo ( ArrayList < R > ( size ) , transform ) . compactIfPossible ( ) <EOL> }

/**
 * A memory-optimized version of [Iterable.map].
 * @see Iterable.map
 */


inline fun < T , R > Collection < T > . memoryOptimizedMapIndexed ( transform : ( index : Int , T ) -> R ) : List < R >

{ <EOL> return mapIndexedTo ( ArrayList < R > ( size ) , transform ) . compactIfPossible ( ) <EOL> }

/**
 * A memory-optimized version of [Iterable.mapIndexed].
 * @see Iterable.mapIndexed
 */


inline fun < T , R : Any > Collection < T > . memoryOptimizedMapNotNull ( transform : ( T ) -> R ? ) : List < R >

{ <EOL> return mapNotNullTo ( ArrayList ( ) , transform ) . compactIfPossible ( ) <EOL> }

/**
 * A memory-optimized version of [Iterable.mapNotNull].
 * @see Iterable.mapNotNull
 */


inline fun < T , R > Collection < T > . memoryOptimizedFlatMap ( transform : ( T ) -> Iterable < R > ) : List < R >

{ <EOL> return flatMapTo ( ArrayList < R > ( ) , transform ) . compactIfPossible ( ) <EOL> }

/**
 * A memory-optimized version of [Iterable.flatMap].
 * @see Iterable.flatMap
 */


inline fun < T > Collection < T > . memoryOptimizedFilter ( predicate : ( T ) -> Boolean ) : List < T >

{ <EOL> return filterTo ( ArrayList ( ) , predicate ) . compactIfPossible ( ) <EOL> }

/**
 * A memory-optimized version of [Iterable.filter].
 * @see Iterable.filter
 */


inline fun < T > Collection < T > . memoryOptimizedFilterNot ( predicate : ( T ) -> Boolean ) : List < T >

{ <EOL> return filterNotTo ( ArrayList ( ) , predicate ) . compactIfPossible ( ) <EOL> }

/**
 * A memory-optimized version of [Iterable.filterNot].
 * @see Iterable.filterNot
 */


inline fun < reified T > Collection < * > . memoryOptimizedFilterIsInstance ( ) : List < T >

{ <EOL> return filterIsInstanceTo ( ArrayList < T > ( ) ) . compactIfPossible ( ) <EOL> }

/**
 * A memory-optimized version of [Iterable.filterIsInstance].
 * @see Iterable.filterIsInstance
 */


infix fun < T > List < T > . memoryOptimizedPlus ( elements : List < T > ) : List < T >

= <EOL> when ( val resultSize = size + elements . size ) { <EOL> <NUM_LIT:0> -> emptyList ( ) <EOL> <NUM_LIT:1> -> Collections . singletonList ( if ( isEmpty ( ) ) elements . first ( ) else first ( ) ) <EOL> else -> ArrayList < T > ( resultSize ) . also { <EOL> it . addAll ( this ) <EOL> it . addAll ( elements ) <EOL> } <EOL> }

/**
 * A memory-optimized version of [Iterable.plus].
 * @see Iterable.plus
 */


infix fun < T > List < T > . memoryOptimizedPlus ( element : T ) : List < T >

= <EOL> when ( size ) { <EOL> <NUM_LIT:0> -> Collections . singletonList ( element ) <EOL> else -> ArrayList < T > ( size + <NUM_LIT:1> ) . also { <EOL> it . addAll ( this ) <EOL> it . add ( element ) <EOL> } <EOL> }


infix fun < T , R > Collection < T > . memoryOptimizedZip ( other : Collection < R > ) : List < Pair < T , R > >

{ <EOL> return when { <EOL> isEmpty ( ) || other . isEmpty ( ) -> emptyList ( ) <EOL> min ( size , other . size ) == <NUM_LIT:1> -> listOf ( first ( ) to other . first ( ) ) <EOL> else -> zip ( other ) { t1 , t2 -> t1 to t2 } <EOL> } <EOL> }

/**
 * A memory-optimized version of [Iterable.zip].
 * @see Iterable.zip
 */


fun < T > Sequence < T > . atMostOne ( ) : T ?

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

/**
 * [Sequence] variant of [org.jetbrains.kotlin.utils.atMostOne]
 *
 * So, when:
 * - there is no element then `null` will be returned
 * - there is a single element then the element will be returned
 * - there is more than one element then the error will be thrown
 * @see org.jetbrains.kotlin.utils.atMostOne
 */


inline fun < reified T > Iterable < * > . findIsInstanceAnd ( predicate : ( T ) -> Boolean ) : T ?

{ <EOL> for ( element in this ) { <EOL> if ( element is T && predicate ( element ) ) { <EOL> return element <EOL> } <EOL> } <EOL> return null <EOL> }

/**
 * The variant of [org.jetbrains.kotlin.util.collectionUtils.filterIsInstanceAnd] extension function but to find the first element
 * which is an instance of type [T] and satisfies [predicate] condition
 * @see org.jetbrains.kotlin.util.collectionUtils.filterIsInstanceAnd
 */


fun < T > Collection < T > . toSmartList ( ) : List < T >

= SmartList < T > ( this )

/**
 * The same as [Collection.toMutableList] extension function, but it returns a SmartList which is better with in sense of memory consumption
 * @see Collection.toMutableList
 */


@ OptIn ( FrontendInternals :: class ) <EOL> fun ResolutionFacade . getLanguageVersionSettings ( ) : LanguageVersionSettings

= <EOL> frontendService < LanguageVersionSettings > ( )

/**
 * Helper methods for commonly used frontend components.
 * Use them to avoid explicit opt-ins.
 * Before adding a new helper method please make sure component doesn't have fragile invariants that can be violated by external use.
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun ByteArray . toHexString ( format : HexFormat = HexFormat . Default ) : String

= toHexString ( <NUM_LIT:0> , size , format )

/**
 * Formats bytes in this array using the specified [format].
 *
 * Note that only [HexFormat.upperCase] and [HexFormat.BytesHexFormat] affect formatting.
 *
 * @param format the [HexFormat] to use for formatting, [HexFormat.Default] by default.
 *
 * @throws IllegalArgumentException if the result length is more than [String] maximum capacity.
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun ByteArray . toHexString ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = size , format : HexFormat = HexFormat . Default ) : String

{ <EOL> AbstractList . checkBoundsIndexes ( startIndex , endIndex , size ) <EOL> if ( startIndex == endIndex ) { <EOL> return "<STR_LIT>" <EOL> } <EOL> val byteToDigits = if ( format . upperCase ) BYTE_TO_UPPER_CASE_HEX_DIGITS else BYTE_TO_LOWER_CASE_HEX_DIGITS <EOL> val bytesFormat = format . bytes <EOL> if ( bytesFormat . noLineAndGroupSeparator ) { <EOL> return toHexStringNoLineAndGroupSeparator ( startIndex , endIndex , bytesFormat , byteToDigits ) <EOL> } <EOL> return toHexStringSlowPath ( startIndex , endIndex , bytesFormat , byteToDigits ) <EOL> }

/**
 * Formats bytes in this array using the specified [HexFormat].
 *
 * Note that only [HexFormat.upperCase] and [HexFormat.BytesHexFormat] affect formatting.
 *
 * @param startIndex the beginning (inclusive) of the subrange to format, 0 by default.
 * @param endIndex the end (exclusive) of the subrange to format, size of this array by default.
 * @param format the [HexFormat] to use for formatting, [HexFormat.Default] by default.
 *
 * @throws IndexOutOfBoundsException when [startIndex] or [endIndex] is out of range of this array indices.
 * @throws IllegalArgumentException when `startIndex > endIndex`.
 * @throws IllegalArgumentException if the result length is more than [String] maximum capacity.
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun String . hexToByteArray ( format : HexFormat = HexFormat . Default ) : ByteArray

= hexToByteArray ( <NUM_LIT:0> , length , format )

/**
 * Parses bytes from this string using the specified [HexFormat].
 *
 * Note that only [HexFormat.BytesHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 * Also, any of the char sequences CRLF, LF and CR is considered a valid line separator.
 *
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IllegalArgumentException if this string does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> private fun String . hexToByteArray ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = length , format : HexFormat = HexFormat . Default ) : ByteArray

{ <EOL> AbstractList . checkBoundsIndexes ( startIndex , endIndex , length ) <EOL> if ( startIndex == endIndex ) { <EOL> return byteArrayOf ( ) <EOL> } <EOL> val bytesFormat = format . bytes <EOL> if ( bytesFormat . noLineAndGroupSeparator ) { <EOL> hexToByteArrayNoLineAndGroupSeparator ( startIndex , endIndex , bytesFormat ) ? . let { return it } <EOL> } <EOL> return hexToByteArraySlowPath ( startIndex , endIndex , bytesFormat ) <EOL> }

/**
 * Parses bytes from this string using the specified [HexFormat].
 *
 * Note that only [HexFormat.BytesHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 * Also, any of the char sequences CRLF, LF and CR is considered a valid line separator.
 *
 * @param startIndex the beginning (inclusive) of the substring to parse, 0 by default.
 * @param endIndex the end (exclusive) of the substring to parse, length of this string by default.
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IndexOutOfBoundsException when [startIndex] or [endIndex] is out of range of this string indices.
 * @throws IllegalArgumentException when `startIndex > endIndex`.
 * @throws IllegalArgumentException if the substring does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun Byte . toHexString ( format : HexFormat = HexFormat . Default ) : String

{ <EOL> val digits = if ( format . upperCase ) UPPER_CASE_HEX_DIGITS else LOWER_CASE_HEX_DIGITS <EOL> val numberFormat = format . number <EOL> if ( numberFormat . isDigitsOnly ) { <EOL> val charArray = CharArray ( <NUM_LIT:2> ) <EOL> val value = this . toInt ( ) <EOL> charArray [ <NUM_LIT:0> ] = digits [ ( value shr <NUM_LIT:4> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:1> ] = digits [ value and <NUM_LIT> ] <EOL> return if ( numberFormat . removeLeadingZeros ) <EOL> charArray . concatToString ( startIndex = ( countLeadingZeroBits ( ) shr <NUM_LIT:2> ) . coerceAtMost ( <NUM_LIT:1> ) ) <EOL> else <EOL> charArray . concatToString ( ) <EOL> } <EOL> return toLong ( ) . toHexStringImpl ( numberFormat , digits , bits = <NUM_LIT:8> ) <EOL> }

/**
 * Formats this `Byte` value using the specified [format].
 *
 * Note that only [HexFormat.upperCase] and [HexFormat.NumberHexFormat] affect formatting.
 *
 * @param format the [HexFormat] to use for formatting, [HexFormat.Default] by default.
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun String . hexToByte ( format : HexFormat = HexFormat . Default ) : Byte

= hexToByte ( <NUM_LIT:0> , length , format )

/**
 * Parses a `Byte` value from this string using the specified [format].
 *
 * Note that only [HexFormat.NumberHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 *
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IllegalArgumentException if this string does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> private fun String . hexToByte ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = length , format : HexFormat = HexFormat . Default ) : Byte

= <EOL> hexToIntImpl ( startIndex , endIndex , format , maxDigits = <NUM_LIT:2> ) . toByte ( )

/**
 * Parses a `Byte` value from this string using the specified [format].
 *
 * Note that only [HexFormat.NumberHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 *
 * @param startIndex the beginning (inclusive) of the substring to parse, 0 by default.
 * @param endIndex the end (exclusive) of the substring to parse, length of this string by default.
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IndexOutOfBoundsException when [startIndex] or [endIndex] is out of range of this string indices.
 * @throws IllegalArgumentException when `startIndex > endIndex`.
 * @throws IllegalArgumentException if the substring does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun Short . toHexString ( format : HexFormat = HexFormat . Default ) : String

{ <EOL> val digits = if ( format . upperCase ) UPPER_CASE_HEX_DIGITS else LOWER_CASE_HEX_DIGITS <EOL> val numberFormat = format . number <EOL> if ( numberFormat . isDigitsOnly ) { <EOL> val charArray = CharArray ( <NUM_LIT:4> ) <EOL> val value = this . toInt ( ) <EOL> charArray [ <NUM_LIT:0> ] = digits [ ( value shr <NUM_LIT:12> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:1> ] = digits [ ( value shr <NUM_LIT:8> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:2> ] = digits [ ( value shr <NUM_LIT:4> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:3> ] = digits [ value and <NUM_LIT> ] <EOL> return if ( numberFormat . removeLeadingZeros ) <EOL> charArray . concatToString ( startIndex = ( countLeadingZeroBits ( ) shr <NUM_LIT:2> ) . coerceAtMost ( <NUM_LIT:3> ) ) <EOL> else <EOL> charArray . concatToString ( ) <EOL> } <EOL> return toLong ( ) . toHexStringImpl ( numberFormat , digits , bits = <NUM_LIT:16> ) <EOL> }

/**
 * Formats this `Short` value using the specified [format].
 *
 * Note that only [HexFormat.upperCase] and [HexFormat.NumberHexFormat] affect formatting.
 *
 * @param format the [HexFormat] to use for formatting, [HexFormat.Default] by default.
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun String . hexToShort ( format : HexFormat = HexFormat . Default ) : Short

= hexToShort ( <NUM_LIT:0> , length , format )

/**
 * Parses a `Short` value from this string using the specified [format].
 *
 * Note that only [HexFormat.NumberHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 *
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IllegalArgumentException if this string does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> private fun String . hexToShort ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = length , format : HexFormat = HexFormat . Default ) : Short

= <EOL> hexToIntImpl ( startIndex , endIndex , format , maxDigits = <NUM_LIT:4> ) . toShort ( )

/**
 * Parses a `Short` value from this string using the specified [format].
 *
 * Note that only [HexFormat.NumberHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 *
 * @param startIndex the beginning (inclusive) of the substring to parse, 0 by default.
 * @param endIndex the end (exclusive) of the substring to parse, length of this string by default.
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IndexOutOfBoundsException when [startIndex] or [endIndex] is out of range of this string indices.
 * @throws IllegalArgumentException when `startIndex > endIndex`.
 * @throws IllegalArgumentException if the substring does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun Int . toHexString ( format : HexFormat = HexFormat . Default ) : String

{ <EOL> val digits = if ( format . upperCase ) UPPER_CASE_HEX_DIGITS else LOWER_CASE_HEX_DIGITS <EOL> val numberFormat = format . number <EOL> if ( numberFormat . isDigitsOnly ) { <EOL> val charArray = CharArray ( <NUM_LIT:8> ) <EOL> val value = this <EOL> charArray [ <NUM_LIT:0> ] = digits [ ( value shr <NUM_LIT> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:1> ] = digits [ ( value shr <NUM_LIT> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:2> ] = digits [ ( value shr <NUM_LIT:20> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:3> ] = digits [ ( value shr <NUM_LIT:16> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:4> ] = digits [ ( value shr <NUM_LIT:12> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:5> ] = digits [ ( value shr <NUM_LIT:8> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:6> ] = digits [ ( value shr <NUM_LIT:4> ) and <NUM_LIT> ] <EOL> charArray [ <NUM_LIT:7> ] = digits [ value and <NUM_LIT> ] <EOL> return if ( numberFormat . removeLeadingZeros ) <EOL> charArray . concatToString ( startIndex = ( countLeadingZeroBits ( ) shr <NUM_LIT:2> ) . coerceAtMost ( <NUM_LIT:7> ) ) <EOL> else <EOL> charArray . concatToString ( ) <EOL> } <EOL> return toLong ( ) . toHexStringImpl ( numberFormat , digits , bits = <NUM_LIT> ) <EOL> }

/**
 * Formats this `Int` value using the specified [format].
 *
 * Note that only [HexFormat.upperCase] and [HexFormat.NumberHexFormat] affect formatting.
 *
 * @param format the [HexFormat] to use for formatting, [HexFormat.Default] by default.
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun String . hexToInt ( format : HexFormat = HexFormat . Default ) : Int

= hexToInt ( <NUM_LIT:0> , length , format )

/**
 * Parses an `Int` value from this string using the specified [format].
 *
 * Note that only [HexFormat.NumberHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 *
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IllegalArgumentException if this string does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> private fun String . hexToInt ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = length , format : HexFormat = HexFormat . Default ) : Int

= <EOL> hexToIntImpl ( startIndex , endIndex , format , maxDigits = <NUM_LIT:8> )

/**
 * Parses an `Int` value from this string using the specified [format].
 *
 * Note that only [HexFormat.NumberHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 *
 * @param startIndex the beginning (inclusive) of the substring to parse, 0 by default.
 * @param endIndex the end (exclusive) of the substring to parse, length of this string by default.
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IndexOutOfBoundsException when [startIndex] or [endIndex] is out of range of this string indices.
 * @throws IllegalArgumentException when `startIndex > endIndex`.
 * @throws IllegalArgumentException if the substring does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun Long . toHexString ( format : HexFormat = HexFormat . Default ) : String

{ <EOL> val digits = if ( format . upperCase ) UPPER_CASE_HEX_DIGITS else LOWER_CASE_HEX_DIGITS <EOL> val numberFormat = format . number <EOL> if ( numberFormat . isDigitsOnly ) { <EOL> val charArray = CharArray ( <NUM_LIT:16> ) <EOL> val value = this <EOL> charArray [ <NUM_LIT:0> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:1> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:2> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:3> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:4> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:5> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:6> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:7> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:8> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:9> ] = digits [ ( ( value shr <NUM_LIT> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:10> ] = digits [ ( ( value shr <NUM_LIT:20> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:11> ] = digits [ ( ( value shr <NUM_LIT:16> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT:12> ] = digits [ ( ( value shr <NUM_LIT:12> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT> ] = digits [ ( ( value shr <NUM_LIT:8> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT> ] = digits [ ( ( value shr <NUM_LIT:4> ) and <NUM_LIT> ) . toInt ( ) ] <EOL> charArray [ <NUM_LIT> ] = digits [ ( value and <NUM_LIT> ) . toInt ( ) ] <EOL> return if ( numberFormat . removeLeadingZeros ) <EOL> charArray . concatToString ( startIndex = ( countLeadingZeroBits ( ) shr <NUM_LIT:2> ) . coerceAtMost ( <NUM_LIT> ) ) <EOL> else <EOL> charArray . concatToString ( ) <EOL> } <EOL> return toHexStringImpl ( numberFormat , digits , bits = <NUM_LIT> ) <EOL> }

/**
 * Formats this `Long` value using the specified [format].
 *
 * Note that only [HexFormat.upperCase] and [HexFormat.NumberHexFormat] affect formatting.
 *
 * @param format the [HexFormat] to use for formatting, [HexFormat.Default] by default.
 */


@ ExperimentalStdlibApi <EOL> @ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> public fun String . hexToLong ( format : HexFormat = HexFormat . Default ) : Long

= hexToLong ( <NUM_LIT:0> , length , format )

/**
 * Parses a `Long` value from this string using the specified [format].
 *
 * Note that only [HexFormat.NumberHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 *
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IllegalArgumentException if this string does not comply with the specified [format].
 */


@ ExperimentalStdlibApi <EOL> private fun String . hexToLong ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = length , format : HexFormat = HexFormat . Default ) : Long

= <EOL> hexToLongImpl ( startIndex , endIndex , format , maxDigits = <NUM_LIT:16> )

/**
 * Parses a `Long` value from this string using the specified [format].
 *
 * Note that only [HexFormat.NumberHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 *
 * @param startIndex the beginning (inclusive) of the substring to parse, 0 by default.
 * @param endIndex the end (exclusive) of the substring to parse, length of this string by default.
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IndexOutOfBoundsException when [startIndex] or [endIndex] is out of range of this string indices.
 * @throws IllegalArgumentException when `startIndex > endIndex`.
 * @throws IllegalArgumentException if the substring does not comply with the specified [format].
 */


@ InternalSerializationApi <EOL> public open fun findPolymorphicSerializerOrNull ( decoder : CompositeDecoder , klassName : String ? <EOL> ) : DeserializationStrategy < T > ?

= decoder . serializersModule . getPolymorphic ( baseClass , klassName )

/**
 * Lookups an actual serializer for given [klassName] withing the current [base class][baseClass].
 * May use context from the [decoder].
 */


@ InternalSerializationApi <EOL> public open fun findPolymorphicSerializerOrNull ( encoder : Encoder , value : T ) : SerializationStrategy < T > ?

= <EOL> encoder . serializersModule . getPolymorphic ( baseClass , value )

/**
 * Lookups an actual serializer for given [value] within the current [base class][baseClass].
 * May use context from the [encoder].
 */


fun module ( moduleName : String , dependencies : List < ScenarioModule > = emptyList ( ) , additionalCompilationArguments : List < String > = emptyList ( ) , compilationOptionsModifier : ( ( JvmCompilationConfiguration ) -> Unit ) ? = null , incrementalCompilationOptionsModifier : ( ( IncrementalJvmCompilationConfiguration < * > ) -> Unit ) ? = null , ) : ScenarioModule

/**
 * Creates a module for a scenario.
 *
 * Modules with the same combination of [Module.scenarioDslCacheKey], [compilationOptionsModifier], and [incrementalCompilationOptionsModifier] are compiled initially only once per tests run.
 *
 * In the case you are using custom values for [compilationOptionsModifier] or [incrementalCompilationOptionsModifier], consider sharing the same lambda between tests for better cacheability results.
 *
 * @param moduleName The name of the module.
 * @param dependencies (optional) The list of scenario modules that this module depends on. Defaults to an empty list.
 * @param additionalCompilationArguments (optional) The list of additional compilation arguments for this module. Defaults to an empty list.
 * @param compilationOptionsModifier (optional) A function that can be used to modify the compilation configuration for this module.
 * @param incrementalCompilationOptionsModifier (optional) A function that can be used to modify the incremental compilation configuration for this module.
 * @return The created scenario module in the compiled state.
 */


fun println ( vararg objects : Any ? ) : IndentingPrinter

/**
 * Prints [objects] by concatenating the results of their [Any.toString] calls, also appending a line break at the end.
 *
 * @return `this`
 */


fun print ( vararg objects : Any ? ) : IndentingPrinter

/**
 * Prints [objects] by concatenating the results of their [Any.toString] calls.
 *
 * @return `this`
 */


fun pushIndent ( ) : IndentingPrinter

/**
 * Increases the indentation level by one.
 *
 * @return `this`
 */


fun popIndent ( ) : IndentingPrinter

/**
 * Decreases the indentation level by one.
 *
 * @return `this`
 */


override fun toString ( ) : String


inline fun IndentingPrinter . withIndent ( block : ( ) -> Unit )

{ <EOL> pushIndent ( ) <EOL> block ( ) <EOL> popIndent ( ) <EOL> }

/**
 * The text printed within [block] will be indented.
 */


public fun tryLock ( owner : Any ? = null ) : Boolean

/**
 * Tries to lock this mutex, returning `false` if this mutex is already locked.
 *
 * It is recommended to use [withLock] for safety reasons, so that the acquired lock is always
 * released at the end of your critical section, and [unlock] is never invoked before a successful
 * lock acquisition.
 *
 * @param owner Optional owner token for debugging. When `owner` is specified (non-null value) and this mutex
 * is already locked with the same token (same identity), this function throws [IllegalStateException].
 */


public suspend fun lock ( owner : Any ? = null )

/**
 * Locks this mutex, suspending caller until the lock is acquired (in other words, while the lock is held elsewhere).
 *
 * This suspending function is cancellable: if the [Job] of the current coroutine is cancelled while this
 * suspending function is waiting, this function immediately resumes with [CancellationException].
 * There is a **prompt cancellation guarantee**: even if this function is ready to return the result, but was cancelled
 * while suspended, [CancellationException] will be thrown. See [suspendCancellableCoroutine] for low-level details.
 * This function releases the lock if it was already acquired by this function before the [CancellationException]
 * was thrown.
 *
 * Note that this function does not check for cancellation when it is not suspended.
 * Use [yield] or [CoroutineScope.isActive] to periodically check for cancellation in tight loops if needed.
 *
 * Use [tryLock] to try acquiring the lock without waiting.
 *
 * This function is fair; suspended callers are resumed in first-in-first-out order.
 *
 * It is recommended to use [withLock] for safety reasons, so that the acquired lock is always
 * released at the end of the critical section, and [unlock] is never invoked before a successful
 * lock acquisition.
 *
 * @param owner Optional owner token for debugging. When `owner` is specified (non-null value) and this mutex
 * is already locked with the same token (same identity), this function throws [IllegalStateException].
 */


public fun holdsLock ( owner : Any ) : Boolean

/**
 * Checks whether this mutex is locked by the specified owner.
 *
 * @return `true` when this mutex is locked by the specified owner;
 * `false` if the mutex is not locked or locked by another owner.
 */


public fun unlock ( owner : Any ? = null )

/**
 * Unlocks this mutex. Throws [IllegalStateException] if invoked on a mutex that is not locked or
 * was locked with a different owner token (by identity).
 *
 * It is recommended to use [withLock] for safety reasons, so that the acquired lock is always
 * released at the end of the critical section, and [unlock] is never invoked before a successful
 * lock acquisition.
 *
 * @param owner Optional owner token for debugging. When `owner` is specified (non-null value) and this mutex
 * was locked with the different token (by identity), this function throws [IllegalStateException].
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public fun Mutex ( locked : Boolean = false ) : Mutex

= <EOL> MutexImpl ( locked )

/**
 * Creates a [Mutex] instance.
 * The mutex created is fair: lock is granted in first come, first served order.
 *
 * @param locked initial state of the mutex.
 */


@ OptIn ( ExperimentalContracts :: class ) <EOL> public suspend inline fun < T > Mutex . withLock ( owner : Any ? = null , action : ( ) -> T ) : T

{ <EOL> contract { <EOL> callsInPlace ( action , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> lock ( owner ) <EOL> return try { <EOL> action ( ) <EOL> } finally { <EOL> unlock ( owner ) <EOL> } <EOL> }

/**
 * Executes the given [action] under this mutex's lock.
 *
 * @param owner Optional owner token for debugging. When `owner` is specified (non-null value) and this mutex
 * is already locked with the same token (same identity), this function throws [IllegalStateException].
 *
 * @return the return value of the action.
 */


private fun holdsLockImpl ( owner : Any ? ) : Int

{ <EOL> while ( true ) { <EOL> if ( ! isLocked ) return HOLDS_LOCK_UNLOCKED <EOL> val curOwner = this . owner . value <EOL> if ( curOwner === NO_OWNER ) continue <EOL> return if ( curOwner === owner ) HOLDS_LOCK_YES else HOLDS_LOCK_ANOTHER_OWNER <EOL> } <EOL> }

/**
 * [HOLDS_LOCK_UNLOCKED] if the mutex is unlocked
 * [HOLDS_LOCK_YES] if the mutex is held with the specified [owner]
 * [HOLDS_LOCK_ANOTHER_OWNER] if the mutex is held with a different owner
 */


@ DisplayName ( "<STR_LIT>" ) <EOL> @ GradleAndroidTest <EOL> fun testKT49798AgpVersionAttrNotPublished ( gradleVersion : GradleVersion , agpVersion : String , jdkVersion : JdkVersions . ProvidedJdk , )

{ <EOL> project ( "<STR_LIT>" , gradleVersion , buildOptions = defaultBuildOptions . copy ( androidVersion = agpVersion ) , buildJdk = jdkVersion . location ) { <EOL> build ( "<STR_LIT>" ) { <EOL> val libProject = subProject ( "<STR_LIT:lib>" ) <EOL> val debugPublicationDirectory = libProject . projectPath . resolve ( "<STR_LIT>" ) <EOL> val releasePublicationDirectory = libProject . projectPath . resolve ( "<STR_LIT>" ) <EOL> listOf ( debugPublicationDirectory , releasePublicationDirectory ) . forEach { publicationDirectory -> <EOL> assertDirectoryExists ( publicationDirectory ) <EOL> val moduleFiles = Files . walk ( publicationDirectory ) . use { it . filter { file -> file . extension == "<STR_LIT>" } . toList ( ) } <EOL> assertTrue ( moduleFiles . isNotEmpty ( ) , "<STR_LIT>" ) <EOL> assertTrue ( moduleFiles . size == <NUM_LIT:1> , "<STR_LIT>" ) <EOL> val moduleFile = moduleFiles . single ( ) <EOL> val moduleFileText = moduleFile . readText ( ) <EOL> assertTrue ( "<STR_LIT>" !in moduleFileText , "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Starting from AGP version 7.1.0-alpha13, a new attribute com.android.build.api.attributes.AgpVersionAttr was added.
 * This attribute is *not intended* to be published.
 */


= lastScheduledTask . getAndSet ( null ) ? : pollBuffer ( )

/**
 * Retrieves and removes task from the head of the queue
 * Invariant: this method is called only by the owner of the queue.
 */


fun add ( task : Task , fair : Boolean = false ) : Task ?

{ <EOL> if ( fair ) return addLast ( task ) <EOL> val previous = lastScheduledTask . getAndSet ( task ) ? : return null <EOL> return addLast ( previous ) <EOL> }

/**
 * Invariant: Called only by the owner of the queue, returns
 * `null` if task was added, task that wasn't added otherwise.
 */


private fun addLast ( task : Task ) : Task ?

{ <EOL> if ( bufferSize == BUFFER_CAPACITY - <NUM_LIT:1> ) return task <EOL> if ( task . isBlocking ) blockingTasksInBuffer . incrementAndGet ( ) <EOL> val nextIndex = producerIndex . value and MASK <EOL> while ( buffer [ nextIndex ] != null ) { <EOL> Thread . yield ( ) <EOL> } <EOL> buffer . lazySet ( nextIndex , task ) <EOL> producerIndex . incrementAndGet ( ) <EOL> return null <EOL> }


fun trySteal ( stealingMode : StealingMode , stolenTaskRef : ObjectRef < Task ? > ) : Long

{ <EOL> val task = when ( stealingMode ) { <EOL> STEAL_ANY -> pollBuffer ( ) <EOL> else -> stealWithExclusiveMode ( stealingMode ) <EOL> } <EOL> if ( task != null ) { <EOL> stolenTaskRef . element = task <EOL> return TASK_STOLEN <EOL> } <EOL> return tryStealLastScheduled ( stealingMode , stolenTaskRef ) <EOL> }

/**
 * Tries stealing from this queue into the [stolenTaskRef] argument.
 *
 * Returns [NOTHING_TO_STEAL] if queue has nothing to steal, [TASK_STOLEN] if at least task was stolen
 * or positive value of how many nanoseconds should pass until the head of this queue will be available to steal.
 *
 * [StealingMode] controls what tasks to steal:
 * - [STEAL_ANY] is default mode for scheduler, task from the head (in FIFO order) is stolen
 * - [STEAL_BLOCKING_ONLY] is mode for stealing *an arbitrary* blocking task, which is used by the scheduler when helping in Dispatchers.IO mode
 * - [STEAL_CPU_ONLY] is a kludge for `runSingleTaskFromCurrentSystemDispatcher`
 */


private fun tryStealLastScheduled ( stealingMode : StealingMode , stolenTaskRef : ObjectRef < Task ? > ) : Long

{ <EOL> while ( true ) { <EOL> val lastScheduled = lastScheduledTask . value ? : return NOTHING_TO_STEAL <EOL> if ( ( lastScheduled . maskForStealingMode and stealingMode ) == <NUM_LIT:0> ) { <EOL> return NOTHING_TO_STEAL <EOL> } <EOL> val time = schedulerTimeSource . nanoTime ( ) <EOL> val staleness = time - lastScheduled . submissionTime <EOL> if ( staleness < WORK_STEALING_TIME_RESOLUTION_NS ) { <EOL> return WORK_STEALING_TIME_RESOLUTION_NS - staleness <EOL> } <EOL> if ( lastScheduledTask . compareAndSet ( lastScheduled , null ) ) { <EOL> stolenTaskRef . element = lastScheduled <EOL> return TASK_STOLEN <EOL> } <EOL> continue <EOL> } <EOL> }

/**
 * Contract on return value is the same as for [trySteal]
 */


fun efficientNetB0AdditionalTraining ( )

{ <EOL> val modelHub = ONNXModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = ONNXModels . CVnoTop . EfficientNetB0 <EOL> modelHub . loadModel ( modelType ) . use { model -> <EOL> println ( model ) <EOL> val preprocessing = modelType . createPreprocessing ( model ) . onnx { onnxModel = model } <EOL> val dogsVsCatsDatasetPath = dogsCatsSmallDatasetPath ( ) <EOL> val dataset = OnFlyImageDataset . create ( File ( dogsVsCatsDatasetPath ) , FromFolders ( mapping = mapOf ( "<STR_LIT>" to <NUM_LIT:0> , "<STR_LIT>" to <NUM_LIT:1> ) ) , preprocessing ) . shuffle ( ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> topModel . use { <EOL> topModel . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> topModel . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE ) <EOL> val accuracy = topModel . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * This examples demonstrates the transfer learning concept on EfficientNetB0 model:
 * - Model configuration, model weights and labels are obtained from [ONNXModelHub].
 * - All layers, excluding the last [Dense], are added to the new Neural Network, its weights are frozen.
 * - ONNX frozen model is used as a preprocessing stage via `onnx` stage of the Image Preprocessing DSL.
 * - New Dense layers are added and initialized via defined initializers.
 * - Model is re-trained on [dogsCatsDatasetPath] dataset.
 *
 *
 * We use the preprocessing DSL to describe the dataset generation pipeline.
 * We demonstrate the workflow on the subset of Kaggle Cats vs Dogs binary classification dataset.
 */


= efficientNetB0AdditionalTraining ( )


= System . load ( filename )

/**
 * Load library by its absolute path
 */


= System . loadLibrary ( name )


fun load ( kClass : KClass < * > , filename : String , )

= load0 ( kClass , filename , true )

/**
 * Load library by its absolute path from a different classloader
 */


fun loadLibrary ( kClass : KClass < * > , name : String , )

= load0 ( kClass , name , false )

/**
 * Load library by its name from a different classloader
 */


public fun < T > PlotContext . x ( column : ColumnReference < T > , parameters : LetsPlotPositionalMappingParametersContinuous < T > . ( ) -> Unit = { } ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( X , column . name ( ) , LetsPlotPositionalMappingParametersContinuous < T > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `x` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to map to the x-coordinate.
 * @param parameters additional mapping parameters.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > PlotContext . x ( values : Iterable < T > , name : String ? = null , parameters : LetsPlotPositionalMappingParametersContinuous < T > . ( ) -> Unit = { } ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( X , values . toList ( ) , name , LetsPlotPositionalMappingParametersContinuous < T > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `x` aesthetic to iterable of values.
 *
 * @param values the iterable containing the x-coordinate values.
 * @param name optional name for this aesthetic mapping.
 * @param parameters additional mapping parameters.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun PlotContext . x ( column : String , parameters : LetsPlotPositionalMappingParametersContinuous < Any ? > . ( ) -> Unit = { } ) : PositionalMapping < Any ? >

{ <EOL> return addPositionalMapping < Any ? > ( X , column , LetsPlotPositionalMappingParametersContinuous < Any ? > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `x` aesthetic to a data column by [String].
 *
 * @param column the data column to map to the x-coordinate.
 * @param parameters additional mapping parameters.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > PlotContext . x ( values : DataColumn < T > , parameters : LetsPlotPositionalMappingParametersContinuous < T > . ( ) -> Unit = { } ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( X , values , LetsPlotPositionalMappingParametersContinuous < T > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `x` aesthetic to a data column.
 *
 * @param values the data column to map to the x-coordinate.
 * @param parameters additional mapping parameters.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun PlotContext . x ( parameters : AxisParametersWithSetter . ( ) -> Unit = { } )

{ <EOL> x . apply ( parameters ) <EOL> }

/**
 * Applies configurations to x-axis parameters.
 *
 * @param parameters the configurations to apply to the x-axis parameters.
 */


public fun < T > PlotContext . y ( column : ColumnReference < T > , parameters : LetsPlotPositionalMappingParametersContinuous < T > . ( ) -> Unit = { } ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y , column . name ( ) , LetsPlotPositionalMappingParametersContinuous < T > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `y` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to map to the y-coordinate.
 * @param parameters additional mapping parameters.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > PlotContext . y ( values : Iterable < T > , name : String ? = null , parameters : LetsPlotPositionalMappingParametersContinuous < T > . ( ) -> Unit = { } ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y , values . toList ( ) , name , LetsPlotPositionalMappingParametersContinuous < T > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `y` aesthetic to iterable of values.
 *
 * @param values the iterable containing the y-coordinate values.
 * @param name optional name for this aesthetic mapping.
 * @param parameters additional mapping parameters.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun PlotContext . y ( column : String , parameters : LetsPlotPositionalMappingParametersContinuous < Any ? > . ( ) -> Unit = { } ) : PositionalMapping < Any ? >

{ <EOL> return addPositionalMapping < Any ? > ( Y , column , LetsPlotPositionalMappingParametersContinuous < Any ? > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `y` aesthetic to a data column by [String].
 *
 * @param column the data column to map to the y-coordinate.
 * @param parameters additional mapping parameters.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > PlotContext . y ( values : DataColumn < T > , parameters : LetsPlotPositionalMappingParametersContinuous < T > . ( ) -> Unit = { } ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y , values , LetsPlotPositionalMappingParametersContinuous < T > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `y` aesthetic to a data column.
 *
 * @param values the data column to map to the y-coordinate.
 * @param parameters additional mapping parameters.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun PlotContext . y ( parameters : AxisParametersWithSetter . ( ) -> Unit = { } )

{ <EOL> y . apply ( parameters ) <EOL> }

/**
 * Applies configurations to y-axis parameters.
 *
 * @param parameters the configurations to apply to the y-axis parameters.
 */


internal fun defaultActivationName ( layer : Layer )

= "<STR_LIT>"

/** Default activation name in TensorFlow graph, based on [layer]'s name. */


internal fun defaultAssignOpName ( name : String )

= "<STR_LIT>"

/** Default Assign op name in TensorFlow graph, based on variable's name. */


internal fun defaultInitializerOpName ( name : String )

= "<STR_LIT>"

/** Default Initializer op name in TensorFlow graph, based on variable's name. */


internal fun defaultOptimizerVariableName ( name : String )

= "<STR_LIT>"

/** Default optimizer variable name in TensorFlow graph, based on variable's name. */


internal fun convBiasVarName ( name : String , dim : Int ) : String

= layerVarName ( name , "<STR_LIT>" )

/** Default Conv bias variable name in TensorFlow graph, based on layer's name. */


internal fun convKernelVarName ( name : String , dim : Int ) : String

= layerVarName ( name , "<STR_LIT>" )

/** Default Conv kernel variable name in TensorFlow graph, based on layer's name. */


internal fun convTransposeBiasVarName ( name : String , dim : Int ) : String

= layerVarName ( name , "<STR_LIT>" )

/** Default Conv transpose bias variable name in TensorFlow graph, based on layer's name. */


internal fun convTransposeKernelVarName ( name : String , dim : Int ) : String

{ <EOL> return layerVarName ( name , "<STR_LIT>" ) <EOL> }

/** Default Conv transpose kernel variable name in TensorFlow graph, based on layer's name. */


internal fun depthwiseConv2dBiasVarName ( name : String ) : String

= layerVarName ( name , "<STR_LIT>" )

/** Default DepthwiseConv2d bias variable name in TensorFlow graph, based on layer's name. */


internal fun depthwiseConv2dKernelVarName ( name : String ) : String

= layerVarName ( name , "<STR_LIT>" )

/** Default DepthwiseConv2d kernel variable name in TensorFlow graph, based on layer's name. */


internal fun separableConv2dBiasVarName ( name : String )

= layerVarName ( name , "<STR_LIT>" )

/** Default SeparableConv2d bias variable name in TensorFlow graph, based on layer's name. */


internal fun separableConv2dDepthwiseKernelVarName ( name : String )

= <EOL> layerVarName ( name , "<STR_LIT>" )

/** Default SeparableConv2d depthwise kernel variable name in TensorFlow graph, based on layer's name. */


internal fun separableConv2dPointwiseKernelVarName ( name : String )

/** Default SeparableConv2d pointwise kernel variable name in TensorFlow graph, based on layer's name. */


internal fun denseBiasVarName ( name : String )

= layerVarName ( name , "<STR_LIT>" )

/** Default Dense bias variable name in TensorFlow graph, based on layer's name. */


internal fun denseKernelVarName ( name : String )

= layerVarName ( name , "<STR_LIT>" )

/** Default Dense kernel variable name in TensorFlow graph, based on layer's name. */


internal fun batchNormGammaVarName ( name : String )

= layerVarName ( name , "<STR_LIT>" )

/** Default BatchNorm gamma variable name in TensorFlow graph, based on layer's name. */


internal fun batchNormBetaVarName ( name : String )

= layerVarName ( name , "<STR_LIT>" )

/** Default BatchNorm beta variable name in TensorFlow graph, based on layer's name. */


internal fun batchNormMovingMeanVarName ( name : String )

= layerVarName ( name , "<STR_LIT>" )

/** Default BatchNorm moving mean variable name in TensorFlow graph, based on layer's name. */


internal fun batchNormMovingVarianceVarName ( name : String )

= layerVarName ( name , "<STR_LIT>" )

/** Default BatchNorm moving variance variable name in TensorFlow graph, based on layer's name. */


fun append ( char : String , name : String , categoryCode : String )

{ <EOL> val charCode = char . hexToInt ( ) <EOL> val categoryId = categoryId ( categoryCode ) <EOL> when { <EOL> name . endsWith ( "<STR_LIT>" ) -> rangeFirst ( charCode , categoryId ) <EOL> name . endsWith ( "<STR_LIT>" ) -> rangeLast ( charCode , categoryId ) <EOL> else -> append ( charCode , categoryId ) <EOL> } <EOL> lastAppendedCharCode = charCode <EOL> }

/**
 * Appends a line from the UnicodeData.txt file.
 */


fun build ( ) : Triple < List < Int > , List < Int > , List < Int > >

{ <EOL> for ( code in lastAppendedCharCode + <NUM_LIT:1> .. <NUM_LIT> ) { <EOL> appendSingleChar ( code , unassignedCategoryId ) <EOL> } <EOL> var index = ranges . lastIndex <EOL> while ( index > <NUM_LIT:0> ) { <EOL> val previous = ranges [ index - <NUM_LIT:1> ] <EOL> val previousEnd = previous . rangeEnd ( ) <EOL> val previousEndCategory = previous . categoryIdOf ( previousEnd ) <EOL> val current = ranges [ index ] <EOL> if ( current . prepend ( previousEnd , previousEndCategory ) ) { <EOL> val newPrevious = removeLast ( previous ) <EOL> if ( newPrevious != null ) { <EOL> ranges [ index - <NUM_LIT:1> ] = newPrevious <EOL> } else { <EOL> ranges . removeAt ( index - <NUM_LIT:1> ) <EOL> index -- <EOL> } <EOL> } else { <EOL> index -- <EOL> } <EOL> } <EOL> return Triple ( ranges . map { it . rangeStart ( ) } , ranges . map { it . rangeEnd ( ) } , ranges . map { it . category ( ) } ) <EOL> }

/**
 * Optimizes the number of ranges and returns them.
 *
 * Returns a [Triple] containing lists of range starts, ends and categories in that particular order.
 */


private fun rangeFirst ( charCode : Int , categoryId : String )

{ <EOL> append ( charCode , categoryId ) <EOL> }

/**
 * Appends the [charCode] as the start of a range of chars with the specified [categoryId].
 */


private fun rangeLast ( charCode : Int , categoryId : String )

{ <EOL> if ( ! shouldSkip ( categoryId ) ) { <EOL> check ( ranges . last ( ) . rangeEnd ( ) == lastAppendedCharCode ) <EOL> check ( ranges . last ( ) . categoryIdOf ( lastAppendedCharCode ) == categoryId ) <EOL> } <EOL> for ( code in lastAppendedCharCode + <NUM_LIT:1> .. charCode ) { <EOL> appendSingleChar ( code , categoryId ) <EOL> } <EOL> }

/**
 * Appends the [charCode] as the end of a range of chars with the specified [categoryId].
 * Chars between last appended char and the [charCode] are considered to have the specified [categoryId].
 */


private fun append ( charCode : Int , categoryId : String )

{ <EOL> for ( code in lastAppendedCharCode + <NUM_LIT:1> until charCode ) { <EOL> appendSingleChar ( code , unassignedCategoryId ) <EOL> } <EOL> appendSingleChar ( charCode , categoryId ) <EOL> }

/**
 * Appends the [charCode] with the specified [categoryId].
 * Chars between last appended char and the [charCode] are considered to be unassigned.
 */


private fun appendSingleChar ( charCode : Int , categoryId : String )

{ <EOL> if ( shouldSkip ( categoryId ) ) return <EOL> if ( ranges . isEmpty ( ) ) { <EOL> ranges . add ( createRange ( charCode , categoryId ) ) <EOL> return <EOL> } <EOL> val lastRange = ranges . last ( ) <EOL> if ( ! lastRange . append ( charCode , categoryId ) ) { <EOL> val newLastRange = evolveLastRange ( lastRange , charCode , categoryId ) <EOL> if ( newLastRange != null ) { <EOL> ranges [ ranges . lastIndex ] = newLastRange <EOL> } else { <EOL> ranges . add ( createRange ( charCode , categoryId ) ) <EOL> } <EOL> } <EOL> }

/**
 * Appends the [charCode] with the specified [categoryId] to the last range, or a new range containing the [charCode] is created.
 * The last range can be transformed to another range type to accommodate the [charCode].
 */


private fun createRange ( charCode : Int , categoryId : String ) : RangePattern

{ <EOL> return PeriodicRangePattern . from ( charCode , categoryId , sequenceLength = <NUM_LIT:1> , isPeriodic = true , unassignedCategoryId , makeOnePeriodCategory ) <EOL> }

/**
 * Creates the simplest range containing the single [charCode].
 */


private fun removeLast ( range : RangePattern ) : RangePattern ?

{ <EOL> if ( range . rangeLength ( ) == <NUM_LIT:1> ) { <EOL> return null <EOL> } <EOL> val rangeStart = range . rangeStart ( ) <EOL> var result = createRange ( rangeStart , range . categoryIdOf ( rangeStart ) ) <EOL> for ( code in rangeStart + <NUM_LIT:1> until range . rangeEnd ( ) ) { <EOL> val categoryId = range . categoryIdOf ( code ) <EOL> if ( ! shouldSkip ( categoryId ) ) { <EOL> result = if ( result . append ( code , categoryId ) ) result else evolveLastRange ( result , code , categoryId ) ! ! <EOL> } <EOL> } <EOL> return result <EOL> }

/**
 * Removes the last char in the specified [range].
 * Returns the simplest pattern that accommodated the remaining chars in the [range],
 * or `null` if the [range] contained a single char.
 */


protected abstract fun categoryId ( categoryCode : String ) : String

/**
 * The id to use for the [categoryCode] - the Unicode general category code.
 */


protected abstract fun shouldSkip ( categoryId : String ) : Boolean

/**
 * Returns true if this range builder skips chars with the specified [categoryId].
 */


protected open fun evolveLastRange ( lastRange : RangePattern , charCode : Int , categoryId : String ) : RangePattern ?

= null

/**
 * Appends the [charCode] with the specified [categoryId] to the [lastRange] and returns the resulting range,
 * or returns `null` if [charCode] can't be appended to the [lastRange].
 * The [lastRange] can be transformed to another range type to accommodate the [charCode].
 */


{ <EOL> runImageRecognitionPrediction ( modelType = TFModels . CV . NASNetLarge ( ) ) <EOL> }

/**
 * This example demonstrates the inference concept on NasNetLarge model:
 * - Model configuration, model weights and labels are obtained from [TFModelHub].
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - Model predicts on a few images located in resources.
 * - Special preprocessing (used in NasNetLarge during training on ImageNet dataset) is applied to each image before prediction.
 *
 * NOTE: Input resolution is 331*331
 */


= nasNetLargePrediction ( )


fun checkPoolThreadsCreated ( expectedThreadsCount : Int = CORES_COUNT )

{ <EOL> val threadsCount = maxSequenceNumber ( ) ! ! <EOL> assertEquals ( expectedThreadsCount , threadsCount , "<STR_LIT>" ) <EOL> }

/**
 * Asserts that [expectedThreadsCount] pool worker threads were created.
 * Note that 'created' doesn't mean 'exists' because pool supports dynamic shrinking
 */


fun checkPoolThreadsCreated ( range : IntRange , base : Int = CORES_COUNT )

{ <EOL> val maxSequenceNumber = maxSequenceNumber ( ) ! ! <EOL> val r = ( range . first ) .. ( range . last + base ) <EOL> assertTrue ( maxSequenceNumber in r , "<STR_LIT>" ) <EOL> }

/**
 * Asserts that any number of pool worker threads in [range] were created.
 * Note that 'created' doesn't mean 'exists' because pool supports dynamic shrinking
 */


internal fun Json . deserializationNamesMap ( descriptor : SerialDescriptor ) : Map < String , Int >

= <EOL> schemaCache . getOrPut ( descriptor , JsonDeserializationNamesKey ) { descriptor . buildDeserializationNamesMap ( this ) }

/**
 * Contains strategy-mapped names and @JsonNames,
 * so original names are not stored when strategy is `null`.
 */


@ OptIn ( ExperimentalSerializationApi :: class ) <EOL> internal fun SerialDescriptor . getJsonNameIndex ( json : Json , name : String ) : Int

{ <EOL> if ( json . decodeCaseInsensitive ( this ) ) { <EOL> return getJsonNameIndexSlowPath ( json , name . lowercase ( ) ) <EOL> } <EOL> val strategy = namingStrategy ( json ) <EOL> if ( strategy != null ) return getJsonNameIndexSlowPath ( json , name ) <EOL> val index = getElementIndex ( name ) <EOL> if ( index != CompositeDecoder . UNKNOWN_NAME ) return index <EOL> if ( ! json . configuration . useAlternativeNames ) return index <EOL> return getJsonNameIndexSlowPath ( json , name ) <EOL> }

/**
 * Serves same purpose as [SerialDescriptor.getElementIndex] but respects [JsonNames] annotation
 * and [JsonConfiguration] settings.
 */


@ OptIn ( ExperimentalSerializationApi :: class ) <EOL> internal fun SerialDescriptor . getJsonNameIndexOrThrow ( json : Json , name : String , suffix : String = "<STR_LIT>" ) : Int

{ <EOL> val index = getJsonNameIndex ( json , name ) <EOL> if ( index == CompositeDecoder . UNKNOWN_NAME ) <EOL> throw SerializationException ( "<STR_LIT>" ) <EOL> return index <EOL> }

/**
 * Throws on [CompositeDecoder.UNKNOWN_NAME]
 */


public inline fun < reified DomainType : Comparable < DomainType > > continuousColorBrewer ( type : BrewerPalette ? = null , domain : ClosedRange < DomainType > , nullValue : Color ? = null , transform : Transformation ? = null ) : ScaleContinuousColorBrewer < DomainType >

= ScaleContinuousColorBrewer ( domain . let { <EOL> listOf ( it . start , it . endInclusive ) <EOL> } , type , nullValue , transform )

/**
 * Sequential, diverging and qualitative color scales from colorbrewer.org.
 *
 * @param type [BrewerPalette] pallet.
 * @param DomainType scale domain type.
 * @param domain [ClosedRange] defining the scale domain.
 * @param nullValue value which null is mapped to.
 * @param transform the transformation of scale.
 *
 * @return new continuous color scale.
 */


public inline fun < reified DomainType : Comparable < DomainType > > continuousColorBrewer ( type : BrewerPalette ? = null , domainMin : DomainType ? = null , domainMax : DomainType ? = null , nullValue : Color ? = null , transform : Transformation ? = null ) : ScaleContinuousColorBrewer < DomainType >

= ScaleContinuousColorBrewer ( listOf ( domainMin , domainMax ) , type , nullValue , transform )

/**
 * Sequential, diverging and qualitative color scales from colorbrewer.org.
 *
 * @param type [BrewerPalette] pallet.
 * @param DomainType scale domain type.
 * @param domainMin scale domain minimum.
 * @param domainMax scale domain maximum.
 * @param nullValue value which null is mapped to.
 * @param transform scale transformation.
 *
 * @return new continuous color scale.
 */


public inline fun < reified DomainType > categoricalColorBrewer ( type : BrewerPalette ? = null , domain : List < DomainType > ? = null , ) : ScaleCategoricalColorBrewer < DomainType >

= ScaleCategoricalColorBrewer ( domain , type )

/**
 * Sequential, diverging and qualitative color scales from colorbrewer.org.
 *
 * @param type [BrewerPalette] pallet.
 * @param DomainType scale domain type.
 * @param domain [List] defining the scale domain.
 *
 * @return new categorical color scale.
 */


fun kotlinToNative ( nativeBacked : NativeBacked , returnType : BridgedType , kotlinValues : List < BridgeTypedKotlinValue > , independent : Boolean , block : NativeCodeBuilder . ( nativeValues : List < NativeExpression > ) -> NativeExpression ) : KotlinExpression

/**
 * Generates the expression to convert given Kotlin values to native counterparts, pass through the bridge,
 * use inside the native code produced by [block] and then return the result back.
 *
 * @param block produces native code lines into the builder and returns the expression to be used as the result.
 */


fun nativeToKotlin ( nativeBacked : NativeBacked , returnType : BridgedType , nativeValues : List < BridgeTypedNativeValue > , block : KotlinCodeBuilder . ( kotlinValues : List < KotlinExpression > ) -> KotlinExpression ) : NativeExpression

/**
 * Generates the expression to convert given native values to Kotlin counterparts, pass through the bridge,
 * use inside the Kotlin code produced by [block] and then return the result back.
 */


fun prepare ( ) : NativeBridges

/**
 * Prepares all requested native bridges.
 */


fun isSupported ( nativeBacked : NativeBacked ) : Boolean

/**
 * @return `true` iff given entity is supported by these bridges,
 * i.e. all bridges it depends on can be successfully generated.
 */


{ <EOL> ioState = IOState . CLOSED <EOL> inputStream . close ( ) <EOL> }


public fun readRemainingFrames ( ) : Array < FloatArray >

{ <EOL> val count = remainingFrames <EOL> if ( count > Int . MAX_VALUE ) { <EOL> throw WavFileException ( "<STR_LIT>" ) <EOL> } <EOL> val buffer = Array ( format . numChannels ) { FloatArray ( count . toInt ( ) ) } <EOL> val readCount = readFrames ( buffer , count . toInt ( ) ) <EOL> check ( readCount == count . toInt ( ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> return buffer <EOL> }

/**
 * Read all remaining frames from WAV file and return them as an array of
 * results for each of the channels of input file.
 *
 * @return Array with sound data for each channel
 */


public fun readFrames ( returnBuffer : Array < FloatArray > , count : Int , offset : Int = <NUM_LIT:0> ) : Int

{ <EOL> var myOffset = offset <EOL> if ( ioState != IOState . READING ) { <EOL> throw IOException ( "<STR_LIT>" ) <EOL> } <EOL> for ( f in <NUM_LIT:0> until count ) { <EOL> if ( frameCounter == frames ) { <EOL> return f <EOL> } <EOL> for ( c in <NUM_LIT:0> until format . numChannels ) { <EOL> returnBuffer [ c ] [ myOffset ] = format . floatOffset + readSingleSample ( ) . toFloat ( ) / format . floatScale <EOL> } <EOL> myOffset ++ <EOL> frameCounter ++ <EOL> } <EOL> return count <EOL> }

/**
 * Read some number of frames from a specific offset in the buffer into a multidimensional
 * float array.
 *
 * @param returnBuffer the buffer to read samples into
 * @param count the number of frames to read
 * @param offset the buffer offset to read from
 * @return the number of frames read
 */


{ <EOL> var resultSample = <NUM_LIT:0L> <EOL> for ( b in <NUM_LIT:0> until format . bytesPerSample ) { <EOL> if ( bufferPointer == bytesRead ) { <EOL> val read = inputStream . read ( buffer , <NUM_LIT:0> , bufferSize ) <EOL> if ( read == - <NUM_LIT:1> ) { <EOL> throw WavFileException ( "<STR_LIT>" ) <EOL> } <EOL> bytesRead = read <EOL> bufferPointer = <NUM_LIT:0> <EOL> } <EOL> var v = buffer [ bufferPointer ] . toLong ( ) <EOL> if ( b < format . bytesPerSample - <NUM_LIT:1> || format . bytesPerSample == <NUM_LIT:1> ) { <EOL> v = v and <NUM_LIT> . toLong ( ) <EOL> } <EOL> resultSample += ( v shl b * <NUM_LIT:8> ) <EOL> bufferPointer ++ <EOL> } <EOL> return resultSample <EOL> }

/**
 * Read a single sample from the buffer.
 *
 * @return the sample read
 * @throws IOException Signals that an I/O exception has occurred
 * @throws WavFileException a WavFile-specific exception
 */


internal fun readLittleEndian ( buffer : ByteArray , position : Int , count : Int ) : Long

{ <EOL> var currPosition = position + count - <NUM_LIT:1> <EOL> var returnValue = ( buffer [ currPosition ] . toLong ( ) and <NUM_LIT> ) <EOL> for ( b in <NUM_LIT:0> until count - <NUM_LIT:1> ) { <EOL> returnValue = ( returnValue shl <NUM_LIT:8> ) + ( buffer [ -- currPosition ] . toLong ( ) and <NUM_LIT> ) <EOL> } <EOL> return returnValue <EOL> }

/**
 * Read little-endian data from the buffer.
 *
 * @param buffer to read from
 * @param position the starting position to read from
 * @param count the number of bytes to read
 * @return a little-endian long value read from buffer
 */


public fun < T : Any > serializersModuleOf ( kClass : KClass < T > , serializer : KSerializer < T > ) : SerializersModule

= <EOL> SerializersModule { contextual ( kClass , serializer ) }

/**
 * Returns a [SerializersModule] which has one class with one [serializer] for [ContextualSerializer].
 */


public inline fun < reified T : Any > serializersModuleOf ( serializer : KSerializer < T > ) : SerializersModule

= <EOL> serializersModuleOf ( T :: class , serializer )


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public inline fun SerializersModule ( builderAction : SerializersModuleBuilder . ( ) -> Unit ) : SerializersModule

{ <EOL> val builder = SerializersModuleBuilder ( ) <EOL> builder . builderAction ( ) <EOL> return builder . build ( ) <EOL> }

/**
 * A builder function for creating a [SerializersModule].
 * Serializers can be added via [SerializersModuleBuilder.contextual] or [SerializersModuleBuilder.polymorphic].
 * Since [SerializersModuleBuilder] also implements [SerialModuleCollector],
 * it is possible to copy whole another module to this builder with [SerializersModule.dumpTo]
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public fun EmptySerializersModule ( ) : SerializersModule

= @ Suppress ( "<STR_LIT:DEPRECATION>" ) EmptySerializersModule

/**
 * A [SerializersModule] which is empty and returns `null` from each method.
 */


public override fun < T : Any > contextual ( kClass : KClass < T > , serializer : KSerializer < T > ) : Unit

= <EOL> registerSerializer ( kClass , ContextualProvider . Argless ( serializer ) )

/**
 * Adds [serializer] associated with given [kClass] for contextual serialization.
 * If [kClass] has generic type parameters, consider registering provider instead.
 *
 * Throws [SerializationException] if a module already has serializer or provider associated with a [kClass].
 * To overwrite an already registered serializer, [SerializersModule.overwriteWith] can be used.
 */


public override fun < T : Any > contextual ( kClass : KClass < T > , provider : ( typeArgumentsSerializers : List < KSerializer < * > > ) -> KSerializer < * > ) : Unit

= registerSerializer ( kClass , ContextualProvider . WithTypeArguments ( provider ) )

/**
 * Registers [provider] associated with given generic [kClass] for contextual serialization.
 * When a serializer is requested from a module, provider is being called with type arguments serializers
 * of the particular [kClass] usage.
 *
 * Example:
 * ```
 * class Holder(@Contextual val boxI: Box<Int>, @Contextual val boxS: Box<String>)
 *
 * val module = SerializersModule {
 * // args[0] contains Int.serializer() or String.serializer(), depending on the property
 * contextual(Box::class) { args -> BoxSerializer(args[0]) }
 * }
 * ```
 *
 * Throws [SerializationException] if a module already has provider or serializer associated with a [kClass].
 * To overwrite an already registered serializer, [SerializersModule.overwriteWith] can be used.
 */


public override fun < Base : Any , Sub : Base > polymorphic ( baseClass : KClass < Base > , actualClass : KClass < Sub > , actualSerializer : KSerializer < Sub > )

{ <EOL> registerPolymorphicSerializer ( baseClass , actualClass , actualSerializer ) <EOL> }

/**
 * Adds [serializer][actualSerializer] associated with given [actualClass] in the scope of [baseClass] for polymorphic serialization.
 * Throws [SerializationException] if a module already has serializer associated with a [actualClass].
 * To overwrite an already registered serializer, [SerializersModule.overwriteWith] can be used.
 */


public override fun < Base : Any > polymorphicDefaultSerializer ( baseClass : KClass < Base > , defaultSerializerProvider : ( value : Base ) -> SerializationStrategy < Base > ? <EOL> )

{ <EOL> registerDefaultPolymorphicSerializer ( baseClass , defaultSerializerProvider , false ) <EOL> }

/**
 * Adds a default serializers provider associated with the given [baseClass] to the resulting module.
 * [defaultSerializerProvider] is invoked when no polymorphic serializers for `value` in the scope of [baseClass] were found.
 *
 * Default serializers provider affects only serialization process. To affect deserialization process, use
 * [SerializersModuleBuilder.polymorphicDefaultDeserializer].
 *
 * [defaultSerializerProvider] can be stateful and lookup a serializer for the missing type dynamically.
 */


public override fun < Base : Any > polymorphicDefaultDeserializer ( baseClass : KClass < Base > , defaultDeserializerProvider : ( className : String ? ) -> DeserializationStrategy < Base > ? <EOL> )

{ <EOL> registerDefaultPolymorphicDeserializer ( baseClass , defaultDeserializerProvider , false ) <EOL> }

/**
 * Adds a default deserializers provider associated with the given [baseClass] to the resulting module.
 * [defaultDeserializerProvider] is invoked when no polymorphic serializers associated with the `className`
 * in the scope of [baseClass] were found. `className` could be `null` for formats that support nullable class discriminators
 * (currently only `Json` with `useArrayPolymorphism` set to `false`).
 *
 * Default deserializers provider affects only deserialization process. To affect serialization process, use
 * [SerializersModuleBuilder.polymorphicDefaultSerializer].
 *
 * [defaultDeserializerProvider] can be stateful and lookup a serializer for the missing type dynamically.
 *
 * @see PolymorphicModuleBuilder.defaultDeserializer
 */


public fun include ( module : SerializersModule )

{ <EOL> module . dumpTo ( this ) <EOL> }

/**
 * Copies the content of [module] module into the current builder.
 */


public inline fun < reified T : Any > SerializersModuleBuilder . contextual ( serializer : KSerializer < T > ) : Unit

= <EOL> contextual ( T :: class , serializer )

/**
 * Adds [serializer] associated with given type [T] for contextual serialization.
 * Throws [SerializationException] if a module already has serializer associated with the given type.
 * To overwrite an already registered serializer, [SerializersModule.overwriteWith] can be used.
 */


public inline fun < Base : Any > SerializersModuleBuilder . polymorphic ( baseClass : KClass < Base > , baseSerializer : KSerializer < Base > ? = null , builderAction : PolymorphicModuleBuilder < Base > . ( ) -> Unit = { } )

{ <EOL> val builder = PolymorphicModuleBuilder ( baseClass , baseSerializer ) <EOL> builder . builderAction ( ) <EOL> builder . buildTo ( this ) <EOL> }

/**
 * Creates a builder to register subclasses of a given [baseClass] for polymorphic serialization.
 * If [baseSerializer] is not null, registers it as a serializer for [baseClass],
 * which is useful if the base class is serializable itself. To register subclasses,
 * [PolymorphicModuleBuilder.subclass] builder function can be used.
 *
 * If a serializer already registered for the given KClass in the given scope, an [IllegalArgumentException] is thrown.
 * To override registered serializers, combine built module with another using [SerializersModule.overwriteWith].
 *
 * @see PolymorphicSerializer
 */


operator fun < T > set ( key : Key < T > , value : T ) : T ?

/**
 * @return The previous value or null if no previous value was set
 */


fun kotlinSourceSetName ( disambiguationClassifier : String , androidSourceSetName : String , type : AndroidVariantType ? <EOL> ) : String ?

/**
 * Returns the name of the corresponding [KotlinSourceSet]
 * This function can be called w/ or w/o a specific [type].
 */


fun defaultKotlinSourceSetName ( target : KotlinAndroidTarget , @ Suppress ( "<STR_LIT:TYPEALIAS_EXPANSION_DEPRECATION>" ) variant : DeprecatedAndroidBaseVariant ) : String ?

= null

/**
 * Returns the name of the default KotlinSourceSet for a given Android compilation.
 * Returns `null`, if this naming schema does not know about it. In this case, the
 * 'default' defaultSourceSetName will be constructed by the compilation.
 */


@ JvmStatic <EOL> fun writeData ( message : MessageLite , stringTable : JvmStringTable ) : Array < String >

= <EOL> BitEncoding . encodeBytes ( writeDataBytes ( stringTable , message ) )

/**
 * Serializes [message] and [stringTable] into a string array which must be further written to [Metadata.data1]
 */


private fun isLowSurrogateOfSupplement ( string : CharSequence , index : Int ) : Boolean

= <EOL> index < string . length && string [ index ] . isLowSurrogate ( ) && index > <NUM_LIT:0> && string [ index - <NUM_LIT:1> ] . isHighSurrogate ( )

/** Returns true if [index] points to a low surrogate following a high surrogate */


fun merge ( vararg contexts : ScriptEvaluationContextData ? ) : ScriptEvaluationContextData ?

{ <EOL> val nonEmpty = ArrayList < ScriptEvaluationContextData > ( ) <EOL> for ( data in contexts ) { <EOL> if ( data != null && ! data . isEmpty ( ) ) { <EOL> nonEmpty . add ( data ) <EOL> } <EOL> } <EOL> return when { <EOL> nonEmpty . isEmpty ( ) -> null <EOL> nonEmpty . size == <NUM_LIT:1> -> nonEmpty . first ( ) <EOL> else -> ScriptEvaluationContextData ( nonEmpty . asIterable ( ) ) <EOL> } <EOL> }

/**
 * optimized alternative to the constructor with multiple base configurations
 */


= EmptyTuple

/**
 * Returns the instance of Tuple0.
 * @see t
 */


fun < T1 > tupleOf ( _1 : T1 ) : Tuple1 < T1 >

= Tuple1 < T1 > ( _1 )

/**
 * Returns a new Tuple1 of the given arguments.
 * @see t
 * @see X
 */


= Tuple2 < T1 , T2 > ( _1 , _2 )

/**
 * Returns a new Tuple2 of the given arguments.
 * @see t
 * @see X
 */


= Tuple3 < T1 , T2 , T3 > ( _1 , _2 , _3 )

/**
 * Returns a new Tuple3 of the given arguments.
 * @see t
 * @see X
 */


= Tuple4 < T1 , T2 , T3 , T4 > ( _1 , _2 , _3 , _4 )

/**
 * Returns a new Tuple4 of the given arguments.
 * @see t
 * @see X
 */


= Tuple5 < T1 , T2 , T3 , T4 , T5 > ( _1 , _2 , _3 , _4 , _5 )

/**
 * Returns a new Tuple5 of the given arguments.
 * @see t
 * @see X
 */


= Tuple6 < T1 , T2 , T3 , T4 , T5 , T6 > ( _1 , _2 , _3 , _4 , _5 , _6 )

/**
 * Returns a new Tuple6 of the given arguments.
 * @see t
 * @see X
 */


= Tuple7 < T1 , T2 , T3 , T4 , T5 , T6 , T7 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 )

/**
 * Returns a new Tuple7 of the given arguments.
 * @see t
 * @see X
 */


= Tuple8 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 )

/**
 * Returns a new Tuple8 of the given arguments.
 * @see t
 * @see X
 */


= Tuple9 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 )

/**
 * Returns a new Tuple9 of the given arguments.
 * @see t
 * @see X
 */


= Tuple10 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 )

/**
 * Returns a new Tuple10 of the given arguments.
 * @see t
 * @see X
 */


= Tuple11 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 )

/**
 * Returns a new Tuple11 of the given arguments.
 * @see t
 * @see X
 */


= Tuple12 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 )

/**
 * Returns a new Tuple12 of the given arguments.
 * @see t
 * @see X
 */


= Tuple13 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 )

/**
 * Returns a new Tuple13 of the given arguments.
 * @see t
 * @see X
 */


= Tuple14 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 )

/**
 * Returns a new Tuple14 of the given arguments.
 * @see t
 * @see X
 */


= Tuple15 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 )

/**
 * Returns a new Tuple15 of the given arguments.
 * @see t
 * @see X
 */


= Tuple16 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 )

/**
 * Returns a new Tuple16 of the given arguments.
 * @see t
 * @see X
 */


= Tuple17 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 )

/**
 * Returns a new Tuple17 of the given arguments.
 * @see t
 * @see X
 */


= Tuple18 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 )

/**
 * Returns a new Tuple18 of the given arguments.
 * @see t
 * @see X
 */


= Tuple19 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 , _19 )

/**
 * Returns a new Tuple19 of the given arguments.
 * @see t
 * @see X
 */


= Tuple20 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 , _19 , _20 )

/**
 * Returns a new Tuple20 of the given arguments.
 * @see t
 * @see X
 */


= Tuple21 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 , _19 , _20 , _21 )

/**
 * Returns a new Tuple21 of the given arguments.
 * @see t
 * @see X
 */


= Tuple22 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 , _19 , _20 , _21 , _22 )

/**
 * Returns a new Tuple22 of the given arguments.
 * @see t
 * @see X
 */


= EmptyTuple

/**
 * Returns the instance of Tuple0.
 * @see tupleOf
 */


= Tuple1 < T1 > ( _1 )

/**
 * Returns a new Tuple1 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple2 < T1 , T2 > ( _1 , _2 )

/**
 * Returns a new Tuple2 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple3 < T1 , T2 , T3 > ( _1 , _2 , _3 )

/**
 * Returns a new Tuple3 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple4 < T1 , T2 , T3 , T4 > ( _1 , _2 , _3 , _4 )

/**
 * Returns a new Tuple4 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple5 < T1 , T2 , T3 , T4 , T5 > ( _1 , _2 , _3 , _4 , _5 )

/**
 * Returns a new Tuple5 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple6 < T1 , T2 , T3 , T4 , T5 , T6 > ( _1 , _2 , _3 , _4 , _5 , _6 )

/**
 * Returns a new Tuple6 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple7 < T1 , T2 , T3 , T4 , T5 , T6 , T7 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 )

/**
 * Returns a new Tuple7 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple8 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 )

/**
 * Returns a new Tuple8 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple9 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 )

/**
 * Returns a new Tuple9 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple10 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 )

/**
 * Returns a new Tuple10 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple11 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 )

/**
 * Returns a new Tuple11 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple12 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 )

/**
 * Returns a new Tuple12 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple13 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 )

/**
 * Returns a new Tuple13 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple14 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 )

/**
 * Returns a new Tuple14 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple15 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 )

/**
 * Returns a new Tuple15 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple16 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 )

/**
 * Returns a new Tuple16 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple17 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 )

/**
 * Returns a new Tuple17 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple18 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 )

/**
 * Returns a new Tuple18 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple19 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 , _19 )

/**
 * Returns a new Tuple19 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple20 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 , _19 , _20 )

/**
 * Returns a new Tuple20 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple21 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 , _19 , _20 , _21 )

/**
 * Returns a new Tuple21 of the given arguments.
 * @see tupleOf
 * @see X
 */


= Tuple22 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 > ( _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 , _9 , _10 , _11 , _12 , _13 , _14 , _15 , _16 , _17 , _18 , _19 , _20 , _21 , _22 )

/**
 * Returns a new Tuple22 of the given arguments.
 * @see tupleOf
 * @see X
 */


private fun findAvailableConstructors ( scope : FirScope , targetClassName : Name ) : List < FirFunctionSymbol < * > >

{ <EOL> val classLikeSymbol = scope . findFirstClassifierByName ( targetClassName ) as? FirClassLikeSymbol <EOL> ? : return emptyList ( ) <EOL> val constructors = ( classLikeSymbol as? FirClassSymbol ) ? . declarationSymbols ? . filterIsInstance < FirConstructorSymbol > ( ) . orEmpty ( ) <EOL> val samConstructor = classLikeSymbol . getSamConstructor ( ) <EOL> return constructors + listOfNotNull ( samConstructor ) <EOL> }

/**
 * Finds constructors with a given [targetClassName] available within the [scope], including SAM constructors
 * (which are not explicitly declared in the class).
 *
 * Includes type-aliased constructors too if typealias confirms to the [targetClassName].
 *
 * Do not confuse with constructors **declared** in the scope (see [FirScope.processDeclaredConstructors]).
 */


private fun FirClassLikeSymbol < * > . hasTypeParameterFromParent ( ) : Boolean

= typeParameterSymbols . orEmpty ( ) . any { <EOL> it . containingDeclarationSymbol != this <EOL> }

/**
 * Returns true if the class symbol has a type parameter that is supposed to be provided for its parent class.
 *
 * Example:
 * class Outer<T> {
 * inner class Inner // Inner has an implicit type parameter `T`.
 * }
 */


private fun FirScope . isScopeForClassCloserThanAnotherScopeForClass ( another : FirScope , from : KtClassOrObject ) : Boolean

{ <EOL> if ( ! isScopeForClass ( ) || ! another . isScopeForClass ( ) ) return false <EOL> if ( this == another ) return false <EOL> val classId = correspondingClassIdIfExists ( ) <EOL> val classIdOfAnother = another . correspondingClassIdIfExists ( ) <EOL> if ( classId == classIdOfAnother ) return false <EOL> val candidates = setOfNotNull ( classId , classIdOfAnother , classId . idWithoutCompanion ( ) , classIdOfAnother . idWithoutCompanion ( ) ) <EOL> val closestClassId = findMostInnerClassMatchingId ( from , candidates ) <EOL> return closestClassId == classId || ( closestClassId != classIdOfAnother && closestClassId == classId . idWithoutCompanion ( ) ) <EOL> }

/**
 * Assuming that both this [FirScope] and [another] are [FirNestedClassifierScope] or [FirClassUseSiteMemberScope] and both of them
 * are surrounding [from], returns whether this [FirScope] is closer than [another] based on the distance from [from].
 *
 * If one of this [FirScope] and [another] is not [FirNestedClassifierScope] or [FirClassUseSiteMemberScope], it returns false.
 *
 * Example:
 * class Outer { // scope1 ClassId = Other
 * class Inner { // scope2 ClassId = Other.Inner
 * fun foo() {
 * // Distance to scopes for classes from <element> in the order from the closest:
 * // scope2 -> scope3 -> scope1
 * <element>
 * }
 * companion object { // scope3 ClassId = Other.Inner.Companion
 * }
 * }
 * }
 *
 * This function determines the distance based on [ClassId].
 */


private fun findMostInnerClassMatchingId ( innerClass : KtClassOrObject , candidates : Set < ClassId > ) : ClassId ?

{ <EOL> var classInNestedClass : KtClassOrObject ? = innerClass <EOL> while ( classInNestedClass != null ) { <EOL> val containingClassId = classInNestedClass . getClassId ( ) <EOL> if ( containingClassId in candidates ) return containingClassId <EOL> classInNestedClass = classInNestedClass . findClassOrObjectParent ( ) <EOL> } <EOL> return null <EOL> }

/**
 * Travels all containing classes of [innerClass] and finds the one matching ClassId with one of [candidates]. Returns the matching
 * ClassId. If it does not have a matching ClassId, it returns null.
 */


private fun FirScope . isWiderThan ( another : FirScope ) : Boolean

= <EOL> toPartialOrder ( ) . scopeDistanceLevel > another . toPartialOrder ( ) . scopeDistanceLevel

/**
 * Returns whether this [FirScope] is a scope wider than [another] based on the above [PartialOrderOfScope] or not.
 */


private fun List < FirScope > . hasScopeCloserThan ( base : FirScope , from : KtElement )

= any { scope -> <EOL> if ( scope . isScopeForClass ( ) && base . isScopeForClass ( ) ) { <EOL> val classContainingFrom = from . findClassOrObjectParent ( ) ? : return@any false <EOL> return@any scope . isScopeForClassCloserThanAnotherScopeForClass ( base , classContainingFrom ) <EOL> } <EOL> base . isWiderThan ( scope ) <EOL> }

/**
 * Assuming that all scopes in this List<FirScope> and [base] are surrounding [from], returns whether an element of
 * this List<FirScope> is closer than [base] based on the distance from [from].
 */


private fun importDirectiveForDifferentSymbolWithSameNameIsPresent ( classId : ClassId ) : Boolean

{ <EOL> val importDirectivesWithSameImportedFqName = containingFile . collectDescendantsOfType { importedDirective : KtImportDirective -> <EOL> importedDirective . importedFqName ? . shortName ( ) == classId . shortClassName <EOL> } <EOL> return importDirectivesWithSameImportedFqName . isNotEmpty ( ) && <EOL> importDirectivesWithSameImportedFqName . all { it . importedFqName != classId . asSingleFqName ( ) } <EOL> }

/**
 * Returns true if [containingFile] has a [KtImportDirective] whose imported FqName is the same as [classId] but references a different
 * symbol.
 */


private fun findClassifierQualifierToShorten ( wholeQualifierClassId : ClassId , wholeQualifierElement : KtElement , ) : ElementToShorten ?

{ <EOL> val positionScopes = shorteningContext . findScopesAtPosition ( wholeQualifierElement , getNamesToImport ( ) , towerContextProvider , withImplicitReceivers = false , ) ? : return null <EOL> val allClassIds = wholeQualifierClassId . outerClassesWithSelf <EOL> val allQualifiedElements = wholeQualifierElement . qualifiedElementsWithSelf <EOL> for ( ( classId , element ) in allClassIds . zip ( allQualifiedElements ) ) { <EOL> if ( ! element . inSelection ) continue <EOL> shortenClassifierQualifier ( positionScopes , classId , element ) ? . let { return it } <EOL> } <EOL> val lastQualifier = allQualifiedElements . last ( ) <EOL> if ( ! lastQualifier . inSelection ) return null <EOL> return findFakePackageToShorten ( lastQualifier ) <EOL> }

/**
 * Finds the longest qualifier in [wholeQualifierElement] which can be safely shortened in the [positionScopes].
 * [wholeQualifierClassId] is supposed to reflect the class which is referenced by the [wholeQualifierElement].
 *
 * N.B. Even if the [wholeQualifierElement] is not strictly in the [selection],
 * some outer part of it might be, and we want to shorten that.
 * So we have to check all the outer qualifiers.
 */


private fun importBreaksExistingReferences ( classToImport : ClassId , importAllInParent : Boolean ) : Boolean

{ <EOL> return importAffectsUsagesOfClassesWithSameName ( classToImport , importAllInParent ) <EOL> }

/**
 * Returns `true` if adding [classToImport] import to the [file] might alter or break the
 * resolve of existing references in the file.
 *
 * N.B.: At the moment it might have both false positives and false negatives, since it does not
 * check all possible references.
 */


private fun importBreaksExistingReferences ( callableToImport : FirCallableSymbol < * > , importAllInParent : Boolean ) : Boolean

{ <EOL> if ( callableToImport is FirConstructorSymbol ) { <EOL> val classToImport = callableToImport . classIdIfExists <EOL> if ( classToImport != null ) { <EOL> return importAffectsUsagesOfClassesWithSameName ( classToImport , importAllInParent ) <EOL> } <EOL> } <EOL> return false <EOL> }

/**
 * Same as above, but for more general callable symbols.
 *
 * Currently only checks constructor calls, assuming `true` for everything else.
 */


private fun KtExpression . isCompanionMemberUsedForEnumEntryInit ( resolvedSymbol : FirCallableSymbol < * > ) : Boolean

{ <EOL> val enumEntry = getNonStrictParentOfType < KtEnumEntry > ( ) ? : return false <EOL> val firEnumEntry = enumEntry . resolveToFirSymbol ( firResolveSession ) as? FirEnumEntrySymbol ? : return false <EOL> val classNameOfResolvedSymbol = resolvedSymbol . callableId . className ? : return false <EOL> return firEnumEntry . callableId . className == classNameOfResolvedSymbol . parent ( ) && <EOL> classNameOfResolvedSymbol . shortName ( ) == SpecialNames . DEFAULT_NAME_FOR_COMPANION_OBJECT <EOL> }

/**
 * Returns whether a member of companion is used to initialize the enum entry or not. For example,
 * enum class C(val i: Int) {
 * ONE(<expr>C.K</expr>) // C.ONE uses C.K for initialization
 * ;
 * companion object {
 * const val K = 1
 * }
 * }
 */


private fun shortenIfAlreadyImported ( firQualifiedAccess : FirQualifiedAccessExpression , calledSymbol : FirCallableSymbol < * > , expressionInScope : KtExpression , ) : Boolean

{ <EOL> if ( expressionInScope . isCompanionMemberUsedForEnumEntryInit ( calledSymbol ) ) return false <EOL> val candidates = resolveUnqualifiedAccess ( firQualifiedAccess , calledSymbol . name , expressionInScope ) <EOL> val scopeForQualifiedAccess = candidates . findScopeForSymbol ( calledSymbol ) ? : return false <EOL> if ( candidates . mapNotNull { it . candidate . originScope } . hasScopeCloserThan ( scopeForQualifiedAccess , expressionInScope ) ) return false <EOL> val candidatesWithinSamePriorityScopes = candidates . filter { it . candidate . originScope == scopeForQualifiedAccess } <EOL> return candidatesWithinSamePriorityScopes . isEmpty ( ) || <EOL> candidatesWithinSamePriorityScopes . singleOrNull ( ) ? . isInBestCandidates == true <EOL> }

/**
 * Returns whether it is fine to shorten [firQualifiedAccess] or not.
 *
 * @param firQualifiedAccess FIR for the shortening target expression
 * @param calledSymbol The symbol referenced by the qualified access expression
 * @param expressionInScope An expression under the same scope as the shortening target expression
 *
 * The decision has two steps:
 * 1. Collect all candidates matching [firQualifiedAccess]
 * - We use `AllCandidatesResolver(shorteningContext.analysisSession.useSiteSession).getAllCandidates( .. fake FIR .. )`. See
 * [resolveUnqualifiedAccess] above.
 * 2. Check whether the candidate with the highest priority based on the distance to the scope from [expressionInScope] is the same
 * as [calledSymbol] ot not
 * - We use [hasScopeCloserThan] to determine the distance to the scope
 */


private fun getSingleUnambiguousCandidate ( namedReference : FirErrorNamedReference ) : FirCallableSymbol < * > ?

{ <EOL> val coneAmbiguityError = namedReference . diagnostic as? ConeAmbiguityError ? : return null <EOL> val candidates = coneAmbiguityError . candidates . map { it . symbol as FirCallableSymbol < * > } <EOL> require ( candidates . isNotEmpty ( ) ) { "<STR_LIT>" } <EOL> val distinctCandidates = candidates . distinctBy { it . callableId } <EOL> return distinctCandidates . singleOrNull ( ) <EOL> ? : errorWithAttachment ( "<STR_LIT>" ) { <EOL> withEntry ( "<STR_LIT>" , distinctCandidates . map { it . callableId . asSingleFqName ( ) } . joinToString ( ) ) <EOL> } <EOL> }

/**
 * If [namedReference] is ambiguous and all candidates point to the callables with same callableId,
 * returns the first candidate; otherwise returns null.
 */


private fun FirThisReference . referencesClosestReceiver ( ) : Boolean

{ <EOL> require ( ! isImplicit ) { <EOL> "<STR_LIT>" <EOL> } <EOL> if ( labelName == null ) return true <EOL> val psi = psi as? KtThisExpression ? : return false <EOL> val implicitReceivers = towerContextProvider . getClosestAvailableParentContext ( psi ) ? . implicitReceiverStack ? : return false <EOL> val closestImplicitReceiver = implicitReceivers . lastOrNull ( ) ? : return false <EOL> return boundSymbol == closestImplicitReceiver . boundSymbol <EOL> }

/**
 * Checks whether `this` expression references the closest receiver in the current position.
 *
 * If it is the case, then we can safely remove the label from it (if it exists).
 */


private fun thisLabelShortenStrategy ( thisReference : FirThisReference ) : ShortenStrategy

{ <EOL> val referencedSymbol = thisReference . boundSymbol <EOL> val strategy = when ( referencedSymbol ) { <EOL> is FirClassLikeSymbol < * > -> classShortenStrategy ( referencedSymbol ) <EOL> is FirCallableSymbol < * > -> callableShortenStrategy ( referencedSymbol ) <EOL> else -> ShortenStrategy . DO_NOT_SHORTEN <EOL> } <EOL> return strategy <EOL> }

/**
 * This method intentionally mirrors the appearance
 * of the [classShortenStrategy] and [callableShortenStrategy] filters,
 * but ATM we don't have a way to properly handle
 * [FirThisReference]s through the existing filters.
 *
 * We need a better way to decide shortening strategy
 * for labeled and regular `this` expressions (KT-63555).
 */


private fun removeRedundantElements ( qualifier : KtElement )

{ <EOL> typesToShorten . removeAll { it . element . qualifier ? . isInsideOf ( qualifier ) == true } <EOL> qualifiersToShorten . removeAll { it . element . receiverExpression . isInsideOf ( qualifier ) } <EOL> }

/**
 * Remove entries from [typesToShorten] and [qualifiersToShorten] if their qualifiers will be shortened
 * when we shorten [qualifier].
 */


private fun KtElement . findClassOrObjectParent ( ) : KtClassOrObject ?

= parentOfType ( )

/**
 * N.B. We don't use [containingClassOrObject] because it works only for [KtDeclaration]s,
 * and also check only the immediate (direct) parent.
 *
 * For this function, we want to find the parent [KtClassOrObject] declaration no matter
 * how far it is from the element.
 */


public fun complete ( ) : Boolean

/**
 * Completes this job. The result is `true` if this job was completed as a result of this invocation and
 * `false` otherwise (if it was already completed).
 *
 * Subsequent invocations of this function have no effect and always produce `false`.
 *
 * This function transitions this job into _completed_ state if it was not completed or cancelled yet.
 * However, that if this job has children, then it transitions into _completing_ state and becomes _complete_
 * once all its children are [complete][isCompleted]. See [Job] for details.
 */


public fun completeExceptionally ( exception : Throwable ) : Boolean

/**
 * Completes this job exceptionally with a given [exception]. The result is `true` if this job was
 * completed as a result of this invocation and `false` otherwise (if it was already completed).
 * [exception] parameter is used as an additional debug information that is not handled by any exception handlers.
 *
 * Subsequent invocations of this function have no effect and always produce `false`.
 *
 * This function transitions this job into _cancelled_ state if it was not completed or cancelled yet.
 * However, that if this job has children, then it transitions into _cancelling_ state and becomes _cancelled_
 * once all its children are [complete][isCompleted]. See [Job] for details.
 *
 * Its responsibility of the caller to properly handle and report the given [exception], all job's children will receive
 * a [CancellationException] with the [exception] as a cause for the sake of diagnostic.
 */


@ DelicateDeclarationStorageApi <EOL> fun forEachCachedDeclarationSymbol ( block : ( IrSymbol ) -> Unit )

{ <EOL> functionCache . values . forEachWithRemapping ( symbolsMappingForLazyClasses :: remapFunctionSymbol , block ) <EOL> constructorCache . values . forEach ( block ) <EOL> propertyCache . normal . values . forEachWithRemapping ( symbolsMappingForLazyClasses :: remapPropertySymbol , block ) <EOL> propertyCache . synthetic . values . forEachWithRemapping ( symbolsMappingForLazyClasses :: remapPropertySymbol , block ) <EOL> getterForPropertyCache . values . forEachWithRemapping ( symbolsMappingForLazyClasses :: remapFunctionSymbol , block ) <EOL> setterForPropertyCache . values . forEachWithRemapping ( symbolsMappingForLazyClasses :: remapFunctionSymbol , block ) <EOL> backingFieldForPropertyCache . values . forEach ( block ) <EOL> propertyForBackingFieldCache . values . forEach ( block ) <EOL> delegateVariableForPropertyCache . values . forEach ( block ) <EOL> }

/**
 * This function is quite messy and doesn't have a good contract of what exactly is traversed.
 * The basic idea is to traverse the symbols which can be reasonably referenced from other modules.
 *
 * Be careful when using it, and avoid it, except really needed.
 */


fun createAndCacheIrFunction ( function : FirFunction , irParent : IrDeclarationParent ? , predefinedOrigin : IrDeclarationOrigin ? = null , isLocal : Boolean = false , fakeOverrideOwnerLookupTag : ConeClassLikeLookupTag ? = null , allowLazyDeclarationsCreation : Boolean = false ) : IrSimpleFunction

{ <EOL> val symbol = getIrFunctionSymbol ( function . symbol , fakeOverrideOwnerLookupTag , isLocal ) as IrSimpleFunctionSymbol <EOL> return callablesGenerator . createIrFunction ( function , irParent , symbol , predefinedOrigin , isLocal = isLocal , fakeOverrideOwnerLookupTag = fakeOverrideOwnerLookupTag , allowLazyDeclarationsCreation ) <EOL> }

/**
 * @param allowLazyDeclarationsCreation should be passed only during fake-override generation
 */


@ LeakedDeclarationCaches <EOL> internal fun generateUnboundFakeOverrides ( )

{ <EOL> for ( ( identifier , symbol ) in irForFirSessionDependantDeclarationMap ) { <EOL> if ( symbol . isBound ) continue <EOL> val ( originalSymbol , dispatchReceiverLookupTag , _ ) = identifier <EOL> generateDeclaration ( originalSymbol , dispatchReceiverLookupTag ) <EOL> } <EOL> }

/**
 * This function iterates over all f/o symbols created in declaration storage and binds all unbound symbols
 *
 * Usually all symbols are bound after fir2ir conversion is over, but there is a case in MPP scenario when some fake-override
 * for common classes appears only during conversion of platform session:
 *
 * // MODULE: common
 * expect interface A
 *
 * interface B : A {
 * // f/o fun foo() // (1)
 * }
 *
 * // MODULE: platform()()(common)
 * actual interface A {
 * fun foo() // (2)
 * }
 *
 * fun test(b: B) {
 * b.foo() // (3)
 * }
 *
 * Here during common module conversion there is no `foo` function in scope of class B, so (1) is not generated
 * During conversion of function test we reference symbol for (1) at line (3), so this symbol is created. But
 * there is no code which generate actual IR for this symbol, because IR for f/o is generated only during
 * conversion of corresponing class (and `B` is already converted)
 *
 * So to fix this issue we need to call this method after conversion of platform module
 */