public fun progress ( message : String )

/**
 * This level is for showing significant execution steps.
 *
 * What could be considered `progress`:
 * - Documentation generation started
 * - Documentation generation has successfully finished
 *
 * What could not be considered `progress`:
 * - Processing submodules
 * - Transforming pages
 *
 * These can be shown by default if there is no other way to track progress (like Gradle's progress bar),
 * and should be at the same level or one of the debug levels otherwise.
 *
 * Dokka's `progress` maps to:
 *
 * * CLI - shown by default
 * * Gradle - `info`
 * * Maven - `debug`
 */


public fun debug ( message : String )

/**
 * This level is for logging non-user actionable messages,
 * like internal errors that cannot be fixed/worked around by users themselves or atomic generation steps.
 * These outputs could be attached to particular Dokka issues, so that the Dokka team could analyze them.
 *
 * What could be considered `debug`:
 * * Processing submodules
 * * Transforming
 *
 * What could not be considered `debug`:
 * * Cannot resolve a sample for $functionName: $fqLink
 *
 * Dokka's `debug` maps to:
 * * CLI - `debug`
 * * Gradle - `debug`
 * * Maven - `debug`
 */


public fun info ( message : String )

/**
 * This level is for logging useful messages about Dokka usage.
 *
 * What could be considered `info`:
 * * The HTML output is generated here: <PATH>
 *
 * What could not be considered `info`:
 * * Cannot resolve a sample for $functionName: $fqLink
 *
 * Dokka's `info` maps to:
 * * CLI - shown by default
 * * Gradle - `info`
 * * Maven - `info`
 */


public fun warn ( message : String )

/**
 * This level is for logging messages about issues during the documentation generation,
 * which do not stop the generation with an error but somehow affect the final result.
 * For example, if a particular source link could not be rendered.
 * It is mandatory for the messages of this level to be understandable to the user.
 *
 * What could be considered a `warn`:
 * * Cannot resolve a sample for $functionName: $fqLink. Please check the comments for the function.
 * The link should be formed according to the following rules:...
 *
 * What could not be considered a `warn`:
 * * Dokka is performing: $generationName
 *
 * Dokka's `warn` maps to:
 * * CLI - `warn`
 * * Gradle - `warn`
 * * Maven - `warn`
 */


public fun error ( message : String )

/**
 * This level is for logging error messages that describe what prevented Dokka from proceeding
 * with successful documentation generation. Likely, users will submit these error messages to Dokka's issues.
 *
 * What could be considered an `error`:
 * * Something went wrong, and the generation could not be performed. Please report it to the Dokka team.
 *
 * What could not be considered an `error`:
 * * Cannot resolve a sample for $functionName: $fqLink. Please check the comments for the function.
 * The link should be formed according to the following rules:...
 *
 * Dokka's `error` maps to:
 * * CLI - `error`
 * * Gradle - `error`
 * * Maven - `error`
 */


@ Composable <EOL> fun JetsnackSurface ( modifier : Modifier = Modifier , shape : Shape = RectangleShape , color : Color = JetsnackTheme . colors . uiBackground , contentColor : Color = JetsnackTheme . colors . textSecondary , border : BorderStroke ? = null , elevation : Dp = <NUM_LIT:0> . dp , content : @ Composable ( ) -> Unit )

{ <EOL> Box ( modifier = modifier . shadow ( elevation = elevation , shape = shape , clip = false ) . zIndex ( elevation . value ) . then ( if ( border != null ) Modifier . border ( border , shape ) else Modifier ) . background ( color = getBackgroundColorForElevation ( color , elevation ) , shape = shape ) . clip ( shape ) ) { <EOL> CompositionLocalProvider ( LocalContentColor provides contentColor , content = content ) <EOL> } <EOL> }

/**
 * An alternative to [androidx.compose.material.Surface] utilizing
 * [com.example.jetsnack.ui.theme.JetsnackColors]
 */


private fun Color . withElevation ( elevation : Dp ) : Color

{ <EOL> val foreground = calculateForeground ( elevation ) <EOL> return foreground . compositeOver ( this ) <EOL> }

/**
 * Applies a [Color.White] overlay to this color based on the [elevation]. This increases visibility
 * of elevation for surfaces in a dark theme.
 *
 * TODO: Remove when public https://issuetracker.google.com/155181601
 */


private fun calculateForeground ( elevation : Dp ) : Color

{ <EOL> val alpha = ( ( <NUM_LIT> * ln ( elevation . value + <NUM_LIT:1> ) ) + <NUM_LIT> ) / <NUM_LIT> <EOL> return Color . White . copy ( alpha = alpha ) <EOL> }

/**
 * @return the alpha-modified [Color.White] to overlay on top of the surface color to produce
 * the resultant color.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > Iterable ( crossinline iterator : ( ) -> Iterator < T > ) : Iterable < T >

= object : Iterable < T > { <EOL> override fun iterator ( ) : Iterator < T > = iterator ( ) <EOL> }

/**
 * Given an [iterator] function constructs an [Iterable] instance that returns values through the [Iterator]
 * provided by that function.
 * @sample samples.collections.Iterables.Building.iterable
 */


@ PublishedApi <EOL> internal fun < T > Iterable < T > . collectionSizeOrNull ( ) : Int ?

= if ( this is Collection < * > ) this . size else null

/**
 * Returns the size of this iterable if it is known, or `null` otherwise.
 */


@ PublishedApi <EOL> internal fun < T > Iterable < T > . collectionSizeOrDefault ( default : Int ) : Int

= if ( this is Collection < * > ) this . size else default

/**
 * Returns the size of this iterable if it is known, or the specified [default] value otherwise.
 */


public fun < T > Iterable < Iterable < T > > . flatten ( ) : List < T >

{ <EOL> val result = ArrayList < T > ( ) <EOL> for ( element in this ) { <EOL> result . addAll ( element ) <EOL> } <EOL> return result <EOL> }

/**
 * Returns a single list of all elements from all collections in the given collection.
 * @sample samples.collections.Iterables.Operations.flattenIterable
 */


public fun < T , R > Iterable < Pair < T , R > > . unzip ( ) : Pair < List < T > , List < R > >

{ <EOL> val expectedSize = collectionSizeOrDefault ( <NUM_LIT:10> ) <EOL> val listT = ArrayList < T > ( expectedSize ) <EOL> val listR = ArrayList < R > ( expectedSize ) <EOL> for ( pair in this ) { <EOL> listT . add ( pair . first ) <EOL> listR . add ( pair . second ) <EOL> } <EOL> return listT to listR <EOL> }

/**
 * Returns a pair of lists, where
 * *first* list is built from the first values of each pair from this collection,
 * *second* list is built from the second values of each pair from this collection.
 * @sample samples.collections.Iterables.Operations.unzipIterable
 */


fun compilerOptions ( configure : CO . ( ) -> Unit )

{ <EOL> configure ( compilerOptions ) <EOL> }

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


fun compilerOptions ( configure : Action < in CO > )

{ <EOL> configure . execute ( compilerOptions ) <EOL> }


public fun PsiElement . canBeAnalysed ( ) : Boolean

= <EOL> withValidityAssertion { analysisSession . analysisScopeProvider . canBeAnalysed ( this ) }

/**
 * Checks if [PsiElement] is inside analysis scope.
 * That means [org.jetbrains.kotlin.analysis.api.symbols.KtSymbol] can be built by this [PsiElement]
 *
 * @see analysisScope
 */


{ <EOL> val b = JvmModuleProtoBuf . Module . newBuilder ( ) <EOL> kmModule . packageParts . forEach { ( fqName , packageParts ) -> <EOL> PackageParts ( fqName ) . apply { <EOL> for ( fileFacade in packageParts . fileFacades ) { <EOL> addPart ( fileFacade , null ) <EOL> } <EOL> for ( ( multiFileClassPart , multiFileFacade ) in packageParts . multiFileClassParts ) { <EOL> addPart ( multiFileClassPart , multiFileFacade ) <EOL> } <EOL> addTo ( b ) <EOL> } <EOL> } <EOL> return b . build ( ) . serializeToByteArray ( CompilerMetadataVersion ( version . toIntArray ( ) , false ) , <NUM_LIT:0> ) <EOL> }

/**
 * Encodes and writes this metadata of the Kotlin module file.
 *
 * This method encodes all available data, including [version].
 *
 * @throws IllegalArgumentException if [kmModule] is not correct and cannot be written or if [version] is not supported for writing.
 */


@ JvmStatic <EOL> @ UnstableMetadataApi <EOL> public fun read ( bytes : ByteArray ) : KotlinModuleMetadata

