@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUByte ( radix : Int ) : UByte

= toUByteOrNull ( radix ) ? : numberFormatError ( this )

/**
 * Parses the string as a signed [UByte] number and returns the result.
 * @throws NumberFormatException 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.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUShort ( ) : UShort

= toUShortOrNull ( ) ? : numberFormatError ( this )

/**
 * Parses the string as a [UShort] number and returns the result.
 * @throws NumberFormatException if the string is not a valid representation of a number.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUShort ( radix : Int ) : UShort

= toUShortOrNull ( radix ) ? : numberFormatError ( this )

/**
 * Parses the string as a [UShort] number and returns the result.
 * @throws NumberFormatException 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.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUInt ( ) : UInt

= toUIntOrNull ( ) ? : numberFormatError ( this )

/**
 * Parses the string as an [UInt] number and returns the result.
 * @throws NumberFormatException if the string is not a valid representation of a number.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUInt ( radix : Int ) : UInt

= toUIntOrNull ( radix ) ? : numberFormatError ( this )

/**
 * Parses the string as an [UInt] number and returns the result.
 * @throws NumberFormatException 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.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toULong ( ) : ULong

= toULongOrNull ( ) ? : numberFormatError ( this )

/**
 * Parses the string as a [ULong] number and returns the result.
 * @throws NumberFormatException if the string is not a valid representation of a number.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toULong ( radix : Int ) : ULong

= toULongOrNull ( radix ) ? : numberFormatError ( this )

/**
 * Parses the string as a [ULong] number and returns the result.
 * @throws NumberFormatException 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.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUByteOrNull ( ) : UByte ?

= toUByteOrNull ( radix = <NUM_LIT:10> )

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


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUByteOrNull ( radix : Int ) : UByte ?

{ <EOL> val int = this . toUIntOrNull ( radix ) ? : return null <EOL> if ( int > UByte . MAX_VALUE ) return null <EOL> return int . toUByte ( ) <EOL> }

/**
 * Parses the string as an [UByte] 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.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUShortOrNull ( ) : UShort ?

= toUShortOrNull ( radix = <NUM_LIT:10> )

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


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUShortOrNull ( radix : Int ) : UShort ?

{ <EOL> val int = this . toUIntOrNull ( radix ) ? : return null <EOL> if ( int > UShort . MAX_VALUE ) return null <EOL> return int . toUShort ( ) <EOL> }

/**
 * Parses the string as an [UShort] 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.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUIntOrNull ( ) : UInt ?

= toUIntOrNull ( radix = <NUM_LIT:10> )

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


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toUIntOrNull ( radix : Int ) : UInt ?

{ <EOL> checkRadix ( radix ) <EOL> val length = this . length <EOL> if ( length == <NUM_LIT:0> ) return null <EOL> val limit : UInt = UInt . MAX_VALUE <EOL> val start : Int <EOL> val firstChar = this [ <NUM_LIT:0> ] <EOL> if ( firstChar < '<CHAR_LIT:0>' ) { <EOL> if ( length == <NUM_LIT:1> || firstChar != '<CHAR_LIT>' ) return null <EOL> start = <NUM_LIT:1> <EOL> } else { <EOL> start = <NUM_LIT:0> <EOL> } <EOL> val limitForMaxRadix = <NUM_LIT> <EOL> var limitBeforeMul = limitForMaxRadix <EOL> val uradix = radix . toUInt ( ) <EOL> var result = <NUM_LIT> <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 / uradix <EOL> if ( result > limitBeforeMul ) { <EOL> return null <EOL> } <EOL> } else { <EOL> return null <EOL> } <EOL> } <EOL> result *= uradix <EOL> val beforeAdding = result <EOL> result += digit . toUInt ( ) <EOL> if ( result < beforeAdding ) return null <EOL> } <EOL> return result <EOL> }

/**
 * Parses the string as an [UInt] 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.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toULongOrNull ( ) : ULong ?

= toULongOrNull ( radix = <NUM_LIT:10> )

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


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun String . toULongOrNull ( radix : Int ) : ULong ?

{ <EOL> checkRadix ( radix ) <EOL> val length = this . length <EOL> if ( length == <NUM_LIT:0> ) return null <EOL> val limit : ULong = ULong . MAX_VALUE <EOL> val start : Int <EOL> val firstChar = this [ <NUM_LIT:0> ] <EOL> if ( firstChar < '<CHAR_LIT:0>' ) { <EOL> if ( length == <NUM_LIT:1> || firstChar != '<CHAR_LIT>' ) return null <EOL> start = <NUM_LIT:1> <EOL> } else { <EOL> start = <NUM_LIT:0> <EOL> } <EOL> val limitForMaxRadix = <NUM_LIT> <EOL> var limitBeforeMul = limitForMaxRadix <EOL> val uradix = radix . toULong ( ) <EOL> var result = <NUM_LIT> <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 / uradix <EOL> if ( result > limitBeforeMul ) { <EOL> return null <EOL> } <EOL> } else { <EOL> return null <EOL> } <EOL> } <EOL> result *= uradix <EOL> val beforeAdding = result <EOL> result += digit . toUInt ( ) <EOL> if ( result < beforeAdding ) return null <EOL> } <EOL> return result <EOL> }

/**
 * Parses the string as an [ULong] 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.
 */


abstract fun IrClass . addTransformedInClassAtomic ( atomicProperty : IrProperty , index : Int ) : IrProperty

/**
 * Builds a volatile property that can be atomically updated instead of the given atomicfu property,
 * and replaces the original declaration in the parent class.
 * Returns the new volatile property.
 */


abstract fun IrDeclarationContainer . addTransformedStaticAtomic ( atomicProperty : IrProperty , index : Int ) : IrProperty

/**
 * Builds a volatile property that can be atomically updated instead of the given static atomicfu property
 * and replaces the original declaration in the parent container.
 * Returns the new volatile property.
 */


private fun IrDeclarationContainer . addTransformedAtomicArray ( atomicProperty : IrProperty , index : Int ) : IrProperty

{ <EOL> val parentContainer = this <EOL> with ( atomicSymbols . createBuilder ( atomicProperty . symbol ) ) { <EOL> val javaAtomicArrayField = buildAtomicArrayField ( atomicProperty , parentContainer ) <EOL> return parentContainer . replacePropertyAtIndex ( javaAtomicArrayField , atomicProperty . visibility , isVar = false , isStatic = parentContainer is IrFile , index ) . also { <EOL> atomicfuPropertyToAtomicHandler [ atomicProperty ] = it <EOL> } <EOL> } <EOL> }

/**
 * Builds an array that can be atomically updated instead of the given atomicfu atomic array
 * and replaces the original declaration in the parent class.
 * Returns the generated array.
 * For JVM: atomic arrays are replaced with the corresponding java.util.concurrent.Atomic*Array
 * For Native: atomic arrays are replaced with the corresponding kotlin.concurrent.Atomic*Array
 * (In the future atomic arrays will be commonized in Kotlin stdlib)
 *
 * val intArr = kotlinx.atomicfu.AtomicIntArray(45) --> val intArr = java.util.concurrent.AtomicIntegerArray(45) // JVM
 * val intArr = kotlinx.atomicfu.AtomicIntArray(45) --> val intArr = kotlin.concurrent.AtomicIntArray(45) // Native
 */


private fun IrDeclarationContainer . transformDelegatedAtomic ( atomicProperty : IrProperty )

{ <EOL> val getDelegate = atomicProperty . backingField ? . initializer ? . expression <EOL> require ( getDelegate is IrCall ) { "<STR_LIT>" + <EOL> "<STR_LIT>" + CONSTRAINTS_MESSAGE } <EOL> val delegateVolatileField = when { <EOL> getDelegate . isAtomicFactoryCall ( ) -> { <EOL> with ( atomicSymbols . createBuilder ( atomicProperty . symbol ) ) { <EOL> buildVolatileBackingField ( atomicProperty , this @ transformDelegatedAtomic , false ) . also { <EOL> declarations . add ( it ) <EOL> } <EOL> } <EOL> } <EOL> getDelegate . symbol . owner . isGetter -> { <EOL> val delegate = getDelegate . getCorrespondingProperty ( ) <EOL> check ( delegate . parent == atomicProperty . parent ) { <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + CONSTRAINTS_MESSAGE } <EOL> val volatileProperty = atomicfuPropertyToVolatile [ delegate ] <EOL> ? : error ( "<STR_LIT>" ) <EOL> volatileProperty . backingField <EOL> ? : error ( "<STR_LIT>" ) <EOL> } <EOL> else -> error ( "<STR_LIT>" + CONSTRAINTS_MESSAGE ) <EOL> } <EOL> atomicProperty . getter ? . transformAccessor ( delegateVolatileField ) <EOL> atomicProperty . setter ? . transformAccessor ( delegateVolatileField ) <EOL> atomicProperty . backingField = null <EOL> }

/**
 * Transforms the given property that was delegated to the atomic property:
 * delegates accessors to the volatile property that was generated instead of the atomic property.
 */


protected fun AbstractAtomicfuIrBuilder . buildVolatileBackingField ( atomicProperty : IrProperty , parentContainer : IrDeclarationContainer , tweakBooleanToInt : Boolean ) : IrField

{ <EOL> val atomicField = requireNotNull ( atomicProperty . backingField ) { "<STR_LIT>" + CONSTRAINTS_MESSAGE } <EOL> val fieldType = ( atomicField . type as IrSimpleType ) . atomicToPrimitiveType ( ) <EOL> val initializer = atomicField . initializer ? . expression <EOL> if ( initializer == null ) { <EOL> val initBlock = atomicField . getInitBlockForField ( parentContainer ) <EOL> val initExprWithIndex = initBlock . getInitExprWithIndexFromInitBlock ( atomicField . symbol ) <EOL> ? : error ( "<STR_LIT>" + CONSTRAINTS_MESSAGE ) <EOL> val atomicFactoryCall = initExprWithIndex . value . value <EOL> val initExprIndex = initExprWithIndex . index <EOL> val initValue = atomicFactoryCall . getAtomicFactoryValueArgument ( ) <EOL> return irVolatileField ( atomicProperty . name . asString ( ) + VOLATILE , if ( tweakBooleanToInt && fieldType . isBoolean ( ) ) irBuiltIns . intType else fieldType , null , atomicField . annotations , parentContainer ) . also { <EOL> initBlock . updateFieldInitialization ( atomicField . symbol , it . symbol , initValue , initExprIndex ) <EOL> } <EOL> } else { <EOL> val initValue = initializer . getAtomicFactoryValueArgument ( ) <EOL> return irVolatileField ( atomicProperty . name . asString ( ) + VOLATILE , if ( tweakBooleanToInt && fieldType . isBoolean ( ) ) irBuiltIns . intType else fieldType , initValue , atomicField . annotations , parentContainer ) <EOL> } <EOL> }

/**
 * Builds a private volatile field initialized with the initial value of the given atomic property:
 * private val a = atomic(0) --> private @Volatile a: Int = 0
 */


private fun AbstractAtomicfuIrBuilder . buildAtomicArrayField ( atomicProperty : IrProperty , parentContainer : IrDeclarationContainer ) : IrField

{ <EOL> val atomicArrayField = <EOL> requireNotNull ( atomicProperty . backingField ) { "<STR_LIT>" + CONSTRAINTS_MESSAGE } <EOL> val initializer = atomicArrayField . initializer ? . expression <EOL> if ( initializer == null ) { <EOL> val initBlock = atomicArrayField . getInitBlockForField ( parentContainer ) <EOL> val initExprWithIndex = initBlock . getInitExprWithIndexFromInitBlock ( atomicArrayField . symbol ) <EOL> ? : error ( "<STR_LIT>" + CONSTRAINTS_MESSAGE ) <EOL> val atomicFactoryCall = initExprWithIndex . value . value <EOL> val initExprIndex = initExprWithIndex . index <EOL> val arraySize = atomicFactoryCall . getArraySizeArgument ( ) <EOL> return irAtomicArrayField ( atomicArrayField . name , atomicSymbols . getAtomicArrayClassByAtomicfuArrayType ( atomicArrayField . type ) , atomicArrayField . isStatic , atomicArrayField . annotations , arraySize , ( atomicFactoryCall as IrFunctionAccessExpression ) . dispatchReceiver , parentContainer ) . also { <EOL> val initExpr = it . initializer ? . expression <EOL> ? : error ( "<STR_LIT>" + CONSTRAINTS_MESSAGE ) <EOL> it . initializer = null <EOL> initBlock . updateFieldInitialization ( atomicArrayField . symbol , it . symbol , initExpr , initExprIndex ) <EOL> } <EOL> } else { <EOL> val arraySize = initializer . getArraySizeArgument ( ) <EOL> return irAtomicArrayField ( atomicArrayField . name , atomicSymbols . getAtomicArrayClassByAtomicfuArrayType ( atomicArrayField . type ) , atomicArrayField . isStatic , atomicArrayField . annotations , arraySize , ( initializer as IrFunctionAccessExpression ) . dispatchReceiver , parentContainer ) <EOL> } <EOL> }

