@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun String . encodeToByteArray ( ) : ByteArray

{ <EOL> return encodeUtf8 ( this , <NUM_LIT:0> , length , false ) <EOL> }

/**
 * Encodes this string to an array of bytes in UTF-8 encoding.
 *
 * Any malformed char sequence is replaced by the replacement byte sequence.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ Suppress ( "<STR_LIT:ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS>" ) <EOL> public actual fun String . encodeToByteArray ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = this . length , throwOnInvalidSequence : Boolean = false ) : ByteArray

{ <EOL> AbstractList . checkBoundsIndexes ( startIndex , endIndex , length ) <EOL> return encodeUtf8 ( this , startIndex , endIndex , throwOnInvalidSequence ) <EOL> }

/**
 * Encodes this string or its substring to an array of bytes in UTF-8 encoding.
 *
 * @param startIndex the beginning (inclusive) of the substring to encode, 0 by default.
 * @param endIndex the end (exclusive) of the substring to encode, length of this string by default.
 * @param throwOnInvalidSequence specifies whether to throw an exception on malformed char sequence or replace.
 *
 * @throws IndexOutOfBoundsException if [startIndex] is less than zero or [endIndex] is greater than the length of this string.
 * @throws IllegalArgumentException if [startIndex] is greater than [endIndex].
 * @throws CharacterCodingException if this string contains malformed char sequence and [throwOnInvalidSequence] is true.
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.5>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun String . toUpperCase ( ) : String

= asDynamic ( ) . toUpperCase ( )

/**
 * Returns a copy of this string converted to upper case using the rules of the default locale.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun String . uppercase ( ) : String

= asDynamic ( ) . toUpperCase ( )

/**
 * Returns a copy of this string converted to upper case using Unicode mapping rules of the invariant locale.
 *
 * This function supports one-to-many and many-to-one character mapping,
 * thus the length of the returned string can be different from the length of the original string.
 *
 * @sample samples.text.Strings.uppercase
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.5>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun String . toLowerCase ( ) : String

= asDynamic ( ) . toLowerCase ( )

/**
 * Returns a copy of this string converted to lower case using the rules of the default locale.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun String . lowercase ( ) : String

= asDynamic ( ) . toLowerCase ( )

/**
 * Returns a copy of this string converted to lower case using Unicode mapping rules of the invariant locale.
 *
 * This function supports one-to-many and many-to-one character mapping,
 * thus the length of the returned string can be different from the length of the original string.
 *
 * @sample samples.text.Strings.lowercase
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> @ Suppress ( "<STR_LIT:ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS>" ) <EOL> public actual fun String . compareTo ( other : String , ignoreCase : Boolean = false ) : Int

{ <EOL> if ( ignoreCase ) { <EOL> val n1 = this . length <EOL> val n2 = other . length <EOL> val min = minOf ( n1 , n2 ) <EOL> if ( min == <NUM_LIT:0> ) return n1 - n2 <EOL> for ( index in <NUM_LIT:0> until min ) { <EOL> var thisChar = this [ index ] <EOL> var otherChar = other [ index ] <EOL> if ( thisChar != otherChar ) { <EOL> thisChar = thisChar . uppercaseChar ( ) <EOL> otherChar = otherChar . uppercaseChar ( ) <EOL> if ( thisChar != otherChar ) { <EOL> thisChar = thisChar . lowercaseChar ( ) <EOL> otherChar = otherChar . lowercaseChar ( ) <EOL> if ( thisChar != otherChar ) { <EOL> return thisChar . compareTo ( otherChar ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> return n1 - n2 <EOL> } else { <EOL> return compareTo ( other ) <EOL> } <EOL> }

/**
 * Compares two strings lexicographically, optionally ignoring case differences.
 *
 * If [ignoreCase] is true, the result of `Char.uppercaseChar().lowercaseChar()` on each character is compared.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> public actual infix fun CharSequence ? . contentEquals ( other : CharSequence ? ) : Boolean

= contentEqualsImpl ( other )

/**
 * Returns `true` if the contents of this char sequence are equal to the contents of the specified [other],
 * i.e. both char sequences contain the same number of the same characters in the same order.
 *
 * @sample samples.text.Strings.contentEquals
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> public actual fun CharSequence ? . contentEquals ( other : CharSequence ? , ignoreCase : Boolean ) : Boolean

{ <EOL> return if ( ignoreCase ) <EOL> this . contentEqualsIgnoreCaseImpl ( other ) <EOL> else <EOL> this . contentEqualsImpl ( other ) <EOL> }

/**
 * Returns `true` if the contents of this char sequence are equal to the contents of the specified [other], optionally ignoring case difference.
 *
 * @param ignoreCase `true` to ignore character case when comparing contents.
 *
 * @sample samples.text.Strings.contentEquals
 */