{ <EOL> return wrapIntoMetadataExceptionWhenNeeded { <EOL> val result = ModuleMapping . loadModuleMapping ( bytes , "<STR_LIT>" , skipMetadataVersionCheck = false , isJvmPackageNameSupported = true ) { throwIfNotCompatible ( it , lenient = false ) } <EOL> when ( result ) { <EOL> ModuleMapping . EMPTY , ModuleMapping . CORRUPTED -> <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> val module = readModuleMetadataImpl ( result ) <EOL> KotlinModuleMetadata ( module , JvmMetadataVersion ( result . version . toArray ( ) ) ) <EOL> } <EOL> }

/**
 * Parses the given byte array with the .kotlin_module file content and returns the [KotlinModuleMetadata] instance,
 * or `null` if this byte array encodes a module with an unsupported metadata version.
 *
 * @throws IllegalArgumentException if an error happened while parsing the given byte array,
 * which means that it is either not the content of a `.kotlin_module` file, or it has been corrupted.
 */


fun TestAnalysisContext . singleSourceSet ( ) : DokkaConfiguration . DokkaSourceSet

{ <EOL> return this . configuration . sourceSets . single ( ) <EOL> }

/**
 * @return the only existing source set or an exception
 */


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

= java . util . Collections . singletonMap ( pair . first , pair . second )

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


public inline fun < K , V > ConcurrentMap < K , V > . getOrPut ( key : K , defaultValue : ( ) -> V ) : V

{ <EOL> return this . get ( key ) <EOL> ? : defaultValue ( ) . let { default -> this . putIfAbsent ( key , default ) ? : default } <EOL> }

/**
 * Concurrent getOrPut, that is safe for concurrent maps.
 *
 * Returns the value for the given [key]. If the key is not found in the map, calls the [defaultValue] function,
 * puts its result into the map under the given key and returns it.
 *
 * This method guarantees not to put the value into the map if the key is already there,
 * but the [defaultValue] function may be invoked even if the key is already in the map.
 */


public fun < K : Comparable < K > , V > Map < out K , V > . toSortedMap ( ) : SortedMap < K , V >

= TreeMap ( this )

/**
 * Converts this [Map] to a [SortedMap]. The resulting [SortedMap] determines the equality and order of keys according to their natural sorting order.
 *
 * Note that if the natural sorting order of keys considers any two keys of this map equal
 * (this could happen if the equality of keys according to [Comparable.compareTo] is inconsistent with the equality according to [Any.equals]),
 * only the value associated with the last of them gets into the resulting map.
 *
 * @sample samples.collections.Maps.Transformations.mapToSortedMap
 */


public fun < K , V > Map < out K , V > . toSortedMap ( comparator : Comparator < in K > ) : SortedMap < K , V >

= <EOL> TreeMap < K , V > ( comparator ) . apply { putAll ( this @ toSortedMap ) }

/**
 * Converts this [Map] to a [SortedMap]. The resulting [SortedMap] determines the equality and order of keys according to the sorting order provided by the given [comparator].
 *
 * Note that if the `comparator` considers any two keys of this map equal, only the value associated with the last of them gets into the resulting map.
 *
 * @sample samples.collections.Maps.Transformations.mapToSortedMapWithComparator
 */


public fun < K : Comparable < K > , V > sortedMapOf ( vararg pairs : Pair < K , V > ) : SortedMap < K , V >

= <EOL> TreeMap < K , V > ( ) . apply { putAll ( pairs ) }

/**
 * Returns a new [SortedMap] with the specified contents, given as a list of pairs
 * where the first value is the key and the second is the value.
 *
 * The resulting [SortedMap] determines the equality and order of keys according to their natural sorting order.
 *
 * @sample samples.collections.Maps.Instantiation.sortedMapFromPairs
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public fun < K , V > sortedMapOf ( comparator : Comparator < in K > , vararg pairs : Pair < K , V > ) : SortedMap < K , V >

= <EOL> TreeMap < K , V > ( comparator ) . apply { putAll ( pairs ) }

/**
 * Returns a new [SortedMap] with the specified contents, given as a list of pairs
 * where the first value is the key and the second is the value.
 *
 * The resulting [SortedMap] determines the equality and order of keys according to the sorting order provided by the given [comparator].
 *
 * @sample samples.collections.Maps.Instantiation.sortedMapWithComparatorFromPairs
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun Map < String , String > . toProperties ( ) : Properties

= <EOL> Properties ( ) . apply { putAll ( this @ toProperties ) }

/**
 * Converts this [Map] to a [Properties] object.
 *
 * @sample samples.collections.Maps.Transformations.mapToProperties
 */


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

= when { <EOL> expectedSize < <NUM_LIT:0> -> expectedSize <EOL> expectedSize < <NUM_LIT:3> -> expectedSize + <NUM_LIT:1> <EOL> expectedSize < INT_MAX_POWER_OF_TWO -> ( ( expectedSize / <NUM_LIT> ) + <NUM_LIT> ) . toInt ( ) <EOL> else -> Int . MAX_VALUE <EOL> }

/**
 * Calculate the initial capacity of a map, based on Guava's
 * [com.google.common.collect.Maps.capacity](https://github.com/google/guava/blob/v28.2/guava/src/com/google/common/collect/Maps.java#L325)
 * approach.
 */


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

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

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


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

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

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


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

{ <EOL> return addPositionalMapping < Any ? > ( SLOPE , column , null ) <EOL> }

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


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

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

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


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

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

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


{ <EOL> val modelHub = ONNXModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val model = ONNXModels . PoseDetection . MoveNetSinglePoseLighting . pretrainedModel ( modelHub ) <EOL> model . printSummary ( ) <EOL> model . use { poseDetectionModel -> <EOL> val result = mutableMapOf < BufferedImage , DetectedPose > ( ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:3> ) { <EOL> val file = getFileFromResource ( "<STR_LIT>" ) <EOL> val image = ImageConverter . toBufferedImage ( file ) <EOL> val detectedPose = poseDetectionModel . detectPose ( image ) <EOL> detectedPose . landmarks . forEach { <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> detectedPose . edges . forEach { <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> result [ image ] = detectedPose <EOL> } <EOL> val panel = JPanel ( FlowLayout ( FlowLayout . CENTER , <NUM_LIT:0> , <NUM_LIT:0> ) ) <EOL> val height = <NUM_LIT> <EOL> for ( ( image , detectedPose ) in result ) { <EOL> val displayedImage = pipeline < BufferedImage > ( ) <EOL> . resize { outputWidth = ( height * image . width ) / image . height ; outputHeight = height } <EOL> . apply ( image ) <EOL> panel . add ( createDetectedPosePanel ( displayedImage , detectedPose ) ) <EOL> } <EOL> showFrame ( "<STR_LIT>" , panel ) <EOL> } <EOL> }

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


= poseDetectionMoveNetLightAPI ( )


private fun FunctionDescriptor . getObjCMethodInfo ( onlyExternal : Boolean ) : ObjCMethodInfo ?

{ <EOL> if ( this . kind . isReal ) { <EOL> this . decodeObjCMethodAnnotation ( ) ? . let { return it } <EOL> if ( onlyExternal ) { <EOL> return null <EOL> } <EOL> } <EOL> return overriddenDescriptors . firstNotNullOfOrNull { it . getObjCMethodInfo ( onlyExternal ) } <EOL> }

/**
 * @param onlyExternal indicates whether to accept overriding methods from Kotlin classes
 */


private fun IrSimpleFunction . getObjCMethodInfo ( onlyExternal : Boolean ) : ObjCMethodInfo ?

{ <EOL> if ( this . isFakeOverrideInProgressOfBuilding ( ) ) { <EOL> decodeObjCMethodAnnotation ( ) ? . let { return it } <EOL> } <EOL> if ( this . isReal ) { <EOL> this . decodeObjCMethodAnnotation ( ) ? . let { return it } <EOL> if ( onlyExternal ) { <EOL> return null <EOL> } <EOL> } <EOL> return overriddenSymbols . firstNotNullOfOrNull { <EOL> assert ( it . owner != this ) { "<STR_LIT>" } <EOL> it . owner . getObjCMethodInfo ( onlyExternal ) <EOL> } <EOL> }


= bytes [ position ++ ]


= <EOL> readByte ( ) . toUByte ( )


= <EOL> ( bytes [ position ] . toInt ( ) and <NUM_LIT> shl <NUM_LIT> ) or <EOL> ( bytes [ position + <NUM_LIT:1> ] . toInt ( ) and <NUM_LIT> shl <NUM_LIT:16> ) or <EOL> ( bytes [ position + <NUM_LIT:2> ] . toInt ( ) and <NUM_LIT> shl <NUM_LIT:8> ) or <EOL> ( bytes [ position + <NUM_LIT:3> ] . toInt ( ) and <NUM_LIT> ) . also { position += <NUM_LIT:4> }

/**
 * Reads a big-endian (network byte order) 32-bit integer.
 */


= <EOL> ( bytes [ position ] . toLong ( ) and <NUM_LIT> shl <NUM_LIT> ) or <EOL> ( bytes [ position + <NUM_LIT:1> ] . toLong ( ) and <NUM_LIT> shl <NUM_LIT> ) or <EOL> ( bytes [ position + <NUM_LIT:2> ] . toLong ( ) and <NUM_LIT> shl <NUM_LIT> ) or <EOL> ( bytes [ position + <NUM_LIT:3> ] . toLong ( ) and <NUM_LIT> shl <NUM_LIT> ) or <EOL> ( bytes [ position + <NUM_LIT:4> ] . toLong ( ) and <NUM_LIT> shl <NUM_LIT> ) or <EOL> ( bytes [ position + <NUM_LIT:5> ] . toLong ( ) and <NUM_LIT> shl <NUM_LIT:16> ) or <EOL> ( bytes [ position + <NUM_LIT:6> ] . toLong ( ) and <NUM_LIT> shl <NUM_LIT:8> ) or <EOL> ( bytes [ position + <NUM_LIT:7> ] . toLong ( ) and <NUM_LIT> ) . also { position += <NUM_LIT:8> }

/**
 * Reads a big-endian (network byte order) 64-bit integer.
 */


= PlotSvgExport . buildSvgImageFromRawSpecs ( toLetsPlot ( ) . toSpec ( ) )

/**
 * Exports the plot to SVG format.
 *
 * @receiver [Plot] - the plot to export.
 *
 * @return A [String] in SVG format representing the exported plot.
 */


public fun PlotGrid . toSVG ( ) : String

= PlotSvgExport . buildSvgImageFromRawSpecs ( wrap ( ) . toSpec ( ) )

/**
 * Exports the plot grid to SVG format.
 *
 * @receiver [PlotGrid] - the plot grid to export.
 *
 * @return A [String] in SVG format representing the exported plot.
 */


public fun PlotBunch . toSVG ( ) : String

/**
 * Exports the plot bunch to SVG format.
 *
 * @receiver [PlotBunch] - the plot bunch to export.
 *
 * @return A [String] in SVG format representing the exported plot.
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun CharSequence . elementAt ( index : Int ) : Char

{ <EOL> return get ( index ) <EOL> }

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


= <EOL> currentChar == <NUM_LIT:0> && lookAhead == <NUM_LIT:0> && index >= pattern . size && ! isSpecial

/** Checks if there are any characters in the pattern. */


= <EOL> ! isEmpty ( ) && ! isSpecial && isLetter ( currentChar )

/** Return true if the current character is letter, false otherwise .*/


= currentChar in <NUM_LIT> .. <NUM_LIT>

/** Check if the current char is high/low surrogate. */


{ <EOL> this . flags = flags <EOL> lookAhead = currentChar <EOL> lookAheadSpecialToken = curSpecialToken <EOL> index = curTokenIndex + <NUM_LIT:1> <EOL> lookAheadTokenIndex = curTokenIndex <EOL> movePointer ( ) <EOL> }

/**
 * Restores flags for Lexer
 * @param flags
 */


{ <EOL> movePointer ( ) <EOL> return lookBack <EOL> }

/** Returns current character and moves string index to the next one. */


{ <EOL> val res = curSpecialToken <EOL> movePointer ( ) <EOL> return res <EOL> }

/** Returns current special token and moves string index to the next one */


{ <EOL> lookAhead = currentChar <EOL> lookAheadSpecialToken = curSpecialToken <EOL> index = lookAheadTokenIndex <EOL> lookAheadTokenIndex = curTokenIndex <EOL> movePointer ( ) <EOL> }

/**
 * Reread current character. May be required if a previous token changes mode
 * to one with different character interpretation.
 */


{ <EOL> prevNonWhitespaceIndex = index <EOL> index ++ <EOL> if ( mode != Mode . ESCAPE && flags and Pattern . COMMENTS != <NUM_LIT:0> ) { <EOL> skipComments ( ) <EOL> } <EOL> return prevNonWhitespaceIndex <EOL> }

/**
 * Returns the next character index to read and moves pointer to the next one.
 * If comments flag is on this method will skip comments and whitespaces.
 *
 * The following actions are equivalent if comments flag is off:
 * currentChar = pattern[index++] == currentChar = pattern[nextIndex]
 */


{ <EOL> val length = pattern . size - <NUM_LIT:2> <EOL> do { <EOL> while ( index < length && pattern [ index ] . isWhitespace ( ) ) { <EOL> index ++ <EOL> } <EOL> if ( index < length && pattern [ index ] == '<CHAR_LIT>' ) { <EOL> index ++ <EOL> while ( index < length && ! pattern [ index ] . isLineSeparator ( ) ) { <EOL> index ++ <EOL> } <EOL> } else { <EOL> return index <EOL> } <EOL> } while ( true ) <EOL> }


@ OptIn ( ExperimentalNativeApi :: class ) <EOL> private fun nextCodePoint ( ) : Int

{ <EOL> val high = pattern [ nextIndex ( ) ] <EOL> if ( high . isHighSurrogate ( ) ) { <EOL> val lowExpectedIndex = prevNonWhitespaceIndex + <NUM_LIT:1> <EOL> if ( lowExpectedIndex < pattern . size ) { <EOL> val low = pattern [ lowExpectedIndex ] <EOL> if ( low . isLowSurrogate ( ) ) { <EOL> nextIndex ( ) <EOL> return Char . toCodePoint ( high , low ) <EOL> } <EOL> } <EOL> } <EOL> return high . toInt ( ) <EOL> }

/**
 * Returns the next code point in the pattern string.
 */


{ <EOL> lookBack = currentChar <EOL> currentChar = lookAhead <EOL> curSpecialToken = lookAheadSpecialToken <EOL> curTokenIndex = lookAheadTokenIndex <EOL> lookAheadTokenIndex = index <EOL> var reread : Boolean <EOL> do { <EOL> lookAhead = if ( index < pattern . size ) nextCodePoint ( ) else <NUM_LIT:0> <EOL> lookAheadSpecialToken = null <EOL> if ( mode == Mode . ESCAPE ) { <EOL> processInEscapeMode ( ) <EOL> } <EOL> reread = when ( mode ) { <EOL> Mode . PATTERN -> processInPatternMode ( ) <EOL> Mode . RANGE -> processInRangeMode ( ) <EOL> else -> false <EOL> } <EOL> } while ( reread ) <EOL> }

/**
 * Moves pointer one position right. Saves the current character to [lookBack],
 * [lookAhead] to the current one and finally read one more to [lookAhead].
 */


private fun processInEscapeMode ( ) : Boolean

{ <EOL> if ( lookAhead == '<CHAR_LIT:\\>' . toInt ( ) ) { <EOL> val lookAheadChar : Char = if ( index < pattern . size ) pattern [ nextIndex ( ) ] else '<CHAR_LIT>' <EOL> lookAhead = lookAheadChar . toInt ( ) <EOL> if ( lookAheadChar == '<CHAR_LIT>' ) { <EOL> mode = savedMode <EOL> index = prevNonWhitespaceIndex <EOL> nextIndex ( ) <EOL> lookAhead = if ( index <= pattern . size - <NUM_LIT:2> ) nextCodePoint ( ) else <NUM_LIT:0> <EOL> } else { <EOL> lookAhead = '<CHAR_LIT:\\>' . toInt ( ) <EOL> index = prevNonWhitespaceIndex <EOL> } <EOL> } <EOL> return false <EOL> }

/**
 * Processing an escaped sequence like "\Q foo \E". Just skip a character if it is not \E.
 * Returns whether we need to reread the character or not
 */


private fun processInPatternMode ( ) : Boolean

{ <EOL> if ( lookAhead . isSurrogatePair ( ) ) { <EOL> return false <EOL> } <EOL> val lookAheadChar = lookAhead . toChar ( ) <EOL> if ( lookAheadChar == '<CHAR_LIT:\\>' ) { <EOL> return processEscapedChar ( ) <EOL> } <EOL> when ( lookAheadChar ) { <EOL> '<CHAR_LIT>' , '<CHAR_LIT:*>' , '<CHAR_LIT>' -> { <EOL> val mode = if ( index < pattern . size ) pattern [ index ] else '<CHAR_LIT:*>' <EOL> when ( mode ) { <EOL> '<CHAR_LIT>' -> { lookAhead = lookAhead or Lexer . QMOD_POSSESSIVE ; nextIndex ( ) } <EOL> '<CHAR_LIT>' -> { lookAhead = lookAhead or Lexer . QMOD_RELUCTANT ; nextIndex ( ) } <EOL> else -> lookAhead = lookAhead or Lexer . QMOD_GREEDY <EOL> } <EOL> } <EOL> '<CHAR_LIT>' -> lookAheadSpecialToken = processQuantifier ( ) <EOL> '<CHAR_LIT:$>' -> lookAhead = CHAR_DOLLAR <EOL> '<CHAR_LIT>' -> { <EOL> if ( pattern [ index ] != '<CHAR_LIT>' ) { <EOL> lookAhead = CHAR_LEFT_PARENTHESIS <EOL> } else { <EOL> nextIndex ( ) <EOL> var char = pattern [ prevNonWhitespaceIndex + <NUM_LIT:1> ] <EOL> when ( char ) { <EOL> '<CHAR_LIT>' -> { <EOL> lookAhead = CHAR_NEG_LOOKAHEAD ; nextIndex ( ) <EOL> } <EOL> '<CHAR_LIT>' -> { <EOL> lookAhead = CHAR_POS_LOOKAHEAD ; nextIndex ( ) <EOL> } <EOL> '<CHAR_LIT>' -> { <EOL> lookAhead = CHAR_ATOMIC_GROUP ; nextIndex ( ) <EOL> } <EOL> '<CHAR_LIT>' -> { <EOL> nextIndex ( ) <EOL> char = pattern [ index ] <EOL> when ( char ) { <EOL> '<CHAR_LIT>' -> { <EOL> lookAhead = CHAR_NEG_LOOKBEHIND ; nextIndex ( ) <EOL> } <EOL> '<CHAR_LIT>' -> { <EOL> lookAhead = CHAR_POS_LOOKBEHIND ; nextIndex ( ) <EOL> } <EOL> else -> { <EOL> val name = readGroupName ( ) <EOL> lookAhead = CHAR_NAMED_GROUP <EOL> lookAheadSpecialToken = NamedGroup ( name ) <EOL> } <EOL> } <EOL> } <EOL> else -> { <EOL> lookAhead = readFlags ( ) <EOL> if ( lookAhead >= <NUM_LIT> ) { <EOL> lookAhead = lookAhead and <NUM_LIT> <EOL> flags = lookAhead <EOL> lookAhead = lookAhead shl <NUM_LIT:16> <EOL> lookAhead = CHAR_FLAGS or lookAhead <EOL> } else { <EOL> flags = lookAhead <EOL> lookAhead = lookAhead shl <NUM_LIT:16> <EOL> lookAhead = CHAR_NONCAP_GROUP or lookAhead <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_RIGHT_PARENTHESIS <EOL> '<CHAR_LIT>' -> { lookAhead = CHAR_LEFT_SQUARE_BRACKET ; mode = Mode . RANGE } <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_CARET <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_VERTICAL_BAR <EOL> '<CHAR_LIT:.>' -> lookAhead = CHAR_DOT <EOL> } <EOL> return false <EOL> }

/** Processes a next character in [Mode.PATTERN] mode. Returns whether we need to reread the character or not */


private fun processInRangeMode ( ) : Boolean

{ <EOL> if ( lookAhead . isSurrogatePair ( ) ) { <EOL> return false <EOL> } <EOL> val lookAheadChar = lookAhead . toChar ( ) <EOL> when ( lookAheadChar ) { <EOL> '<CHAR_LIT:\\>' -> return processEscapedChar ( ) <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_LEFT_SQUARE_BRACKET <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_RIGHT_SQUARE_BRACKET <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_CARET <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_AMPERSAND <EOL> '<CHAR_LIT:->' -> lookAhead = CHAR_HYPHEN <EOL> } <EOL> return false <EOL> }

/** Processes a character inside a range. Returns whether we need to reread the character or not */


private fun processEscapedChar ( ) : Boolean

{ <EOL> val escapedCharIndex = prevNonWhitespaceIndex + <NUM_LIT:1> <EOL> if ( escapedCharIndex >= pattern . size - <NUM_LIT:2> ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> index = escapedCharIndex <EOL> val lookAheadChar = pattern [ nextIndex ( ) ] <EOL> lookAhead = lookAheadChar . toInt ( ) <EOL> when ( lookAheadChar ) { <EOL> '<CHAR_LIT>' , '<CHAR_LIT>' -> { <EOL> val cs = parseCharClassName ( ) <EOL> val negative = lookAheadChar == '<CHAR_LIT>' <EOL> lookAheadSpecialToken = AbstractCharClass . getPredefinedClass ( cs , negative ) <EOL> lookAhead = <NUM_LIT:0> <EOL> } <EOL> '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT:d>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' -> { <EOL> lookAheadSpecialToken = AbstractCharClass . getPredefinedClass ( pattern . concatToString ( prevNonWhitespaceIndex , prevNonWhitespaceIndex + <NUM_LIT:1> ) , false ) <EOL> lookAhead = <NUM_LIT:0> <EOL> } <EOL> '<CHAR_LIT>' -> { <EOL> savedMode = mode <EOL> mode = Mode . ESCAPE <EOL> index = escapedCharIndex <EOL> nextIndex ( ) <EOL> return true <EOL> } <EOL> '<CHAR_LIT>' -> lookAhead = '<CHAR_LIT>' . toInt ( ) <EOL> '<CHAR_LIT>' -> lookAhead = '<CHAR_LIT:\n>' . toInt ( ) <EOL> '<CHAR_LIT>' -> lookAhead = '<CHAR_LIT:\r>' . toInt ( ) <EOL> '<CHAR_LIT:f>' -> lookAhead = '<CHAR_LIT>' . toInt ( ) <EOL> '<CHAR_LIT:a>' -> lookAhead = '<CHAR_LIT>' . toInt ( ) <EOL> '<CHAR_LIT:e>' -> lookAhead = '<CHAR_LIT>' . toInt ( ) <EOL> '<CHAR_LIT:1>' , '<CHAR_LIT:2>' , '<CHAR_LIT:3>' , '<CHAR_LIT:4>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT:9>' -> { <EOL> if ( mode == Mode . PATTERN ) { <EOL> lookAhead = <NUM_LIT> . toInt ( ) or lookAhead <EOL> } <EOL> } <EOL> '<CHAR_LIT>' -> { <EOL> if ( pattern [ nextIndex ( ) ] != '<CHAR_LIT>' ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> val name = readGroupName ( ) <EOL> lookAhead = CHAR_NAMED_GROUP_REF <EOL> lookAheadSpecialToken = NamedGroup ( name ) <EOL> } <EOL> '<CHAR_LIT:0>' -> lookAhead = readOctals ( ) <EOL> '<CHAR_LIT:x>' -> lookAhead = readHex ( "<STR_LIT>" , <NUM_LIT:2> ) <EOL> '<CHAR_LIT>' -> lookAhead = readHex ( "<STR_LIT>" , <NUM_LIT:4> ) <EOL> '<CHAR_LIT:b>' -> lookAhead = CHAR_WORD_BOUND <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_NONWORD_BOUND <EOL> '<CHAR_LIT:A>' -> lookAhead = CHAR_START_OF_INPUT <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_PREVIOUS_MATCH <EOL> '<CHAR_LIT:Z>' -> lookAhead = CHAR_END_OF_LINE <EOL> '<CHAR_LIT:z>' -> lookAhead = CHAR_END_OF_INPUT <EOL> '<CHAR_LIT>' -> lookAhead = CHAR_LINEBREAK <EOL> '<CHAR_LIT:c>' -> { <EOL> if ( index < pattern . size - <NUM_LIT:2> ) { <EOL> lookAhead = pattern [ nextIndex ( ) ] . toInt ( ) and <NUM_LIT> <EOL> } else { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> } <EOL> '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT:l>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' -> <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> return false <EOL> }

/** Processes an escaped (\x) character in any mode. Returns whether we need to reread the character or not */


private fun processQuantifier ( ) : Quantifier

{ <EOL> @ OptIn ( ExperimentalNativeApi :: class ) <EOL> assert ( lookAhead == '<CHAR_LIT>' . toInt ( ) ) <EOL> val sb = StringBuilder ( <NUM_LIT:4> ) <EOL> var min = - <NUM_LIT:1> <EOL> var max = - <NUM_LIT:1> <EOL> var char : Char = if ( index < pattern . size ) { <EOL> pattern [ nextIndex ( ) ] <EOL> } else { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> while ( char != '<CHAR_LIT>' ) { <EOL> if ( char == '<CHAR_LIT:U+002C>' && min < <NUM_LIT:0> ) { <EOL> try { <EOL> val minParsed = sb . toString ( ) . toInt ( ) <EOL> min = if ( minParsed >= <NUM_LIT:0> ) minParsed else throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> sb . setLength ( <NUM_LIT:0> ) <EOL> } catch ( nfe : NumberFormatException ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> } else { <EOL> sb . append ( char ) <EOL> } <EOL> char = if ( index < pattern . size ) pattern [ nextIndex ( ) ] else break <EOL> } <EOL> if ( char != '<CHAR_LIT>' ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> if ( sb . isNotEmpty ( ) ) { <EOL> try { <EOL> val maxParsed = sb . toString ( ) . toInt ( ) <EOL> max = if ( maxParsed >= <NUM_LIT:0> ) maxParsed else throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> if ( min < <NUM_LIT:0> ) { <EOL> min = max <EOL> } <EOL> } catch ( nfe : NumberFormatException ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> } <EOL> if ( min < <NUM_LIT:0> || max >= <NUM_LIT:0> && max < min ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> val mod = if ( index < pattern . size ) pattern [ index ] else '<CHAR_LIT:*>' <EOL> when ( mod ) { <EOL> '<CHAR_LIT>' -> { lookAhead = Lexer . QUANT_COMP_P ; nextIndex ( ) } <EOL> '<CHAR_LIT>' -> { lookAhead = Lexer . QUANT_COMP_R ; nextIndex ( ) } <EOL> else -> lookAhead = Lexer . QUANT_COMP <EOL> } <EOL> return Quantifier ( min , max ) <EOL> }

/** Process [lookAhead] in assumption that it's quantifier. */


{ <EOL> var positive = true <EOL> var result = flags <EOL> while ( index < pattern . size ) { <EOL> val char = pattern [ index ] <EOL> when ( char ) { <EOL> '<CHAR_LIT:->' -> { <EOL> if ( ! positive ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> positive = false <EOL> } <EOL> '<CHAR_LIT:c>' -> result = if ( positive ) <EOL> result or Pattern . CANON_EQ <EOL> else <EOL> result xor Pattern . CANON_EQ and result <EOL> '<CHAR_LIT>' -> result = if ( positive ) <EOL> result or Pattern . CASE_INSENSITIVE <EOL> else <EOL> result xor Pattern . CASE_INSENSITIVE and result <EOL> '<CHAR_LIT:d>' -> result = if ( positive ) <EOL> result or Pattern . UNIX_LINES <EOL> else <EOL> result xor Pattern . UNIX_LINES and result <EOL> '<CHAR_LIT>' -> result = if ( positive ) <EOL> result or Pattern . MULTILINE <EOL> else <EOL> result xor Pattern . MULTILINE and result <EOL> '<CHAR_LIT>' -> result = if ( positive ) <EOL> result or Pattern . DOTALL <EOL> else <EOL> result xor Pattern . DOTALL and result <EOL> '<CHAR_LIT>' -> { } <EOL> '<CHAR_LIT>' -> { } <EOL> '<CHAR_LIT:x>' -> result = if ( positive ) <EOL> result or Pattern . COMMENTS <EOL> else <EOL> result xor Pattern . COMMENTS and result <EOL> '<CHAR_LIT::>' -> { <EOL> nextIndex ( ) <EOL> return result <EOL> } <EOL> '<CHAR_LIT>' -> { <EOL> nextIndex ( ) <EOL> return result or ( <NUM_LIT:1> shl <NUM_LIT:8> ) <EOL> } <EOL> else -> { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> } <EOL> nextIndex ( ) <EOL> } <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> }

/** Process expression flags given with (?idmsux-idmsux). Returns the flags processed. */


private fun parseCharClassName ( ) : String

{ <EOL> val sb = StringBuilder ( <NUM_LIT:10> ) <EOL> if ( index < pattern . size - <NUM_LIT:2> ) { <EOL> if ( pattern [ index ] != '<CHAR_LIT>' ) { <EOL> return "<STR_LIT>" <EOL> } <EOL> nextIndex ( ) <EOL> var char = pattern [ nextIndex ( ) ] <EOL> while ( index < pattern . size - <NUM_LIT:2> && char != '<CHAR_LIT>' ) { <EOL> sb . append ( char ) <EOL> char = pattern [ nextIndex ( ) ] <EOL> } <EOL> if ( char != '<CHAR_LIT>' ) throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> if ( sb . isEmpty ( ) ) throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> val res = sb . toString ( ) <EOL> return when { <EOL> res . length == <NUM_LIT:1> -> "<STR_LIT>" <EOL> res . length > <NUM_LIT:3> && ( res . startsWith ( "<STR_LIT>" ) || res . startsWith ( "<STR_LIT>" ) ) -> res . substring ( <NUM_LIT:2> ) <EOL> else -> res <EOL> } <EOL> }

/** Parse character classes names and verifies correction of the syntax */


private fun readHex ( radixName : String , max : Int ) : Int

{ <EOL> val builder = StringBuilder ( max ) <EOL> val length = pattern . size - <NUM_LIT:2> <EOL> var i = <NUM_LIT:0> <EOL> while ( i < max && index < length ) { <EOL> builder . append ( pattern [ nextIndex ( ) ] ) <EOL> i ++ <EOL> } <EOL> if ( i == max ) { <EOL> try { <EOL> return builder . toString ( ) . toInt ( <NUM_LIT:16> ) <EOL> } catch ( e : NumberFormatException ) { } <EOL> } <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> }


{ <EOL> val length = pattern . size - <NUM_LIT:2> <EOL> var result = <NUM_LIT:0> <EOL> var digit = digitOf ( pattern [ index ] , <NUM_LIT:8> ) <EOL> if ( digit == - <NUM_LIT:1> ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , patternString , curTokenIndex ) <EOL> } <EOL> val max = if ( digit > <NUM_LIT:3> ) <NUM_LIT:2> else <NUM_LIT:3> <EOL> var i = <NUM_LIT:0> <EOL> while ( i < max && index < length && digit != - <NUM_LIT:1> ) { <EOL> result *= <NUM_LIT:8> <EOL> result += digit <EOL> nextIndex ( ) <EOL> digit = digitOf ( pattern [ index ] , <NUM_LIT:8> ) <EOL> i ++ <EOL> } <EOL> return result <EOL> }


{ <EOL> return ch >= <NUM_LIT:0> <EOL> }

/** Returns true if [ch] is a plain token. */


fun getCanonicalClass ( ch : Int ) : Int

= getCanonicalClassInternal ( ch )

/** Gets canonical class for given codepoint from decomposition mappings table. */


fun isDecomposedCharBoundary ( ch : Int ) : Boolean

= getCanonicalClass ( ch ) == <NUM_LIT:0>

/** Tests Unicode codepoint if it is a boundary of decomposed Unicode codepoint. */


fun hasSingleCodepointDecomposition ( ch : Int ) : Boolean

= hasSingleCodepointDecompositionInternal ( ch )

/** Tests if given codepoint is a canonical decomposition of another codepoint. */


fun hasDecompositionNonNullCanClass ( ch : Int ) : Boolean

= <EOL> ( ch == <NUM_LIT> ) or ( ch == <NUM_LIT> ) or ( ch == <NUM_LIT> ) or ( ch == <NUM_LIT> )

/** Tests if given codepoint has canonical decomposition and given codepoint's canonical class is not 0. */


@ OptIn ( ExperimentalNativeApi :: class ) <EOL> fun normalize ( input : String ) : String

{ <EOL> val inputChars = input . toCharArray ( ) <EOL> val inputLength = inputChars . size <EOL> var inputCodePointsIndex = <NUM_LIT:0> <EOL> var decompHangulIndex = <NUM_LIT:0> <EOL> val inputCodePoints = IntArray ( inputLength ) <EOL> var resCodePoints = IntArray ( inputLength * MAX_DECOMPOSITION_LENGTH ) <EOL> var ch : Int <EOL> var decomp : IntArray ? <EOL> val decompHangul : IntArray <EOL> val result = StringBuilder ( ) <EOL> var i = <NUM_LIT:0> <EOL> while ( i < inputLength ) { <EOL> ch = input . codePointAt ( i ) <EOL> inputCodePoints [ inputCodePointsIndex ++ ] = ch <EOL> i += if ( Char . isSupplementaryCodePoint ( ch ) ) <NUM_LIT:2> else <NUM_LIT:1> <EOL> } <EOL> var resCodePointsIndex = decomposeString ( inputCodePoints , inputCodePointsIndex , resCodePoints ) <EOL> resCodePoints = Lexer . getCanonicalOrder ( resCodePoints , resCodePointsIndex ) <EOL> decompHangul = IntArray ( resCodePoints . size ) <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> for ( i in <NUM_LIT:0> .. resCodePointsIndex - <NUM_LIT:1> ) { <EOL> val curSymb = resCodePoints [ i ] <EOL> decomp = getHangulDecomposition ( curSymb ) <EOL> if ( decomp == null ) { <EOL> decompHangul [ decompHangulIndex ++ ] = curSymb <EOL> } else { <EOL> decompHangul [ decompHangulIndex ++ ] = decomp [ <NUM_LIT:0> ] <EOL> decompHangul [ decompHangulIndex ++ ] = decomp [ <NUM_LIT:1> ] <EOL> if ( decomp . size == <NUM_LIT:3> ) { <EOL> decompHangul [ decompHangulIndex ++ ] = decomp [ <NUM_LIT:2> ] <EOL> } <EOL> } <EOL> } <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> for ( i in <NUM_LIT:0> .. decompHangulIndex - <NUM_LIT:1> ) { <EOL> result . append ( Char . toChars ( decompHangul [ i ] ) ) <EOL> } <EOL> return result . toString ( ) <EOL> }


fun getCanonicalOrder ( inputInts : IntArray , length : Int ) : IntArray

{ <EOL> val inputLength = if ( length < inputInts . size ) <EOL> length <EOL> else <EOL> inputInts . size <EOL> for ( i in <NUM_LIT:1> .. inputLength - <NUM_LIT:1> ) { <EOL> var j = i - <NUM_LIT:1> <EOL> val iCanonicalClass = getCanonicalClass ( inputInts [ i ] ) <EOL> val ch : Int <EOL> if ( iCanonicalClass == <NUM_LIT:0> ) { <EOL> continue <EOL> } <EOL> while ( j > - <NUM_LIT:1> ) { <EOL> if ( getCanonicalClass ( inputInts [ j ] ) > iCanonicalClass ) { <EOL> j = j - <NUM_LIT:1> <EOL> } else { <EOL> break <EOL> } <EOL> } <EOL> ch = inputInts [ i ] <EOL> for ( k in i downTo j + <NUM_LIT:1> + <NUM_LIT:1> ) { <EOL> inputInts [ k ] = inputInts [ k - <NUM_LIT:1> ] <EOL> } <EOL> inputInts [ j + <NUM_LIT:1> ] = ch <EOL> } <EOL> return inputInts <EOL> }

/**
 * Rearrange codepoints in [inputInts] according to canonical order. Return an array with rearranged codepoints.
 */


fun getHangulDecomposition ( ch : Int ) : IntArray ?

{ <EOL> val SIndex = ch - SBase <EOL> if ( SIndex < <NUM_LIT:0> || SIndex >= SCount ) { <EOL> return null <EOL> } else { <EOL> val L = LBase + SIndex / NCount <EOL> val V = VBase + SIndex % NCount / TCount <EOL> var T = SIndex % TCount <EOL> val decomp : IntArray <EOL> if ( T == <NUM_LIT:0> ) { <EOL> decomp = intArrayOf ( L , V ) <EOL> } else { <EOL> T = TBase + T <EOL> decomp = intArrayOf ( L , V , T ) <EOL> } <EOL> return decomp <EOL> } <EOL> }

/**
 * Gets decomposition for given Hangul syllable.
 * This is an implementation of Hangul decomposition algorithm
 * according to http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf "3.12 Conjoining Jamo Behavior".
 */


@ HtmlTagMarker <EOL> inline fun RUBY . rt ( classes : String ? = null , crossinline block : RT . ( ) -> Unit = { } ) : Unit

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


@ HtmlTagMarker <EOL> inline fun RUBY . rp ( classes : String ? = null , crossinline block : RP . ( ) -> Unit = { } ) : Unit

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

/**
 * Parenthesis for ruby annotation text
 */


fun getAt ( name : String ) : NativeBinary

= getByName ( name )

/** Provide an access to binaries using the [] operator in Groovy DSL. */


operator fun get ( name : String ) : NativeBinary

= getByName ( name )

/** Provide an access to binaries using the [] operator in Kotlin DSL. */


abstract fun getByName ( name : String ) : NativeBinary

/** Returns a binary with the given [name]. Throws an exception if there is no such binary. */


abstract fun findByName ( name : String ) : NativeBinary ?

/** Returns a binary with the given [name]. Returns null if there is no such binary. */


abstract fun getExecutable ( namePrefix : String , buildType : NativeBuildType ) : Executable

/** Returns an executable with the given [namePrefix] and the given build type. Throws an exception if there is no such binary.*/


fun getExecutable ( namePrefix : String , buildType : String ) : Executable

= <EOL> getExecutable ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun getExecutable ( buildType : NativeBuildType ) : Executable

= getExecutable ( "<STR_LIT>" , buildType )

/** Returns an executable with the empty name prefix and the given build type. Throws an exception if there is no such binary.*/


fun getExecutable ( buildType : String ) : Executable


abstract fun findExecutable ( namePrefix : String , buildType : NativeBuildType ) : Executable ?

/** Returns an executable with the given [namePrefix] and the given build type. Returns null if there is no such binary. */


fun findExecutable ( namePrefix : String , buildType : String ) : Executable ?

= <EOL> findExecutable ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun findExecutable ( buildType : NativeBuildType ) : Executable ?

= findExecutable ( "<STR_LIT>" , buildType )

/** Returns an executable with the empty name prefix and the given build type. Returns null if there is no such binary. */


fun findExecutable ( buildType : String ) : Executable ?


abstract fun getStaticLib ( namePrefix : String , buildType : NativeBuildType ) : StaticLibrary

/** Returns a static library with the given [namePrefix] and the given build type. Throws an exception if there is no such binary.*/


fun getStaticLib ( namePrefix : String , buildType : String ) : StaticLibrary

= <EOL> getStaticLib ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun getStaticLib ( buildType : NativeBuildType ) : StaticLibrary

= getStaticLib ( "<STR_LIT>" , buildType )

/** Returns a static library with the empty name prefix and the given build type. Throws an exception if there is no such binary.*/


fun getStaticLib ( buildType : String ) : StaticLibrary


abstract fun findStaticLib ( namePrefix : String , buildType : NativeBuildType ) : StaticLibrary ?

/** Returns a static library with the given [namePrefix] and the given build type. Returns null if there is no such binary. */


fun findStaticLib ( namePrefix : String , buildType : String ) : StaticLibrary ?

= <EOL> findStaticLib ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun findStaticLib ( buildType : NativeBuildType ) : StaticLibrary ?

= findStaticLib ( "<STR_LIT>" , buildType )

/** Returns a static library with the empty name prefix and the given build type. Returns null if there is no such binary. */


fun findStaticLib ( buildType : String ) : StaticLibrary ?


abstract fun getSharedLib ( namePrefix : String , buildType : NativeBuildType ) : SharedLibrary

/** Returns a shared library with the given [namePrefix] and the given build type. Throws an exception if there is no such binary.*/


fun getSharedLib ( namePrefix : String , buildType : String ) : SharedLibrary

= <EOL> getSharedLib ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun getSharedLib ( buildType : NativeBuildType ) : SharedLibrary

= getSharedLib ( "<STR_LIT>" , buildType )

/** Returns a shared library with the empty name prefix and the given build type. Throws an exception if there is no such binary.*/


fun getSharedLib ( buildType : String ) : SharedLibrary


abstract fun findSharedLib ( namePrefix : String , buildType : NativeBuildType ) : SharedLibrary ?

/** Returns a shared library with the given [namePrefix] and the given build type. Returns null if there is no such binary. */


fun findSharedLib ( namePrefix : String , buildType : String ) : SharedLibrary ?

= <EOL> findSharedLib ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun findSharedLib ( buildType : NativeBuildType ) : SharedLibrary ?

= findSharedLib ( "<STR_LIT>" , buildType )

/** Returns a shared library with the empty name prefix and the given build type. Returns null if there is no such binary. */


fun findSharedLib ( buildType : String ) : SharedLibrary ?


abstract fun getFramework ( namePrefix : String , buildType : NativeBuildType ) : Framework

/** Returns an Objective-C framework with the given [namePrefix] and the given build type. Throws an exception if there is no such binary.*/


fun getFramework ( namePrefix : String , buildType : String ) : Framework

= <EOL> getFramework ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun getFramework ( buildType : NativeBuildType ) : Framework

= getFramework ( "<STR_LIT>" , buildType )

/** Returns an Objective-C framework with the empty name prefix and the given build type. Throws an exception if there is no such binary.*/


fun getFramework ( buildType : String ) : Framework


abstract fun findFramework ( namePrefix : String , buildType : NativeBuildType ) : Framework ?

/** Returns an Objective-C framework with the given [namePrefix] and the given build type. Returns null if there is no such binary. */


fun findFramework ( namePrefix : String , buildType : String ) : Framework ?

= <EOL> findFramework ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun findFramework ( buildType : NativeBuildType ) : Framework ?

= findFramework ( "<STR_LIT>" , buildType )

/** Returns an Objective-C framework with the empty name prefix and the given build type. Returns null if there is no such binary. */


fun findFramework ( buildType : String ) : Framework ?


abstract fun getTest ( namePrefix : String , buildType : NativeBuildType ) : TestExecutable

/** Returns a test executable with the given [namePrefix] and the given build type. Throws an exception if there is no such binary.*/


fun getTest ( namePrefix : String , buildType : String ) : TestExecutable

= <EOL> getTest ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun getTest ( buildType : NativeBuildType ) : TestExecutable

= getTest ( "<STR_LIT>" , buildType )

/** Returns a test executable with the empty name prefix and the given build type. Throws an exception if there is no such binary.*/


fun getTest ( buildType : String ) : TestExecutable

= getTest ( "<STR_LIT>" , buildType )


abstract fun findTest ( namePrefix : String , buildType : NativeBuildType ) : TestExecutable ?

/** Returns a test executable with the given [namePrefix] and the given build type. Returns null if there is no such binary. */


fun findTest ( namePrefix : String , buildType : String ) : TestExecutable ?

= <EOL> findTest ( namePrefix , NativeBuildType . valueOf ( buildType . toUpperCaseAsciiOnly ( ) ) )


fun findTest ( buildType : NativeBuildType ) : TestExecutable ?

= findTest ( "<STR_LIT>" , buildType )

/** Returns a test executable with the empty name prefix and the given build type. Returns null if there is no such binary. */


fun findTest ( buildType : String ) : TestExecutable ?

= findTest ( "<STR_LIT>" , buildType )


@ JvmOverloads <EOL> fun executable ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Executable . ( ) -> Unit = { } )

= createBinaries ( namePrefix , namePrefix , NativeOutputKind . EXECUTABLE , buildTypes , :: Executable , configure )

/** Creates an executable with the given [namePrefix] for each build type and configures it. */


@ JvmOverloads <EOL> fun executable ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Executable . ( ) -> Unit = { } )

= createBinaries ( "<STR_LIT>" , project . name , NativeOutputKind . EXECUTABLE , buildTypes , :: Executable , configure )

/** Creates an executable with the empty name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun executable ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < Executable > )

= executable ( namePrefix , buildTypes ) { configure . execute ( this ) }


@ JvmOverloads <EOL> fun executable ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < Executable > )

= executable ( buildTypes ) { configure . execute ( this ) }

/** Creates an executable with the default name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun staticLib ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : StaticLibrary . ( ) -> Unit = { } )

= createBinaries ( namePrefix , namePrefix , NativeOutputKind . STATIC , buildTypes , :: StaticLibrary , configure )

/** Creates a static library with the given [namePrefix] for each build type and configures it. */


@ JvmOverloads <EOL> fun staticLib ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : StaticLibrary . ( ) -> Unit = { } )

= createBinaries ( "<STR_LIT>" , project . name , NativeOutputKind . STATIC , buildTypes , :: StaticLibrary , configure )

/** Creates a static library with the empty name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun staticLib ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < StaticLibrary > )

= staticLib ( namePrefix , buildTypes ) { configure . execute ( this ) }


@ JvmOverloads <EOL> fun staticLib ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < StaticLibrary > )

= staticLib ( buildTypes ) { configure . execute ( this ) }

/** Creates a static library with the default name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun sharedLib ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : SharedLibrary . ( ) -> Unit = { } )

= createBinaries ( namePrefix , namePrefix , NativeOutputKind . DYNAMIC , buildTypes , :: SharedLibrary , configure )

/** Creates a shared library with the given [namePrefix] for each build type and configures it. */


@ JvmOverloads <EOL> fun sharedLib ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : SharedLibrary . ( ) -> Unit = { } )

= createBinaries ( "<STR_LIT>" , project . name , NativeOutputKind . DYNAMIC , buildTypes , :: SharedLibrary , configure )

/** Creates a shared library with the empty name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun sharedLib ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < SharedLibrary > )

= sharedLib ( namePrefix , buildTypes ) { configure . execute ( this ) }


@ JvmOverloads <EOL> fun sharedLib ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < SharedLibrary > )

= sharedLib ( buildTypes ) { configure . execute ( this ) }

/** Creates a shared library with the default name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun framework ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Framework . ( ) -> Unit = { } )

= createBinaries ( namePrefix , namePrefix , NativeOutputKind . FRAMEWORK , buildTypes , :: Framework , configure )

/** Creates an Objective-C framework with the given [namePrefix] for each build type and configures it. */


@ JvmOverloads <EOL> fun framework ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Framework . ( ) -> Unit = { } )

= createBinaries ( "<STR_LIT>" , project . name , NativeOutputKind . FRAMEWORK , buildTypes , :: Framework , configure )

/** Creates an Objective-C framework with the empty name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun framework ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < Framework > )

= framework ( namePrefix , buildTypes ) { configure . execute ( this ) }


@ JvmOverloads <EOL> fun framework ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < Framework > )

= framework ( buildTypes ) { configure . execute ( this ) }

/** Creates an Objective-C framework with the default name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun test ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : TestExecutable . ( ) -> Unit = { } )

= createBinaries ( namePrefix , namePrefix , NativeOutputKind . TEST , buildTypes , :: TestExecutable , configure )

/** Creates a test executable with the given [namePrefix] for each build type and configures it. */


@ JvmOverloads <EOL> fun test ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : TestExecutable . ( ) -> Unit = { } )

= createBinaries ( "<STR_LIT>" , "<STR_LIT:test>" , NativeOutputKind . TEST , buildTypes , :: TestExecutable , configure )

/** Creates a test executable with the empty name prefix for each build type and configures it. */


@ JvmOverloads <EOL> fun test ( namePrefix : String , buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < TestExecutable > )

= test ( namePrefix , buildTypes ) { configure . execute ( this ) }


@ JvmOverloads <EOL> fun test ( buildTypes : Collection < NativeBuildType > = NativeBuildType . DEFAULT_BUILD_TYPES , configure : Action < TestExecutable > )

= test ( buildTypes ) { configure . execute ( this ) }

/** Creates a test executable with the default name prefix for each build type and configures it. */


fun transformExternalFunction ( function : IrSimpleFunction ) : List < IrDeclaration > ?

{ <EOL> if ( function . valueParameters . any { it . defaultValue != null } ) <EOL> return null <EOL> function . returnType = doubleIfNumber ( function . returnType ) <EOL> val valueParametersAdapters = function . valueParameters . map { parameter -> <EOL> val varargElementType = parameter . varargElementType <EOL> if ( varargElementType != null ) { <EOL> CopyToJsArrayAdapter ( parameter . type , varargElementType ) <EOL> } else { <EOL> parameter . type . kotlinToJsAdapterIfNeeded ( isReturn = false ) <EOL> } <EOL> } <EOL> val resultAdapter = <EOL> function . returnType . jsToKotlinAdapterIfNeeded ( isReturn = true ) <EOL> if ( resultAdapter == null && valueParametersAdapters . all { it == null } ) <EOL> return null <EOL> val newFun = context . irFactory . createStaticFunctionWithReceivers ( function . parent , name = Name . identifier ( function . name . asStringStripSpecialMarkers ( ) + "<STR_LIT>" ) , function , remapMultiFieldValueClassStructure = context :: remapMultiFieldValueClassStructure ) <EOL> function . valueParameters . forEachIndexed { index , newParameter -> <EOL> val adapter = valueParametersAdapters [ index ] <EOL> if ( adapter != null ) { <EOL> newParameter . type = adapter . toType <EOL> } <EOL> } <EOL> resultAdapter ? . let { <EOL> function . returnType = resultAdapter . fromType <EOL> } <EOL> val builder = context . createIrBuilder ( newFun . symbol ) <EOL> newFun . body = createAdapterFunctionBody ( builder , newFun , function , valueParametersAdapters , resultAdapter ) <EOL> newFun . annotations = emptyList ( ) <EOL> context . mapping . wasmJsInteropFunctionToWrapper [ function ] = newFun <EOL> return listOf ( function , newFun ) <EOL> }

/**
 * external fun foo(x: KotlinType): KotlinType
 *
 * ->
 *
 * external fun foo(x: JsType): JsType
 * fun foo__externalAdapter(x: KotlinType): KotlinType = adaptResult(foo(adaptParameter(x)));
 */


fun transformExportFunction ( function : IrSimpleFunction ) : List < IrDeclaration > ?

{ <EOL> val valueParametersAdapters = function . valueParameters . map { <EOL> it . type . jsToKotlinAdapterIfNeeded ( isReturn = false ) <EOL> } <EOL> val resultAdapter = <EOL> function . returnType . kotlinToJsAdapterIfNeeded ( isReturn = true ) <EOL> if ( resultAdapter == null && valueParametersAdapters . all { it == null } ) <EOL> return null <EOL> val newFun = context . irFactory . createStaticFunctionWithReceivers ( function . parent , name = Name . identifier ( function . name . asStringStripSpecialMarkers ( ) + "<STR_LIT>" ) , function , remapMultiFieldValueClassStructure = context :: remapMultiFieldValueClassStructure ) <EOL> newFun . valueParameters . forEachIndexed { index , newParameter -> <EOL> val adapter = valueParametersAdapters [ index ] <EOL> if ( adapter != null ) { <EOL> newParameter . type = adapter . fromType <EOL> } <EOL> } <EOL> resultAdapter ? . let { <EOL> newFun . returnType = resultAdapter . toType <EOL> } <EOL> val builder : DeclarationIrBuilder = context . createIrBuilder ( newFun . symbol ) <EOL> newFun . body = createAdapterFunctionBody ( builder , newFun , function , valueParametersAdapters , resultAdapter ) <EOL> newFun . annotations += builder . irCallConstructor ( jsRelatedSymbols . jsNameConstructor , typeArguments = emptyList ( ) ) . also { <EOL> it . putValueArgument ( <NUM_LIT:0> , builder . irString ( function . getJsNameOrKotlinName ( ) . identifier ) ) <EOL> } <EOL> function . annotations = function . annotations . filter { it . symbol != jsRelatedSymbols . jsExportConstructor } <EOL> return listOf ( function , newFun ) <EOL> }

/**
 * @JsExport
 * fun foo(x: KotlinType): KotlinType { <original-body> }
 *
 * ->
 *
 * @JsExport
 * @JsName("foo")
 * fun foo__JsExportAdapter(x: JsType): JsType =
 * adaptResult(foo(adaptParameter(x)));
 *
 * fun foo(x: KotlinType): KotlinType { <original-body> }
 */


@ ExternalKotlinTargetApi <EOL> fun IdeDependencyResolver . withEffect ( effect : IdeDependencyEffect )

= IdeDependencyResolver { sourceSet -> <EOL> this@withEffect . resolve ( sourceSet ) . also { dependencies -> effect ( sourceSet , dependencies ) } <EOL> }

/**
 * Wraps the given [IdeDependencyResolver] with the specified [effect]
 * The resulting resolver will first resolve the dependencies and then execute the effect on the result
 */


internal fun Configuration . asTransitiveDependencies ( )

{ <EOL> isVisible = false <EOL> isCanBeConsumed = false <EOL> isTransitive = true <EOL> isCanBeResolved = true <EOL> }

/**
 * Mark this [Configuration] as a transitive.
 *
 * Dependencies must be added to this configuration, as a result of its resolution, artifacts from these dependencies are returned.
 *
 * See: https://docs.gradle.org/7.5.1/userguide/declaring_dependencies.html
 */


internal fun Configuration . asBucket ( )

{ <EOL> isVisible = true <EOL> isCanBeResolved = false <EOL> isCanBeConsumed = false <EOL> }

/**
 * Mark this [Configuration] as a bucket for declaring dependencies.
 *
 * Bucket combines artifacts from the specified dependencies,
 * and allows you to resolve in consumer configuration.
 *
 * See: https://docs.gradle.org/7.5.1/userguide/declaring_dependencies.html#sec:resolvable-consumable-configs
 */


internal fun Configuration . asProducer ( )

{ <EOL> isVisible = false <EOL> isCanBeResolved = false <EOL> isCanBeConsumed = true <EOL> }

/**
 * Mark this [Configuration] as a 'producer' that exposes artifacts and their dependencies for consumption by other
 * projects
 *
 * See: https://docs.gradle.org/7.5.1/userguide/declaring_dependencies.html#sec:resolvable-consumable-configs
 */


override fun add ( element : @ UnsafeVariance E ) : PersistentSet < E >

/**
 * Returns the result of adding the specified [element] to this set.
 *
 * @return a new persistent set with the specified [element] added;
 * or this instance if it already contains the element.
 */


override fun addAll ( elements : Collection < @ UnsafeVariance E > ) : PersistentSet < E >

/**
 * Returns the result of adding all elements of the specified [elements] collection to this set.
 *
 * @return a new persistent set with elements of the specified [elements] collection added;
 * or this instance if it already contains every element of the specified collection.
 */


override fun remove ( element : @ UnsafeVariance E ) : PersistentSet < E >

/**
 * Returns the result of removing the specified [element] from this set.
 *
 * @return a new persistent set with the specified [element] removed;
 * or this instance if there is no such element in this set.
 */


override fun removeAll ( elements : Collection < @ UnsafeVariance E > ) : PersistentSet < E >

/**
 * Returns the result of removing all elements in this set that are also
 * contained in the specified [elements] collection.
 *
 * @return a new persistent set with elements in this set that are also
 * contained in the specified [elements] collection removed;
 * or this instance if no modifications were made in the result of this operation.
 */


override fun removeAll ( predicate : ( E ) -> Boolean ) : PersistentSet < E >

/**
 * Returns the result of removing all elements in this set that match the specified [predicate].
 *
 * @return a new persistent set with elements matching the specified [predicate] removed;
 * or this instance if no elements match the predicate.
 */


override fun retainAll ( elements : Collection < @ UnsafeVariance E > ) : PersistentSet < E >

/**
 * Returns all elements in this set that are also
 * contained in the specified [elements] collection.
 *
 * @return a new persistent set with elements in this set that are also
 * contained in the specified [elements] collection;
 * or this instance if no modifications were made in the result of this operation.
 */


override fun clear ( ) : PersistentSet < E >

/**
 * Returns an empty persistent set.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun min ( a : UInt , b : UInt ) : UInt

{ <EOL> return minOf ( a , b ) <EOL> }

/**
 * Returns the smaller of two values.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun min ( a : ULong , b : ULong ) : ULong

{ <EOL> return minOf ( a , b ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun max ( a : UInt , b : UInt ) : UInt

{ <EOL> return maxOf ( a , b ) <EOL> }

/**
 * Returns the greater of two values.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun max ( a : ULong , b : ULong ) : ULong

{ <EOL> return maxOf ( a , b ) <EOL> }


= <EOL> if ( Paths . get ( path ) . isAbsolute ) File ( path ) else resolveRelative ( path )

/**
 * If given [path] is relative, resolves it relative to dependecies directory.
 * In case of absolute path just wraps it into a [File].
 *
 * Support of both relative and absolute path kinds allows to substitute predefined
 * dependencies with system ones.
 *
 * TODO: It looks like DependencyProcessor have two split responsibilities:
 * * Dependency resolving
 * * Dependency downloading
 * Also it is tightly tied to KonanProperties.
 */


public expect fun < T > atomic ( initial : T , trace : TraceBase = None ) : AtomicRef < T >

/**
 * Creates atomic reference with a given [initial] value and a [trace] object to [trace modifications][Trace] of the value.
 *
 * It can only be used to initialize a private or internal read-only property, like this:
 *
 * ```
 * private val f = atomic<Type>(initial, trace)
 * ```
 */


public expect fun < T > atomic ( initial : T ) : AtomicRef < T >

/**
 * Creates atomic reference with a given [initial] value.
 *
 * It can only be used to initialize a private or internal read-only property, like this:
 *
 * ```
 * private val f = atomic<Type>(initial)
 * ```
 */


public expect fun atomic ( initial : Int , trace : TraceBase = None ) : AtomicInt

/**
 * Creates atomic [Int] with a given [initial] value and a [trace] object to [trace modifications][Trace] of the value.
 *
 * It can only be used to initialize a private or internal read-only property, like this:
 *
 * ```
 * private val f = atomic(initialInt, trace)
 * ```
 */


public expect fun atomic ( initial : Int ) : AtomicInt

/**
 * Creates atomic [Int] with a given [initial] value.
 *
 * It can only be used to initialize a private or internal read-only property, like this:
 *
 * ```
 * private val f = atomic(initialInt)
 * ```
 */


public expect fun atomic ( initial : Long , trace : TraceBase = None ) : AtomicLong

/**
 * Creates atomic [Long] with a given [initial] value and a [trace] object to [trace modifications][Trace] of the value.
 *
 * It can only be used to initialize a private or internal read-only property, like this:
 *
 * ```
 * private val f = atomic(initialLong, trace)
 * ```
 */


public expect fun atomic ( initial : Long ) : AtomicLong

/**
 * Creates atomic [Long] with a given [initial] value.
 *
 * It can only be used to initialize a private or internal read-only property, like this:
 *
 * ```
 * private val f = atomic(initialLong)
 * ```
 */


public expect fun atomic ( initial : Boolean , trace : TraceBase = None ) : AtomicBoolean

/**
 * Creates atomic [Boolean] with a given [initial] value and a [trace] object to [trace modifications][Trace] of the value.
 *
 * It can only be used to initialize a private or internal read-only property, like this:
 *
 * ```
 * private val f = atomic(initialBoolean, trace)
 * ```
 */


public expect fun atomic ( initial : Boolean ) : AtomicBoolean

/**
 * Creates atomic [Boolean] with a given [initial] value.
 *
 * It can only be used to initialize a private or internal read-only property, like this:
 *
 * ```
 * private val f = atomic(initialBoolean)
 * ```
 */


@ OptionalJsName ( ATOMIC_ARRAY_OF_NULLS ) <EOL> public fun < T > atomicArrayOfNulls ( size : Int ) : AtomicArray < T ? >

= AtomicArray ( size )

/**
 * Creates array of AtomicRef<T> of specified size, where each element is initialised with null value
 */


public fun lazySet ( value : T )

/**
 * Maps to [AtomicReferenceFieldUpdater.lazySet].
 */


public fun compareAndSet ( expect : T , update : T ) : Boolean

/**
 * Maps to [AtomicReferenceFieldUpdater.compareAndSet].
 */


public fun getAndSet ( value : T ) : T

/**
 * Maps to [AtomicReferenceFieldUpdater.getAndSet].
 */


public inline fun < T > AtomicRef < T > . loop ( action : ( T ) -> Unit ) : Nothing

{ <EOL> while ( true ) { <EOL> action ( value ) <EOL> } <EOL> }

/**
 * Infinite loop that reads this atomic variable and performs the specified [action] on its value.
 */


public inline fun < T > AtomicRef < T > . update ( function : ( T ) -> T )

{ <EOL> while ( true ) { <EOL> val cur = value <EOL> val upd = function ( cur ) <EOL> if ( compareAndSet ( cur , upd ) ) return <EOL> } <EOL> }

/**
 * Updates variable atomically using the specified [function] of its value.
 */


public inline fun < T > AtomicRef < T > . getAndUpdate ( function : ( T ) -> T ) : T

{ <EOL> while ( true ) { <EOL> val cur = value <EOL> val upd = function ( cur ) <EOL> if ( compareAndSet ( cur , upd ) ) return cur <EOL> } <EOL> }

/**
 * Updates variable atomically using the specified [function] of its value and returns its old value.
 */


public inline fun < T > AtomicRef < T > . updateAndGet ( function : ( T ) -> T ) : T

{ <EOL> while ( true ) { <EOL> val cur = value <EOL> val upd = function ( cur ) <EOL> if ( compareAndSet ( cur , upd ) ) return upd <EOL> } <EOL> }

/**
 * Updates variable atomically using the specified [function] of its value and returns its new value.
 */


public fun lazySet ( value : Boolean )

/**
 * Maps to [AtomicIntegerFieldUpdater.lazySet].
 */


public fun compareAndSet ( expect : Boolean , update : Boolean ) : Boolean

/**
 * Maps to [AtomicIntegerFieldUpdater.compareAndSet].
 */


public fun getAndSet ( value : Boolean ) : Boolean

/**
 * Maps to [AtomicIntegerFieldUpdater.getAndSet].
 */


public inline fun AtomicBoolean . loop ( action : ( Boolean ) -> Unit ) : Nothing


public inline fun AtomicBoolean . update ( function : ( Boolean ) -> Boolean )


public inline fun AtomicBoolean . getAndUpdate ( function : ( Boolean ) -> Boolean ) : Boolean


public inline fun AtomicBoolean . updateAndGet ( function : ( Boolean ) -> Boolean ) : Boolean


public fun lazySet ( value : Int )


public fun compareAndSet ( expect : Int , update : Int ) : Boolean


public fun getAndSet ( value : Int ) : Int


public fun getAndIncrement ( ) : Int

/**
 * Maps to [AtomicIntegerFieldUpdater.getAndIncrement].
 */


public fun getAndDecrement ( ) : Int

/**
 * Maps to [AtomicIntegerFieldUpdater.getAndDecrement].
 */


public fun getAndAdd ( delta : Int ) : Int

/**
 * Maps to [AtomicIntegerFieldUpdater.getAndAdd].
 */


public fun addAndGet ( delta : Int ) : Int

/**
 * Maps to [AtomicIntegerFieldUpdater.addAndGet].
 */


public fun incrementAndGet ( ) : Int

/**
 * Maps to [AtomicIntegerFieldUpdater.incrementAndGet].
 */


public fun decrementAndGet ( ) : Int

/**
 * Maps to [AtomicIntegerFieldUpdater.decrementAndGet].
 */


public inline operator fun plusAssign ( delta : Int )

/**
 * Performs atomic addition of [delta].
 */


public inline operator fun minusAssign ( delta : Int )

/**
 * Performs atomic subtraction of [delta].
 */


public inline fun AtomicInt . loop ( action : ( Int ) -> Unit ) : Nothing


public inline fun AtomicInt . update ( function : ( Int ) -> Int )


public inline fun AtomicInt . getAndUpdate ( function : ( Int ) -> Int ) : Int


public inline fun AtomicInt . updateAndGet ( function : ( Int ) -> Int ) : Int


public fun lazySet ( value : Long )

/**
 * Maps to [AtomicLongFieldUpdater.lazySet].
 */


public fun compareAndSet ( expect : Long , update : Long ) : Boolean

/**
 * Maps to [AtomicLongFieldUpdater.compareAndSet].
 */


public fun getAndSet ( value : Long ) : Long

/**
 * Maps to [AtomicLongFieldUpdater.getAndSet].
 */


public fun getAndIncrement ( ) : Long

/**
 * Maps to [AtomicLongFieldUpdater.getAndIncrement].
 */


public fun getAndDecrement ( ) : Long

/**
 * Maps to [AtomicLongFieldUpdater.getAndDecrement].
 */


public fun getAndAdd ( delta : Long ) : Long

/**
 * Maps to [AtomicLongFieldUpdater.getAndAdd].
 */


public fun addAndGet ( delta : Long ) : Long

/**
 * Maps to [AtomicLongFieldUpdater.addAndGet].
 */


public fun incrementAndGet ( ) : Long

/**
 * Maps to [AtomicLongFieldUpdater.incrementAndGet].
 */


public fun decrementAndGet ( ) : Long

/**
 * Maps to [AtomicLongFieldUpdater.decrementAndGet].
 */


public inline operator fun plusAssign ( delta : Long )


public inline operator fun minusAssign ( delta : Long )


public inline fun AtomicLong . loop ( action : ( Long ) -> Unit ) : Nothing

{ <EOL> while ( true ) { <EOL> action ( value ) <EOL> } <EOL> }

/**
 * Infinite loop that reads this atomic variable and performs the specified [action] on its value.
 */


public inline fun AtomicLong . update ( function : ( Long ) -> Long )

{ <EOL> while ( true ) { <EOL> val cur = value <EOL> val upd = function ( cur ) <EOL> if ( compareAndSet ( cur , upd ) ) return <EOL> } <EOL> }

/**
 * Updates variable atomically using the specified [function] of its value.
 */


public inline fun AtomicLong . getAndUpdate ( function : ( Long ) -> Long ) : Long

{ <EOL> while ( true ) { <EOL> val cur = value <EOL> val upd = function ( cur ) <EOL> if ( compareAndSet ( cur , upd ) ) return cur <EOL> } <EOL> }

/**
 * Updates variable atomically using the specified [function] of its value and returns its old value.
 */


public inline fun AtomicLong . updateAndGet ( function : ( Long ) -> Long ) : Long

{ <EOL> while ( true ) { <EOL> val cur = value <EOL> val upd = function ( cur ) <EOL> if ( compareAndSet ( cur , upd ) ) return upd <EOL> } <EOL> }

/**
 * Updates variable atomically using the specified [function] of its value and returns its new value.
 */


{ <EOL> shared = true <EOL> return Segment ( data , pos , limit , true , false ) <EOL> }

/**
 * Returns a new segment that shares the underlying byte array with this. Adjusting pos and limit
 * are safe but writes are forbidden. This also marks the current segment as shared, which
 * prevents it from being pooled.
 */


= Segment ( data . copyOf ( ) , pos , limit , false , true )

/** Returns a new segment that its own private copy of the underlying byte array. */


{ <EOL> val result = if ( next !== this ) next else null <EOL> prev ! ! . next = next <EOL> next ! ! . prev = prev <EOL> next = null <EOL> prev = null <EOL> return result <EOL> }

/**
 * Removes this segment of a circularly-linked list and returns its successor.
 * Returns null if the list is now empty.
 */


fun push ( segment : Segment ) : Segment

{ <EOL> segment . prev = this <EOL> segment . next = next <EOL> next ! ! . prev = segment <EOL> next = segment <EOL> return segment <EOL> }

/**
 * Appends `segment` after this segment in the circularly-linked list. Returns the pushed segment.
 */


{ <EOL> require ( byteCount > <NUM_LIT:0> && byteCount <= limit - pos ) { "<STR_LIT>" } <EOL> val prefix : Segment <EOL> if ( byteCount >= SHARE_MINIMUM ) { <EOL> prefix = sharedCopy ( ) <EOL> } else { <EOL> prefix = SegmentPool . take ( ) <EOL> data . copyInto ( prefix . data , startIndex = pos , endIndex = pos + byteCount ) <EOL> } <EOL> prefix . limit = prefix . pos + byteCount <EOL> pos += byteCount <EOL> prev ! ! . push ( prefix ) <EOL> return prefix <EOL> }

/**
 * Splits this head of a circularly-linked list into two segments. The first segment contains the
 * data in `[pos..pos+byteCount)`. The second segment contains the data in
 * `[pos+byteCount..limit)`. This can be useful when moving partial segments from one buffer to
 * another.
 *
 * Returns the new head of the circularly-linked list.
 */


{ <EOL> check ( prev !== this ) { "<STR_LIT>" } <EOL> if ( ! prev ! ! . owner ) return <EOL> val byteCount = limit - pos <EOL> val availableByteCount = SIZE - prev ! ! . limit + if ( prev ! ! . shared ) <NUM_LIT:0> else prev ! ! . pos <EOL> if ( byteCount > availableByteCount ) return <EOL> writeTo ( prev ! ! , byteCount ) <EOL> pop ( ) <EOL> SegmentPool . recycle ( this ) <EOL> }

/**
 * Call this when the tail and its predecessor may both be less than half full. This will copy
 * data so that segments can be recycled.
 */


fun writeTo ( sink : Segment , byteCount : Int )

{ <EOL> check ( sink . owner ) { "<STR_LIT>" } <EOL> if ( sink . limit + byteCount > SIZE ) { <EOL> if ( sink . shared ) throw IllegalArgumentException ( ) <EOL> if ( sink . limit + byteCount - sink . pos > SIZE ) throw IllegalArgumentException ( ) <EOL> sink . data . copyInto ( sink . data , startIndex = sink . pos , endIndex = sink . limit ) <EOL> sink . limit -= sink . pos <EOL> sink . pos = <NUM_LIT:0> <EOL> } <EOL> data . copyInto ( sink . data , destinationOffset = sink . limit , startIndex = pos , endIndex = pos + byteCount ) <EOL> sink . limit += byteCount <EOL> pos += byteCount <EOL> }

/** Moves `byteCount` bytes from this segment to `sink`. */


internal fun Segment . indexOfBytesInbound ( bytes : ByteArray , startOffset : Int ) : Int

{ <EOL> var offset = startOffset <EOL> val limit = size - bytes . size + <NUM_LIT:1> <EOL> val firstByte = bytes [ <NUM_LIT:0> ] <EOL> while ( offset < limit ) { <EOL> val idx = indexOf ( firstByte , offset , limit ) <EOL> if ( idx < <NUM_LIT:0> ) { <EOL> return - <NUM_LIT:1> <EOL> } <EOL> var found = true <EOL> for ( innerIdx in <NUM_LIT:1> until bytes . size ) { <EOL> if ( data [ pos + idx + innerIdx ] != bytes [ innerIdx ] ) { <EOL> found = false <EOL> break <EOL> } <EOL> } <EOL> if ( found ) { <EOL> return idx <EOL> } else { <EOL> offset ++ <EOL> } <EOL> } <EOL> return - <NUM_LIT:1> <EOL> }

/**
 * Searches for a `bytes` pattern within this segment starting at the offset `startOffset`.
 * `startOffset` is relative and should be within `[0, size)`.
 */


internal fun Segment . indexOfBytesOutbound ( bytes : ByteArray , startOffset : Int , head : Segment ? ) : Int

{ <EOL> var offset = startOffset <EOL> val firstByte = bytes [ <NUM_LIT:0> ] <EOL> while ( offset in <NUM_LIT:0> until size ) { <EOL> val idx = indexOf ( firstByte , offset , size ) <EOL> if ( idx < <NUM_LIT:0> ) { <EOL> return - <NUM_LIT:1> <EOL> } <EOL> var seg = this <EOL> var scanOffset = offset <EOL> var found = true <EOL> for ( element in bytes ) { <EOL> if ( scanOffset == seg . size ) { <EOL> val next = seg . next <EOL> if ( next === head ) return - <NUM_LIT:1> <EOL> seg = next ! ! <EOL> scanOffset = <NUM_LIT:0> <EOL> } <EOL> if ( element != seg . data [ seg . pos + scanOffset ] ) { <EOL> found = false <EOL> break <EOL> } <EOL> scanOffset ++ <EOL> } <EOL> if ( found ) { <EOL> return offset <EOL> } <EOL> offset ++ <EOL> } <EOL> return - <NUM_LIT:1> <EOL> }

/**
 * Searches for a `bytes` pattern starting in between offset `startOffset` and `size` within this segment
 * and continued in the following segments.
 * `startOffset` is relative and should be within `[0, size)`.
 */


@ Test <EOL> fun testExistingStorageIsProperlyModifiedOnSuccess ( )

{ <EOL> val storageRoot = workingDir . resolve ( "<STR_LIT>" ) <EOL> val key1 = LookupSymbolKey ( "<STR_LIT:a>" , "<STR_LIT:a>" ) <EOL> val key2 = LookupSymbolKey ( "<STR_LIT:b>" , "<STR_LIT:b>" ) <EOL> val key3 = LookupSymbolKey ( "<STR_LIT:c>" , "<STR_LIT:c>" ) <EOL> val key4 = LookupSymbolKey ( "<STR_LIT:d>" , "<STR_LIT:d>" ) <EOL> val key5 = LookupSymbolKey ( "<STR_LIT:e>" , "<STR_LIT:e>" ) <EOL> withLookupMapInTransaction ( storageRoot , useInMemoryWrapper = false , successful = true ) { <EOL> it [ key1 ] = setOf ( <NUM_LIT:1> , <NUM_LIT:2> ) <EOL> it [ key2 ] = setOf ( <NUM_LIT:1> , <NUM_LIT:2> ) <EOL> it [ key3 ] = setOf ( <NUM_LIT:1> ) <EOL> } <EOL> withLookupMapInTransaction ( storageRoot , useInMemoryWrapper = true , successful = true ) { <EOL> it . append ( key1 , setOf ( <NUM_LIT:3> ) ) <EOL> it . remove ( key2 ) <EOL> it [ key3 ] = setOf ( <NUM_LIT:5> ) <EOL> it . append ( key4 , setOf ( <NUM_LIT:4> ) ) <EOL> it . append ( key5 , setOf ( <NUM_LIT:5> ) ) <EOL> } <EOL> withLookupMapInTransaction ( storageRoot , useInMemoryWrapper = false , successful = true ) { <EOL> assertEquals ( setOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) , it [ key1 ] ) <EOL> assertNull ( it [ key2 ] ) <EOL> assertEquals ( setOf ( <NUM_LIT:5> ) , it [ key3 ] ) <EOL> assertEquals ( setOf ( <NUM_LIT:4> ) , it [ key4 ] ) <EOL> assertEquals ( setOf ( <NUM_LIT:5> ) , it [ key5 ] ) <EOL> } <EOL> withLookupMapInTransaction ( storageRoot , useInMemoryWrapper = true , successful = true ) { <EOL> it . clear ( ) <EOL> it . append ( key1 , setOf ( <NUM_LIT:4> ) ) <EOL> } <EOL> withLookupMapInTransaction ( storageRoot , useInMemoryWrapper = false , successful = true ) { <EOL> assertEquals ( setOf ( <NUM_LIT:4> ) , it [ key1 ] ) <EOL> assertNull ( it [ key2 ] ) <EOL> assertNull ( it [ key3 ] ) <EOL> assertNull ( it [ key4 ] ) <EOL> assertNull ( it [ key5 ] ) <EOL> } <EOL> }

/**
 * Covered scenarios:
 * - By existing key
 * - set (key3)
 * - append (key1)
 * - remove (key2)
 * - By non-existing key
 * - set (key5)
 * - append (key4)
 * - clean
 */


fun resnet50additionalTrainingWithHelper ( )

{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CV . ResNet50 ( ) <EOL> val model = modelHub . loadModel ( modelType ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> val pretrainedModel = model . removeLastLayer ( ) <EOL> val topModel = Sequential . of ( Dense ( name = "<STR_LIT>" , kernelInitializer = GlorotUniform ( ) , biasInitializer = GlorotUniform ( ) , outputSize = <NUM_LIT> , activation = Activations . Relu ) , Dense ( name = "<STR_LIT>" , kernelInitializer = GlorotUniform ( ) , biasInitializer = GlorotUniform ( ) , outputSize = NUM_CLASSES , activation = Activations . Linear ) , noInput = true ) <EOL> val model2 = Functional . of ( pretrainedModel = pretrainedModel , topModel = topModel ) <EOL> val dataset = OnFlyImageDataset . create ( File ( dogsCatsSmallDatasetPath ( ) ) , FromFolders ( mapping = mapOf ( "<STR_LIT>" to <NUM_LIT:0> , "<STR_LIT>" to <NUM_LIT:1> ) ) , modelType . createPreprocessing ( model2 ) ) . shuffle ( ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> model2 . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . loadWeightsForFrozenLayers ( hdfFile ) <EOL> val accuracyBeforeTraining = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> it . fit ( dataset = train , batchSize = TRAINING_BATCH_SIZE , epochs = EPOCHS ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example demonstrates the transfer learning concept on ResNet'50 model:
 * - Model configuration, model weights and labels are obtained from [TFModelHub].
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - All layers, excluding the last [Dense], are added to the new Neural Network, its weights are frozen.
 * - New Dense layers are added and initialized via defined initializers.
 * - Model is re-trained on [dogsCatsSmallDatasetPath] dataset.
 *
 * We use the preprocessing DSL to describe the dataset generation pipeline.
 * We demonstrate the workflow on the subset of Kaggle Cats vs Dogs binary classification dataset.
 */


= resnet50additionalTrainingWithHelper ( )


fun isVersionRequirementTableWrittenCorrectly ( version : BinaryVersion ) : Boolean

= <EOL> isKotlin1Dot4OrLater ( version )

/**
 * Before metadata version 1.4, version requirements for nested classes were deserialized incorrectly: the version requirement table was
 * loaded from the outermost class and passed to the nested classes and their members, even though indices of their version requirements
 * were pointing to the other table stored in the nested class (which was not read by deserialization). See KT-25120 for more information.
 */


@ Composable <EOL> fun JetsnackSnackbar ( snackbarData : SnackbarData , modifier : Modifier = Modifier , actionOnNewLine : Boolean = false , shape : Shape = MaterialTheme . shapes . small , backgroundColor : Color = JetsnackTheme . colors . uiBackground , contentColor : Color = JetsnackTheme . colors . textSecondary , actionColor : Color = JetsnackTheme . colors . brand , elevation : Dp = <NUM_LIT:6> . dp )

{ <EOL> Snackbar ( snackbarData = snackbarData , modifier = modifier , actionOnNewLine = actionOnNewLine , shape = shape , backgroundColor = backgroundColor , contentColor = contentColor , actionColor = actionColor , elevation = elevation ) <EOL> }

/**
 * An alternative to [androidx.compose.material.Snackbar] utilizing
 * [com.example.jetsnack.ui.theme.JetsnackColors]
 */


internal fun Project . applyDebugKeystoreFix ( testFixesProperties : TestFixesProperties )

{ <EOL> plugins . withId ( "<STR_LIT>" , fix < AppExtension > ( testFixesProperties ) ) <EOL> plugins . withId ( "<STR_LIT>" , fix < LibraryExtension > ( testFixesProperties ) ) <EOL> plugins . withId ( "<STR_LIT>" , fix < FeatureExtension > ( testFixesProperties ) ) <EOL> plugins . withId ( "<STR_LIT>" , fix < TestExtension > ( testFixesProperties ) ) <EOL> }

/**
 * AGP 7+ creates a keystore that is not compatible with lover versions of AGP,
 * but could consume keystores created by them.
 *
 * With this fix 'debug.keystore' could be checked in into the repo and shared
 * between test executions.
 */


private fun IrConstructor . checkConstructorDelegation ( ) : InvalidConstructorDelegation ?

{ <EOL> if ( origin == PartiallyLinkedDeclarationOrigin . MISSING_DECLARATION ) <EOL> return null <EOL> val statements = ( body as? IrBlockBody ) ? . statements ? : return null <EOL> val constructedClass = parentAsClass <EOL> val constructedClassSymbol = constructedClass . symbol <EOL> val actualSuperClassSymbol = constructedClass . superTypes . firstNotNullOfOrNull { superType -> <EOL> val superClassSymbol = ( superType as? IrSimpleType ) ? . classifier as? IrClassSymbol ? : return@firstNotNullOfOrNull null <EOL> if ( superClassSymbol . owner . isClass ) superClassSymbol else null <EOL> } ? : builtIns . anyClass <EOL> val actualSuperClass = actualSuperClassSymbol . owner <EOL> statements . forEach { statement -> <EOL> if ( statement !is IrDelegatingConstructorCall ) return@forEach <EOL> val calledConstructorSymbol = statement . symbol <EOL> val calledConstructor = calledConstructorSymbol . owner <EOL> val invalidConstructorDelegationFound = <EOL> if ( calledConstructor . origin != PartiallyLinkedDeclarationOrigin . MISSING_DECLARATION ) { <EOL> val constructedSuperClassSymbol = calledConstructor . parentAsClass . symbol <EOL> constructedSuperClassSymbol != constructedClassSymbol <EOL> && constructedSuperClassSymbol != actualSuperClassSymbol <EOL> && ( ! constructedClass . isExternal || constructedSuperClassSymbol != builtIns . anyClass ) <EOL> } else { <EOL> ( calledConstructorSymbol . signature as? IdSignature . CommonSignature ) ? . let { constructorSignature -> <EOL> val constructedSuperClassId = DeclarationId ( constructorSignature . packageFqName , constructorSignature . declarationFqName . substringBeforeLast ( '<CHAR_LIT:.>' ) ) <EOL> actualSuperClass . declarationId != constructedSuperClassId <EOL> } ? : false <EOL> } <EOL> if ( invalidConstructorDelegationFound ) <EOL> return InvalidConstructorDelegation ( constructorSymbol = symbol , superClassSymbol = actualSuperClassSymbol , unexpectedSuperClassConstructorSymbol = calledConstructorSymbol ) <EOL> } <EOL> return null <EOL> }

/**
 * Checks if there is an issue with constructor delegation.
 */


private fun IrFunction . rewriteTypesInFunction ( ) : ExploredClassifier . Unusable ?

{ <EOL> var result : ExploredClassifier . Unusable ? by Delegates . vetoable ( null ) { _ , oldValue , _ -> oldValue == null } <EOL> fun IrValueParameter . fixType ( ) { <EOL> val newType = type . toPartiallyLinkedMarkerTypeOrNull ( ) ? : return <EOL> type = newType <EOL> if ( varargElementType != null ) varargElementType = newType <EOL> defaultValue = null <EOL> result = newType . unusableClassifier <EOL> } <EOL> dispatchReceiverParameter ? . fixType ( ) <EOL> extensionReceiverParameter ? . fixType ( ) <EOL> valueParameters . forEach { it . fixType ( ) } <EOL> returnType . toPartiallyLinkedMarkerTypeOrNull ( ) ? . let { newReturnType -> <EOL> returnType = newReturnType <EOL> result = newReturnType . unusableClassifier <EOL> } <EOL> typeParameters . forEach { tp -> <EOL> tp . superTypes . toPartiallyLinkedMarkerTypeOrNull ( ) ? . let { newSuperType -> <EOL> tp . superTypes = listOf ( newSuperType ) <EOL> result = newSuperType . unusableClassifier <EOL> } <EOL> } <EOL> return result <EOL> }

/**
 * Returns the first encountered [ExploredClassifier.Unusable].
 */


private fun MutableList < IrStatement > . eliminateDeadCodeStatements ( )

{ <EOL> var hasPartialLinkageRuntimeError = false <EOL> removeIf { statement -> <EOL> val needToRemove = when ( statement ) { <EOL> is IrInstanceInitializerCall , <EOL> is IrDelegatingConstructorCall , <EOL> is IrEnumConstructorCall -> false <EOL> else -> hasPartialLinkageRuntimeError <EOL> } <EOL> hasPartialLinkageRuntimeError = hasPartialLinkageRuntimeError || statement . isPartialLinkageRuntimeError ( ) <EOL> needToRemove <EOL> } <EOL> }

/**
 * Removes statements after the first IR p.l. error (everything after the IR p.l. error if effectively dead code and do not need
 * to be kept in the IR tree).
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public actual fun UIntArray . elementAt ( index : Int ) : UInt

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

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


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public actual fun ULongArray . elementAt ( index : Int ) : ULong


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public actual fun UByteArray . elementAt ( index : Int ) : UByte


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public actual fun UShortArray . elementAt ( index : Int ) : UShort


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public actual fun UIntArray . asList ( ) : List < UInt >

{ <EOL> return object : AbstractList < UInt > ( ) , RandomAccess { <EOL> override val size : Int get ( ) = this@asList . size <EOL> override fun isEmpty ( ) : Boolean = this@asList . isEmpty ( ) <EOL> override fun contains ( element : UInt ) : Boolean = this@asList . contains ( element ) <EOL> override fun get ( index : Int ) : UInt { <EOL> AbstractList . checkElementIndex ( index , size ) <EOL> return this@asList [ index ] <EOL> } <EOL> override fun indexOf ( element : UInt ) : Int { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> if ( ( element as Any ? ) !is UInt ) return - <NUM_LIT:1> <EOL> return this@asList . indexOf ( element ) <EOL> } <EOL> override fun lastIndexOf ( element : UInt ) : Int { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> if ( ( element as Any ? ) !is UInt ) return - <NUM_LIT:1> <EOL> return this@asList . lastIndexOf ( element ) <EOL> } <EOL> } <EOL> }

/**
 * Returns a [List] that wraps the original array.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public actual fun ULongArray . asList ( ) : List < ULong >

{ <EOL> return object : AbstractList < ULong > ( ) , RandomAccess { <EOL> override val size : Int get ( ) = this@asList . size <EOL> override fun isEmpty ( ) : Boolean = this@asList . isEmpty ( ) <EOL> override fun contains ( element : ULong ) : Boolean = this@asList . contains ( element ) <EOL> override fun get ( index : Int ) : ULong { <EOL> AbstractList . checkElementIndex ( index , size ) <EOL> return this@asList [ index ] <EOL> } <EOL> override fun indexOf ( element : ULong ) : Int { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> if ( ( element as Any ? ) !is ULong ) return - <NUM_LIT:1> <EOL> return this@asList . indexOf ( element ) <EOL> } <EOL> override fun lastIndexOf ( element : ULong ) : Int { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> if ( ( element as Any ? ) !is ULong ) return - <NUM_LIT:1> <EOL> return this@asList . lastIndexOf ( element ) <EOL> } <EOL> } <EOL> }


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public actual fun UByteArray . asList ( ) : List < UByte >

{ <EOL> return object : AbstractList < UByte > ( ) , RandomAccess { <EOL> override val size : Int get ( ) = this@asList . size <EOL> override fun isEmpty ( ) : Boolean = this@asList . isEmpty ( ) <EOL> override fun contains ( element : UByte ) : Boolean = this@asList . contains ( element ) <EOL> override fun get ( index : Int ) : UByte { <EOL> AbstractList . checkElementIndex ( index , size ) <EOL> return this@asList [ index ] <EOL> } <EOL> override fun indexOf ( element : UByte ) : Int { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> if ( ( element as Any ? ) !is UByte ) return - <NUM_LIT:1> <EOL> return this@asList . indexOf ( element ) <EOL> } <EOL> override fun lastIndexOf ( element : UByte ) : Int { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> if ( ( element as Any ? ) !is UByte ) return - <NUM_LIT:1> <EOL> return this@asList . lastIndexOf ( element ) <EOL> } <EOL> } <EOL> }


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public actual fun UShortArray . asList ( ) : List < UShort >

{ <EOL> return object : AbstractList < UShort > ( ) , RandomAccess { <EOL> override val size : Int get ( ) = this@asList . size <EOL> override fun isEmpty ( ) : Boolean = this@asList . isEmpty ( ) <EOL> override fun contains ( element : UShort ) : Boolean = this@asList . contains ( element ) <EOL> override fun get ( index : Int ) : UShort { <EOL> AbstractList . checkElementIndex ( index , size ) <EOL> return this@asList [ index ] <EOL> } <EOL> override fun indexOf ( element : UShort ) : Int { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> if ( ( element as Any ? ) !is UShort ) return - <NUM_LIT:1> <EOL> return this@asList . indexOf ( element ) <EOL> } <EOL> override fun lastIndexOf ( element : UShort ) : Int { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> if ( ( element as Any ? ) !is UShort ) return - <NUM_LIT:1> <EOL> return this@asList . lastIndexOf ( element ) <EOL> } <EOL> } <EOL> }


public actual inline fun < reified T > Collection < T > . toTypedArray ( ) : Array < T >

{ <EOL> val result = arrayOfNulls < T > ( size ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in this ) result [ index ++ ] = element <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return result as Array < T > <EOL> }

/**
 * 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
 */


@ Test <EOL> fun createZeroFilledByteArray ( )

{ <EOL> val dim1 = <NUM_LIT:5> <EOL> val dim2 = <NUM_LIT:7> <EOL> val dim3 = <NUM_LIT:3> <EOL> val a = mk . zeros < Byte > ( dim1 , dim2 , dim3 ) <EOL> assertEquals ( dim1 * dim2 * dim3 , a . size ) <EOL> assertEquals ( dim1 * dim2 * dim3 , a . data . size ) <EOL> assertTrue { a . all { it == <NUM_LIT:0> . toByte ( ) } } <EOL> }

/**
 * This method checks if a byte array of a given size is correctly created with all elements set to zero.
 */


@ Test <EOL> fun createByteArrayFilledWithOnes ( )

{ <EOL> val dim1 = <NUM_LIT:5> <EOL> val dim2 = <NUM_LIT:7> <EOL> val dim3 = <NUM_LIT:3> <EOL> val a = mk . ones < Byte > ( dim1 , dim2 , dim3 ) <EOL> assertEquals ( dim1 * dim2 * dim3 , a . size ) <EOL> assertEquals ( dim1 * dim2 * dim3 , a . data . size ) <EOL> assertTrue { a . all { it == <NUM_LIT:1> . toByte ( ) } } <EOL> }

/**
 * Creates a byte array filled with ones of a given size and checks if all elements are set to one.
 */


@ Test <EOL> fun createThreeDimensionalArrayFromByteList ( )

{ <EOL> val list = <EOL> listOf ( listOf ( listOf < Byte > ( <NUM_LIT:1> , <NUM_LIT:3> ) , listOf < Byte > ( <NUM_LIT:7> , <NUM_LIT:8> ) ) , listOf ( listOf < Byte > ( <NUM_LIT:4> , <NUM_LIT:7> ) , listOf < Byte > ( <NUM_LIT:9> , <NUM_LIT:2> ) ) ) <EOL> val a : D3Array < Byte > = mk . ndarray ( list ) <EOL> assertEquals ( list , a . toListD3 ( ) ) <EOL> }

/**
 * Creates a three-dimensional array from a list of byte lists
 * and checks if the array's list representation matches the input list.
 */


@ Test <EOL> fun createThreeDimensionalArrayFromByteSet ( )

{ <EOL> val set = setOf < Byte > ( <NUM_LIT:1> , <NUM_LIT:3> , <NUM_LIT:8> , <NUM_LIT:4> , <NUM_LIT:9> , <NUM_LIT:2> , <NUM_LIT:7> , <NUM_LIT:5> , <NUM_LIT:11> , <NUM_LIT> , - <NUM_LIT:8> , - <NUM_LIT:1> ) <EOL> val shape = intArrayOf ( <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:2> ) <EOL> val a : D3Array < Byte > = mk . ndarray ( set , shape = shape ) <EOL> assertEquals ( set . size , a . size ) <EOL> assertEquals ( set , a . toSet ( ) ) <EOL> }

/**
 * Creates a three-dimensional array from a set of bytes
 * and checks if the array's set representation matches the input set.
 */