/**
 * Builds an atomic array field initialized with the initial size of the given atomic array,
 * the generated field has the same visibility as the original atomic array:
 * internal val intArr = kotlinx.atomicfu.AtomicIntArray --> internal val intArr = j.u.c.a.AtomicIntegerArray // JVM
 * internal val intArr = kotlin.concurrent.AtomicIntArray // Native
 */


private fun IrAnonymousInitializer . getInitExprWithIndexFromInitBlock ( oldFieldSymbol : IrFieldSymbol ) : IndexedValue < IrSetField > ?

= <EOL> body . statements . withIndex ( ) . singleOrNull { it . value is IrSetField && ( it . value as IrSetField ) . symbol == oldFieldSymbol } ? . let { <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> it as IndexedValue < IrSetField > <EOL> }

/**
 * In case if atomic property is initialized in init block it's declaration is replaced with the volatile property
 * and initialization of the backing field is also performed in the init block:
 *
 * private val _a: AtomicInt --> @Volatile var _a: Int
 *
 * init { init {
 * _a = atomic(0) _a = 0
 * } }
 */


public fun < T > lineType ( column : ColumnReference < T > , parameters : LetsPlotNonPositionalMappingParametersCategorical < T , LineType > . ( ) -> Unit = { } ) : NonPositionalMapping < T , LineType >