{ <EOL> val modelHub = <EOL> ONNXModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val model = ONNXModels . ObjectDetection . SSDMobileNetV1 . pretrainedModel ( modelHub ) <EOL> model . printSummary ( ) <EOL> model . use { detectionModel -> <EOL> println ( detectionModel ) <EOL> val imageFile = getFileFromResource ( "<STR_LIT>" ) <EOL> val detectedObjects = <EOL> detectionModel . detectObjects ( imageFile = imageFile , topK = <NUM_LIT> ) <EOL> detectedObjects . forEach { <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * This examples demonstrates the light-weight inference API with [SSDMobileNetV1ObjectDetectionModel] on SSD model:
 * - Model is obtained from [ONNXModelHub].
 * - Model predicts rectangles for the detected objects on a few images located in resources.
 * - The detected rectangles related to the objects are drawn on the images used for prediction.
 */


= ssdMobileLightAPI ( )


private fun FirBlock . tryConvertDynamicIncrementOrDecrementToIr ( ) : IrExpression ?

{ <EOL> val unary = statements . findIsInstanceAnd < FirProperty > { it . name == SpecialNames . UNARY } <EOL> val operationReceiver = ( unary ? . initializer ? : statements . lastOrNull ( ) ) <EOL> ? . unwrapDesugaredAssignmentValueReference ( ) as? FirQualifiedAccessExpression <EOL> ? : return null <EOL> if ( operationReceiver . resolvedType !is ConeDynamicType ) { <EOL> return null <EOL> } <EOL> val operationCall = when ( val it = statements [ statements . lastIndex - <NUM_LIT:1> ] ) { <EOL> is FirVariableAssignment -> it . rValue as? FirFunctionCall ? : return null <EOL> is FirFunctionCall -> extractOperationFromDynamicSetCall ( it ) ? : return null <EOL> else -> return null <EOL> } <EOL> val operationReceiverReceiver = statements <EOL> . findIsInstanceAnd < FirProperty > { it . name == SpecialNames . RECEIVER || it . name == SpecialNames . ARRAY } ? . initializer <EOL> ? : ( operationReceiver as? FirQualifiedAccessExpression ) ? . explicitReceiver <EOL> val isArray = statements . find { it is FirProperty && it . name == SpecialNames . ARRAY } != null <EOL> val convertedOperationReceiver = callGenerator . convertToIrCall ( operationReceiver , operationReceiver . resolvedType , convertToIrReceiverExpression ( operationReceiverReceiver , operationReceiver ) , noArguments = isArray , ) . applyIf ( isArray ) { <EOL> require ( this is IrDynamicOperatorExpression ) <EOL> val arrayAccess = operationReceiver as? FirFunctionCall ? : return null <EOL> val originalVararg = arrayAccess . resolvedArgumentMapping ? . keys ? . filterIsInstance < FirVarargArgumentsExpression > ( ) ? . firstOrNull ( ) <EOL> originalVararg ? . arguments ? . forEach { <EOL> val indexNVariable = ( it as? FirPropertyAccessExpression ) ? . calleeReference ? . toResolvedPropertySymbol ( ) ? . fir <EOL> val initializer = indexNVariable ? . initializer ? : return@forEach <EOL> arguments . add ( convertToIrExpression ( initializer ) ) <EOL> } <EOL> this <EOL> } <EOL> return callGenerator . convertToIrCall ( operationCall , operationCall . resolvedType , convertedOperationReceiver , ) <EOL> }

/**
 * This function tries to "sugar back" `FirBlock`s generated in
 * [org.jetbrains.kotlin.fir.builder.AbstractRawFirBuilder.generateIncrementOrDecrementBlockForArrayAccess] and
 * [org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.FirExpressionsResolveTransformer.transformIncrementDecrementExpression]
 */


private fun FirWhenExpression . isDeeplyProperlyExhaustive ( ) : Boolean

{ <EOL> if ( ! isProperlyExhaustive ) { <EOL> return false <EOL> } <EOL> val nestedElseIfExpression = branches . lastOrNull ( ) ? . nestedElseIfOrNull ( ) ? : return true <EOL> return nestedElseIfExpression . isDeeplyProperlyExhaustive ( ) <EOL> }

/**
 * TODO this shouldn't be required anymore once KT-65997 is fixed.
 */


private fun FirWhenExpression . convertWhenBranchesTo ( result : MutableList < IrBranch > , whenExpressionType : ConeKotlinType , flattenElse : Boolean , ) : MutableList < IrBranch >

{ <EOL> for ( branch in branches ) { <EOL> if ( flattenElse ) { <EOL> val elseIfExpression = branch . nestedElseIfOrNull ( ) <EOL> if ( elseIfExpression != null ) { <EOL> elseIfExpression . convertWhenBranchesTo ( result , whenExpressionType , flattenElse = true ) <EOL> break <EOL> } <EOL> } <EOL> result . add ( branch . toIrWhenBranch ( whenExpressionType ) ) <EOL> } <EOL> return result <EOL> }

/**
 * Converts the branches to [IrBranch]es.
 *
 * If [flattenElse] is `true` and the else branch contains another [FirWhenExpression] that's built from an `if`,
 * its branches will be added directly to the [result] list instead.
 *
 * TODO this shouldn't be required anymore once KT-65997 is fixed.
 */


fun entry ( action : Action < in Entry > )

{ <EOL> entries . add ( project . provider { <EOL> val instance = project . objects . newInstance < Entry > ( _target ) . apply { <EOL> action . execute ( this ) <EOL> } <EOL> project . objects . newInstance < GenerateCompilationDatabase . Entry > ( ) . apply { <EOL> directory . set ( instance . directory ) <EOL> files . from ( instance . files ) <EOL> arguments . set ( instance . arguments ) <EOL> output . set ( instance . output ) <EOL> } <EOL> } ) <EOL> }

/**
 * Add an entry to the compilation database for [target] with optional [sanitizer].
 *
 * @param action configure [Entry]
 */


{ <EOL> doTestFriendPaths ( File ( tmpdir , "<STR_LIT>" ) . relativeTo ( File ( "<STR_LIT>" ) . absoluteFile ) ) <EOL> }


{ <EOL> doTestFriendPaths ( File ( tmpdir , "<STR_LIT:lib>" ) . relativeTo ( File ( "<STR_LIT>" ) . absoluteFile ) ) <EOL> }


protected fun checkPackageContent ( session : FirSession , packageFqName : FqName , moduleDescriptor : ModuleDescriptor , testDataPath : String )

{ <EOL> val declarationNames = DescriptorUtils . getAllDescriptors ( moduleDescriptor . getPackage ( packageFqName ) . memberScope ) <EOL> . mapTo ( sortedSetOf ( ) ) { it . name } <EOL> val provider = session . symbolProvider <EOL> val builder = StringBuilder ( ) <EOL> val firRenderer = FirRenderer ( builder ) <EOL> for ( name in declarationNames ) { <EOL> for ( symbol in provider . getTopLevelCallableSymbols ( packageFqName , name ) ) { <EOL> firRenderer . renderElementAsString ( symbol . fir ) <EOL> builder . appendLine ( ) <EOL> } <EOL> } <EOL> for ( name in declarationNames ) { <EOL> val classLikeSymbol = provider . getClassLikeSymbolByClassId ( ClassId . topLevel ( packageFqName . child ( name ) ) ) ? : continue <EOL> firRenderer . renderElementAsString ( classLikeSymbol . fir ) <EOL> builder . appendLine ( ) <EOL> } <EOL> KotlinTestUtils . assertEqualsToFile ( File ( testDataPath ) , builder . toString ( ) . trimEnd ( ) + "<STR_LIT:\n>" ) <EOL> }

/**
 * Since fir symbol providers can't get all names in package (only fir provider can do it),
 * we should collect that names from module descriptor from FE 1.0
 */


private fun getFilePath ( filePattern : String ) : String

{ <EOL> return substitutePropertiesValues ( filePattern ) { propertyValue -> <EOL> propertyValue <EOL> . replace ( '<CHAR_LIT:\\>' , '<CHAR_LIT:/>' ) <EOL> . replace ( "<STR_LIT:$>" , "<STR_LIT>" ) <EOL> } . replace ( '<CHAR_LIT:\\>' , '<CHAR_LIT:/>' ) <EOL> }

/**
 * Get file path from a string pattern
 *
 * Implementation is mostly copied from [DefaultMavenSettingsBuilder.getFile]
 */


fun CliJavaModuleFinder . computeDefaultRootModules ( ) : List < String >

{ <EOL> val result = arrayListOf < String > ( ) <EOL> val systemModules = systemModules . associateBy ( JavaModule :: name ) <EOL> val javaSeExists = "<STR_LIT>" in systemModules <EOL> if ( javaSeExists ) { <EOL> result . add ( "<STR_LIT>" ) <EOL> } <EOL> fun JavaModule . Explicit . exportsAtLeastOnePackageUnqualified ( ) : Boolean = moduleInfo . exports . any { it . toModules . isEmpty ( ) } <EOL> if ( ! javaSeExists ) { <EOL> for ( ( name , module ) in systemModules ) { <EOL> if ( name . startsWith ( "<STR_LIT>" ) && module . exportsAtLeastOnePackageUnqualified ( ) ) { <EOL> result . add ( name ) <EOL> } <EOL> } <EOL> } <EOL> for ( ( name , module ) in systemModules ) { <EOL> if ( ! name . startsWith ( "<STR_LIT>" ) && module . exportsAtLeastOnePackageUnqualified ( ) ) { <EOL> result . add ( name ) <EOL> } <EOL> } <EOL> return result <EOL> }

/**
 * Computes the JDK's default root modules. See [JEP 261: Module System](http://openjdk.java.net/jeps/261).
 */


private fun handleAsGenericTypeQualifier ( element : KtElement ) : KtCallInfo ?

{ <EOL> if ( element !is KtExpression ) return null <EOL> val wholeQualifier = element . getQualifiedExpressionForSelector ( ) as? KtDotQualifiedExpression ? : element <EOL> val call = wholeQualifier . getPossiblyQualifiedCallExpression ( ) ? : return null <EOL> if ( call . typeArgumentList == null || call . valueArgumentList != null ) return null <EOL> return KtSuccessCallInfo ( KtGenericTypeQualifier ( token , wholeQualifier ) ) <EOL> }

/**
 * Handles call expressions like `Foo<Bar>` or `test.Foo<Bar>` in calls like `Foo<Bar>::foo` and `test.Foo<Bar>::foo`.
 *
 * ATM does not perform any resolve checks, since it does not seem possible with [BindingContext], so it might give some
 * false positives.
 */


private inline fun < reified T > assertUnsignedNumberEncoding ( expected : String , actual : T , actualPrimitive : JsonPrimitive , )

{ <EOL> assertEquals ( expected , actualPrimitive . toString ( ) , "<STR_LIT>" ) <EOL> parametrizedTest { mode -> <EOL> assertEquals ( expected , default . encodeToString ( JsonElement . serializer ( ) , actualPrimitive , mode ) , "<STR_LIT>" , ) <EOL> } <EOL> }

/**
 * Helper function for [testJsonPrimitiveUnsignedNumbers]
 *
 * Asserts that an [unsigned number][actual] can be used to create a [JsonPrimitive][actualPrimitive],
 * which can be decoded correctly.
 *
 * @param expected the expected string value of [actual]
 * @param actual the unsigned number
 * @param T should be an unsigned number
 */


abstract fun runtimeJarForTests ( ) : File


abstract fun runtimeJarForTestsWithJdk8 ( ) : File


abstract fun minimalRuntimeJarForTests ( ) : File

/**
 * Jar with minimal version of kotlin stdlib (may be same as runtimeJarForTests)
 */


abstract fun reflectJarForTests ( ) : File


abstract fun kotlinTestJarForTests ( ) : File


abstract fun scriptRuntimeJarForTests ( ) : File


abstract fun jvmAnnotationsForTests ( ) : File


abstract fun getAnnotationsJar ( ) : File

/**
 * compiler/testData/mockJDK/jre/lib/annotations.jar
 */


abstract fun fullJsStdlib ( ) : File


abstract fun defaultJsStdlib ( ) : File

/**
 * Jar with minimal version of kotlin stdlib JS (may be same as fullJsStdlib)
 */


abstract fun kotlinTestJsKLib ( ) : File


fun Tuple1 < * > . take0 ( ) : EmptyTuple

= EmptyTuple

/**
 * This file contains all functions to take N items from the beginning or end of a Tuple.
 * If 0 items are taken, the result will be [EmptyTuple].
 *
 * For example:
 * ```kotlin
 * tupleOf(1, 2, 3, 4).take2() == tupleOf(1, 2)
 * tupleOf(1, 2, 3, 4).takeLast2() == tupleOf(3, 4)
 * ```
 */


override fun put ( key : K , value : V ) : V ?

{ <EOL> if ( put ( array , shift , key , value ) ) { <EOL> if ( ++ size_ >= ( THRESHOLD ushr shift ) ) { <EOL> rehash ( ) <EOL> } <EOL> } <EOL> return null <EOL> }

/**
 * Never returns previous values
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public fun String . toByteOrNull ( ) : Byte ?

= toByteOrNull ( radix = <NUM_LIT:10> )

/**
 * Parses the string as a signed [Byte] number and returns the result
 * or `null` if the string is not a valid representation of a number.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public fun String . toByteOrNull ( radix : Int ) : Byte ?

{ <EOL> val int = this . toIntOrNull ( radix ) ? : return null <EOL> if ( int < Byte . MIN_VALUE || int > Byte . MAX_VALUE ) return null <EOL> return int . toByte ( ) <EOL> }

/**
 * Parses the string as a signed [Byte] number and returns the result
 * or `null` if the string is not a valid representation of a number.
 *
 * @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public fun String . toShortOrNull ( ) : Short ?

= toShortOrNull ( radix = <NUM_LIT:10> )

/**
 * Parses the string as a [Short] number and returns the result
 * or `null` if the string is not a valid representation of a number.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public fun String . toShortOrNull ( radix : Int ) : Short ?

{ <EOL> val int = this . toIntOrNull ( radix ) ? : return null <EOL> if ( int < Short . MIN_VALUE || int > Short . MAX_VALUE ) return null <EOL> return int . toShort ( ) <EOL> }

/**
 * Parses the string as a [Short] number and returns the result
 * or `null` if the string is not a valid representation of a number.
 *
 * @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public fun String . toIntOrNull ( ) : Int ?

= toIntOrNull ( radix = <NUM_LIT:10> )

/**
 * Parses the string as an [Int] number and returns the result
 * or `null` if the string is not a valid representation of a number.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public fun String . toIntOrNull ( radix : Int ) : Int ?

{ <EOL> checkRadix ( radix ) <EOL> val length = this . length <EOL> if ( length == <NUM_LIT:0> ) return null <EOL> val start : Int <EOL> val isNegative : Boolean <EOL> val limit : Int <EOL> val firstChar = this [ <NUM_LIT:0> ] <EOL> if ( firstChar < '<CHAR_LIT:0>' ) { <EOL> if ( length == <NUM_LIT:1> ) return null <EOL> start = <NUM_LIT:1> <EOL> if ( firstChar == '<CHAR_LIT:->' ) { <EOL> isNegative = true <EOL> limit = Int . MIN_VALUE <EOL> } else if ( firstChar == '<CHAR_LIT>' ) { <EOL> isNegative = false <EOL> limit = - Int . MAX_VALUE <EOL> } else <EOL> return null <EOL> } else { <EOL> start = <NUM_LIT:0> <EOL> isNegative = false <EOL> limit = - Int . MAX_VALUE <EOL> } <EOL> val limitForMaxRadix = ( - Int . MAX_VALUE ) / <NUM_LIT> <EOL> var limitBeforeMul = limitForMaxRadix <EOL> var result = <NUM_LIT:0> <EOL> for ( i in start until length ) { <EOL> val digit = digitOf ( this [ i ] , radix ) <EOL> if ( digit < <NUM_LIT:0> ) return null <EOL> if ( result < limitBeforeMul ) { <EOL> if ( limitBeforeMul == limitForMaxRadix ) { <EOL> limitBeforeMul = limit / radix <EOL> if ( result < limitBeforeMul ) { <EOL> return null <EOL> } <EOL> } else { <EOL> return null <EOL> } <EOL> } <EOL> result *= radix <EOL> if ( result < limit + digit ) return null <EOL> result -= digit <EOL> } <EOL> return if ( isNegative ) result else - result <EOL> }

/**
 * Parses the string as an [Int] number and returns the result
 * or `null` if the string is not a valid representation of a number.
 *
 * @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public fun String . toLongOrNull ( ) : Long ?

= toLongOrNull ( radix = <NUM_LIT:10> )

/**
 * Parses the string as a [Long] number and returns the result
 * or `null` if the string is not a valid representation of a number.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public fun String . toLongOrNull ( radix : Int ) : Long ?

{ <EOL> checkRadix ( radix ) <EOL> val length = this . length <EOL> if ( length == <NUM_LIT:0> ) return null <EOL> val start : Int <EOL> val isNegative : Boolean <EOL> val limit : Long <EOL> val firstChar = this [ <NUM_LIT:0> ] <EOL> if ( firstChar < '<CHAR_LIT:0>' ) { <EOL> if ( length == <NUM_LIT:1> ) return null <EOL> start = <NUM_LIT:1> <EOL> if ( firstChar == '<CHAR_LIT:->' ) { <EOL> isNegative = true <EOL> limit = Long . MIN_VALUE <EOL> } else if ( firstChar == '<CHAR_LIT>' ) { <EOL> isNegative = false <EOL> limit = - Long . MAX_VALUE <EOL> } else <EOL> return null <EOL> } else { <EOL> start = <NUM_LIT:0> <EOL> isNegative = false <EOL> limit = - Long . MAX_VALUE <EOL> } <EOL> val limitForMaxRadix = ( - Long . MAX_VALUE ) / <NUM_LIT> <EOL> var limitBeforeMul = limitForMaxRadix <EOL> var result = <NUM_LIT:0L> <EOL> for ( i in start until length ) { <EOL> val digit = digitOf ( this [ i ] , radix ) <EOL> if ( digit < <NUM_LIT:0> ) return null <EOL> if ( result < limitBeforeMul ) { <EOL> if ( limitBeforeMul == limitForMaxRadix ) { <EOL> limitBeforeMul = limit / radix <EOL> if ( result < limitBeforeMul ) { <EOL> return null <EOL> } <EOL> } else { <EOL> return null <EOL> } <EOL> } <EOL> result *= radix <EOL> if ( result < limit + digit ) return null <EOL> result -= digit <EOL> } <EOL> return if ( isNegative ) result else - result <EOL> }

/**
 * Parses the string as a [Long] number and returns the result
 * or `null` if the string is not a valid representation of a number.
 *
 * @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
 */


private fun isNotLessSpecificCallWithArgumentMapping ( call1 : FlatSignature < C > , call2 : FlatSignature < C > , discriminateGenerics : Boolean , useOriginalSamTypes : Boolean ) : Boolean

{ <EOL> return tryCompareDescriptorsFromScripts ( call1 . candidateDescriptor ( ) , call2 . candidateDescriptor ( ) ) ? : compareCallsByUsedArguments ( call1 , call2 , discriminateGenerics , useOriginalSamTypes ) <EOL> }

/**
 * `call1` is not less specific than `call2`
 */


private fun compareCallsByUsedArguments ( call1 : FlatSignature < C > , call2 : FlatSignature < C > , discriminateGenerics : Boolean , useOriginalSamTypes : Boolean ) : Boolean

{ <EOL> if ( discriminateGenerics ) { <EOL> val isGeneric1 = call1 . isGeneric <EOL> val isGeneric2 = call2 . isGeneric <EOL> if ( isGeneric1 && ! isGeneric2 ) return false <EOL> if ( ! isGeneric1 && isGeneric2 ) return true <EOL> if ( isGeneric1 && isGeneric2 ) return false <EOL> } <EOL> if ( ! call1 . isExpect && call2 . isExpect ) return true <EOL> if ( call1 . isExpect && ! call2 . isExpect ) return false <EOL> if ( call1 . contextReceiverCount > call2 . contextReceiverCount ) return true <EOL> if ( call1 . contextReceiverCount < call2 . contextReceiverCount ) return false <EOL> return createEmptyConstraintSystem ( ) . isSignatureNotLessSpecific ( call1 , call2 , SpecificityComparisonWithNumerics , specificityComparator , useOriginalSamTypes ) <EOL> }

/**
 * Returns `true` if [call1] is definitely more or equally specific [call2],
 * `false` otherwise.
 */


private fun tryCompareDescriptorsFromScripts ( d1 : CallableDescriptor , d2 : CallableDescriptor ) : Boolean ?

{ <EOL> val containingDeclaration1 = d1 . containingDeclaration <EOL> val containingDeclaration2 = d2 . containingDeclaration <EOL> if ( containingDeclaration1 is ScriptDescriptor && containingDeclaration2 is ScriptDescriptor ) { <EOL> when { <EOL> containingDeclaration1 . priority > containingDeclaration2 . priority -> return true <EOL> containingDeclaration1 . priority < containingDeclaration2 . priority -> return false <EOL> } <EOL> } <EOL> return null <EOL> }

/**
 * Returns `true` if `d1` is definitely not less specific than `d2`,
 * `false` if `d1` is definitely less specific than `d2`,
 * `null` if undecided.
 */


private fun isNotLessSpecificCallableReferenceDescriptor ( f : CallableDescriptor , g : CallableDescriptor ) : Boolean

{ <EOL> if ( f . valueParameters . size != g . valueParameters . size ) return false <EOL> if ( f . varargParameterPosition ( ) != g . varargParameterPosition ( ) ) return false <EOL> val fSignature = FlatSignature . createFromCallableDescriptor ( f ) <EOL> val gSignature = FlatSignature . createFromCallableDescriptor ( g ) <EOL> if ( ! createEmptyConstraintSystem ( ) . isSignatureNotLessSpecific ( fSignature , gSignature , SpecificityComparisonWithNumerics , specificityComparator ) ) { <EOL> return false <EOL> } <EOL> if ( f is CallableMemberDescriptor && g is CallableMemberDescriptor ) { <EOL> if ( ! f . isExpect && g . isExpect ) return true <EOL> if ( f . isExpect && ! g . isExpect ) return false <EOL> } <EOL> if ( platformOverloadsSpecificityComparator . isMoreSpecificShape ( g , f ) ) { <EOL> return false <EOL> } <EOL> return true <EOL> }

/**
 * Returns `true` if `f` is definitely not less specific than `g`,
 * `false` if `f` is definitely less specific than `g`,
 * `null` if undecided.
 */


fun getContributedClassifier ( name : Name , location : LookupLocation ) : ClassifierDescriptor ?

/**
 * Returns only non-deprecated classifiers.
 *
 * See [getContributedClassifierIncludeDeprecated] to get all classifiers.
 */


fun getContributedClassifierIncludeDeprecated ( name : Name , location : LookupLocation ) : DescriptorWithDeprecation < ClassifierDescriptor > ?

= <EOL> getContributedClassifier ( name , location ) ? . let { DescriptorWithDeprecation . createNonDeprecated ( it ) }

/**
 * Returns contributed classifier, but discriminates deprecated
 *
 * This method can return some classifier where [getContributedClassifier] haven't returned any,
 * but it should never return different one, even if it is deprecated.
 * Note that implementors are encouraged to provide non-deprecated classifier if it doesn't contradict
 * contract above.
 */


fun getContributedDescriptors ( kindFilter : DescriptorKindFilter = DescriptorKindFilter . ALL , nameFilter : ( Name ) -> Boolean = MemberScope . ALL_NAME_FILTER ) : Collection < DeclarationDescriptor >

/**
 * All visible descriptors from current scope possibly filtered by the given name and kind filters
 * (that means that the implementation is not obliged to use the filters but may do so when it gives any performance advantage).
 */


fun abiMetadataProcessor ( annotationVisitor : AnnotationVisitor , removeDataClassCopyIfConstructorIsPrivate : Boolean , preserveDeclarationOrder : Boolean , classesToBeDeleted : Set < String > , pruneClass : Boolean , treatInternalAsPrivate : Boolean , ) : AnnotationVisitor

= <EOL> kotlinClassHeaderVisitor { header -> <EOL> val metadataVersion = header . metadataVersion . takeIf { v -> <EOL> val major = v . getOrNull ( <NUM_LIT:0> ) ? : <NUM_LIT:0> <EOL> val minor = v . getOrNull ( <NUM_LIT:1> ) ? : <NUM_LIT:0> <EOL> major > <NUM_LIT:1> || major == <NUM_LIT:1> && minor >= <NUM_LIT:4> <EOL> } ? : intArrayOf ( <NUM_LIT:1> , <NUM_LIT:4> ) <EOL> val newHeader = runCatching { <EOL> KotlinClassMetadata . transform ( header ) { metadata -> <EOL> when ( metadata ) { <EOL> is KotlinClassMetadata . Class -> { <EOL> metadata . kmClass . removePrivateDeclarations ( removeDataClassCopyIfConstructorIsPrivate , preserveDeclarationOrder , classesToBeDeleted , pruneClass , treatInternalAsPrivate , ) <EOL> } <EOL> is KotlinClassMetadata . FileFacade -> { <EOL> metadata . kmPackage . removePrivateDeclarations ( preserveDeclarationOrder , pruneClass , treatInternalAsPrivate ) <EOL> } <EOL> is KotlinClassMetadata . MultiFileClassPart -> { <EOL> metadata . kmPackage . removePrivateDeclarations ( preserveDeclarationOrder , pruneClass , treatInternalAsPrivate ) <EOL> } <EOL> else -> Unit <EOL> } <EOL> } <EOL> } . getOrElse { cause -> <EOL> if ( System . getProperty ( "<STR_LIT>" ) . toBoolean ( ) ) { <EOL> val actual = "<STR_LIT>" <EOL> val expected = JvmMetadataVersion . LATEST_STABLE_SUPPORTED . toString ( ) <EOL> throw AssertionError ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" , cause ) <EOL> } <EOL> header <EOL> } <EOL> annotationVisitor . visitKotlinMetadata ( newHeader ) <EOL> }

/**
 * Wrap the visitor for a Kotlin Metadata annotation to strip out private and local
 * functions, properties, and type aliases as well as local delegated properties.
 */


private fun kotlinClassHeaderVisitor ( body : ( Metadata ) -> Unit ) : AnnotationVisitor

= <EOL> object : AnnotationVisitor ( Opcodes . API_VERSION ) { <EOL> var kind : Int = <NUM_LIT:1> <EOL> var metadataVersion : IntArray = intArrayOf ( ) <EOL> var data1 : MutableList < String > = mutableListOf ( ) <EOL> var data2 : MutableList < String > = mutableListOf ( ) <EOL> var extraString : String ? = null <EOL> var packageName : String ? = null <EOL> var extraInt : Int = <NUM_LIT:0> <EOL> override fun visit ( name : String , value : Any ? ) { <EOL> when ( name ) { <EOL> KIND_FIELD_NAME -> kind = value as Int <EOL> METADATA_EXTRA_INT_FIELD_NAME -> extraInt = value as Int <EOL> METADATA_VERSION_FIELD_NAME -> metadataVersion = value as IntArray <EOL> METADATA_EXTRA_STRING_FIELD_NAME -> extraString = value as String <EOL> METADATA_PACKAGE_NAME_FIELD_NAME -> packageName = value as String <EOL> } <EOL> } <EOL> override fun visitArray ( name : String ) : AnnotationVisitor ? { <EOL> val destination = when ( name ) { <EOL> METADATA_DATA_FIELD_NAME -> data1 <EOL> METADATA_STRINGS_FIELD_NAME -> data2 <EOL> else -> return null <EOL> } <EOL> return object : AnnotationVisitor ( Opcodes . API_VERSION ) { <EOL> override fun visit ( name : String ? , value : Any ? ) { <EOL> destination += value as String <EOL> } <EOL> } <EOL> } <EOL> override fun visitEnd ( ) { <EOL> body ( Metadata ( kind , metadataVersion , data1 . toTypedArray ( ) , data2 . toTypedArray ( ) , extraString , packageName , extraInt ) ) <EOL> } <EOL> }

/**
 * Parse a KotlinClassHeader from an existing Kotlin Metadata annotation visitor.
 */


private fun AnnotationVisitor . visitKotlinMetadata ( header : Metadata )

{ <EOL> visit ( KIND_FIELD_NAME , header . kind ) <EOL> visit ( METADATA_VERSION_FIELD_NAME , header . metadataVersion ) <EOL> if ( header . data1 . isNotEmpty ( ) ) { <EOL> visitArray ( METADATA_DATA_FIELD_NAME ) . apply { <EOL> header . data1 . forEach { visit ( null , it ) } <EOL> visitEnd ( ) <EOL> } <EOL> } <EOL> if ( header . data2 . isNotEmpty ( ) ) { <EOL> visitArray ( METADATA_STRINGS_FIELD_NAME ) . apply { <EOL> header . data2 . forEach { visit ( null , it ) } <EOL> visitEnd ( ) <EOL> } <EOL> } <EOL> if ( header . extraString . isNotEmpty ( ) ) { <EOL> visit ( METADATA_EXTRA_STRING_FIELD_NAME , header . extraString ) <EOL> } <EOL> if ( header . packageName . isNotEmpty ( ) ) { <EOL> visit ( METADATA_PACKAGE_NAME_FIELD_NAME , header . packageName ) <EOL> } <EOL> if ( header . extraInt != <NUM_LIT:0> ) { <EOL> visit ( METADATA_EXTRA_INT_FIELD_NAME , header . extraInt ) <EOL> } <EOL> visitEnd ( ) <EOL> }

/**
 * Serialize a KotlinClassHeader to an existing Kotlin Metadata annotation visitor.
 */


public fun KtExpression . getKtType ( ) : KtType ?

= <EOL> withValidityAssertion { analysisSession . expressionTypeProvider . getKtExpressionType ( this ) }

/**
 * Get type of given expression.
 *
 * Return:
 * - [KtExpression] type if given [KtExpression] is real expression;
 * - `null` for [KtExpression] inside pacakges and import declarations;
 * - `Unit` type for statements;
 */


public fun KtDeclaration . getReturnKtType ( ) : KtType

= <EOL> withValidityAssertion { analysisSession . expressionTypeProvider . getReturnTypeForKtDeclaration ( this ) }

/**
 * Returns the return type of the given [KtDeclaration] as [KtType].
 *
 * IMPORTANT: For `vararg foo: T` parameter returns full `Array<out T>` type (unlike
 * [KtValueParameterSymbol.returnType][org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol.returnType],
 * which returns `T`).
 */


public fun KtFunction . getFunctionalType ( ) : KtType

= <EOL> withValidityAssertion { analysisSession . expressionTypeProvider . getFunctionalTypeForKtFunction ( this ) }

/**
 * Returns the functional type of the given [KtFunction].
 *
 * For a regular function, it would be kotlin.FunctionN<Ps, R> where
 * N is the number of value parameters in the function;
 * Ps are types of value parameters;
 * R is the return type of the function.
 * Depending on the function's attributes, such as `suspend` or reflective access, different functional type,
 * such as `SuspendFunction`, `KFunction`, or `KSuspendFunction`, will be constructed.
 */


public fun PsiElement . getExpectedType ( ) : KtType ?

= <EOL> withValidityAssertion { analysisSession . expressionTypeProvider . getExpectedType ( this ) }

/**
 * Returns the expected [KtType] of this [PsiElement] if it is an expression. The returned value should not be a
 * [org.jetbrains.kotlin.analysis.api.types.KtErrorType].
 */


public fun KtExpression . isDefinitelyNull ( ) : Boolean

= <EOL> withValidityAssertion { analysisSession . expressionTypeProvider . isDefinitelyNull ( this ) }

/**
 * Returns `true` if this expression is definitely null, based on declared nullability and smart cast types derived from
 * data-flow analysis facts. Examples:
 * ```
 * public fun <T : Any> foo(t: T, nt: T?, s: String, ns: String?) {
 * t // t.isDefinitelyNull() == false && t.isDefinitelyNotNull() == true
 * nt // nt.isDefinitelyNull() == false && nt.isDefinitelyNotNull() == false
 * s // s.isDefinitelyNull() == false && s.isDefinitelyNotNull() == true
 * ns // ns.isDefinitelyNull() == false && ns.isDefinitelyNotNull() == false
 *
 * if (ns != null) {
 * ns // ns.isDefinitelyNull() == false && ns.isDefinitelyNotNull() == true
 * } else {
 * ns // ns.isDefinitelyNull() == true && ns.isDefinitelyNotNull() == false
 * }
 *
 * ns!! // From this point on: ns.isDefinitelyNull() == false && ns.isDefinitelyNotNull() == true
 * }
 * ```
 * Note that only nullability from "stable" smart cast types is considered. The
 * [spec](https://kotlinlang.org/spec/type-inference.html#smart-cast-sink-stability) provides an explanation on smart cast stability.
 */


public fun KtExpression . isDefinitelyNotNull ( ) : Boolean

= <EOL> withValidityAssertion { analysisSession . expressionTypeProvider . isDefinitelyNotNull ( this ) }

/**
 * Returns `true` if this expression is definitely not null. See [isDefinitelyNull] for examples.
 */


{ <EOL> val modelHub = ONNXModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = ONNXModels . PoseDetection . MoveNetMultiPoseLighting <EOL> val model = modelHub . loadModel ( modelType ) <EOL> model . printSummary ( ) <EOL> model . use { <EOL> println ( it ) <EOL> val imageFile = getFileFromResource ( "<STR_LIT>" ) <EOL> val inputImage = ImageConverter . toBufferedImage ( imageFile ) <EOL> val preprocessor = pipeline < BufferedImage > ( ) <EOL> . resize { <EOL> outputHeight = <NUM_LIT> <EOL> outputWidth = <NUM_LIT> <EOL> } <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . call ( modelType . preprocessor ) <EOL> val inputData = preprocessor . apply ( inputImage ) <EOL> val rawPoseLandmarks = it . predict ( inputData ) { result -> <EOL> result . get2DFloatArray ( "<STR_LIT>" ) <EOL> } <EOL> println ( rawPoseLandmarks . contentDeepToString ( ) ) <EOL> val poses = rawPoseLandmarks . mapNotNull { floats -> <EOL> val probability = floats [ <NUM_LIT> ] <EOL> if ( probability < <NUM_LIT> ) return@mapNotNull null <EOL> val foundPoseLandmarks = mutableListOf < PoseLandmark > ( ) <EOL> for ( keyPointIdx in <NUM_LIT:0> .. <NUM_LIT:16> ) { <EOL> val poseLandmark = PoseLandmark ( x = floats [ <NUM_LIT:3> * keyPointIdx + <NUM_LIT:1> ] , y = floats [ <NUM_LIT:3> * keyPointIdx ] , probability = floats [ <NUM_LIT:3> * keyPointIdx + <NUM_LIT:2> ] , label = "<STR_LIT>" ) <EOL> foundPoseLandmarks . add ( poseLandmark ) <EOL> } <EOL> val detectedObject = DetectedObject ( xMin = floats [ <NUM_LIT> ] , xMax = floats [ <NUM_LIT> ] , yMin = floats [ <NUM_LIT> ] , yMax = floats [ <NUM_LIT> ] , probability = probability ) <EOL> val detectedPose = DetectedPose ( foundPoseLandmarks , emptyList ( ) ) <EOL> detectedObject to detectedPose <EOL> } <EOL> val multiPoseDetectionResult = MultiPoseDetectionResult ( poses ) <EOL> showFrame ( "<STR_LIT>" , createMultipleDetectedPosesPanel ( inputImage , multiPoseDetectionResult ) ) <EOL> } <EOL> }

/**
 * This examples demonstrates the inference concept on SSD model:
 * - Model is obtained from [ONNXModelHub].
 * - Model predicts on a few images located in resources.
 * - Special preprocessing is applied to each image before prediction.
 */


= multiPoseDetectionMoveNet ( )


= runTest { <EOL> expect ( <NUM_LIT:1> ) <EOL> val result = withTimeout ( <NUM_LIT> ) { <EOL> expect ( <NUM_LIT:2> ) <EOL> "<STR_LIT:OK>" <EOL> } <EOL> assertEquals ( "<STR_LIT:OK>" , result ) <EOL> finish ( <NUM_LIT:3> ) <EOL> }

/**
 * Tests a case of no timeout and no suspension inside.
 */


= runTest { <EOL> expect ( <NUM_LIT:1> ) <EOL> val result = withTimeout ( <NUM_LIT> ) { <EOL> expect ( <NUM_LIT:2> ) <EOL> yield ( ) <EOL> expect ( <NUM_LIT:3> ) <EOL> "<STR_LIT:OK>" <EOL> } <EOL> assertEquals ( "<STR_LIT:OK>" , result ) <EOL> finish ( <NUM_LIT:4> ) <EOL> }

/**
 * Tests a case of no timeout and one suspension inside.
 */


= runTest { <EOL> expect ( <NUM_LIT:1> ) <EOL> launch { <EOL> expect ( <NUM_LIT:4> ) <EOL> yield ( ) <EOL> expect ( <NUM_LIT:7> ) <EOL> } <EOL> expect ( <NUM_LIT:2> ) <EOL> val result = withTimeout ( <NUM_LIT> ) { <EOL> expect ( <NUM_LIT:3> ) <EOL> yield ( ) <EOL> expect ( <NUM_LIT:5> ) <EOL> "<STR_LIT:OK>" <EOL> } <EOL> assertEquals ( "<STR_LIT:OK>" , result ) <EOL> expect ( <NUM_LIT:6> ) <EOL> yield ( ) <EOL> finish ( <NUM_LIT:8> ) <EOL> }

/**
 * Tests proper dispatching of `withTimeout` blocks
 */


@ Test <EOL> fun testYieldBlockingWithTimeout ( )

= runTest ( expected = { it is CancellationException } ) { <EOL> withTimeout ( <NUM_LIT:100> ) { <EOL> while ( true ) { <EOL> yield ( ) <EOL> } <EOL> } <EOL> }

/**
 * Tests that a 100% CPU-consuming loop will react on timeout if it has yields.
 */


@ Test <EOL> fun testWithTimeoutChildWait ( )

= runTest { <EOL> expect ( <NUM_LIT:1> ) <EOL> withTimeout ( <NUM_LIT:100> ) { <EOL> expect ( <NUM_LIT:2> ) <EOL> launch { <EOL> expect ( <NUM_LIT:4> ) <EOL> } <EOL> expect ( <NUM_LIT:3> ) <EOL> } <EOL> finish ( <NUM_LIT:5> ) <EOL> }

/**
 * Tests that [withTimeout] waits for children coroutines to complete.
 */


fun collectTailSuspendCalls ( context : CommonBackendContext , irFunction : IrSimpleFunction ) : TailSuspendCalls

{ <EOL> require ( irFunction . isSuspend ) { "<STR_LIT>" } <EOL> val body = irFunction . body ? : return TailSuspendCalls ( emptySet ( ) , false ) <EOL> class VisitorState ( val insideTryBlock : Boolean , val isTailExpression : Boolean ) <EOL> val isUnitReturn = irFunction . returnType . isUnit ( ) <EOL> var hasNotTailSuspendCall = false <EOL> val tailSuspendCalls = mutableSetOf < IrCall > ( ) <EOL> val tailReturnableBlocks = mutableSetOf < IrReturnableBlockSymbol > ( ) <EOL> val visitor = object : IrElementVisitor < Unit , VisitorState > { <EOL> override fun visitElement ( element : IrElement , data : VisitorState ) { <EOL> element . acceptChildren ( this , VisitorState ( data . insideTryBlock , isTailExpression = false ) ) <EOL> } <EOL> override fun visitTypeOperator ( expression : IrTypeOperatorCall , data : VisitorState ) { <EOL> if ( expression . operator == IrTypeOperator . IMPLICIT_CAST ) { <EOL> expression . acceptChildren ( this , data ) <EOL> } else { <EOL> super . visitTypeOperator ( expression , data ) <EOL> } <EOL> } <EOL> override fun visitTry ( aTry : IrTry , data : VisitorState ) { <EOL> aTry . tryResult . accept ( this , VisitorState ( insideTryBlock = true , isTailExpression = false ) ) <EOL> aTry . catches . forEach { it . result . accept ( this , data ) } <EOL> require ( aTry . finallyExpression == null ) { "<STR_LIT>" } <EOL> } <EOL> private fun isTailReturn ( expression : IrReturn ) = <EOL> expression . returnTargetSymbol == irFunction . symbol || expression . returnTargetSymbol in tailReturnableBlocks <EOL> override fun visitReturn ( expression : IrReturn , data : VisitorState ) { <EOL> expression . value . accept ( this , VisitorState ( data . insideTryBlock , isTailReturn ( expression ) ) ) <EOL> } <EOL> override fun visitExpressionBody ( body : IrExpressionBody , data : VisitorState ) = <EOL> body . acceptChildren ( this , data ) <EOL> override fun visitBlockBody ( body : IrBlockBody , data : VisitorState ) = <EOL> visitStatementContainer ( body , data ) <EOL> override fun visitContainerExpression ( expression : IrContainerExpression , data : VisitorState ) { <EOL> if ( expression is IrReturnableBlock && data . isTailExpression ) <EOL> tailReturnableBlocks . add ( expression . symbol ) <EOL> visitStatementContainer ( expression , data ) <EOL> } <EOL> private fun visitStatementContainer ( expression : IrStatementContainer , data : VisitorState ) { <EOL> expression . statements . forEachIndexed { index , irStatement -> <EOL> val isTailStatement = if ( index == expression . statements . lastIndex ) { <EOL> data . isTailExpression <EOL> } else { <EOL> isUnitReturn && expression . statements [ index + <NUM_LIT:1> ] . let { <EOL> it is IrReturn && isTailReturn ( it ) && it . value . isUnitRead ( ) <EOL> } <EOL> } <EOL> irStatement . accept ( this , VisitorState ( data . insideTryBlock , isTailStatement ) ) <EOL> } <EOL> } <EOL> override fun visitWhen ( expression : IrWhen , data : VisitorState ) { <EOL> expression . branches . forEach { <EOL> it . condition . accept ( this , VisitorState ( data . insideTryBlock , isTailExpression = false ) ) <EOL> it . result . accept ( this , data ) <EOL> } <EOL> } <EOL> override fun visitCall ( expression : IrCall , data : VisitorState ) { <EOL> if ( expression . isSuspend ) { <EOL> if ( ! data . insideTryBlock && data . isTailExpression ) <EOL> tailSuspendCalls . add ( expression ) <EOL> else <EOL> hasNotTailSuspendCall = true <EOL> } <EOL> val isTailExpression = data . isTailExpression && expression . isReturnIfSuspendedCall ( ) <EOL> expression . acceptChildren ( this , VisitorState ( data . insideTryBlock , isTailExpression ) ) <EOL> } <EOL> private fun IrExpression . isUnitRead ( ) : Boolean { <EOL> if ( this is IrTypeOperatorCall ) { <EOL> return this . argument . isUnitRead ( ) <EOL> } <EOL> return this is IrGetObjectValue && symbol == context . irBuiltIns . unitClass <EOL> } <EOL> private fun IrCall . isReturnIfSuspendedCall ( ) = <EOL> symbol == context . ir . symbols . returnIfSuspended <EOL> } <EOL> body . accept ( visitor , VisitorState ( insideTryBlock = false , isTailExpression = true ) ) <EOL> return TailSuspendCalls ( tailSuspendCalls , hasNotTailSuspendCall ) <EOL> }

/**
 * Collects calls to be treated as tail calls: "last" expressions which are either direct return statement with a call
 * to other suspend function, or, for a Unit-returning function, a call to other suspend function, also returning Unit.
 */


protected open fun doTestByMainFile ( mainFile : KtFile , mainModule : KtTestModule , testServices : TestServices )

{ <EOL> throw UnsupportedOperationException ( "<STR_LIT>" + "<STR_LIT>" ) <EOL> }

/**
 * Consider implementing this method if you can choose some main file in your test case. It can be, for example, a file with a caret.
 *
 * Examples of use cases:
 *
 * - Collect diagnostics of the file
 * - Get an element at the caret and invoke some logic
 * - Do some operations on [mainFile] and dump a state of other files in [mainModule]
 *
 * Only one [KtFile] can be the main one.
 *
 * The main file is selected based on the following rules:
 *
 * - A single file in the [main][isMainModule] module
 * - A single file in the project
 * - The file has a selected expression
 * - The file has a caret
 * - The file name is equal to "main" or equal to the defined [AnalysisApiTestDirectives.MAIN_FILE_NAME]
 *
 * @see findMainFile
 * @see isMainFile
 * @see AnalysisApiTestDirectives.MAIN_FILE_NAME
 */


protected open fun doTestByMainModuleAndOptionalMainFile ( mainFile : KtFile ? , mainModule : KtTestModule , testServices : TestServices )

{ <EOL> doTestByMainFile ( mainFile ? : error ( "<STR_LIT>" ) , mainModule , testServices ) <EOL> }

/**
 * Consider implementing this method if you have logic around [KtTestModule], or you don't always have a [mainFile] and have some custom
 * logic for such exceptional cases (e.g., taking the first file from [mainModule]).
 *
 * Examples of use cases:
 *
 * - Find all declarations in the module
 * - Find a declaration by qualified name and invoke some logic
 * - Process all files in the module
 *
 * Only one [KtTestModule] can be the main one.
 *
 * The main module is selected based on the following rules:
 *
 * - It is the only module
 * - It has a main file (see [doTestByMainFile] for details)
 * - The module has a defined [AnalysisApiTestDirectives.MAIN_MODULE] directive
 * - The module name is equal to [ModuleStructureExtractor.DEFAULT_MODULE_NAME]
 *
 * Use [doTestByMainModuleAndOptionalMainFile] only if [doTestByMainFile] is not suitable for your use case.
 *
 * @param mainFile a dedicated main file if it exists (see [findMainFile])
 *
 * @see findMainModule
 * @see isMainModule
 * @see AnalysisApiTestDirectives.MAIN_MODULE
 */


protected open fun doTest ( testServices : TestServices )

{ <EOL> val ( mainFile , mainModule ) = findMainFileAndModule ( testServices ) <EOL> doTestByMainModuleAndOptionalMainFile ( mainFile , mainModule , testServices ) <EOL> }

/**
 * Consider implementing this method if your test logic needs the whole
 * [KtTestModuleStructure][org.jetbrains.kotlin.analysis.test.framework.project.structure.KtTestModuleStructure].
 *
 * Examples of use cases:
 *
 * - Find all files in all modules
 * - Find two declarations from different files and different modules and compare them
 *
 * The [KtTestModuleStructure][org.jetbrains.kotlin.analysis.test.framework.project.structure.KtTestModuleStructure] can be accessed via
 * [ktTestModuleStructure] on [testServices].
 *
 * Use only if [doTestByMainModuleAndOptionalMainFile] is not suitable for your use case.
 */


private fun String . addAllDependenciesFromOtherConfigurations ( project : Project , vararg configurationNames : String )

{ <EOL> project . configurations . named ( this ) . configure { receiverConfiguration -> <EOL> receiverConfiguration . dependencies . addAllLater ( project . listProperty < Dependency > { <EOL> configurationNames <EOL> . map { project . configurations . getByName ( it ) } <EOL> . flatMap { it . allDependencies } <EOL> } ) <EOL> } <EOL> }

/**
 * Adds `allDependencies` of configurations mentioned in `configurationNames` to configuration named [this] in
 * a lazy manner
 */


public fun < T > middle ( column : ColumnReference < T > , ) : PositionalMapping < T >

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

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


public fun < T > middle ( column : KProperty < T > , ) : PositionalMapping < T >

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

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


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

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

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


public fun < T > middle ( values : Iterable < T > , ) : PositionalMapping < T >

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

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


public fun < T > middle ( values : DataColumn < T > , ) : PositionalMapping < T >

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

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


public fun < T > DataFrame < T > . take ( n : Int ) : DataFrame < T >

{ <EOL> require ( n >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> return getRows ( <NUM_LIT:0> until n . coerceAtMost ( nrow ) ) <EOL> }

/**
 * Returns a DataFrame containing first [n] rows.
 *
 * @throws IllegalArgumentException if [n] is negative.
 */


public fun < T > DataFrame < T > . takeLast ( n : Int = <NUM_LIT:1> ) : DataFrame < T >

{ <EOL> require ( n >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> return drop ( ( nrow - n ) . coerceAtLeast ( <NUM_LIT:0> ) ) <EOL> }

/**
 * Returns a DataFrame containing last [n] rows.
 *
 * @throws IllegalArgumentException if [n] is negative.
 */


public fun < T > DataFrame < T > . takeWhile ( predicate : RowFilter < T > ) : DataFrame < T >

= <EOL> firstOrNull { ! predicate ( it , it ) } ? . let { take ( it . index ) } ? : this

/**
 * Returns a DataFrame containing first rows that satisfy the given [predicate].
 */


public fun < C > ColumnSet < C > . take ( n : Int ) : ColumnSet < C >

= transform { it . take ( n ) }

/**
 * @include [CommonTakeFirstDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[colsOf][SingleColumn.colsOf]`<`[String][String]`>().`[take][ColumnSet.take]`(2) }`
 *
 * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { .. }.`[take][ColumnSet.take]`(2) }`
 */


public fun ColumnsSelectionDsl < * > . take ( n : Int ) : ColumnSet < * >

= <EOL> this . asSingleColumn ( ) . takeCols ( n )

/**
 * @include [CommonTakeFirstDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[take][ColumnsSelectionDsl.take]`(5) }`
 */


public fun SingleColumn < DataRow < * > > . takeCols ( n : Int ) : ColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . transformSingle { it . cols ( ) . take ( n ) }

/**
 * @include [CommonTakeFirstDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { myColumnGroup.`[takeCols][SingleColumn.takeCols]`(1) }`
 */


public fun String . takeCols ( n : Int ) : ColumnSet < * >

= columnGroup ( this ) . takeCols ( n )

/**
 * @include [CommonTakeFirstDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "myColumnGroup".`[takeCols][String.takeCols]`(1) }`
 */


public fun KProperty < * > . takeCols ( n : Int ) : ColumnSet < * >

= columnGroup ( this ) . takeCols ( n )

/**
 * @include [CommonTakeFirstDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { Type::myColumnGroup.`[takeCols][SingleColumn.takeCols]`(1) }`
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColumnGroup.`[takeCols][KProperty.takeCols]`(1) }`
 */


public fun ColumnPath . takeCols ( n : Int ) : ColumnSet < * >

= columnGroup ( this ) . takeCols ( n )

/**
 * @include [CommonTakeFirstDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["myColumnGroup"].`[takeCols][ColumnPath.takeCols]`(1) }`
 */


public fun < C > ColumnSet < C > . takeLast ( n : Int = <NUM_LIT:1> ) : ColumnSet < C >

= transform { it . takeLast ( n ) }

/**
 * @include [CommonTakeLastDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[colsOf][SingleColumn.colsOf]`<`[String][String]`>().`[takeLast][ColumnSet.takeLast]`(2) }`
 *
 * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { .. }.`[takeLast][ColumnSet.takeLast]`(2) }`
 */


public fun ColumnsSelectionDsl < * > . takeLast ( n : Int = <NUM_LIT:1> ) : ColumnSet < * >

= <EOL> asSingleColumn ( ) . takeLastCols ( n )

/**
 * @include [CommonTakeLastDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[takeLast][ColumnsSelectionDsl.takeLast]`(5) }`
 */


public fun SingleColumn < DataRow < * > > . takeLastCols ( n : Int ) : ColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . transformSingle { it . cols ( ) . takeLast ( n ) }

/**
 * @include [CommonTakeLastDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { myColumnGroup.`[takeLast][SingleColumn.takeLastCols]`(1) }`
 */


public fun String . takeLastCols ( n : Int ) : ColumnSet < * >

= columnGroup ( this ) . takeLastCols ( n )

/**
 * @include [CommonTakeLastDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "myColumnGroup".`[takeLastCols][String.takeLastCols]`(1) }`
 */


public fun KProperty < * > . takeLastCols ( n : Int ) : ColumnSet < * >

/**
 * @include [CommonTakeLastDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { Type::myColumnGroup.`[takeLastCols][SingleColumn.takeLastCols]`(1) }`
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColumnGroup.`[takeLastCols][KProperty.takeLastCols]`(1) }`
 */


public fun ColumnPath . takeLastCols ( n : Int ) : ColumnSet < * >

/**
 * @include [CommonTakeLastDocs]
 * @set [CommonTakeAndDropDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["myColumnGroup"].`[takeLastCols][ColumnPath.takeLastCols]`(1) }`
 */


public fun < C > ColumnSet < C > . takeWhile ( predicate : ColumnFilter < C > ) : ColumnSet < C >

= <EOL> transform { it . takeWhile ( predicate ) }

/**
 * @include [CommonTakeFirstWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[colsOf][SingleColumn.colsOf]`<`[String][String]`>().`[takeWhile][ColumnSet.takeWhile]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 *
 * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { .. }.`[takeWhile][ColumnSet.takeWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun ColumnsSelectionDsl < * > . takeWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

= <EOL> asSingleColumn ( ) . takeColsWhile ( predicate )

/**
 * @include [CommonTakeFirstWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[takeWhile][ColumnsSelectionDsl.takeWhile]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 */


public fun SingleColumn < DataRow < * > > . takeColsWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . transformSingle { it . cols ( ) . takeWhile ( predicate ) }

/**
 * @include [CommonTakeFirstWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { myColumnGroup.`[takeWhile][SingleColumn.takeColsWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun String . takeColsWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

= <EOL> columnGroup ( this ) . takeColsWhile ( predicate )

/**
 * @include [CommonTakeFirstWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "myColumnGroup".`[takeColsWhile][String.takeColsWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun KProperty < * > . takeColsWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

/**
 * @include [CommonTakeFirstWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { Type::myColumnGroup.`[takeColsWhile][SingleColumn.takeColsWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColumnGroup.`[takeColsWhile][KProperty.takeColsWhile]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 */


public fun ColumnPath . takeColsWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

/**
 * @include [CommonTakeFirstWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["myColumnGroup"].`[takeColsWhile][ColumnPath.takeColsWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun < C > ColumnSet < C > . takeLastWhile ( predicate : ColumnFilter < C > ) : ColumnSet < C >

= <EOL> transform { it . takeLastWhile ( predicate ) }

/**
 * @include [CommonTakeLastWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[colsOf][SingleColumn.colsOf]`<`[String][String]`>().`[takeLastWhile][ColumnSet.takeLastWhile]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 *
 * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { .. }.`[takeLastWhile][ColumnSet.takeLastWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun ColumnsSelectionDsl < * > . takeLastWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

= <EOL> asSingleColumn ( ) . takeLastColsWhile ( predicate )

/**
 * @include [CommonTakeLastWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[takeLastWhile][ColumnsSelectionDsl.takeLastWhile]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 */


public fun SingleColumn < DataRow < * > > . takeLastColsWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . transformSingle { it . cols ( ) . takeLastWhile ( predicate ) }

/**
 * @include [CommonTakeLastWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { myColumnGroup.`[takeLastColsWhile][SingleColumn.takeLastColsWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun String . takeLastColsWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

= <EOL> columnGroup ( this ) . takeLastColsWhile ( predicate )

/**
 * @include [CommonTakeLastWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "myColumnGroup".`[takeLastColsWhile][String.takeLastColsWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun KProperty < * > . takeLastColsWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

/**
 * @include [CommonTakeLastWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { Type::myColumnGroup.`[takeLastColsWhile][SingleColumn.takeLastColsWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColumnGroup.`[takeLastColsWhile][KProperty.takeLastColsWhile]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 */


public fun ColumnPath . takeLastColsWhile ( predicate : ColumnFilter < * > ) : ColumnSet < * >

/**
 * @include [CommonTakeLastWhileDocs]
 * @set [CommonTakeAndDropWhileDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["myColumnGroup"].`[takeLastColsWhile][ColumnPath.takeLastColsWhile]` { it.`[name][ColumnWithPath.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


internal fun < F , S , R > applyIfBothNotNull ( first : F ? , second : S ? , operation : ( F , S ) -> R ) : R ?

= <EOL> if ( first == null || second == null ) null else operation ( first , second )

/**
 * Applies [operation] to [first] and [second] if both not-null, otherwise returns null
 */


internal fun < F : R , S : R , R > applyWithDefault ( first : F ? , second : S ? , operation : ( F , S ) -> R ) : R ?

= when { <EOL> first == null && second == null -> null <EOL> first == null -> second <EOL> second == null -> first <EOL> else -> operation ( first , second ) <EOL> }

/**
 * If both [first] and [second] are null, then return null
 * If only one of [first] and [second] is null, then return other one
 * Otherwise, return result of [operation]
 */


public abstract operator fun times ( scalar : Int ) : DateTimeUnit

/** Produces a date-time unit that is a multiple of this unit times the specified integer [scalar] value. */


internal fun ArtifactContent . write ( artifactFile : File , rootDir : File )

{ <EOL> val sources = sources . joinToString ( "<STR_LIT:\n>" ) { it . toRelativeString ( rootDir ) } <EOL> val outputs = outputs . joinToString ( "<STR_LIT:\n>" ) { it . toRelativeString ( rootDir ) } <EOL> val reports = reports . joinToString ( "<STR_LIT:\n>" ) { it . toRelativeString ( rootDir ) } <EOL> artifactFile . writeText ( "<STR_LIT>" ) <EOL> }

/**
 * Write Kover artifact content to the file.
 */


internal fun File . parseArtifactFile ( rootDir : File ) : ArtifactContent

{ <EOL> if ( ! exists ( ) || ! name . endsWith ( "<STR_LIT>" ) ) return ArtifactContent ( emptySet ( ) , emptySet ( ) , emptySet ( ) ) <EOL> val iterator = readLines ( ) . iterator ( ) <EOL> val sources = iterator . groupUntil { it . isEmpty ( ) } . map { rootDir . resolve ( it ) } . toSet ( ) <EOL> val outputs = iterator . groupUntil { it . isEmpty ( ) } . map { rootDir . resolve ( it ) } . toSet ( ) <EOL> val reports = iterator . groupUntil { it . isEmpty ( ) } . map { rootDir . resolve ( it ) } . toSet ( ) <EOL> return ArtifactContent ( sources , outputs , reports ) <EOL> }

/**
 * Read Kover artifact content from the file.
 */


public operator fun BufferedInputStream . iterator ( ) : ByteIterator

= <EOL> object : ByteIterator ( ) { <EOL> var nextByte = - <NUM_LIT:1> <EOL> var nextPrepared = false <EOL> var finished = false <EOL> private fun prepareNext ( ) { <EOL> if ( ! nextPrepared && ! finished ) { <EOL> nextByte = read ( ) <EOL> nextPrepared = true <EOL> finished = ( nextByte == - <NUM_LIT:1> ) <EOL> } <EOL> } <EOL> public override fun hasNext ( ) : Boolean { <EOL> prepareNext ( ) <EOL> return ! finished <EOL> } <EOL> public override fun nextByte ( ) : Byte { <EOL> prepareNext ( ) <EOL> if ( finished ) <EOL> throw NoSuchElementException ( "<STR_LIT>" ) <EOL> val res = nextByte . toByte ( ) <EOL> nextPrepared = false <EOL> return res <EOL> } <EOL> }

/** Returns an [Iterator] of bytes read from this input stream. */


@ kotlin . internal . InlineOnly <EOL> public inline fun String . byteInputStream ( charset : Charset = Charsets . UTF_8 ) : ByteArrayInputStream

= ByteArrayInputStream ( toByteArray ( charset ) )

/** Creates a new byte input stream for the string. */


@ kotlin . internal . InlineOnly <EOL> public inline fun ByteArray . inputStream ( ) : ByteArrayInputStream

= ByteArrayInputStream ( this )

/**
 * Creates an input stream for reading data from this byte array.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun ByteArray . inputStream ( offset : Int , length : Int ) : ByteArrayInputStream

= ByteArrayInputStream ( this , offset , length )

/**
 * Creates an input stream for reading data from the specified portion of this byte array.
 * @param offset the start offset of the portion of the array to read.
 * @param length the length of the portion of the array to read.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun InputStream . buffered ( bufferSize : Int = DEFAULT_BUFFER_SIZE ) : BufferedInputStream

= <EOL> if ( this is BufferedInputStream ) this else BufferedInputStream ( this , bufferSize )

/**
 * Creates a buffered input stream wrapping this stream.
 * @param bufferSize the buffer size to use.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun InputStream . reader ( charset : Charset = Charsets . UTF_8 ) : InputStreamReader

= InputStreamReader ( this , charset )

/** Creates a reader on this input stream using UTF-8 or the specified [charset]. */


@ kotlin . internal . InlineOnly <EOL> public inline fun InputStream . bufferedReader ( charset : Charset = Charsets . UTF_8 ) : BufferedReader

= reader ( charset ) . buffered ( )

/** Creates a buffered reader on this input stream using UTF-8 or the specified [charset]. */


@ kotlin . internal . InlineOnly <EOL> public inline fun OutputStream . buffered ( bufferSize : Int = DEFAULT_BUFFER_SIZE ) : BufferedOutputStream

= <EOL> if ( this is BufferedOutputStream ) this else BufferedOutputStream ( this , bufferSize )

/**
 * Creates a buffered output stream wrapping this stream.
 * @param bufferSize the buffer size to use.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun OutputStream . writer ( charset : Charset = Charsets . UTF_8 ) : OutputStreamWriter

= OutputStreamWriter ( this , charset )

/** Creates a writer on this output stream using UTF-8 or the specified [charset]. */


@ kotlin . internal . InlineOnly <EOL> public inline fun OutputStream . bufferedWriter ( charset : Charset = Charsets . UTF_8 ) : BufferedWriter

= writer ( charset ) . buffered ( )

/** Creates a buffered writer on this output stream using UTF-8 or the specified [charset]. */


public fun InputStream . copyTo ( out : OutputStream , bufferSize : Int = DEFAULT_BUFFER_SIZE ) : Long

{ <EOL> var bytesCopied : Long = <NUM_LIT:0> <EOL> val buffer = ByteArray ( bufferSize ) <EOL> var bytes = read ( buffer ) <EOL> while ( bytes >= <NUM_LIT:0> ) { <EOL> out . write ( buffer , <NUM_LIT:0> , bytes ) <EOL> bytesCopied += bytes <EOL> bytes = read ( buffer ) <EOL> } <EOL> return bytesCopied <EOL> }

/**
 * Copies this stream to the given output stream, returning the number of bytes copied
 *
 * **Note** It is the caller's responsibility to close both of these resources.
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.3>" , errorSince = "<STR_LIT:1.5>" ) <EOL> public fun InputStream . readBytes ( estimatedSize : Int = DEFAULT_BUFFER_SIZE ) : ByteArray

{ <EOL> val buffer = ByteArrayOutputStream ( maxOf ( estimatedSize , this . available ( ) ) ) <EOL> copyTo ( buffer ) <EOL> return buffer . toByteArray ( ) <EOL> }

/**
 * Reads this stream completely into a byte array.
 *
 * **Note**: It is the caller's responsibility to close this stream.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> public fun InputStream . readBytes ( ) : ByteArray

{ <EOL> val buffer = ByteArrayOutputStream ( maxOf ( DEFAULT_BUFFER_SIZE , this . available ( ) ) ) <EOL> copyTo ( buffer ) <EOL> return buffer . toByteArray ( ) <EOL> }


fun resolve ( sourceSet : KotlinSourceSet , dependencies : Set < IdeaKotlinDependency > )

/**
 * This function is intended to resolve 'additional' artifacts:
 * This means 'artifacts' that can be attached to some existing/already resolved dependency.
 * One good example of such an 'additional artifact' would be a -sources.jar file:
 * It is not a dependency on its own: It shares the coordinates with some [IdeaKotlinBinaryDependency] and can be
 * attached to this dependency to provide extra functionality.
 *
 * Contract:
 * - This function is allowed to attach data to a given [IdeaKotlinDependency]
 * - This function is not allowed to remove data from a given [IdeaKotlinBinaryDependency]
 * - This function is not supposed to modify the [sourceSet]
 *
 * @param sourceSet: The current SourceSet which shall resolve additional dependencies
 * @param dependencies: The already resolved dependencies from prior stages
 */


internal fun IdeAdditionalArtifactResolver ( resolver : IdeDependencyResolver )

= IdeAdditionalArtifactResolver { sourceSet , dependencies -> <EOL> val dependenciesByCoordinates = dependencies . filterIsInstance < IdeaKotlinResolvedBinaryDependency > ( ) <EOL> . filter { it . binaryType == IdeaKotlinBinaryDependency . KOTLIN_COMPILE_BINARY_TYPE } <EOL> . groupBy { it . coordinates ? . copy ( sourceSetName = null ) } <EOL> resolver . resolve ( sourceSet ) . filterIsInstance < IdeaKotlinResolvedBinaryDependency > ( ) <EOL> . filter { it . binaryType == SOURCES_BINARY_TYPE || it . binaryType == DOCUMENTATION_BINARY_TYPE } <EOL> . forEach forEachSourceOrDocumentationDependency @ { sourceOrDocumentationDependency -> <EOL> dependenciesByCoordinates [ sourceOrDocumentationDependency . coordinates ? : return@forEachSourceOrDocumentationDependency ] <EOL> . orEmpty ( ) . forEach forEachMatchedDependency @ { dependency -> <EOL> val classpath = when ( sourceOrDocumentationDependency . binaryType ) { <EOL> SOURCES_BINARY_TYPE -> dependency . sourcesClasspath <EOL> DOCUMENTATION_BINARY_TYPE -> dependency . documentationClasspath <EOL> else -> return@forEachMatchedDependency <EOL> } <EOL> classpath . addAll ( dependency . classpath ) <EOL> } <EOL> } <EOL> }

/**
 * Creates an [IdeAdditionalArtifactResolver] from a given [IdeDependencyResolver]:
 * Dependencies from the [IdeDependencyResolver] need to resolve sources and javadoc using
 * the [SOURCES_BINARY_TYPE] or [DOCUMENTATION_BINARY_TYPE]
 */


@ InternalCoroutinesApi <EOL> public fun < T > ( suspend ( ) -> T ) . startCoroutineCancellable ( completion : Continuation < T > ) : Unit

= runSafely ( completion ) { <EOL> createCoroutineUnintercepted ( completion ) . intercepted ( ) . resumeCancellableWith ( Result . success ( Unit ) ) <EOL> }

/**
 * Use this function to start coroutine in a cancellable way, so that it can be cancelled
 * while waiting to be dispatched.
 */


internal fun < R , T > ( suspend ( R ) -> T ) . startCoroutineCancellable ( receiver : R , completion : Continuation < T > , onCancellation : ( ( cause : Throwable ) -> Unit ) ? = null )

= <EOL> runSafely ( completion ) { <EOL> createCoroutineUnintercepted ( receiver , completion ) . intercepted ( ) . resumeCancellableWith ( Result . success ( Unit ) , onCancellation ) <EOL> }


internal fun Continuation < Unit > . startCoroutineCancellable ( fatalCompletion : Continuation < * > )

= <EOL> runSafely ( fatalCompletion ) { <EOL> intercepted ( ) . resumeCancellableWith ( Result . success ( Unit ) ) <EOL> }

/**
 * Similar to [startCoroutineCancellable], but for already created coroutine.
 * [fatalCompletion] is used only when interception machinery throws an exception
 */


private inline fun runSafely ( completion : Continuation < * > , block : ( ) -> Unit )

{ <EOL> try { <EOL> block ( ) <EOL> } catch ( e : Throwable ) { <EOL> dispatcherFailure ( completion , e ) <EOL> } <EOL> }

/**
 * Runs given block and completes completion with its exception if it occurs.
 * Rationale: [startCoroutineCancellable] is invoked when we are about to run coroutine asynchronously in its own dispatcher.
 * Thus if dispatcher throws an exception during coroutine start, coroutine never completes, so we should treat dispatcher exception
 * as its cause and resume completion.
 */


fun createCandidate ( callInfo : CallInfo , symbol : FirBasedSymbol < * > , explicitReceiverKind : ExplicitReceiverKind , scope : FirScope ? , dispatchReceiver : FirExpression ? = null , givenExtensionReceiverOptions : List < FirExpression > = emptyList ( ) , objectsByName : Boolean = false , isFromOriginalTypeInPresenceOfSmartCast : Boolean = false , ) : Candidate

{ <EOL> var pluginAmbiguity : AmbiguousInterceptedSymbol ? = null <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> @ OptIn ( FirExtensionApiInternals :: class ) <EOL> val symbol = if ( callRefinementExtensions != null && callInfo . callKind == CallKind . Function && symbol is FirNamedFunctionSymbol ) { <EOL> val result = symbol . replaceFromPluginsIfNeeded ( callRefinementExtensions , callInfo ) <EOL> pluginAmbiguity = result . second <EOL> result . first <EOL> } else { <EOL> symbol . unwrapIntegerOperatorSymbolIfNeeded ( callInfo ) <EOL> } <EOL> val result = Candidate ( symbol , dispatchReceiver , givenExtensionReceiverOptions , explicitReceiverKind , context . inferenceComponents . constraintSystemFactory , baseSystem , callInfo , scope , isFromCompanionObjectTypeScope = when ( explicitReceiverKind ) { <EOL> ExplicitReceiverKind . EXTENSION_RECEIVER -> <EOL> givenExtensionReceiverOptions . singleOrNull ( ) . isCandidateFromCompanionObjectTypeScope ( callInfo . session ) <EOL> ExplicitReceiverKind . DISPATCH_RECEIVER -> dispatchReceiver . isCandidateFromCompanionObjectTypeScope ( callInfo . session ) <EOL> ExplicitReceiverKind . NO_EXPLICIT_RECEIVER , ExplicitReceiverKind . BOTH_RECEIVERS -> false <EOL> } , isFromOriginalTypeInPresenceOfSmartCast , context . bodyResolveContext . inferenceSession , ) <EOL> if ( pluginAmbiguity != null ) { <EOL> result . addDiagnostic ( pluginAmbiguity ) <EOL> } <EOL> val callSite = callInfo . callSite <EOL> if ( callSite is FirCallableReferenceAccess ) { <EOL> when { <EOL> symbol is FirValueParameterSymbol || symbol is FirPropertySymbol && symbol . isLocal || symbol is FirBackingFieldSymbol -> { <EOL> result . addDiagnostic ( Unsupported ( "<STR_LIT>" , callSite . calleeReference . source ) ) <EOL> } <EOL> symbol is FirEnumEntrySymbol -> { <EOL> result . addDiagnostic ( Unsupported ( "<STR_LIT>" , callSite . calleeReference . source ) ) <EOL> } <EOL> } <EOL> } else if ( objectsByName && symbol . isRegularClassWithoutCompanion ( callInfo . session ) ) { <EOL> result . addDiagnostic ( NoCompanionObject ) <EOL> } <EOL> if ( callInfo . origin == FirFunctionCallOrigin . Operator ) { <EOL> val normalizedSymbol = when ( symbol ) { <EOL> !is FirFunctionSymbol -> symbol <EOL> else -> callInfo . candidateForCommonInvokeReceiver ? . symbol ? . takeIf { it !is FirFunctionSymbol } <EOL> } <EOL> normalizedSymbol ? . let { result . addDiagnostic ( NotFunctionAsOperator ( normalizedSymbol ) ) } <EOL> } <EOL> if ( symbol is FirPropertySymbol && ! context . session . languageVersionSettings . supportsFeature ( LanguageFeature . PrioritizedEnumEntries ) ) { <EOL> val containingClass = symbol . containingClassLookupTag ( ) ? . toFirRegularClass ( context . session ) <EOL> if ( containingClass != null && symbol . fir . isEnumEntries ( containingClass ) ) { <EOL> result . addDiagnostic ( LowerPriorityToPreserveCompatibilityDiagnostic ) <EOL> } <EOL> } <EOL> return result <EOL> }

/**
 * [createCandidate] doesn't make any guarantees for inapplicable calls. Errors in the call or callee do not necessarily result in an
 * inapplicable [Candidate].
 */


protected abstract fun crop ( tf : Ops , input : Operand < Float > ) : Operand < Float >

/**
 * The actual implementation of cropping operation which each subclassed layer needs to
 * implement. This method will then be called from [build] method to crop the input tensor.
 */


@ ExternalKotlinTargetApi <EOL> fun Jar . includeSources ( compilation : DecoratedExternalKotlinCompilation )

{ <EOL> includeSources ( compilation . internal ) <EOL> }

/**
 *
 * Will add all sources (including transitive dependsOn edges) from the compilation into this jar task given
 * the multiplatform convention.
 *
 * e.g.
 * ```
 * src/commonMain/kotlin/CommonMain.kt
 * src/jvmMain/kotlin/JvmMain.kt
 * ```
 *
 * will be packaged like
 * ```
 * /commonMain/CommonMain.kt
 * /jvmMain/JvmMain.kt
 * ```
 *
 * @since 1.9.20
 */


@ ExternalKotlinTargetApi <EOL> fun DecoratedExternalKotlinTarget . sourcesJarTask ( compilation : DecoratedExternalKotlinCompilation ) : TaskProvider < Jar >

{ <EOL> return sourcesJarTask ( compilation , componentName = lowerCamelCaseName ( targetName , compilation . name . takeUnless { compilation . isMain ( ) } ) , artifactNameAppendix = targetName . toLowerCaseAsciiOnly ( ) ) <EOL> }

/**
 * Registers, or returns if already existing, a sources jar task that contains
 * all sources of the given compilation (see [includeSources])
 *
 * @since 1.9.20
 */


@ ExternalKotlinTargetApi <EOL> fun DecoratedExternalKotlinTarget . publishSources ( jarTask : TaskProvider < Jar > )

{ <EOL> delegate . sourcesElementsPublishedConfiguration . outgoing . artifact ( jarTask ) { artifact -> <EOL> artifact . classifier = "<STR_LIT>" <EOL> } <EOL> }

/**
 * Publishes the sources packaged by the given [jarTask] in this targets' publication.
 *
 * @since 1.9.20
 */


@ ExternalKotlinTargetApi <EOL> fun DecoratedExternalKotlinTarget . publishSources ( compilation : DecoratedExternalKotlinCompilation )

{ <EOL> publishSources ( sourcesJarTask ( compilation ) ) <EOL> }

/**
 * Publishes the sources associated with the given [compilation] in this targets' publication.
 * Will register the corresponding [sourcesJarTask] if necessary.
 *
 * @since 1.9.20
 */


public operator fun < @ kotlin . internal . OnlyInputTypes T > Sequence < T > . contains ( element : T ) : Boolean

{ <EOL> return indexOf ( element ) >= <NUM_LIT:0> <EOL> }

/**
 * Returns `true` if [element] is found in the sequence.
 *
 * The operation is _terminal_.
 */


public fun < T > Sequence < T > . elementAt ( index : Int ) : T

{ <EOL> return elementAtOrElse ( index ) { throw IndexOutOfBoundsException ( "<STR_LIT>" ) } <EOL> }

/**
 * Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this sequence.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Elements.elementAt
 */


public fun < T > Sequence < T > . elementAtOrElse ( index : Int , defaultValue : ( Int ) -> T ) : T

{ <EOL> contract { <EOL> callsInPlace ( defaultValue , InvocationKind . AT_MOST_ONCE ) <EOL> } <EOL> if ( index < <NUM_LIT:0> ) <EOL> return defaultValue ( index ) <EOL> val iterator = iterator ( ) <EOL> var count = <NUM_LIT:0> <EOL> while ( iterator . hasNext ( ) ) { <EOL> val element = iterator . next ( ) <EOL> if ( index == count ++ ) <EOL> return element <EOL> } <EOL> return defaultValue ( index ) <EOL> }

/**
 * Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this sequence.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Elements.elementAtOrElse
 */


public fun < T > Sequence < T > . elementAtOrNull ( index : Int ) : T ?

{ <EOL> if ( index < <NUM_LIT:0> ) <EOL> return null <EOL> val iterator = iterator ( ) <EOL> var count = <NUM_LIT:0> <EOL> while ( iterator . hasNext ( ) ) { <EOL> val element = iterator . next ( ) <EOL> if ( index == count ++ ) <EOL> return element <EOL> } <EOL> return null <EOL> }

/**
 * Returns an element at the given [index] or `null` if the [index] is out of bounds of this sequence.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Elements.elementAtOrNull
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > Sequence < T > . find ( predicate : ( T ) -> Boolean ) : T ?

{ <EOL> return firstOrNull ( predicate ) <EOL> }

/**
 * Returns the first element matching the given [predicate], or `null` if no such element was found.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Elements.find
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > Sequence < T > . findLast ( predicate : ( T ) -> Boolean ) : T ?

{ <EOL> return lastOrNull ( predicate ) <EOL> }

/**
 * Returns the last element matching the given [predicate], or `null` if no such element was found.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Elements.find
 */


public fun < T > Sequence < T > . first ( ) : T

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

/**
 * Returns the first element.
 *
 * The operation is _terminal_.
 *
 * @throws NoSuchElementException if the sequence is empty.
 */


public inline fun < T > Sequence < T > . first ( predicate : ( T ) -> Boolean ) : T

{ <EOL> for ( element in this ) if ( predicate ( element ) ) return element <EOL> throw NoSuchElementException ( "<STR_LIT>" ) <EOL> }

/**
 * Returns the first element matching the given [predicate].
 * @throws [NoSuchElementException] if no such element is found.
 *
 * The operation is _terminal_.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun < T , R : Any > Sequence < T > . firstNotNullOf ( transform : ( T ) -> R ? ) : R

{ <EOL> return firstNotNullOfOrNull ( transform ) ? : throw NoSuchElementException ( "<STR_LIT>" ) <EOL> }

/**
 * Returns the first non-null value produced by [transform] function being applied to elements of this sequence in iteration order,
 * or throws [NoSuchElementException] if no non-null value was produced.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Transformations.firstNotNullOf
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun < T , R : Any > Sequence < T > . firstNotNullOfOrNull ( transform : ( T ) -> R ? ) : R ?

{ <EOL> for ( element in this ) { <EOL> val result = transform ( element ) <EOL> if ( result != null ) { <EOL> return result <EOL> } <EOL> } <EOL> return null <EOL> }

/**
 * Returns the first non-null value produced by [transform] function being applied to elements of this sequence in iteration order,
 * or `null` if no non-null value was produced.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Transformations.firstNotNullOf
 */


public fun < T > Sequence < T > . firstOrNull ( ) : T ?

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

/**
 * Returns the first element, or `null` if the sequence is empty.
 *
 * The operation is _terminal_.
 */


public inline fun < T > Sequence < T > . firstOrNull ( predicate : ( T ) -> Boolean ) : T ?

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

/**
 * Returns the first element matching the given [predicate], or `null` if element was not found.
 *
 * The operation is _terminal_.
 */


public fun < @ kotlin . internal . OnlyInputTypes T > Sequence < T > . indexOf ( element : T ) : Int

{ <EOL> var index = <NUM_LIT:0> <EOL> for ( item in this ) { <EOL> checkIndexOverflow ( index ) <EOL> if ( element == item ) <EOL> return index <EOL> index ++ <EOL> } <EOL> return - <NUM_LIT:1> <EOL> }

/**
 * Returns first index of [element], or -1 if the sequence does not contain element.
 *
 * The operation is _terminal_.
 */


public inline fun < T > Sequence < T > . indexOfFirst ( predicate : ( T ) -> Boolean ) : Int

{ <EOL> var index = <NUM_LIT:0> <EOL> for ( item in this ) { <EOL> checkIndexOverflow ( index ) <EOL> if ( predicate ( item ) ) <EOL> return index <EOL> index ++ <EOL> } <EOL> return - <NUM_LIT:1> <EOL> }

/**
 * Returns index of the first element matching the given [predicate], or -1 if the sequence does not contain such element.
 *
 * The operation is _terminal_.
 */


public inline fun < T > Sequence < T > . indexOfLast ( predicate : ( T ) -> Boolean ) : Int

{ <EOL> var lastIndex = - <NUM_LIT:1> <EOL> var index = <NUM_LIT:0> <EOL> for ( item in this ) { <EOL> checkIndexOverflow ( index ) <EOL> if ( predicate ( item ) ) <EOL> lastIndex = index <EOL> index ++ <EOL> } <EOL> return lastIndex <EOL> }

/**
 * Returns index of the last element matching the given [predicate], or -1 if the sequence does not contain such element.
 *
 * The operation is _terminal_.
 */


public fun < T > Sequence < T > . last ( ) : T

{ <EOL> val iterator = iterator ( ) <EOL> if ( ! iterator . hasNext ( ) ) <EOL> throw NoSuchElementException ( "<STR_LIT>" ) <EOL> var last = iterator . next ( ) <EOL> while ( iterator . hasNext ( ) ) <EOL> last = iterator . next ( ) <EOL> return last <EOL> }

/**
 * Returns the last element.
 *
 * The operation is _terminal_.
 *
 * @throws NoSuchElementException if the sequence is empty.
 *
 * @sample samples.collections.Collections.Elements.last
 */


public inline fun < T > Sequence < T > . last ( predicate : ( T ) -> Boolean ) : T

{ <EOL> var last : T ? = null <EOL> var found = false <EOL> for ( element in this ) { <EOL> if ( predicate ( element ) ) { <EOL> last = element <EOL> found = true <EOL> } <EOL> } <EOL> if ( ! found ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return last as T <EOL> }

/**
 * Returns the last element matching the given [predicate].
 *
 * The operation is _terminal_.
 *
 * @throws NoSuchElementException if no such element is found.
 *
 * @sample samples.collections.Collections.Elements.last
 */


public fun < @ kotlin . internal . OnlyInputTypes T > Sequence < T > . lastIndexOf ( element : T ) : Int

{ <EOL> var lastIndex = - <NUM_LIT:1> <EOL> var index = <NUM_LIT:0> <EOL> for ( item in this ) { <EOL> checkIndexOverflow ( index ) <EOL> if ( element == item ) <EOL> lastIndex = index <EOL> index ++ <EOL> } <EOL> return lastIndex <EOL> }

/**
 * Returns last index of [element], or -1 if the sequence does not contain element.
 *
 * The operation is _terminal_.
 */


public fun < T > Sequence < T > . lastOrNull ( ) : T ?

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

/**
 * Returns the last element, or `null` if the sequence is empty.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Elements.last
 */


public inline fun < T > Sequence < T > . lastOrNull ( predicate : ( T ) -> Boolean ) : T ?

{ <EOL> var last : T ? = null <EOL> for ( element in this ) { <EOL> if ( predicate ( element ) ) { <EOL> last = element <EOL> } <EOL> } <EOL> return last <EOL> }

/**
 * Returns the last element matching the given [predicate], or `null` if no such element was found.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Elements.last
 */


public fun < T > Sequence < T > . single ( ) : T

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

/**
 * Returns the single element, or throws an exception if the sequence is empty or has more than one element.
 *
 * The operation is _terminal_.
 */


public inline fun < T > Sequence < T > . single ( predicate : ( T ) -> Boolean ) : T

{ <EOL> var single : T ? = null <EOL> var found = false <EOL> for ( element in this ) { <EOL> if ( predicate ( element ) ) { <EOL> if ( found ) throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> single = element <EOL> found = true <EOL> } <EOL> } <EOL> if ( ! found ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return single as T <EOL> }

/**
 * Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element.
 *
 * The operation is _terminal_.
 */


public fun < T > Sequence < T > . singleOrNull ( ) : T ?

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

/**
 * Returns single element, or `null` if the sequence is empty or has more than one element.
 *
 * The operation is _terminal_.
 */


public inline fun < T > Sequence < T > . singleOrNull ( predicate : ( T ) -> Boolean ) : T ?

{ <EOL> var single : T ? = null <EOL> var found = false <EOL> for ( element in this ) { <EOL> if ( predicate ( element ) ) { <EOL> if ( found ) return null <EOL> single = element <EOL> found = true <EOL> } <EOL> } <EOL> if ( ! found ) return null <EOL> return single <EOL> }

/**
 * Returns the single element matching the given [predicate], or `null` if element was not found or more than one element was found.
 *
 * The operation is _terminal_.
 */


public fun < T > Sequence < T > . drop ( n : Int ) : Sequence < T >

{ <EOL> require ( n >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> return when { <EOL> n == <NUM_LIT:0> -> this <EOL> this is DropTakeSequence -> this . drop ( n ) <EOL> else -> DropSequence ( this , n ) <EOL> } <EOL> }

/**
 * Returns a sequence containing all elements except first [n] elements.
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @throws IllegalArgumentException if [n] is negative.
 *
 * @sample samples.collections.Collections.Transformations.drop
 */


public fun < T > Sequence < T > . dropWhile ( predicate : ( T ) -> Boolean ) : Sequence < T >

{ <EOL> return DropWhileSequence ( this , predicate ) <EOL> }

/**
 * Returns a sequence containing all elements except first elements that satisfy the given [predicate].
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @sample samples.collections.Collections.Transformations.drop
 */


public fun < T > Sequence < T > . filter ( predicate : ( T ) -> Boolean ) : Sequence < T >

{ <EOL> return FilteringSequence ( this , true , predicate ) <EOL> }

/**
 * Returns a sequence containing only elements matching the given [predicate].
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @sample samples.collections.Collections.Filtering.filter
 */


public fun < T > Sequence < T > . filterIndexed ( predicate : ( index : Int , T ) -> Boolean ) : Sequence < T >

{ <EOL> return TransformingSequence ( FilteringSequence ( IndexingSequence ( this ) , true , { predicate ( it . index , it . value ) } ) , { it . value } ) <EOL> }

/**
 * Returns a sequence containing only elements matching the given [predicate].
 * @param [predicate] function that takes the index of an element and the element itself
 * and returns the result of predicate evaluation on the element.
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @sample samples.collections.Collections.Filtering.filterIndexed
 */


public inline fun < T , C : MutableCollection < in T > > Sequence < T > . filterIndexedTo ( destination : C , predicate : ( index : Int , T ) -> Boolean ) : C

{ <EOL> forEachIndexed { index , element -> <EOL> if ( predicate ( index , element ) ) destination . add ( element ) <EOL> } <EOL> return destination <EOL> }

/**
 * Appends all elements matching the given [predicate] to the given [destination].
 * @param [predicate] function that takes the index of an element and the element itself
 * and returns the result of predicate evaluation on the element.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Filtering.filterIndexedTo
 */


public inline fun < reified R > Sequence < * > . filterIsInstance ( ) : Sequence < @ kotlin . internal . NoInfer R >

{ <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return filter { it is R } as Sequence < R > <EOL> }

/**
 * Returns a sequence containing all elements that are instances of specified type parameter R.
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @sample samples.collections.Collections.Filtering.filterIsInstance
 */


public inline fun < reified R , C : MutableCollection < in R > > Sequence < * > . filterIsInstanceTo ( destination : C ) : C

{ <EOL> for ( element in this ) if ( element is R ) destination . add ( element ) <EOL> return destination <EOL> }

/**
 * Appends all elements that are instances of specified type parameter R to the given [destination].
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Filtering.filterIsInstanceTo
 */


public fun < T > Sequence < T > . filterNot ( predicate : ( T ) -> Boolean ) : Sequence < T >

{ <EOL> return FilteringSequence ( this , false , predicate ) <EOL> }

/**
 * Returns a sequence containing all elements not matching the given [predicate].
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @sample samples.collections.Collections.Filtering.filter
 */


public fun < T : Any > Sequence < T ? > . filterNotNull ( ) : Sequence < T >

{ <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return filterNot { it == null } as Sequence < T > <EOL> }

/**
 * Returns a sequence containing all elements that are not `null`.
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @sample samples.collections.Collections.Filtering.filterNotNull
 */


public fun < C : MutableCollection < in T > , T : Any > Sequence < T ? > . filterNotNullTo ( destination : C ) : C

{ <EOL> for ( element in this ) if ( element != null ) destination . add ( element ) <EOL> return destination <EOL> }

/**
 * Appends all elements that are not `null` to the given [destination].
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Filtering.filterNotNullTo
 */


public inline fun < T , C : MutableCollection < in T > > Sequence < T > . filterNotTo ( destination : C , predicate : ( T ) -> Boolean ) : C

{ <EOL> for ( element in this ) if ( ! predicate ( element ) ) destination . add ( element ) <EOL> return destination <EOL> }

/**
 * Appends all elements not matching the given [predicate] to the given [destination].
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Filtering.filterTo
 */


public inline fun < T , C : MutableCollection < in T > > Sequence < T > . filterTo ( destination : C , predicate : ( T ) -> Boolean ) : C

{ <EOL> for ( element in this ) if ( predicate ( element ) ) destination . add ( element ) <EOL> return destination <EOL> }

/**
 * Appends all elements matching the given [predicate] to the given [destination].
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Filtering.filterTo
 */


public fun < T > Sequence < T > . take ( n : Int ) : Sequence < T >

{ <EOL> require ( n >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> return when { <EOL> n == <NUM_LIT:0> -> emptySequence ( ) <EOL> this is DropTakeSequence -> this . take ( n ) <EOL> else -> TakeSequence ( this , n ) <EOL> } <EOL> }

/**
 * Returns a sequence containing first [n] elements.
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @throws IllegalArgumentException if [n] is negative.
 *
 * @sample samples.collections.Collections.Transformations.take
 */


public fun < T > Sequence < T > . takeWhile ( predicate : ( T ) -> Boolean ) : Sequence < T >

{ <EOL> return TakeWhileSequence ( this , predicate ) <EOL> }

/**
 * Returns a sequence containing first elements satisfying the given [predicate].
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @sample samples.collections.Collections.Transformations.take
 */


public fun < T : Comparable < T > > Sequence < T > . sorted ( ) : Sequence < T >

{ <EOL> return object : Sequence < T > { <EOL> override fun iterator ( ) : Iterator < T > { <EOL> val sortedList = this@sorted . toMutableList ( ) <EOL> sortedList . sort ( ) <EOL> return sortedList . iterator ( ) <EOL> } <EOL> } <EOL> }

/**
 * Returns a sequence that yields elements of this sequence sorted according to their natural sort order.
 *
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 *
 * The operation is _intermediate_ and _stateful_.
 */


public inline fun < T , R : Comparable < R > > Sequence < T > . sortedBy ( crossinline selector : ( T ) -> R ? ) : Sequence < T >

{ <EOL> return sortedWith ( compareBy ( selector ) ) <EOL> }

/**
 * Returns a sequence that yields elements of this sequence sorted according to natural sort order of the value returned by specified [selector] function.
 *
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 *
 * The operation is _intermediate_ and _stateful_.
 *
 * @sample samples.collections.Collections.Sorting.sortedBy
 */


public inline fun < T , R : Comparable < R > > Sequence < T > . sortedByDescending ( crossinline selector : ( T ) -> R ? ) : Sequence < T >

{ <EOL> return sortedWith ( compareByDescending ( selector ) ) <EOL> }

/**
 * Returns a sequence that yields elements of this sequence sorted descending according to natural sort order of the value returned by specified [selector] function.
 *
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 *
 * The operation is _intermediate_ and _stateful_.
 */


public fun < T : Comparable < T > > Sequence < T > . sortedDescending ( ) : Sequence < T >

{ <EOL> return sortedWith ( reverseOrder ( ) ) <EOL> }

/**
 * Returns a sequence that yields elements of this sequence sorted descending according to their natural sort order.
 *
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 *
 * The operation is _intermediate_ and _stateful_.
 */


public fun < T > Sequence < T > . sortedWith ( comparator : Comparator < in T > ) : Sequence < T >

{ <EOL> return object : Sequence < T > { <EOL> override fun iterator ( ) : Iterator < T > { <EOL> val sortedList = this@sortedWith . toMutableList ( ) <EOL> sortedList . sortWith ( comparator ) <EOL> return sortedList . iterator ( ) <EOL> } <EOL> } <EOL> }

/**
 * Returns a sequence that yields elements of this sequence sorted according to the specified [comparator].
 *
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 *
 * The operation is _intermediate_ and _stateful_.
 */


public inline fun < T , K , V > Sequence < T > . associate ( transform : ( T ) -> Pair < K , V > ) : Map < K , V >

{ <EOL> return associateTo ( LinkedHashMap < K , V > ( ) , transform ) <EOL> }

/**
 * Returns a [Map] containing key-value pairs provided by [transform] function
 * applied to elements of the given sequence.
 *
 * If any of two pairs would have the same key the last one gets added to the map.
 *
 * The returned map preserves the entry iteration order of the original sequence.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Transformations.associate
 */


public inline fun < T , K > Sequence < T > . associateBy ( keySelector : ( T ) -> K ) : Map < K , T >

{ <EOL> return associateByTo ( LinkedHashMap < K , T > ( ) , keySelector ) <EOL> }

/**
 * Returns a [Map] containing the elements from the given sequence indexed by the key
 * returned from [keySelector] function applied to each element.
 *
 * If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
 *
 * The returned map preserves the entry iteration order of the original sequence.
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Transformations.associateBy
 */