{ <EOL> return addNonPositionalMapping < T , LineType > ( LINE_TYPE , column . name ( ) , LetsPlotNonPositionalMappingParametersCategorical < T , LineType > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `lineType` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to map to the color.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > lineType ( column : KProperty < T > , parameters : LetsPlotNonPositionalMappingParametersCategorical < T , LineType > . ( ) -> Unit = { } ) : NonPositionalMapping < T , LineType >

{ <EOL> return addNonPositionalMapping < T , LineType > ( LINE_TYPE , column . name , LetsPlotNonPositionalMappingParametersCategorical < T , LineType > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `lineType` aesthetic to a data column by [KProperty].
 *
 * @param column the data column to map to the color.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun lineType ( column : String , parameters : LetsPlotNonPositionalMappingParametersCategorical < Any ? , LineType > . ( ) -> Unit = { } ) : NonPositionalMapping < Any ? , LineType >

{ <EOL> return addNonPositionalMapping ( LINE_TYPE , column , LetsPlotNonPositionalMappingParametersCategorical < Any ? , LineType > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `lineType` aesthetic to a data column by [String].
 *
 * @param column the data column to map to the color.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > lineType ( values : Iterable < T > , name : String ? = null , parameters : LetsPlotNonPositionalMappingParametersCategorical < T , LineType > . ( ) -> Unit = { } ) : NonPositionalMapping < T , LineType >

{ <EOL> return addNonPositionalMapping ( LINE_TYPE , values . toList ( ) , name , LetsPlotNonPositionalMappingParametersCategorical < T , LineType > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `lineType` aesthetic to iterable of values.
 *
 * @param values the iterable containing the values.
 * @param name optional name for this aesthetic mapping.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > lineType ( values : DataColumn < T > , parameters : LetsPlotNonPositionalMappingParametersCategorical < T , LineType > . ( ) -> Unit = { } ) : NonPositionalMapping < T , LineType >

{ <EOL> return addNonPositionalMapping ( LINE_TYPE , values , LetsPlotNonPositionalMappingParametersCategorical < T , LineType > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `lineType` aesthetic to a data column.
 *
 * @param values the data column to map to the color.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


fun containingClass ( context : FirElement ) : FirRegularClass

{ <EOL> val containingDeclaration = containingDeclarations . lastOrNull ( ) ? : errorWithAttachment ( "<STR_LIT>" ) { <EOL> withFirEntry ( "<STR_LIT>" , context ) <EOL> withFirDesignationEntry ( "<STR_LIT>" , resolveTarget . designation ) <EOL> } <EOL> requireWithAttachment ( containingDeclaration is FirRegularClass , { "<STR_LIT>" } , ) { <EOL> withFirEntry ( "<STR_LIT>" , context ) <EOL> withFirDesignationEntry ( "<STR_LIT>" , resolveTarget . designation ) <EOL> } <EOL> return containingDeclaration <EOL> }

/**
 * @param context used as a context in the case of exception
 * @return the last class from [containingDeclarations]
 */


private fun resolveDependencies ( target : FirElementWithResolveState )

{ <EOL> if ( skipDependencyTargetResolutionStep ) return <EOL> val originalDeclaration = ( target as? FirCallableDeclaration ) ? . originalIfFakeOverrideOrDelegated ( ) <EOL> when { <EOL> originalDeclaration != null -> originalDeclaration . lazyResolveToPhase ( resolverPhase ) <EOL> target is FirProperty -> { <EOL> target . correspondingValueParameterFromPrimaryConstructor ? . lazyResolveToPhase ( resolverPhase ) <EOL> target . destructuringDeclarationContainerVariable ? . lazyResolveToPhase ( resolverPhase ) <EOL> } <EOL> target is FirSimpleFunction && target . origin == FirDeclarationOrigin . Synthetic . DataClassMember -> { <EOL> resolveDataClassMemberDependencies ( target ) <EOL> } <EOL> target is FirField && target . origin == FirDeclarationOrigin . Synthetic . DelegateField || target is FirConstructor -> { <EOL> containingClass ( target ) . lazyResolveToPhase ( resolverPhase ) <EOL> } <EOL> target is FirScript -> target . parameters . forEach { it . lazyResolveToPhase ( resolverPhase ) } <EOL> } <EOL> }

/**
 * Requests the resolution for dependencies to avoid race in the case of FIR instance sharing.
 * Will be executed before resolution without a lock.
 *
 * @see resolveDataClassMemberDependencies
 * @see skipDependencyTargetResolutionStep
 */


protected open fun doResolveWithoutLock ( target : FirElementWithResolveState ) : Boolean

= false

/**
 * This method executes **not under the lock** of [target].
 * Any unsafe reads from [target] declaration have to be done under [withReadLock].
 * [performCustomResolveUnderLock] have to be used for modifications.
 *
 * This method can be useful to resolve some dependencies (like [resolveDependencies] in general),
 * but with some phase-specific rules.
 *
 * For instance, to pre-resolve [FirRegularClass] members before the class itself as it is required
 * to build the [CFG][org.jetbrains.kotlin.fir.resolve.dfa.cfg.ControlFlowGraph].
 *
 * @return **true** if [performCustomResolveUnderLock] has been called
 *
 * @see withReadLock
 * @see performCustomResolveUnderLock
 */


protected abstract fun doLazyResolveUnderLock ( target : FirElementWithResolveState )

/**
 * This method executes **under the lock** of [target].
 */


{ <EOL> checkResolveConsistency ( ) <EOL> resolveTarget . visit ( this ) <EOL> }


protected fun performResolve ( target : FirElementWithResolveState )

{ <EOL> resolveDependencies ( target ) <EOL> if ( doResolveWithoutLock ( target ) ) return <EOL> if ( requiresJumpingLock ) { <EOL> checkThatResolvedAtLeastToPreviousPhase ( target ) <EOL> lockProvider . withJumpingLock ( target , resolverPhase , actionUnderLock = { <EOL> doLazyResolveUnderLock ( target ) <EOL> updatePhaseForDeclarationInternals ( target ) <EOL> } , actionOnCycle = { <EOL> handleCycleInResolution ( target ) <EOL> } ) <EOL> } else { <EOL> performCustomResolveUnderLock ( target ) { <EOL> doLazyResolveUnderLock ( target ) <EOL> } <EOL> } <EOL> }

/**
 * Performs the resolution of [target].
 * The [target] element have to be at least in [resolverPhase].[previous][FirResolvePhase.previous] phase.
 *
 * @see resolveDependencies
 * @see doResolveWithoutLock
 * @see doLazyResolveUnderLock
 */


protected open fun handleCycleInResolution ( target : FirElementWithResolveState )

{ <EOL> errorWithFirSpecificEntries ( "<STR_LIT>" , fir = target ) <EOL> }

/**
 * Will be executed in the case of detected cycle between elements during jumping resolve.
 *
 * **There is no guaranties that [target] is guarded by the lock of the current thread**
 *
 * @param target an element with detected cycle
 *
 * @see LLFirLockProvider.withJumpingLock
 */


protected inline fun performCustomResolveUnderLock ( target : FirElementWithResolveState , crossinline action : ( ) -> Unit )

{ <EOL> checkThatResolvedAtLeastToPreviousPhase ( target ) <EOL> requireWithAttachment ( ! requiresJumpingLock , { "<STR_LIT>" } ) { <EOL> withFirEntry ( "<STR_LIT>" , target ) <EOL> } <EOL> lockProvider . withWriteLock ( target , resolverPhase ) { <EOL> action ( ) <EOL> updatePhaseForDeclarationInternals ( target ) <EOL> } <EOL> }

/**
 * Execute [action] under the write lock in the context of [target].
 *
 * Allowed only for non-jumping phases.
 *
 * @see requiresJumpingLock
 */


protected inline fun withReadLock ( target : FirElementWithResolveState , action : ( ) -> Unit )

{ <EOL> checkThatResolvedAtLeastToPreviousPhase ( target ) <EOL> lockProvider . withReadLock ( target , resolverPhase , action ) <EOL> }

/**
 * Execute action under a declaration lock.
 * [action] will be executed only once in case of successful lock.
 * If some another thread is already resolved [target] declaration to [resolverPhase] then [action] won't be executed.
 */


protected open fun IrExpression . prepareToBeUsedIn ( function : IrFunction ) : IrExpression

{ <EOL> return patchDeclarationParents ( function ) <EOL> }

/**
 * Prepares the default value to be used inside the `function` body by patching the parents.
 * In K/JS it also copies the expression in order to avoid duplicate declarations after this lowering.
 *
 * In K/JVM copying doesn't preserve metadata, so the following case won't work:
 *
 * ```
 * import kotlin.reflect.jvm.reflect
 *
 * fun foo(x: Function<*> = {}) {
 * // Will print "null" if lambda is copied
 * println(x.reflect())
 * }
 * ```
 *
 * Thus the duplicate declarations during the lowering pipeline is considered to be a lesser evil.
 */


public fun < I > Operation < I , Bitmap > . toFloatArray ( block : ConvertToFloatArray . ( ) -> Unit ) : Operation < I , FloatData >

{ <EOL> return PreprocessingPipeline ( this , ConvertToFloatArray ( ) . apply ( block ) ) <EOL> }

/** Applies [ConvertToFloatArray] operation to convert the [Bitmap] to a float array. */


public fun < I > Operation < I , Bitmap > . resize ( block : Resize . ( ) -> Unit ) : Operation < I , Bitmap >

{ <EOL> return PreprocessingPipeline ( this , Resize ( ) . apply ( block ) ) <EOL> }

/** Applies [Resize] operation to resize the [Bitmap] to a specific size. */


public fun < I > Operation < I , Bitmap > . rotate ( block : Rotate . ( ) -> Unit ) : Operation < I , Bitmap >

{ <EOL> return PreprocessingPipeline ( this , Rotate ( ) . apply ( block ) ) <EOL> }

/** Applies [Rotate] operation to rotate the [Bitmap] by an arbitrary angle (specified in degrees). */


@ RequiresApi ( Build . VERSION_CODES . O ) <EOL> public fun < I > Operation < I , Bitmap > . crop ( block : Crop . ( ) -> Unit ) : Operation < I , Bitmap >

{ <EOL> return PreprocessingPipeline ( this , Crop ( ) . apply ( block ) ) <EOL> }

/** Applies [Crop] operation to crop the [Bitmap] at a specified region. */


fun < A > topologicalSort ( nodes : Iterable < A > , reportCycle : ( A ) -> Nothing = { throw IllegalStateException ( "<STR_LIT>" ) } , dependencies : A . ( ) -> Iterable < A > , ) : List < A >

{ <EOL> val visiting = mutableSetOf < A > ( ) <EOL> val visited = mutableSetOf < A > ( ) <EOL> fun visit ( node : A ) { <EOL> if ( node in visited ) return <EOL> if ( node in visiting ) reportCycle ( node ) <EOL> visiting . add ( node ) <EOL> node . dependencies ( ) . forEach ( :: visit ) <EOL> visiting . remove ( node ) <EOL> visited . add ( node ) <EOL> } <EOL> nodes . forEach ( :: visit ) <EOL> return visited . toMutableList ( ) . apply { reverse ( ) } <EOL> }

/**
 * Sorts [nodes] topologically collecting direct edges via [dependencies]. [nodes] and [dependencies] must form a directed, acyclic graph.
 * [topologicalSort] will throw an [IllegalStateException] if it encounters a cycle.
 *
 * The algorithm is based on depth-first search, starting in order from each node in [nodes]. Kahn's algorithm is harder to apply to the
 * ad-hoc dependency structure because it's not easily apparent whether a node has no other incoming edges.
 *
 * For example, consider the following structure: `C -> A, C -> B, B -> A`. The resulting order should be `[C, B, A]`. However, `A` is
 * first in the list of dependencies of `C`. Without a way to find the incoming edge from `B` to `A` while processing `C -> A`, a naive
 * implementation of Kahn's algorithm might order `A` before `B`.
 */


inline fun withWriteLock ( target : FirElementWithResolveState , phase : FirResolvePhase , action : ( ) -> Unit , )

{ <EOL> checker . lazyResolveToPhaseInside ( phase ) { <EOL> target . withLock ( toPhase = phase , updatePhase = true , action = action ) <EOL> } <EOL> }

/**
 * Locks an a [FirElementWithResolveState] to resolve from `phase - 1` to [phase] and
 * then updates the [FirElementWithResolveState.resolveState] to a [phase].
 * Does nothing if [target] already has at least [phase] phase.
 *
 * [action] will be executed once if [target] is not yet resolved to [phase] phase.
 *
 * @see withReadLock
 * @see withJumpingLock
 */


inline fun withReadLock ( target : FirElementWithResolveState , phase : FirResolvePhase , action : ( ) -> Unit , )

{ <EOL> checker . lazyResolveToPhaseInside ( phase ) { <EOL> target . withLock ( toPhase = phase , updatePhase = false , action = action ) <EOL> } <EOL> }

/**
 * Locks an a [FirElementWithResolveState] to read something required for [phase].
 * Does nothing if [target] already has at least [phase] phase.
 *
 * [action] will be executed once if [target] is not yet resolved to [phase] phase.
 *
 * @see withWriteLock
 */


private inline fun FirElementWithResolveState . withLock ( toPhase : FirResolvePhase , updatePhase : Boolean , action : ( ) -> Unit , )

{ <EOL> while ( true ) { <EOL> checkCanceled ( ) <EOL> @ OptIn ( ResolveStateAccess :: class ) <EOL> val stateSnapshot = resolveState <EOL> if ( stateSnapshot . resolvePhase >= toPhase ) { <EOL> return <EOL> } <EOL> when ( stateSnapshot ) { <EOL> is FirInProcessOfResolvingToPhaseStateWithoutBarrier -> { <EOL> trySettingBarrier ( toPhase , stateSnapshot ) <EOL> continue <EOL> } <EOL> is FirInProcessOfResolvingToPhaseStateWithBarrier -> { <EOL> waitOnBarrier ( stateSnapshot ) <EOL> continue <EOL> } <EOL> is FirResolvedToPhaseState -> { <EOL> if ( ! tryLock ( toPhase , stateSnapshot ) ) continue <EOL> var exceptionOccurred = false <EOL> try { <EOL> action ( ) <EOL> } catch ( e : Throwable ) { <EOL> exceptionOccurred = true <EOL> throw e <EOL> } finally { <EOL> val newPhase = if ( updatePhase && ! exceptionOccurred ) toPhase else stateSnapshot . resolvePhase <EOL> unlock ( toPhase = newPhase ) <EOL> } <EOL> return <EOL> } <EOL> is FirInProcessOfResolvingToJumpingPhaseState -> { <EOL> errorWithFirSpecificEntries ( "<STR_LIT>" , fir = this ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Locks an a [FirElementWithResolveState] to resolve from `toPhase - 1` to [toPhase] and
 * then updates the [FirElementWithResolveState.resolveState] to a [toPhase] if [updatePhase] is **true**.
 *
 * [updatePhase] == false means that we want to read some data under a lock.
 *
 * If [FirElementWithResolveState] is already at least at [toPhase], does nothing.
 *
 * Otherwise:
 * - Marks [FirElementWithResolveState] as in a process of resovle
 * - performs the resolve by calling [action]
 * - updates the resolve phase to [toPhase] if [updatePhase] is **true**.
 * - notifies other threads waiting on the same lock that the declaration is already resolved by this thread, so other threads can continue its execution.
 *
 *
 * Contention handling:
 * - on lock acquisition, no real lock or barrier is created. Instead, the [FirElementWithResolveState.resolveState] is updated to indicate that the declaration is being resolved now.
 * - If some other thread tries to resolve current [FirElementWithResolveState], it changes `resolveState` and puts the barrier there. Then it awaits on it until the initial thread which hold the lock finishes its job.
 * - This way, no barrier is used in a case when no contention arise.
 */


fun withJumpingLock ( target : FirElementWithResolveState , phase : FirResolvePhase , actionUnderLock : ( ) -> Unit , actionOnCycle : ( ) -> Unit , )

{ <EOL> checker . lazyResolveToPhaseInside ( phase ) { <EOL> target . withJumpingLockImpl ( phase , actionUnderLock , actionOnCycle ) <EOL> } <EOL> }

/**
 * Locks on an a [FirElementWithResolveState] to resolve from `phase - 1` to [phase] and
 * then updates the [resolve state][FirElementWithResolveState.resolveState] to a [phase].
 * Does nothing if [target] already has at least [phase] phase.
 *
 * @param actionUnderLock will be executed once under the lock if [target] is not yet resolved to [phase] phase and there are no cycles
 * @param actionOnCycle will be executed once without the lock if [target] is not yet resolved to [phase] phase and a resolution cycle is found
 *
 * @see withWriteLock
 * @see withJumpingLockImpl
 */


private fun FirElementWithResolveState . withJumpingLockImpl ( toPhase : FirResolvePhase , actionUnderLock : ( ) -> Unit , actionOnCycle : ( ) -> Unit , )

{ <EOL> while ( true ) { <EOL> checkCanceled ( ) <EOL> @ OptIn ( ResolveStateAccess :: class ) <EOL> val currentState = resolveState <EOL> if ( currentState . resolvePhase >= toPhase ) { <EOL> return <EOL> } <EOL> when ( currentState ) { <EOL> is FirResolvedToPhaseState -> { <EOL> if ( ! tryJumpingLock ( toPhase , currentState ) ) continue <EOL> var exceptionOccurred = false <EOL> try { <EOL> actionUnderLock ( ) <EOL> } catch ( e : Throwable ) { <EOL> exceptionOccurred = true <EOL> throw e <EOL> } finally { <EOL> val newPhase = if ( ! exceptionOccurred ) toPhase else currentState . resolvePhase <EOL> jumpingUnlock ( toPhase = newPhase ) <EOL> } <EOL> return <EOL> } <EOL> is FirInProcessOfResolvingToJumpingPhaseState -> { <EOL> val previousState = jumpingResolutionStatesStack . peek ( ) <EOL> if ( previousState != null ) { <EOL> previousState . waitingFor = currentState <EOL> var nextState : FirInProcessOfResolvingToJumpingPhaseState ? = currentState <EOL> while ( nextState != null ) { <EOL> if ( nextState === previousState ) { <EOL> previousState . waitingFor = null <EOL> return actionOnCycle ( ) <EOL> } <EOL> nextState = nextState . waitingFor <EOL> } <EOL> } <EOL> try { <EOL> currentState . latch . await ( DEFAULT_LOCKING_INTERVAL , TimeUnit . MILLISECONDS ) <EOL> } finally { <EOL> previousState ? . waitingFor = null <EOL> } <EOL> } <EOL> is FirInProcessOfResolvingToPhaseStateWithoutBarrier , is FirInProcessOfResolvingToPhaseStateWithBarrier -> { <EOL> errorWithFirSpecificEntries ( "<STR_LIT>" , fir = this ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Locks an a [FirElementWithResolveState] to resolve from `toPhase - 1` to [toPhase] and
 * then updates the [FirElementWithResolveState.resolveState] to a
 * [toPhase] if no exceptions were found during [actionUnderLock].
 *
 * If [FirElementWithResolveState] is already at least at [toPhase], does nothing.
 *
 * ### Happy path:
 * 1. Marks [FirElementWithResolveState] as in a process of resolve
 * 2. Performs the resolve by calling [actionUnderLock]
 * 3. Updates the resolve phase to [toPhase] if there is no exceptions
 * 4. Notifies other threads waiting on the same lock that this thread already resolved the declaration,
 * so other threads can continue its execution
 *
 * ### Cycle handling
 * During step 1 we can realize someone already set [FirInProcessOfResolvingToJumpingPhaseState]
 * for the current [FirElementWithResolveState], so there is a room for a possible deadlock.
 *
 * The requirement for the deadlock is not empty [jumpingResolutionStatesStack] as we should already hold another lock.
 * Otherwise, we can just wait on the [latch][FirInProcessOfResolvingToJumpingPhaseState.latch].
 *
 * In the case of not empty [jumpingResolutionStatesStack], we have the following algorithm:
 * 1. Set [waitingFor][FirInProcessOfResolvingToJumpingPhaseState.waitingFor] for the previous state
 * as we have an intention to take the next lock
 * 2. Iterate over all [waitingFor][FirInProcessOfResolvingToJumpingPhaseState.waitingFor] recursively
 * to detect the possible cycle
 * 3. Execute [actionOnCycle] without the lock in the case of cycle or waining on
 * the [latch][FirInProcessOfResolvingToJumpingPhaseState.latch] to try to take the lock again later
 *
 * @param actionUnderLock will be executed once under the lock if [this] is not yet resolved to [toPhase] phase and there are no cycles
 * @param actionOnCycle will be executed once without the lock if [this] is not yet resolved to [toPhase] phase and a resolution cycle is found
 *
 * @see withJumpingLock
 */


private fun FirElementWithResolveState . tryJumpingLock ( toPhase : FirResolvePhase , stateSnapshot : FirResolveState , ) : Boolean

{ <EOL> val newState = FirInProcessOfResolvingToJumpingPhaseState ( toPhase ) <EOL> val isSucceed = resolveStateFieldUpdater . compareAndSet ( this , stateSnapshot , newState ) <EOL> if ( ! isSucceed ) return false <EOL> jumpingResolutionStatesStack . push ( newState ) <EOL> return true <EOL> }

/**
 * Trying to set [FirInProcessOfResolvingToJumpingPhaseState] to [this].
 *
 * @return **true** if the state is published successfully
 *
 * @see withJumpingLockImpl
 * @see FirInProcessOfResolvingToJumpingPhaseState
 */


private fun FirElementWithResolveState . jumpingUnlock ( toPhase : FirResolvePhase )

{ <EOL> val currentState = jumpingResolutionStatesStack . pop ( ) <EOL> resolveStateFieldUpdater . set ( this , FirResolvedToPhaseState ( toPhase ) ) <EOL> currentState . latch . countDown ( ) <EOL> }

/**
 * Publish [FirResolvedToPhaseState] with [toPhase] phase and unlocks current [FirInProcessOfResolvingToJumpingPhaseState].
 *
 * @see withJumpingLockImpl
 * @see FirInProcessOfResolvingToJumpingPhaseState
 * @see FirResolvedToPhaseState
 */


fun push ( newState : FirInProcessOfResolvingToJumpingPhaseState )

{ <EOL> val states = stateStackHolder . get ( ) <EOL> val currentState = states . lastOrNull ( ) <EOL> currentState ? . waitingFor = newState <EOL> states += newState <EOL> }

/**
 * Adds [newState] to the stack and set [waitingFor][FirInProcessOfResolvingToJumpingPhaseState.waitingFor]
 * for the previous state if needed
 */


fun pop ( ) : FirInProcessOfResolvingToJumpingPhaseState

{ <EOL> val states = stateStackHolder . get ( ) <EOL> val currentState = states . removeLast ( ) <EOL> val prevState = states . lastOrNull ( ) <EOL> requireWithAttachment ( condition = prevState == null || prevState . waitingFor === currentState , message = { "<STR_LIT>" } , ) <EOL> prevState ? . waitingFor = null <EOL> if ( states . isEmpty ( ) ) { <EOL> stateStackHolder . remove ( ) <EOL> } <EOL> return currentState <EOL> }

/**
 * Pops from the top of the stack the last state and return it.
 * Updates [waitingFor][FirInProcessOfResolvingToJumpingPhaseState.waitingFor] for
 * the previous state if needed
 *
 * Note: it doesn't release the [lock][FirInProcessOfResolvingToJumpingPhaseState.latch]
 */


fun peek ( ) : FirInProcessOfResolvingToJumpingPhaseState ?

= stateStackHolder . get ( ) . lastOrNull ( )

/**
 * Current state on the top if exists
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun < T > Array < out T > ? . orEmpty ( ) : Array < out T >

= this ? : emptyArray < T > ( )

/**
 * Returns the array if it's not `null`, or an empty array otherwise.
 * @sample samples.collections.Arrays.Usage.arrayOrEmpty
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun < T > Collection < T > . toTypedArray ( ) : Array < T >

= copyToArray ( this )

/**
 * Returns a *typed* array containing all the elements of this collection.
 *
 * Allocates an array of runtime type `T` having its size equal to the size of this collection
 * and populates the array with the elements of this collection.
 * @sample samples.collections.Collections.Collections.collectionToTypedArray
 */


public actual fun < T > listOf ( element : T ) : List < T >

= arrayListOf ( element )

/**
 * Returns a new read-only list containing only the specified object [element].
 *
 * @sample samples.collections.Collections.Lists.singletonReadOnlyList
 */


public actual fun < T > setOf ( element : T ) : Set < T >

= hashSetOf ( element )

/**
 * Returns a new read-only set containing only the specified object [element].
 *
 * @sample samples.collections.Collections.Sets.singletonReadOnlySet
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual fun < T > MutableList < T > . fill ( value : T ) : Unit

{ <EOL> for ( index in <NUM_LIT:0> .. lastIndex ) { <EOL> this [ index ] = value <EOL> } <EOL> }

/**
 * Fills the list with the provided [value].
 *
 * Each element in the list gets replaced with the [value].
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual fun < T > MutableList < T > . shuffle ( ) : Unit

= shuffle ( Random )

/**
 * Randomly shuffles elements in this list.
 *
 * See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual fun < T > Iterable < T > . shuffled ( ) : List < T >

= toMutableList ( ) . apply { shuffle ( ) }

/**
 * Returns a new list with the elements of this collection randomly shuffled.
 */


public actual fun < T : Comparable < T > > MutableList < T > . sort ( ) : Unit

{ <EOL> collectionsSort ( this , naturalOrder ( ) ) <EOL> }

/**
 * Sorts elements in the list in-place according to their natural sort order.
 *
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 *
 * @sample samples.collections.Collections.Sorting.sortMutableList
 */


public actual fun < T > MutableList < T > . sortWith ( comparator : Comparator < in T > ) : Unit

{ <EOL> collectionsSort ( this , comparator ) <EOL> }

/**
 * Sorts elements in the list in-place according to the order specified with [comparator].
 *
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 *
 * @sample samples.collections.Collections.Sorting.sortMutableListWith
 */


@ PublishedApi <EOL> internal actual fun mapCapacity ( expectedSize : Int ) : Int

= expectedSize

/**
 * JS map and set implementations do not make use of capacities or load factors.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ PublishedApi <EOL> internal fun checkBuilderCapacity ( capacity : Int )

{ <EOL> require ( capacity >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> }

/**
 * Checks a collection builder function capacity argument.
 * In JS no validation is made in Map/Set constructor yet.
 */


public actual fun < K , V > mapOf ( pair : Pair < K , V > ) : Map < K , V >

= hashMapOf ( pair )

/**
 * Returns a new read-only map, mapping only the specified key to the
 * specified value.
 *
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */


protected abstract fun selectKey ( project : Project ) : Project

/**
 * Calculates a part of a key that is used to determine whether an action from [run] was already executed
 */


fun run ( project : Project , actionId : String , action : ( ) -> Unit )

{ <EOL> val performedActions = performedActions . computeIfAbsent ( selectKey ( project ) ) { mutableSetOf ( ) } <EOL> if ( performedActions . add ( actionId ) ) { <EOL> action ( ) <EOL> } <EOL> }

/**
 * Runs an [action] once per key value which is being calculated as a combination of a [selectKey] value and an [actionId]
 *
 * Warning: if KGP is loaded multiple times by different classloaders, actions with the same [actionId] may be executed more than once
 */


fun registeredHandlers ( ) : List < FieldHandlerWithPriority >

/**
 * List all registered handlers with their priorities
 */


public actual fun Double . isNaN ( ) : Boolean

= this != this

/**
 * Returns `true` if the specified number is a
 * Not-a-Number (NaN) value, `false` otherwise.
 */


public actual fun Float . isNaN ( ) : Boolean

= this != this


public actual fun Double . isInfinite ( ) : Boolean

= this == Double . POSITIVE_INFINITY || this == Double . NEGATIVE_INFINITY

/**
 * Returns `true` if this value is infinitely large in magnitude.
 */


public actual fun Float . isInfinite ( ) : Boolean

= this == Float . POSITIVE_INFINITY || this == Float . NEGATIVE_INFINITY


public actual fun Double . isFinite ( ) : Boolean

= ! isInfinite ( ) && ! isNaN ( )

/**
 * Returns `true` if the argument is a finite floating-point value; returns `false` otherwise (for `NaN` and infinity arguments).
 */


public actual fun Float . isFinite ( ) : Boolean

= ! isInfinite ( ) && ! isNaN ( )


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual fun Double . toBits ( ) : Long

= <EOL> doubleToRawBits ( if ( this . isNaN ( ) ) Double . NaN else this )

/**
 * Returns a bit representation of the specified floating-point value as [Long]
 * according to the IEEE 754 floating-point "double format" bit layout.
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual fun Double . toRawBits ( ) : Long

= <EOL> doubleToRawBits ( this )

/**
 * Returns a bit representation of the specified floating-point value as [Long]
 * according to the IEEE 754 floating-point "double format" bit layout,
 * preserving `NaN` values exact layout.
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun Double . Companion . fromBits ( bits : Long ) : Double

= <EOL> doubleFromBits ( bits )

/**
 * Returns the [Double] value corresponding to a given bit representation.
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual fun Float . toBits ( ) : Int

= <EOL> floatToRawBits ( if ( this . isNaN ( ) ) Float . NaN else this )

/**
 * Returns a bit representation of the specified floating-point value as [Int]
 * according to the IEEE 754 floating-point "single format" bit layout.
 *
 * Note that in Kotlin/JS [Float] range is wider than "single format" bit layout can represent,
 * so some [Float] values may overflow, underflow or loose their accuracy after conversion to bits and back.
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual fun Float . toRawBits ( ) : Int

= <EOL> floatToRawBits ( this )

/**
 * Returns a bit representation of the specified floating-point value as [Int]
 * according to the IEEE 754 floating-point "single format" bit layout,
 * preserving `NaN` values exact layout.
 *
 * Note that in Kotlin/JS [Float] range is wider than "single format" bit layout can represent,
 * so some [Float] values may overflow, underflow or loose their accuracy after conversion to bits and back.
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun Float . Companion . fromBits ( bits : Int ) : Float

= <EOL> floatFromBits ( bits )

/**
 * Returns the [Float] value corresponding to a given bit representation.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Int . countOneBits ( ) : Int

{ <EOL> var v = this <EOL> v = ( v and <NUM_LIT> ) + ( v . ushr ( <NUM_LIT:1> ) and <NUM_LIT> ) <EOL> v = ( v and <NUM_LIT> ) + ( v . ushr ( <NUM_LIT:2> ) and <NUM_LIT> ) <EOL> v = ( v and <NUM_LIT> ) + ( v . ushr ( <NUM_LIT:4> ) and <NUM_LIT> ) <EOL> v = ( v and <NUM_LIT> ) + ( v . ushr ( <NUM_LIT:8> ) and <NUM_LIT> ) <EOL> v = ( v and <NUM_LIT> ) + ( v . ushr ( <NUM_LIT:16> ) ) <EOL> return v <EOL> }

/**
 * Counts the number of set bits in the binary representation of this [Int] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun Int . countLeadingZeroBits ( ) : Int

= nativeClz32 ( this )

/**
 * Counts the number of consecutive most significant bits that are zero in the binary representation of this [Int] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Int . countTrailingZeroBits ( ) : Int

= <EOL> Int . SIZE_BITS - ( this or - this ) . inv ( ) . countLeadingZeroBits ( )

/**
 * Counts the number of consecutive least significant bits that are zero in the binary representation of this [Int] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Int . takeHighestOneBit ( ) : Int

= <EOL> if ( this == <NUM_LIT:0> ) <NUM_LIT:0> else <NUM_LIT:1> . shl ( Int . SIZE_BITS - <NUM_LIT:1> - countLeadingZeroBits ( ) )

/**
 * Returns a number having a single bit set in the position of the most significant set bit of this [Int] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Int . takeLowestOneBit ( ) : Int

= <EOL> this and - this

/**
 * Returns a number having a single bit set in the position of the least significant set bit of this [Int] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public actual fun Int . rotateLeft ( bitCount : Int ) : Int

= <EOL> shl ( bitCount ) or ushr ( Int . SIZE_BITS - bitCount )

/**
 * Rotates the binary representation of this [Int] number left by the specified [bitCount] number of bits.
 * The most significant bits pushed out from the left side reenter the number as the least significant bits on the right side.
 *
 * Rotating the number left by a negative bit count is the same as rotating it right by the negated bit count:
 * `number.rotateLeft(-n) == number.rotateRight(n)`
 *
 * Rotating by a multiple of [Int.SIZE_BITS] (32) returns the same number, or more generally
 * `number.rotateLeft(n) == number.rotateLeft(n % 32)`
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public actual fun Int . rotateRight ( bitCount : Int ) : Int

= <EOL> shl ( Int . SIZE_BITS - bitCount ) or ushr ( bitCount )

/**
 * Rotates the binary representation of this [Int] number right by the specified [bitCount] number of bits.
 * The least significant bits pushed out from the right side reenter the number as the most significant bits on the left side.
 *
 * Rotating the number right by a negative bit count is the same as rotating it left by the negated bit count:
 * `number.rotateRight(-n) == number.rotateLeft(n)`
 *
 * Rotating by a multiple of [Int.SIZE_BITS] (32) returns the same number, or more generally
 * `number.rotateRight(n) == number.rotateRight(n % 32)`
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Long . countOneBits ( ) : Int

= <EOL> high . countOneBits ( ) + low . countOneBits ( )

/**
 * Counts the number of set bits in the binary representation of this [Long] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Long . countLeadingZeroBits ( ) : Int

= <EOL> when ( val high = this . high ) { <EOL> <NUM_LIT:0> -> Int . SIZE_BITS + low . countLeadingZeroBits ( ) <EOL> else -> high . countLeadingZeroBits ( ) <EOL> }

/**
 * Counts the number of consecutive most significant bits that are zero in the binary representation of this [Long] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Long . countTrailingZeroBits ( ) : Int

= <EOL> when ( val low = this . low ) { <EOL> <NUM_LIT:0> -> Int . SIZE_BITS + high . countTrailingZeroBits ( ) <EOL> else -> low . countTrailingZeroBits ( ) <EOL> }

/**
 * Counts the number of consecutive least significant bits that are zero in the binary representation of this [Long] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Long . takeHighestOneBit ( ) : Long

= <EOL> when ( val high = this . high ) { <EOL> <NUM_LIT:0> -> Long ( low . takeHighestOneBit ( ) , <NUM_LIT:0> ) <EOL> else -> Long ( <NUM_LIT:0> , high . takeHighestOneBit ( ) ) <EOL> }

/**
 * Returns a number having a single bit set in the position of the most significant set bit of this [Long] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun Long . takeLowestOneBit ( ) : Long

= <EOL> when ( val low = this . low ) { <EOL> <NUM_LIT:0> -> Long ( <NUM_LIT:0> , high . takeLowestOneBit ( ) ) <EOL> else -> Long ( low . takeLowestOneBit ( ) , <NUM_LIT:0> ) <EOL> }

/**
 * Returns a number having a single bit set in the position of the least significant set bit of this [Long] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public actual fun Long . rotateLeft ( bitCount : Int ) : Long

{ <EOL> if ( ( bitCount and <NUM_LIT:31> ) != <NUM_LIT:0> ) { <EOL> val low = this . low <EOL> val high = this . high <EOL> val newLow = low . shl ( bitCount ) or high . ushr ( - bitCount ) <EOL> val newHigh = high . shl ( bitCount ) or low . ushr ( - bitCount ) <EOL> return if ( ( bitCount and <NUM_LIT> ) == <NUM_LIT:0> ) Long ( newLow , newHigh ) else Long ( newHigh , newLow ) <EOL> } else { <EOL> return if ( ( bitCount and <NUM_LIT> ) == <NUM_LIT:0> ) this else Long ( high , low ) <EOL> } <EOL> }

/**
 * Rotates the binary representation of this [Long] number left by the specified [bitCount] number of bits.
 * The most significant bits pushed out from the left side reenter the number as the least significant bits on the right side.
 *
 * Rotating the number left by a negative bit count is the same as rotating it right by the negated bit count:
 * `number.rotateLeft(-n) == number.rotateRight(n)`
 *
 * Rotating by a multiple of [Long.SIZE_BITS] (64) returns the same number, or more generally
 * `number.rotateLeft(n) == number.rotateLeft(n % 64)`
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun Long . rotateRight ( bitCount : Int ) : Long

= rotateLeft ( - bitCount )

/**
 * Rotates the binary representation of this [Long] number right by the specified [bitCount] number of bits.
 * The least significant bits pushed out from the right side reenter the number as the most significant bits on the left side.
 *
 * Rotating the number right by a negative bit count is the same as rotating it left by the negated bit count:
 * `number.rotateRight(-n) == number.rotateLeft(n)`
 *
 * Rotating by a multiple of [Long.SIZE_BITS] (64) returns the same number, or more generally
 * `number.rotateRight(n) == number.rotateRight(n % 64)`
 */


fun Project . externalDocumentationLink ( url : String , packageList : File = projectDir . resolve ( "<STR_LIT>" ) )

{ <EOL> tasks . withType < AbstractDokkaLeafTask > ( ) . configureEach { <EOL> dokkaSourceSets . configureEach { <EOL> externalDocumentationLink { <EOL> this . url = URL ( url ) <EOL> packageListUrl = packageList . toPath ( ) . toUri ( ) . toURL ( ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Package-list by external URL for documentation generation.
 */


override fun SimpleTypeMarker . isSingleClassifierType ( ) : Boolean

{ <EOL> require ( this is SimpleType , this :: errorMessage ) <EOL> return ! isError && <EOL> constructor . declarationDescriptor !is TypeAliasDescriptor && <EOL> ( constructor . declarationDescriptor != null || this is CapturedType || this is NewCapturedType || this is DefinitelyNotNullType || constructor is IntegerLiteralTypeConstructor || isSingleClassifierTypeWithEnhancement ( ) ) <EOL> }

/**
 *
 * SingleClassifierType is one of the following types:
 * - classType
 * - type for type parameter
 * - captured type
 *
 * Such types can contain error types in our arguments, but type constructor isn't errorTypeConstructor
 */


private suspend fun testSendAfterClose ( kind : TestChannelKind )

{ <EOL> assertFailsWith < ClosedSendChannelException > { <EOL> coroutineScope { <EOL> val channel = kind . create < Int > ( ) <EOL> channel . close ( ) <EOL> launch { <EOL> channel . send ( <NUM_LIT:1> ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * [ClosedSendChannelException] should not be eaten.
 * See [https://github.com/Kotlin/kotlinx.coroutines/issues/957]
 */


override fun buildTransformedAtomicExtensionSignature ( atomicExtension : IrFunction , isArrayReceiver : Boolean ) : IrSimpleFunction

{ <EOL> val mangledName = mangleAtomicExtensionName ( atomicExtension . name . asString ( ) , isArrayReceiver ) <EOL> val valueType = ( atomicExtension . extensionReceiverParameter ! ! . type as IrSimpleType ) . atomicToPrimitiveType ( ) <EOL> return pluginContext . irFactory . buildFun { <EOL> name = Name . identifier ( mangledName ) <EOL> isInline = true <EOL> visibility = atomicExtension . visibility <EOL> origin = AbstractAtomicSymbols . ATOMICFU_GENERATED_FUNCTION <EOL> } . apply { <EOL> extensionReceiverParameter = null <EOL> dispatchReceiverParameter = atomicExtension . dispatchReceiverParameter ? . deepCopyWithSymbols ( this ) <EOL> atomicExtension . typeParameters . forEach { addTypeParameter ( it . name . asString ( ) , it . representativeUpperBound ) } <EOL> addSyntheticValueParametersToTransformedAtomicExtension ( isArrayReceiver , valueType ) <EOL> atomicExtension . valueParameters . forEach { addValueParameter ( it . name , it . type ) } <EOL> returnType = atomicExtension . returnType <EOL> this . parent = atomicExtension . parent <EOL> } <EOL> }

/**
 * Builds the signature of the transformed atomic extension:
 *
 * inline fun AtomicInt.foo(arg: Int) --> inline fun foo$atomicfu(dispatchReceiver: Any?, atomicHandler: AtomicIntegerFieldUpdater, arg': Int)
 * inline fun foo$atomicfu$array(atomicArray: AtomicIntegerArray, index: Int, arg': Int)
 */


override fun IrFunction . addSyntheticValueParametersToTransformedAtomicExtension ( isArrayReceiver : Boolean , valueType : IrType )

{ <EOL> if ( isArrayReceiver ) { <EOL> addValueParameter ( ATOMIC_HANDLER , atomicSymbols . getAtomicArrayClassByValueType ( valueType ) . defaultType ) <EOL> addValueParameter ( INDEX , irBuiltIns . intType ) <EOL> } else { <EOL> addValueParameter ( DISPATCH_RECEIVER , irBuiltIns . anyNType ) <EOL> addValueParameter ( ATOMIC_HANDLER , atomicSymbols . getFieldUpdaterType ( valueType ) ) <EOL> } <EOL> }

/**
 * Adds synthetic value parameters to the transformed atomic extension (custom atomic extension or atomicfu inline update functions).
 */


@ Test <EOL> fun writeSplitSourceBufferLeft ( )

{ <EOL> val writeSize = Segment . SIZE / <NUM_LIT:2> + <NUM_LIT:1> <EOL> val sink = Buffer ( ) <EOL> sink . writeString ( '<CHAR_LIT:b>' . repeat ( Segment . SIZE - <NUM_LIT:10> ) ) <EOL> val source = Buffer ( ) <EOL> source . writeString ( '<CHAR_LIT:a>' . repeat ( Segment . SIZE * <NUM_LIT:2> ) ) <EOL> sink . write ( source , writeSize . toLong ( ) ) <EOL> assertEquals ( listOf ( Segment . SIZE - <NUM_LIT:10> , writeSize ) , segmentSizes ( sink ) ) <EOL> assertEquals ( listOf ( Segment . SIZE - writeSize , Segment . SIZE ) , segmentSizes ( source ) ) <EOL> }

/** The big part of source's first segment is being moved. */


@ Test <EOL> fun writeSplitSourceBufferRight ( )

{ <EOL> val writeSize = Segment . SIZE / <NUM_LIT:2> - <NUM_LIT:1> <EOL> val sink = Buffer ( ) <EOL> sink . writeString ( '<CHAR_LIT:b>' . repeat ( Segment . SIZE - <NUM_LIT:10> ) ) <EOL> val source = Buffer ( ) <EOL> source . writeString ( '<CHAR_LIT:a>' . repeat ( Segment . SIZE * <NUM_LIT:2> ) ) <EOL> sink . write ( source , writeSize . toLong ( ) ) <EOL> assertEquals ( listOf ( Segment . SIZE - <NUM_LIT:10> , writeSize ) , segmentSizes ( sink ) ) <EOL> assertEquals ( listOf ( Segment . SIZE - writeSize , Segment . SIZE ) , segmentSizes ( source ) ) <EOL> }

/** The big part of source's first segment is staying put. */


@ Test <EOL> fun readAllWritesAllSegmentsAtOnce ( )

{ <EOL> val write1 = Buffer ( ) <EOL> write1 . writeString ( '<CHAR_LIT:a>' . repeat ( Segment . SIZE ) + '<CHAR_LIT:b>' . repeat ( Segment . SIZE ) + '<CHAR_LIT:c>' . repeat ( Segment . SIZE ) ) <EOL> val source = Buffer ( ) <EOL> source . writeString ( '<CHAR_LIT:a>' . repeat ( Segment . SIZE ) + '<CHAR_LIT:b>' . repeat ( Segment . SIZE ) + '<CHAR_LIT:c>' . repeat ( Segment . SIZE ) ) <EOL> val mockSink = MockSink ( ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:3> ) . toLong ( ) , source . transferTo ( mockSink ) ) <EOL> assertEquals ( <NUM_LIT:0> , source . size ) <EOL> mockSink . assertLog ( "<STR_LIT>" ) <EOL> }

/**
 * When writing data that's already buffered, there's no reason to page the
 * data by segment.
 */


fun checkPsiOrLightTree ( element : D , source : KtSourceElement , context : CheckerContext , reporter : DiagnosticReporter )

/**
 * By default psi tree should be equivalent to light tree and can be processed the same way.
 */


private fun < E : Throwable > E . causeAndStacktrace ( ) : Pair < E , Array < StackTraceElement > >

{ <EOL> val cause = cause <EOL> return if ( cause != null && cause . javaClass == javaClass ) { <EOL> val currentTrace = stackTrace <EOL> if ( currentTrace . any { it . isArtificial ( ) } ) <EOL> cause as E to currentTrace <EOL> else this to emptyArray ( ) <EOL> } else { <EOL> this to emptyArray ( ) <EOL> } <EOL> }

/**
 * Find initial cause of the exception without restored stacktrace.
 * Returns intermediate stacktrace as well in order to avoid excess cloning of array as an optimization.
 */


private fun resolverForModuleDescriptorImpl ( descriptor : ModuleDescriptor ) : ResolverForModule ?

{ <EOL> return projectContext . storageManager . compute { <EOL> checkValid ( ) <EOL> descriptor . assertValid ( ) <EOL> val module = moduleInfoByDescriptor [ descriptor ] <EOL> if ( module == null ) { <EOL> if ( delegateResolver is EmptyResolverForProject < * > ) { <EOL> return@compute null <EOL> } <EOL> return@compute ( delegateResolver as AbstractResolverForProject < M > ) . resolverForModuleDescriptorImpl ( descriptor ) <EOL> } <EOL> resolverByModuleDescriptor . getOrPut ( descriptor ) { <EOL> checkModuleIsCorrect ( module ) <EOL> ResolverForModuleComputationTracker . getInstance ( projectContext . project ) ? . onResolverComputed ( module ) <EOL> createResolverForModule ( descriptor , module ) <EOL> } <EOL> } <EOL> }

/**
 * We have a problem investigating EA-214260 (KT-40301), that is why we separated searching the
 * [ResolverForModule] and reporting the problem in [resolverForModuleDescriptor] (so we can tweak the reported information more
 * accurately).
 *
 * We use the fact that [ResolverForProject] have only two inheritors: [EmptyResolverForProject] and [AbstractResolverForProject].
 * So if the [delegateResolver] is not an [EmptyResolverForProject], it has to be [AbstractResolverForProject].
 *
 * Knowing that, we can safely use [resolverForModuleDescriptorImpl] recursively, and get the same result
 * as with [resolverForModuleDescriptor].
 */


public actual fun ComplexDouble ( re : Double , im : Double ) : ComplexDouble

= WasmComplexDouble ( re , im )

/**
 * Creates a [ComplexDouble] with the given real and imaginary values in floating-point format.
 *
 * @param re the real value of the complex number in double format.
 * @param im the imaginary value of the complex number in double format.
 */


public actual fun ComplexDouble ( re : Number , im : Number ) : ComplexDouble

= ComplexDouble ( re . toDouble ( ) , im . toDouble ( ) )

/**
 * Creates a [ComplexDouble] with the given real and imaginary values in number format.
 *
 * @param re the real value of the complex number in number format.
 * @param im the imaginary value of the complex number in number format.
 */


@ ExperimentalSerializationApi <EOL> public fun < T > Json . decodeFromDynamic ( deserializer : DeserializationStrategy < T > , dynamic : dynamic ) : T

= decodeDynamic ( deserializer , dynamic )

/**
 * Converts native JavaScript objects into Kotlin ones, verifying their types.
 *
 * A result of `decodeFromDynamic(nativeObj)` should be the same as
 * `kotlinx.serialization.json.Json.decodeFromString(kotlin.js.JSON.stringify(nativeObj))`.
 * This class also supports array-based polymorphism if the corresponding flag in [Json.configuration] is set to `true`.
 * Does not support any other [Map] keys than [String].
 * Has limitation on [Long] type: any JS number that is greater than
 * [`abs(2^53-1)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)
 * is considered to be imprecise and therefore can't be deserialized to [Long]. Either use [Double] type
 * for such values or pass them as strings using [LongAsStringSerializer] afterwards.
 *
 * Usage example:
 *
 * ```
 * @Serializable
 * data class Data(val a: Int)
 *
 * @Serializable
 * data class DataWrapper(val s: String, val d: Data?)
 *
 * val dyn: dynamic = js("""{s:"foo", d:{a:42}}""")
 * val parsed = Json.decodeFromDynamic(DataWrapper.serializer(), dyn)
 * parsed == DataWrapper("foo", Data(42)) // true
 * ```
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Json . decodeFromDynamic ( dynamic : dynamic ) : T

= <EOL> decodeFromDynamic ( serializersModule . serializer ( ) , dynamic )

/**
 * A reified version of [decodeFromDynamic].
 */


@ ExperimentalSerializationApi <EOL> public fun < T > Json . encodeToDynamic ( serializer : SerializationStrategy < T > , value : T ) : dynamic

= encodeDynamic ( serializer , value )

/**
 * Converts Kotlin data structures to plain Javascript objects
 *
 * Limitations:
 * * Map keys must be of primitive or enum type
 * * All [Long] values must be less than [`abs(2^53-1)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER).
 * Otherwise, they're encoded as doubles with precision loss and require `isLenient` flag of [Json.configuration] set to true.
 *
 * Example of usage:
 * ```
 * @Serializable
 * open class DataWrapper(open val s: String, val d: String?)
 *
 * val wrapper = DataWrapper("foo", "bar")
 * val plainJS: dynamic = Json.encodeToDynamic(DataWrapper.serializer(), wrapper)
 * ```
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Json . encodeToDynamic ( value : T ) : dynamic

= <EOL> encodeToDynamic ( serializersModule . serializer ( ) , value )

/**
 * A reified version of [encodeToDynamic].
 */


@ Test <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> fun testChild ( )

= runTest { <EOL> val barrier = CyclicBarrier ( <NUM_LIT:3> ) <EOL> repeat ( N_ITERATIONS ) { <EOL> var wasLaunched = false <EOL> var unhandledException : Throwable ? = null <EOL> val handler = CoroutineExceptionHandler { _ , ex -> <EOL> unhandledException = ex <EOL> } <EOL> val scope = CoroutineScope ( pool + handler ) <EOL> val parent = CompletableDeferred < Unit > ( ) <EOL> val launcher = scope . launch { <EOL> barrier . await ( ) <EOL> launch ( parent ) { <EOL> wasLaunched = true <EOL> throw TestException ( ) <EOL> } <EOL> } <EOL> val canceller = scope . launch { <EOL> barrier . await ( ) <EOL> parent . cancel ( ) <EOL> } <EOL> barrier . await ( ) <EOL> joinAll ( launcher , canceller , parent ) <EOL> assertNull ( unhandledException ) <EOL> if ( wasLaunched ) { <EOL> val exception = parent . getCompletionExceptionOrNull ( ) <EOL> assertIs < TestException > ( exception , "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * Perform concurrent launch of a child job & cancellation of the explicit parent job
 */


public abstract fun write ( ) : Metadata

/**
 * Encodes and writes this metadata to the new instance of [Metadata].
 *
 * This method encodes all available data, including [version] and [flags].
 * Due to technical limitations, it is not possible to write the metadata when the specified version is less than 1.4.
 * It is also not possible to write metadata with the version higher that [JvmMetadataVersion.LATEST_STABLE_SUPPORTED] + 1, as
 * we do not know if a metadata format is the same for yet unreleased Kotlin compilers.
 *
 * @throws IllegalArgumentException if metadata is malformed, or metadata was read in lenient mode and cannot be written back,
 * or [version] of this instance is less than 1.4, or [version] of this instance is too high.
 */


public fun transform ( metadata : Metadata , transformer : ( KotlinClassMetadata ) -> Unit ) : Metadata

{ <EOL> return readStrict ( metadata ) . apply ( transformer ) . write ( ) <EOL> }

/**
 * Utility method to combine reading and writing of metadata:
 * First, [metadata] is parsed with [readStrict]; then, [transformer] is called on a read instance.
 * [transformer] may mutate passed instance of [KotlinClassMetadata] to achieve a desired result.
 * After transformation, [KotlinClassMetadata.write] method is called and its result becomes return value of this method.
 *
 * @throws IllegalArgumentException if metadata cannot be read or written
 *
 * @see readStrict
 * @see write
 */


@ JvmStatic <EOL> public fun readStrict ( annotationData : Metadata ) : KotlinClassMetadata

= readMetadataImpl ( annotationData , lenient = false )

/**
 * Reads and parses the given annotation data of a Kotlin JVM class file and returns the correct type of [KotlinClassMetadata] encoded by
 * this annotation, if the metadata version is supported.
 *
 * [annotationData] may be obtained reflectively, constructed manually or with helper [kotlin.metadata.jvm.Metadata] function,
 * or equivalent [KotlinClassHeader] can be used.
 *
 * This method can read only supported metadata versions (see [JvmMetadataVersion.LATEST_STABLE_SUPPORTED] for definition).
 * It will throw an exception if the metadata version is greater than what kotlinx-metadata-jvm understands.
 * It is suitable when your tooling cannot tolerate reading potentially incomplete or incorrect information due to version differences.
 * It is also the only method that allows metadata transformation and `KotlinClassMetadata.write` subsequent calls.
 *
 * @throws IllegalArgumentException if the metadata version is unsupported or if metadata is corrupted
 *
 * @see JvmMetadataVersion.LATEST_STABLE_SUPPORTED
 */


@ JvmStatic <EOL> public fun readLenient ( annotationData : Metadata ) : KotlinClassMetadata

= readMetadataImpl ( annotationData , lenient = true )

/**
 * Reads and parses the given annotation data of a Kotlin JVM class file and returns the correct type of [KotlinClassMetadata] encoded by
 * this annotation. [KotlinClassMetadata] instances obtained from this method cannot be written.
 *
 * [annotationData] may be obtained reflectively, constructed manually or with helper [kotlin.metadata.jvm.Metadata] function,
 * or equivalent [KotlinClassHeader] can be used.
 *
 * This method makes best effort to read unsupported metadata versions.
 * If [annotationData] version is greater than [JvmMetadataVersion.LATEST_STABLE_SUPPORTED] + 1, this method still attempts to read it and may ignore parts of the metadata it does not understand.
 * Keep in mind that this method will still throw an exception if metadata is changed in an unpredictable way.
 * Because obtained metadata can be incomplete, its [KotlinClassMetadata.write] method will throw an exception.
 * This method still cannot read metadata produced by pre-1.0 compilers.
 *
 * @throws IllegalArgumentException if the metadata version is that of Kotlin 1.0, or the metadata format has been changed in an unpredictable way and reading of incompatible metadata is not possible
 *
 * @see JvmMetadataVersion.LATEST_STABLE_SUPPORTED
 */


{ <EOL> val preprocessing = pipeline < BufferedImage > ( ) <EOL> . crop { <EOL> left = <NUM_LIT:100> <EOL> right = <NUM_LIT:0> <EOL> top = <NUM_LIT:100> <EOL> bottom = <NUM_LIT:0> <EOL> } <EOL> . rotate { <EOL> degrees = <NUM_LIT> <EOL> } <EOL> . resize { <EOL> outputWidth = <NUM_LIT> <EOL> outputHeight = <NUM_LIT> <EOL> interpolation = InterpolationType . NEAREST <EOL> } <EOL> . onResult { ImageIO . write ( it , "<STR_LIT>" , File ( "<STR_LIT>" ) ) } <EOL> . pad { <EOL> top = <NUM_LIT:10> <EOL> bottom = <NUM_LIT> <EOL> left = <NUM_LIT:10> <EOL> right = <NUM_LIT:10> <EOL> mode = PaddingMode . Fill ( Color . WHITE ) <EOL> } <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . rescale { <EOL> scalingCoefficient = <NUM_LIT> <EOL> } <EOL> val imageResource = Operation :: class . java . getResource ( "<STR_LIT>" ) <EOL> val image = File ( imageResource ! ! . toURI ( ) ) <EOL> val ( rawImage , shape ) = preprocessing . fileLoader ( ) . load ( image ) <EOL> val bufferedImage = ImageConverter . floatArrayToBufferedImage ( rawImage , shape , ColorMode . BGR , isNormalized = true ) <EOL> showFrame ( "<STR_LIT>" , ImagePanel ( bufferedImage ) ) <EOL> }

/**
 * This example shows how to do image preprocessing using preprocessing DSL for only one image.
 *
 * It includes:
 * - image preprocessing;
 * - image visualisation with the [ImagePanel].
 */


@ Suppress ( "<STR_LIT>" ) <EOL> fun compile ( ) : List < ClassFile >

= sourceFile . compile ( tmpDir )

/** Compiles this source file and returns all generated .class files. */


fun compileAll ( srcDir : File , tmpDir : TemporaryFolder , classpath : List < File > = emptyList ( ) ) : List < ClassFile >

{ <EOL> val classesDir = srcDir . path . let { <EOL> File ( it . substringBeforeLast ( "<STR_LIT:src>" ) + "<STR_LIT>" + it . substringAfterLast ( "<STR_LIT:src>" ) ) <EOL> } <EOL> val kotlinClasses = compileKotlin ( srcDir , classesDir , classpath ) <EOL> val javaClasspath = classpath + listOfNotNull ( kotlinClasses . firstOrNull ( ) ? . classRoot ) <EOL> val javaClasses = compileJava ( srcDir , classesDir = tmpDir . newFolder ( ) , javaClasspath ) <EOL> return kotlinClasses + javaClasses <EOL> }

/** Compiles the source files in the given directory and returns all generated .class files. */


@ HtmlTagMarker <EOL> inline fun PICTURE . source ( classes : String ? = null , crossinline block : SOURCE . ( ) -> Unit = { } ) : Unit

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


@ HtmlTagMarker <EOL> inline fun PICTURE . img ( alt : String ? = null , src : String ? = null , loading : ImgLoading ? = null , classes : String ? = null , crossinline block : IMG . ( ) -> Unit = { } ) : Unit

= IMG ( attributesMapOf ( "<STR_LIT>" , alt , "<STR_LIT:src>" , src , "<STR_LIT>" , loading ? . enumEncode ( ) , "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


private fun BlockHound . Builder . allowBlockingCallsInPrimitiveImplementations ( )

{ <EOL> allowBlockingCallsInJobSupport ( ) <EOL> allowBlockingCallsInThreadSafeHeap ( ) <EOL> allowBlockingCallsInFlow ( ) <EOL> allowBlockingCallsInChannels ( ) <EOL> }

/**
 * Allows blocking calls in various coroutine structures, such as flows and channels.
 *
 * They use locks in implementations, though only for protecting short pieces of fast and well-understood code, so
 * locking in such places doesn't affect the program liveness.
 */


private fun BlockHound . Builder . allowBlockingCallsInJobSupport ( )

{ <EOL> for ( method in listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> }

/**
 * Allows blocking inside [kotlinx.coroutines.JobSupport].
 */


private fun BlockHound . Builder . allowBlockingCallsInDebugProbes ( )

{ <EOL> for ( method in listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> }

/**
 * Allow blocking calls inside [kotlinx.coroutines.debug.internal.DebugProbesImpl].
 */


private fun BlockHound . Builder . allowBlockingCallsInWorkQueue ( )

{ <EOL> allowBlockingCallsInside ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> }

/**
 * Allow blocking calls inside [kotlinx.coroutines.scheduling.WorkQueue]
 */


private fun BlockHound . Builder . allowBlockingCallsInThreadSafeHeap ( )

{ <EOL> for ( method in listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> }

/**
 * Allows blocking inside [kotlinx.coroutines.internal.ThreadSafeHeap].
 */


private fun BlockHound . Builder . allowBlockingCallsInsideStateFlow ( )

/**
 * Allows blocking inside the implementation of [kotlinx.coroutines.flow.StateFlow].
 */


private fun BlockHound . Builder . allowBlockingCallsInsideSharedFlow ( )

{ <EOL> for ( method in listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> for ( method in listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> }

/**
 * Allows blocking inside the implementation of [kotlinx.coroutines.flow.SharedFlow].
 */


private fun BlockHound . Builder . allowBlockingCallsInBroadcastChannels ( )

{ <EOL> for ( method in listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ) <EOL> { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> for ( method in listOf ( "<STR_LIT>" ) ) { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> for ( method in listOf ( "<STR_LIT>" ) ) { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> }

/**
 * Allows blocking inside [kotlinx.coroutines.channels.BroadcastChannel].
 */


private fun BlockHound . Builder . allowBlockingCallsInConflatedChannels ( )

{ <EOL> for ( method in listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> for ( method in listOf ( "<STR_LIT>" ) ) { <EOL> allowBlockingCallsInside ( "<STR_LIT>" , method ) <EOL> } <EOL> }

/**
 * Allows blocking inside [kotlinx.coroutines.channels.ConflatedBufferedChannel].
 */


private fun BlockHound . Builder . allowBlockingWhenEnqueuingTasks ( )

/**
 * Allows blocking when enqueuing tasks into a thread pool.
 *
 * Without this, the following code breaks:
 * ```
 * withContext(Dispatchers.Default) {
 * withContext(newSingleThreadContext("singleThreadedContext")) {
 * }
 * }
 * ```
 */


private fun BlockHound . Builder . allowServiceLoaderInvocationsOnInit ( )

{ <EOL> allowBlockingCallsInside ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> allowBlockingCallsInside ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> allowBlockingCallsInside ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> }

/**
 * Allows instances of [java.util.ServiceLoader] being called.
 *
 * Each instance is listed separately; another approach could be to generally allow the operations performed by
 * service loaders, as they can generally be considered safe. This was not done here because ServiceLoader has a
 * large API surface, with some methods being hidden as implementation details (in particular, the implementation of
 * its iterator is completely opaque). Relying on particular names being used in ServiceLoader's implementation
 * would be brittle, so here we only provide clearance rules for some specific instances.
 */


private fun BlockHound . Builder . allowBlockingCallsInReflectionImpl ( )

/**
 * Allows some blocking calls from the reflection API.
 *
 * The API is big, so surely some other blocking calls will show up, but with these rules in place, at least some
 * simple examples work without problems.
 */


fun remoteUrl ( @ Language ( "<STR_LIT>" ) value : String ) : Unit

= <EOL> remoteUrl . set ( URI ( value ) )

/**
 * Set the value of [remoteUrl].
 *
 * @param[value] will be converted to a [URI]
 */


fun remoteUrl ( value : Provider < String > ) : Unit

= <EOL> remoteUrl . set ( value . map ( :: URI ) )


inline fun < reified T > SparkSession . toDS ( list : List < T > ) : Dataset < T >

= <EOL> createDataset ( list , encoder < T > ( ) )

/**
 * Utility method to create dataset from list
 */


inline fun < reified T > SparkSession . toDF ( list : List < T > , vararg colNames : String ) : Dataset < Row >

= <EOL> toDS ( list ) . run { if ( colNames . isEmpty ( ) ) toDF ( ) else toDF ( * colNames ) }

/**
 * Utility method to create dataframe from list
 */


inline fun < reified T > SparkSession . dsOf ( vararg t : T ) : Dataset < T >

= <EOL> createDataset ( t . toList ( ) , encoder < T > ( ) )

/**
 * Utility method to create dataset from *array or vararg arguments
 */


inline fun < reified T > SparkSession . dfOf ( vararg t : T ) : Dataset < Row >

= <EOL> createDataset ( t . toList ( ) , encoder < T > ( ) ) . toDF ( )

/**
 * Utility method to create dataframe from *array or vararg arguments
 */


inline fun < reified T > SparkSession . dfOf ( colNames : Array < String > , vararg t : T ) : Dataset < Row >

= <EOL> createDataset ( t . toList ( ) , encoder < T > ( ) ) <EOL> . run { if ( colNames . isEmpty ( ) ) toDF ( ) else toDF ( * colNames ) }

/**
 * Utility method to create dataframe from *array or vararg arguments with given column names
 */


inline fun < reified T > List < T > . toDS ( spark : SparkSession ) : Dataset < T >

= <EOL> spark . createDataset ( this , encoder < T > ( ) )


inline fun < reified T > List < T > . toDF ( spark : SparkSession , vararg colNames : String ) : Dataset < Row >

= <EOL> toDS ( spark ) . run { if ( colNames . isEmpty ( ) ) toDF ( ) else toDF ( * colNames ) }


inline fun < reified T > Array < T > . toDS ( spark : SparkSession ) : Dataset < T >

= <EOL> toList ( ) . toDS ( spark )


inline fun < reified T > Array < T > . toDF ( spark : SparkSession , vararg colNames : String ) : Dataset < Row >


inline fun < reified T > RDD < T > . toDS ( spark : SparkSession ) : Dataset < T >

/**
 * Utility method to create dataset from RDD
 */


inline fun < reified T > JavaRDDLike < T , * > . toDS ( spark : SparkSession ) : Dataset < T >

= <EOL> spark . createDataset ( this . rdd ( ) , encoder < T > ( ) )

/**
 * Utility method to create dataset from JavaRDD
 */


inline fun < reified T > JavaRDDLike < T , * > . toDF ( spark : SparkSession , vararg colNames : String ) : Dataset < Row >

/**
 * Utility method to create Dataset<Row> (Dataframe) from JavaRDD.
 * NOTE: [T] must be [Serializable].
 */


inline fun < reified T > RDD < T > . toDF ( spark : SparkSession , vararg colNames : String ) : Dataset < Row >

/**
 * Utility method to create Dataset<Row> (Dataframe) from RDD.
 * NOTE: [T] must be [Serializable].
 */


inline fun < reified T , reified R > Dataset < T > . map ( noinline func : ( T ) -> R ) : Dataset < R >

= <EOL> map ( MapFunction ( func ) , encoder < R > ( ) )

/**
 * (Kotlin-specific)
 * Returns a new Dataset that contains the result of applying [func] to each element.
 */


inline fun < T , reified R > Dataset < T > . flatMap ( noinline func : ( T ) -> Iterator < R > ) : Dataset < R >

= <EOL> flatMap ( func , encoder < R > ( ) )

/**
 * (Kotlin-specific)
 * Returns a new Dataset by first applying a function to all elements of this Dataset,
 * and then flattening the results.
 */


inline fun < reified T , I : Iterable < T > > Dataset < I > . flatten ( ) : Dataset < T >

= <EOL> flatMap ( FlatMapFunction { it . iterator ( ) } , encoder < T > ( ) )

/**
 * (Kotlin-specific)
 * Returns a new Dataset by flattening. This means that a Dataset of an iterable such as
 * `listOf(listOf(1, 2, 3), listOf(4, 5, 6))` will be flattened to a Dataset of `listOf(1, 2, 3, 4, 5, 6)`.
 */


inline fun < T , reified R > Dataset < T > . groupByKey ( noinline func : ( T ) -> R ) : KeyValueGroupedDataset < R , T >

= <EOL> groupByKey ( MapFunction ( func ) , encoder < R > ( ) )

/**
 * (Kotlin-specific)
 * Returns a [KeyValueGroupedDataset] where the data is grouped by the given key [func].
 */


inline fun < T , reified R > Dataset < T > . mapPartitions ( noinline func : ( Iterator < T > ) -> Iterator < R > ) : Dataset < R >

= <EOL> mapPartitions ( func , encoder < R > ( ) )

/**
 * (Kotlin-specific)
 * Returns a new Dataset that contains the result of applying [func] to each partition.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> fun < T : Any > Dataset < T ? > . filterNotNull ( ) : Dataset < T >

= filter { it != null } as Dataset < T >

/**
 * (Kotlin-specific)
 * Filters rows to eliminate [null] values.
 */


inline fun < reified T > Dataset < T > . reduceK ( noinline func : ( T , T ) -> T ) : T

= <EOL> reduce ( ReduceFunction ( func ) )

/**
 * (Kotlin-specific)
 * Reduces the elements of this Dataset using the specified binary function. The given `func`
 * must be commutative and associative or the result may be non-deterministic.
 */


@ JvmName ( "<STR_LIT>" ) <EOL> inline fun < reified T1 , T2 > Dataset < Tuple2 < T1 , T2 > > . takeKeys ( ) : Dataset < T1 >

= map { it . _1 ( ) }

/**
 * (Kotlin-specific)
 * Maps the Dataset to only retain the "keys" or [Tuple2._1] values.
 */


inline fun < reified T1 , T2 > Dataset < Pair < T1 , T2 > > . takeKeys ( ) : Dataset < T1 >

= map { it . first }

/**
 * (Kotlin-specific)
 * Maps the Dataset to only retain the "keys" or [Pair.first] values.
 */


@ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> @ Deprecated ( "<STR_LIT:UseU+0020ScalaU+0020tuplesU+0020instead.>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> inline fun < reified T1 , T2 > Dataset < Arity2 < T1 , T2 > > . takeKeys ( ) : Dataset < T1 >

= map { it . _1 }

/**
 * (Kotlin-specific)
 * Maps the Dataset to only retain the "keys" or [Arity2._1] values.
 */


@ JvmName ( "<STR_LIT>" ) <EOL> inline fun < T1 , reified T2 > Dataset < Tuple2 < T1 , T2 > > . takeValues ( ) : Dataset < T2 >

= map { it . _2 ( ) }

/**
 * (Kotlin-specific)
 * Maps the Dataset to only retain the "values" or [Tuple2._2] values.
 */


inline fun < T1 , reified T2 > Dataset < Pair < T1 , T2 > > . takeValues ( ) : Dataset < T2 >

= map { it . second }

/**
 * (Kotlin-specific)
 * Maps the Dataset to only retain the "values" or [Pair.second] values.
 */


@ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> @ Deprecated ( "<STR_LIT:UseU+0020ScalaU+0020tuplesU+0020instead.>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> inline fun < T1 , reified T2 > Dataset < Arity2 < T1 , T2 > > . takeValues ( ) : Dataset < T2 >

= map { it . _2 }

/**
 * (Kotlin-specific)
 * Maps the Dataset to only retain the "values" or [Arity2._2] values.
 */


@ Deprecated ( message = "<STR_LIT>" , replaceWith = ReplaceWith ( "<STR_LIT>" ) , level = DeprecationLevel . ERROR , ) <EOL> inline fun < T , reified R > Dataset < T > . downcast ( ) : Dataset < R >

= `as` ( encoder < R > ( ) )

/** DEPRECATED: Use [as] or [to] for this. */


inline fun < reified R > Dataset < * > . `as` ( ) : Dataset < R >

= `as` ( encoder < R > ( ) )

/**
 * (Kotlin-specific)
 * Returns a new Dataset where each record has been mapped on to the specified type. The
 * method used to map columns depend on the type of [R]:
 * - When [R] is a class, fields for the class will be mapped to columns of the same name
 * (case sensitivity is determined by [spark.sql.caseSensitive]).
 * - When [R] is a tuple, the columns will be mapped by ordinal (i.e. the first column will
 * be assigned to `_1`).
 * - When [R] is a primitive type (i.e. [String], [Int], etc.), then the first column of the
 * `DataFrame` will be used.
 *
 * If the schema of the Dataset does not match the desired [R] type, you can use [Dataset.select]/[selectTyped]
 * along with [Dataset.alias] or [as]/[to] to rearrange or rename as required.
 *
 * Note that [as]/[to] only changes the view of the data that is passed into typed operations,
 * such as [map], and does not eagerly project away any columns that are not present in
 * the specified class.
 *
 * @see to as alias for [as]
 */


inline fun < reified R > Dataset < * > . to ( ) : Dataset < R >

= `as` ( encoder < R > ( ) )

/**
 * (Kotlin-specific)
 * Returns a new Dataset where each record has been mapped on to the specified type. The
 * method used to map columns depend on the type of [R]:
 * - When [R] is a class, fields for the class will be mapped to columns of the same name
 * (case sensitivity is determined by [spark.sql.caseSensitive]).
 * - When [R] is a tuple, the columns will be mapped by ordinal (i.e. the first column will
 * be assigned to `_1`).
 * - When [R] is a primitive type (i.e. [String], [Int], etc.), then the first column of the
 * `DataFrame` will be used.
 *
 * If the schema of the Dataset does not match the desired [R] type, you can use [Dataset.select]/[selectTyped]
 * along with [Dataset.alias] or [as]/[to] to rearrange or rename as required.
 *
 * Note that [as]/[to] only changes the view of the data that is passed into typed operations,
 * such as [map], and does not eagerly project away any columns that are not present in
 * the specified class.
 *
 * @see as as alias for [to]
 */


inline fun < reified T > Dataset < T > . forEach ( noinline func : ( T ) -> Unit ) : Unit

= foreach ( ForeachFunction ( func ) )

/**
 * (Kotlin-specific)
 * Applies a function [func] to all rows.
 */


inline fun < reified T > Dataset < T > . forEachPartition ( noinline func : ( Iterator < T > ) -> Unit ) : Unit

= <EOL> foreachPartition ( ForeachPartitionFunction ( func ) )

/**
 * (Kotlin-specific)
 * Runs [func] on each partition of this Dataset.
 */


fun < T > Dataset < T > . debugCodegen ( ) : Dataset < T >

= also { KSparkExtensions . debugCodegen ( it ) }

/**
 * It's hard to call `Dataset.debugCodegen` from kotlin, so here is utility for that
 */


fun < T > Dataset < T > . debug ( ) : Dataset < T >

= also { KSparkExtensions . debug ( it ) }

/**
 * It's hard to call `Dataset.debug` from kotlin, so here is utility for that
 */


inline fun < reified L , reified R : Any ? > Dataset < L > . leftJoin ( right : Dataset < R > , col : Column ) : Dataset < Tuple2 < L , R ? > >

= <EOL> joinWith ( right , col , "<STR_LIT>" )

/**
 * Alias for [Dataset.joinWith] which passes "left" argument
 * and respects the fact that in result of left join right relation is nullable
 *
 * @receiver left dataset
 * @param right right dataset
 * @param col join condition
 *
 * @return dataset of [Tuple2] where right element is forced nullable
 */


inline fun < reified L : Any ? , reified R > Dataset < L > . rightJoin ( right : Dataset < R > , col : Column ) : Dataset < Tuple2 < L ? , R > >

/**
 * Alias for [Dataset.joinWith] which passes "right" argument
 * and respects the fact that in result of right join left relation is nullable
 *
 * @receiver left dataset
 * @param right right dataset
 * @param col join condition
 *
 * @return dataset of [Tuple2] where left element is forced nullable
 */


inline fun < reified L , reified R > Dataset < L > . innerJoin ( right : Dataset < R > , col : Column ) : Dataset < Tuple2 < L , R > >

/**
 * Alias for [Dataset.joinWith] which passes "inner" argument
 *
 * @receiver left dataset
 * @param right right dataset
 * @param col join condition
 *
 * @return resulting dataset of [Tuple2]
 */


inline fun < reified L : Any ? , reified R : Any ? > Dataset < L > . fullJoin ( right : Dataset < R > , col : Column , ) : Dataset < Tuple2 < L ? , R ? > >

= joinWith ( right , col , "<STR_LIT>" )

/**
 * Alias for [Dataset.joinWith] which passes "full" argument
 * and respects the fact that in result of join any element of resulting tuple is nullable
 *
 * @receiver left dataset
 * @param right right dataset
 * @param col join condition
 *
 * @return dataset of [Tuple2] where both elements are forced nullable
 */


inline fun < reified T > Dataset < T > . sort ( columns : ( Dataset < T > ) -> Array < Column > ) : Dataset < T >

= sort ( * columns ( this ) )

/**
 * Alias for [Dataset.sort] which forces user to provide sorted columns from the source dataset
 *
 * @receiver source [Dataset]
 * @param columns producer of sort columns
 * @return sorted [Dataset]
 */


@ JvmName ( "<STR_LIT>" ) <EOL> fun < T1 , T2 > Dataset < Tuple2 < T1 , T2 > > . sortByKey ( ) : Dataset < Tuple2 < T1 , T2 > >

= sort ( "<STR_LIT>" )

/** Returns a dataset sorted by the first (`_1`) value of each [Tuple2] inside. */


@ JvmName ( "<STR_LIT>" ) <EOL> fun < T1 , T2 > Dataset < Tuple2 < T1 , T2 > > . sortByValue ( ) : Dataset < Tuple2 < T1 , T2 > >

= sort ( "<STR_LIT>" )

/** Returns a dataset sorted by the second (`_2`) value of each [Tuple2] inside. */


@ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> @ Deprecated ( "<STR_LIT:UseU+0020ScalaU+0020tuplesU+0020instead.>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> fun < T1 , T2 > Dataset < Arity2 < T1 , T2 > > . sortByKey ( ) : Dataset < Arity2 < T1 , T2 > >

= sort ( "<STR_LIT>" )

/** Returns a dataset sorted by the first (`_1`) value of each [Arity2] inside. */


@ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> @ Deprecated ( "<STR_LIT:UseU+0020ScalaU+0020tuplesU+0020instead.>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> fun < T1 , T2 > Dataset < Arity2 < T1 , T2 > > . sortByValue ( ) : Dataset < Arity2 < T1 , T2 > >

= sort ( "<STR_LIT>" )

/** Returns a dataset sorted by the second (`_2`) value of each [Arity2] inside. */


@ JvmName ( "<STR_LIT>" ) <EOL> fun < T1 , T2 > Dataset < Pair < T1 , T2 > > . sortByKey ( ) : Dataset < Pair < T1 , T2 > >

= sort ( "<STR_LIT:first>" )

/** Returns a dataset sorted by the first (`first`) value of each [Pair] inside. */


@ JvmName ( "<STR_LIT>" ) <EOL> fun < T1 , T2 > Dataset < Pair < T1 , T2 > > . sortByValue ( ) : Dataset < Pair < T1 , T2 > >

= sort ( "<STR_LIT:second>" )

/** Returns a dataset sorted by the second (`second`) value of each [Pair] inside. */


inline fun < reified T , R > Dataset < T > . withCached ( blockingUnpersist : Boolean = false , executeOnCached : Dataset < T > . ( ) -> R , ) : R

{ <EOL> val cached = this . cache ( ) <EOL> return cached . executeOnCached ( ) . also { cached . unpersist ( blockingUnpersist ) } <EOL> }

/**
 * This function creates block, where one can call any further computations on already cached dataset
 * Data will be unpersisted automatically at the end of computation
 *
 * it may be useful in many situations, for example, when one needs to write data to several targets
 * ```kotlin
 * ds.withCached {
 * write()
 * .also { it.orc("First destination") }
 * .also { it.avro("Second destination") }
 * }
 * ```
 *
 * @param blockingUnpersist if execution should be blocked until everything persisted will be deleted
 * @param executeOnCached Block which should be executed on cached dataset.
 * @return result of block execution for further usage. It may be anything including source or new dataset
 */


inline fun < reified T > Dataset < * > . toList ( ) : List < T >

= to < T > ( ) . collectAsList ( ) as List < T >

/**
 * Collects the dataset as list where each item has been mapped to type [T].
 */


inline fun < reified T > Dataset < * > . toArray ( ) : Array < T >

= to < T > ( ) . collect ( ) as Array < T >

/**
 * Collects the dataset as Array where each item has been mapped to type [T].
 */


fun < T > Dataset < T > . sort ( col : KProperty1 < T , * > , vararg cols : KProperty1 < T , * > ) : Dataset < T >

= <EOL> sort ( col . name , * cols . map { it . name } . toTypedArray ( ) )

/**
 * Allows to sort data class dataset on one or more of the properties of the data class.
 * ```kotlin
 * val sorted: Dataset<YourClass> = unsorted.sort(YourClass::a)
 * val sorted2: Dataset<YourClass> = unsorted.sort(YourClass::a, YourClass::b)
 * ```
 */


fun < T > Dataset < T > . showDS ( numRows : Int = <NUM_LIT:20> , truncate : Boolean = true ) : Dataset < T >

= apply { show ( numRows , truncate ) }

/**
 * Alternative to [Dataset.show] which returns source dataset.
 * Useful for debug purposes when you need to view content of a dataset as an intermediate operation
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < reified T , reified U1 > Dataset < T > . selectTyped ( c1 : TypedColumn < out Any , U1 > , ) : Dataset < U1 >

= select ( c1 as TypedColumn < T , U1 > )

/**
 * Returns a new Dataset by computing the given [Column] expressions for each element.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < reified T , reified U1 , reified U2 > Dataset < T > . selectTyped ( c1 : TypedColumn < out Any , U1 > , c2 : TypedColumn < out Any , U2 > , ) : Dataset < Tuple2 < U1 , U2 > >

= <EOL> select ( c1 as TypedColumn < T , U1 > , c2 as TypedColumn < T , U2 > , )


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < reified T , reified U1 , reified U2 , reified U3 > Dataset < T > . selectTyped ( c1 : TypedColumn < out Any , U1 > , c2 : TypedColumn < out Any , U2 > , c3 : TypedColumn < out Any , U3 > , ) : Dataset < Tuple3 < U1 , U2 , U3 > >

= <EOL> select ( c1 as TypedColumn < T , U1 > , c2 as TypedColumn < T , U2 > , c3 as TypedColumn < T , U3 > , )


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < reified T , reified U1 , reified U2 , reified U3 , reified U4 > Dataset < T > . selectTyped ( c1 : TypedColumn < out Any , U1 > , c2 : TypedColumn < out Any , U2 > , c3 : TypedColumn < out Any , U3 > , c4 : TypedColumn < out Any , U4 > , ) : Dataset < Tuple4 < U1 , U2 , U3 , U4 > >

= <EOL> select ( c1 as TypedColumn < T , U1 > , c2 as TypedColumn < T , U2 > , c3 as TypedColumn < T , U3 > , c4 as TypedColumn < T , U4 > , )


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < reified T , reified U1 , reified U2 , reified U3 , reified U4 , reified U5 > Dataset < T > . selectTyped ( c1 : TypedColumn < out Any , U1 > , c2 : TypedColumn < out Any , U2 > , c3 : TypedColumn < out Any , U3 > , c4 : TypedColumn < out Any , U4 > , c5 : TypedColumn < out Any , U5 > , ) : Dataset < Tuple5 < U1 , U2 , U3 , U4 , U5 > >

= <EOL> select ( c1 as TypedColumn < T , U1 > , c2 as TypedColumn < T , U2 > , c3 as TypedColumn < T , U3 > , c4 as TypedColumn < T , U4 > , c5 as TypedColumn < T , U5 > , )


override fun inferBinaryName ( location : JavaFileManager . Location ? , file : JavaFileObject ) : String ?

= <EOL> super . inferBinaryName ( location , unwrapObject ( file ) as JavaFileObject )

/** javac does not play nice with wrapped file objects in this method; so we unwrap */


override fun isSameFile ( a : FileObject , b : FileObject ) : Boolean

{ <EOL> return super . isSameFile ( unwrapObject ( a ) , unwrapObject ( b ) ) <EOL> }


fun renderRowTypeName ( markerName : String ) : String

/**
 * How to render a row type. Used as receiver type for column accessors for DSLs.
 * E.g.: `DataRow<Marker>`
 */


fun renderColumnsContainerTypeName ( markerName : String ) : String

/**
 * How to render a columns-container (base type for [DataFrame] and [ColumnSelectionDsl]).
 * Used as receiver type for column accessors.
 * E.g.: `ColumnsContainer<Marker>`
 */


fun BaseField . renderColumnType ( ) : Code

/**
 * How to render a column type from a [BaseField]. Used as return type for column accessors.
 * Result will be a [DataColumn] (or [ColumnGroup], which can be seen as a [DataColumn]).
 * E.g.: `DataColumn<DataFrame<Marker>>`
 */


fun BaseField . renderAccessorFieldType ( ) : Code

/**
 * How to render the field type of [BaseField]. Used as return type for column accessors for DSLs.
 * Result will be either the value type name, a [DataRow] or [DataFrame].
 */


fun BaseField . renderFieldType ( ) : Code

/**
 * How to render the field type of [BaseField]. Used as property type in generated interfaces.
 * Result will be either the value type name, the group field type name or [DataFrame].
 */