@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public actual fun < R , T > ( suspend R . ( ) -> T ) . createCoroutineUnintercepted ( receiver : R , completion : Continuation < T > ) : Continuation < Unit >

{ <EOL> return createCoroutineFromSuspendFunction ( completion ) { <EOL> this . startCoroutineUninterceptedOrReturn ( receiver , completion ) <EOL> } <EOL> }

/**
 * Creates unintercepted coroutine with receiver type [R] and result type [T].
 * This function creates a new, fresh instance of suspendable computation every time it is invoked.
 *
 * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
 * The [completion] continuation is invoked when coroutine completes with result or exception.
 *
 * This function returns unintercepted continuation.
 * Invocation of `resume(Unit)` starts coroutine immediately in the invoker's call stack without going through the
 * [ContinuationInterceptor] that might be present in the completion's [CoroutineContext].
 * It is the invoker's responsibility to ensure that a proper invocation context is established.
 * Note that [completion] of this function may get invoked in an arbitrary context.
 *
 * [Continuation.intercepted] can be used to acquire the intercepted continuation.
 * Invocation of `resume(Unit)` on intercepted continuation guarantees that execution of
 * both the coroutine and [completion] happens in the invocation context established by
 * [ContinuationInterceptor].
 *
 * Repeated invocation of any resume function on the resulting continuation corrupts the
 * state machine of the coroutine and may result in arbitrary behaviour or exception.
 */


public actual fun < T > Continuation < T > . intercepted ( ) : Continuation < T >

= <EOL> ( this as? CoroutineImpl ) ? . intercepted ( ) ? : this

/**
 * Intercepts this continuation with [ContinuationInterceptor].
 *
 * This function shall be used on the immediate result of [createCoroutineUnintercepted] or [suspendCoroutineUninterceptedOrReturn],
 * in which case it checks for [ContinuationInterceptor] in the continuation's [context][Continuation.context],
 * invokes [ContinuationInterceptor.interceptContinuation], caches and returns the result.
 *
 * If this function is invoked on other [Continuation] instances it returns `this` continuation unchanged.
 */


fun nativeCacheKindForTarget ( target : KonanTarget ) : NativeCacheKind ?

= <EOL> property ( "<STR_LIT>" ) . orNull ? . let { NativeCacheKind . byCompilerArgument ( it ) }

/**
 * Dependencies caching strategy for [target].
 */


fun jsKarmaBrowsers ( target : KotlinTarget ? = null ) : String ?

= <EOL> target ? . name ? . prefixIfNot ( "<STR_LIT>" ) ? . let { property ( it ) . orNull } <EOL> ? : property ( KOTLIN_JS_KARMA_BROWSERS ) . orNull

/**
 * Retrieves a comma-separated list of browsers to use when running karma tests for [target]
 * @see KOTLIN_JS_KARMA_BROWSERS
 */


public fun Multik . ndarray ( args : Array < ByteArray > ) : D2Array < Byte >

{ <EOL> val dim0 = args . size <EOL> val dim1 = args [ <NUM_LIT:0> ] . size <EOL> require ( args . all { dim1 == it . size } ) { "<STR_LIT>" } <EOL> val array = ByteArray ( dim0 * dim1 ) <EOL> var index = <NUM_LIT:0> <EOL> for ( i in <NUM_LIT:0> until dim0 ) { <EOL> for ( j in <NUM_LIT:0> until dim1 ) { <EOL> array [ index ++ ] = args [ i ] [ j ] <EOL> } <EOL> } <EOL> val data = MemoryViewByteArray ( array ) <EOL> return D2Array ( data , shape = intArrayOf ( dim0 , dim1 ) , dim = D2 ) <EOL> }

/**
 * Returns an D2Array from Array<ByteArray>.
 */


public fun Multik . ndarray ( args : Array < ShortArray > ) : D2Array < Short >

{ <EOL> val dim0 = args . size <EOL> val dim1 = args [ <NUM_LIT:0> ] . size <EOL> require ( args . all { dim1 == it . size } ) { "<STR_LIT>" } <EOL> val array = ShortArray ( dim0 * dim1 ) <EOL> var index = <NUM_LIT:0> <EOL> for ( i in <NUM_LIT:0> until dim0 ) { <EOL> for ( j in <NUM_LIT:0> until dim1 ) { <EOL> array [ index ++ ] = args [ i ] [ j ] <EOL> } <EOL> } <EOL> val data = MemoryViewShortArray ( array ) <EOL> return D2Array ( data , shape = intArrayOf ( dim0 , dim1 ) , dim = D2 ) <EOL> }

/**
 * Returns an D2Array from Array<ShortArray>.
 */


public fun Multik . ndarray ( args : Array < IntArray > ) : D2Array < Int >

{ <EOL> val dim0 = args . size <EOL> val dim1 = args [ <NUM_LIT:0> ] . size <EOL> require ( args . all { dim1 == it . size } ) { "<STR_LIT>" } <EOL> val array = IntArray ( dim0 * dim1 ) <EOL> var index = <NUM_LIT:0> <EOL> for ( i in <NUM_LIT:0> until dim0 ) { <EOL> for ( j in <NUM_LIT:0> until dim1 ) { <EOL> array [ index ++ ] = args [ i ] [ j ] <EOL> } <EOL> } <EOL> val data = MemoryViewIntArray ( array ) <EOL> return D2Array ( data , shape = intArrayOf ( dim0 , dim1 ) , dim = D2 ) <EOL> }

/**
 * Returns an D2Array from Array<IntArray>.
 */


public fun Multik . ndarray ( args : Array < LongArray > ) : D2Array < Long >

{ <EOL> val dim0 = args . size <EOL> val dim1 = args [ <NUM_LIT:0> ] . size <EOL> require ( args . all { dim1 == it . size } ) { "<STR_LIT>" } <EOL> val array = LongArray ( dim0 * dim1 ) <EOL> var index = <NUM_LIT:0> <EOL> for ( i in <NUM_LIT:0> until dim0 ) { <EOL> for ( j in <NUM_LIT:0> until dim1 ) { <EOL> array [ index ++ ] = args [ i ] [ j ] <EOL> } <EOL> } <EOL> val data = MemoryViewLongArray ( array ) <EOL> return D2Array ( data , shape = intArrayOf ( dim0 , dim1 ) , dim = D2 ) <EOL> }

/**
 * Returns an D2Array from Array<LongArray>.
 */


public fun Multik . ndarray ( args : Array < FloatArray > ) : D2Array < Float >

{ <EOL> val dim0 = args . size <EOL> val dim1 = args [ <NUM_LIT:0> ] . size <EOL> require ( args . all { dim1 == it . size } ) { "<STR_LIT>" } <EOL> val array = FloatArray ( dim0 * dim1 ) <EOL> var index = <NUM_LIT:0> <EOL> for ( i in <NUM_LIT:0> until dim0 ) { <EOL> for ( j in <NUM_LIT:0> until dim1 ) { <EOL> array [ index ++ ] = args [ i ] [ j ] <EOL> } <EOL> } <EOL> val data = MemoryViewFloatArray ( array ) <EOL> return D2Array ( data , shape = intArrayOf ( dim0 , dim1 ) , dim = D2 ) <EOL> }

/**
 * Returns an D2Array from Array<FloatArray>.
 */


public fun Multik . ndarray ( args : Array < DoubleArray > ) : D2Array < Double >

{ <EOL> val dim0 = args . size <EOL> val dim1 = args [ <NUM_LIT:0> ] . size <EOL> require ( args . all { dim1 == it . size } ) { "<STR_LIT>" } <EOL> val array = DoubleArray ( dim0 * dim1 ) <EOL> var index = <NUM_LIT:0> <EOL> for ( i in <NUM_LIT:0> until dim0 ) { <EOL> for ( j in <NUM_LIT:0> until dim1 ) { <EOL> array [ index ++ ] = args [ i ] [ j ] <EOL> } <EOL> } <EOL> val data = MemoryViewDoubleArray ( array ) <EOL> return D2Array ( data , shape = intArrayOf ( dim0 , dim1 ) , dim = D2 ) <EOL> }

/**
 * Returns an D2Array from Array<DoubleArray>.
 */


public fun Array < ByteArray > . toNDArray ( ) : D2Array < Byte >

= Multik . ndarray ( this )


public fun Array < ShortArray > . toNDArray ( ) : D2Array < Short >

= Multik . ndarray ( this )


public fun Array < IntArray > . toNDArray ( ) : D2Array < Int >

= Multik . ndarray ( this )


public fun Array < LongArray > . toNDArray ( ) : D2Array < Long >

= Multik . ndarray ( this )


public fun Array < FloatArray > . toNDArray ( ) : D2Array < Float >

= Multik . ndarray ( this )


public fun Array < DoubleArray > . toNDArray ( ) : D2Array < Double >

= Multik . ndarray ( this )


public fun < T > List < T > . asReversed ( ) : List < T >

= ReversedListReadOnly ( this )

/**
 * Returns a reversed read-only view of the original List.
 * All changes made in the original list will be reflected in the reversed one.
 * @sample samples.collections.ReversedViews.asReversedList
 */


@ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> public fun < T > MutableList < T > . asReversed ( ) : MutableList < T >

= ReversedList ( this )

/**
 * Returns a reversed mutable view of the original mutable List.
 * All changes made in the original list will be reflected in the reversed one and vice versa.
 * @sample samples.collections.ReversedViews.asReversedMutableList
 */


fun getCustomKotlinRepositoryURL ( project : Project ) : String ?

{ <EOL> val communityPluginKotlinRepoURL = project . findProperty ( "<STR_LIT>" ) as? String <EOL> val gradlePropertyKotlinRepoURL = project . findProperty ( "<STR_LIT>" ) as? String <EOL> val kotlinRepoURL = when { <EOL> communityPluginKotlinRepoURL != null -> communityPluginKotlinRepoURL <EOL> gradlePropertyKotlinRepoURL != null -> gradlePropertyKotlinRepoURL <EOL> else -> return null <EOL> } <EOL> LOGGER . info ( "<STR_LIT>" ) <EOL> return kotlinRepoURL <EOL> }

/**
 * Should be used for running against a non-released Kotlin compiler on a system test level.
 *
 * @return a custom repository with development builds of the Kotlin compiler taken from:
 *
 * 1. the Kotlin community project Gradle plugin,
 * 2. or `kotlin_repo_url` Gradle property (from command line or from `gradle.properties`),
 *
 * or null otherwise
 */


fun addCustomKotlinRepositoryIfEnabled ( repositoryHandler : RepositoryHandler , project : Project )

{ <EOL> val kotlinRepoURL = getCustomKotlinRepositoryURL ( project ) ? : return <EOL> repositoryHandler . maven { url = URI . create ( kotlinRepoURL ) } <EOL> }

/**
 * Should be used for running against a non-released Kotlin compiler on a system test level.
 *
 * Adds a custom repository with development builds of the Kotlin compiler to [repositoryHandler]
 * if the URL is provided (see [getCustomKotlinRepositoryURL]).
 */


fun getOverridingKotlinVersion ( project : Project ) : String ?

{ <EOL> val communityPluginKotlinVersion = project . findProperty ( "<STR_LIT>" ) as? String <EOL> val kotlinVersion = when { <EOL> communityPluginKotlinVersion != null -> communityPluginKotlinVersion <EOL> else -> return null <EOL> } <EOL> LOGGER . info ( "<STR_LIT>" ) <EOL> return kotlinVersion <EOL> }

/**
 * Should be used for running against a non-released Kotlin compiler on a system test level.
 *
 * @return a Kotlin version taken from the Kotlin community project Gradle plugin,
 * or null otherwise
 */


fun getOverridingKotlinLanguageVersion ( project : Project ) : String ?

{ <EOL> val communityPluginLanguageVersion = project . findProperty ( "<STR_LIT>" ) as? String <EOL> val gradlePropertyLanguageVersion = project . findProperty ( "<STR_LIT>" ) as? String <EOL> val languageVersion = when { <EOL> communityPluginLanguageVersion != null -> communityPluginLanguageVersion <EOL> gradlePropertyLanguageVersion != null -> gradlePropertyLanguageVersion <EOL> else -> return null <EOL> } <EOL> LOGGER . info ( "<STR_LIT>" ) <EOL> return languageVersion <EOL> }

/**
 * Should be used for running against a non-released Kotlin compiler on a system test level.
 *
 * @return a Kotlin language version taken from:
 *
 * 1. the Kotlin community project Gradle plugin,
 * 2. or `kotlin_language_version` Gradle property (from command line or from `gradle.properties`),
 *
 * or null otherwise
 */


fun getOverridingKotlinApiVersion ( project : Project ) : String ?

{ <EOL> val communityPluginApiVersion = project . findProperty ( "<STR_LIT>" ) as? String <EOL> val gradlePropertyApiVersion = project . findProperty ( "<STR_LIT>" ) as? String <EOL> val apiVersion = when { <EOL> communityPluginApiVersion != null -> communityPluginApiVersion <EOL> gradlePropertyApiVersion != null -> gradlePropertyApiVersion <EOL> else -> return null <EOL> } <EOL> LOGGER . info ( "<STR_LIT>" ) <EOL> return apiVersion <EOL> }

/**
 * Should be used for running against a non-released Kotlin compiler on a system test level.
 *
 * @return a Kotlin API version taken from:
 *
 * 1. the Kotlin community project Gradle plugin,
 * 2. or `kotlin_language_version` Gradle property (from command line or from `gradle.properties`),
 *
 * or null otherwise
 */


@ JvmName ( "<STR_LIT>" ) <EOL> fun com . google . protobuf . kotlin . DslMap < kotlin . String , kotlin . String , AttributesProxy > <EOL> . put ( key : kotlin . String , value : kotlin . String )

{ <EOL> _builder . putAttributes ( key , value ) <EOL> }

/**
 * map<string, string> attributes = 1;
 */


@ kotlin . jvm . JvmSynthetic <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> @ Suppress ( "<STR_LIT:NOTHING_TO_INLINE>" ) <EOL> inline operator fun com . google . protobuf . kotlin . DslMap < kotlin . String , kotlin . String , AttributesProxy > <EOL> . set ( key : kotlin . String , value : kotlin . String )

{ <EOL> put ( key , value ) <EOL> }


@ kotlin . jvm . JvmSynthetic <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> fun com . google . protobuf . kotlin . DslMap < kotlin . String , kotlin . String , AttributesProxy > <EOL> . remove ( key : kotlin . String )

{ <EOL> _builder . removeAttributes ( key ) <EOL> }


@ kotlin . jvm . JvmSynthetic <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> fun com . google . protobuf . kotlin . DslMap < kotlin . String , kotlin . String , AttributesProxy > <EOL> . putAll ( map : kotlin . collections . Map < kotlin . String , kotlin . String > )

{ <EOL> _builder . putAllAttributes ( map ) <EOL> }


@ kotlin . jvm . JvmSynthetic <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> fun com . google . protobuf . kotlin . DslMap < kotlin . String , kotlin . String , AttributesProxy > <EOL> . clear ( )

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


public abstract fun getDirectDependents ( module : KtModule ) : Set < KtModule >

/**
 * Returns all direct dependents of [module], excluding [module] if it depends on itself.
 */


public abstract fun getTransitiveDependents ( module : KtModule ) : Set < KtModule >

/**
 * Returns all direct and indirect dependents of [module], excluding [module] if it depends on itself.
 */


public abstract fun getRefinementDependents ( module : KtModule ) : Set < KtModule >

/**
 * Returns all refinement/depends-on dependents of [module], excluding [module] itself. The result is transitive because refinement
 * dependencies are implicitly transitive.
 */


fun getAsMap ( ) : Map < KtTypeParameterSymbol , KtType >

/**
 * Substitution rules in a form of a `Map<KtTypeParameterSymbol, KtType>`
 */


public fun onModification ( )

/**
 * [onModification] is invoked in a write action before or after global out-of-block modification of all sources.
 *
 * The source code of all source [KtModule]s in the project should be considered modified when this event is received. This includes
 * source files being moved or removed. Thus, all caches related to source code and source files should be invalidated.
 *
 * Library modules (including library sources) do not need to be considered modified, so any caches related to library modules and their
 * contents may be kept.
 *
 * @see KotlinTopics
 */


fun < S > GroupState < S > . getOrNull ( ) : S ?

= if ( exists ( ) ) get ( ) else null

/**
 * (Kotlin-specific)
 * Returns the group state value if it exists, else `null`.
 * This is comparable to [GroupState.getOption], but instead utilises Kotlin's nullability features
 * to get the same result.
 */


operator fun < S > GroupState < S > . getValue ( thisRef : Any ? , property : KProperty < * > ) : S ?

= getOrNull ( )

/**
 * (Kotlin-specific)
 * Allows the group state object to be used as a delegate. Will be `null` if it does not exist.
 *
 * For example:
 * ```kotlin
 * groupedDataset.mapGroupsWithState(GroupStateTimeout.NoTimeout()) { key, values, state: GroupState<Int> ->
 * var s by state
 * ...
 * }
 * ```
 */


operator fun < S > GroupState < S > . setValue ( thisRef : Any ? , property : KProperty < * > , value : S ? ) : Unit

= update ( value )


public fun resolve ( context : ColumnResolutionContext ) : List < ColumnWithPath < C > >

/**
 * Resolves this [ColumnsResolver] as a [List]<[ColumnWithPath]<[C]>>.
 * In many cases this function [transforms][ColumnsResolver.transform] a parent [ColumnsResolver] to reach
 * the current [ColumnsResolver] result.
 */


fun testFailed ( reportTaskPath : String , testTaskPath : String )

{ <EOL> reportHasFailedTests [ reportTaskPath ] = true <EOL> previouslyFailedTestTasks . add ( testTaskPath ) <EOL> }

/**
 * Marks [KotlinTestReport] with [reportTaskPath] as a report containing failed tests during the build.
 * [testTaskPath] is a path of the actual test task with failed tests.
 */


fun hasFailedTests ( path : String ) : Boolean

{ <EOL> return reportHasFailedTests [ path ] ? : false <EOL> }

/**
 * Checks whether [KotlinTestReport] defined by [path] contains any children test tasks that failed during the build
 */


fun reportFailure ( failedTaskPath : String , parentTaskPath : String , failure : Error )

{ <EOL> testTaskSuppressedFailures . computeIfAbsent ( parentTaskPath ) { mutableListOf ( ) } . add ( failedTaskPath to failure ) <EOL> }

/**
 * Reports a test task execution failure (not test failure).
 * @param failedTaskPath is a path of the failed test task
 * @param parentTaskPath is a path of a [KotlinTestReport] that the task reports to
 */


fun getAggregatedTaskFailures ( taskPath : String ) : List < TaskError >

{ <EOL> return testTaskSuppressedFailures [ taskPath ] ? : emptyList ( ) <EOL> }

/**
 * Returns all the test task execution failures (not test failures) related to the [KotlinTestReport] defined by [taskPath]
 */


fun hasTestTaskFailedPreviously ( path : String )

= previouslyFailedTestTasks . remove ( path )

/**
 * Checks whether the test task defined by [path] had failed previously (doesn't matter if it's caused by failed test or any runtime problem).
 * This function is not idempotent as it resets the task's failed state.
 */


public fun ContextView . asCoroutineContext ( ) : ReactorContext

= ReactorContext ( this )

/**
 * Wraps the given [ContextView] into [ReactorContext], so it can be added to the coroutine's context
 * and later used via `coroutineContext[ReactorContext]`.
 */


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun Context . asCoroutineContext ( ) : ReactorContext

= readOnly ( ) . asCoroutineContext ( )


internal fun CoroutineContext . extendReactorContext ( extensions : ContextView ) : CoroutineContext

= <EOL> ( this [ ReactorContext ] ? . context ? . putAll ( extensions ) ? : extensions ) . asCoroutineContext ( )

/**
 * Updates the Reactor context in this [CoroutineContext], adding (or possibly replacing) some values.
 */


public fun TestBase . withVirtualTime ( block : suspend CoroutineScope . ( ) -> Unit )

= runTest { <EOL> withContext ( Dispatchers . Unconfined ) { <EOL> val dispatcher = VirtualTimeDispatcher ( this ) <EOL> withContext ( dispatcher ) { block ( ) } <EOL> checkFinishCall ( allowNotUsingExpect = false ) <EOL> } <EOL> }

/**
 * Runs a test ([TestBase.runTest]) with a virtual time source.
 * This runner has the following constraints:
 * 1) It works only in the event-loop environment and it is relying on it.
 * None of the coroutines should be launched in any dispatcher different from a current
 * 2) Regular tasks always dominate delayed ones. It means that
 * `launch { while(true) yield() }` will block the progress of the delayed tasks
 * 3) [TestBase.finish] should always be invoked.
 * Given all the constraints into account, it is easy to mess up with a test and actually
 * return from [withVirtualTime] before the test is executed completely.
 * To decrease the probability of such error, additional `finish` constraint is added.
 */


override fun FirDeclaration . isPlatformSpecificExported ( ) : Boolean

{ <EOL> if ( this is FirCallableDeclaration && isSubstitutionOrIntersectionOverride ) <EOL> return false <EOL> return ANNOTATIONS_TO_TREAT_AS_EXPORTED . any { hasAnnotation ( it , moduleData . session ) } <EOL> }

/**
 * mimics AbstractKonanDescriptorMangler::DeclarationDescriptor.isPlatformSpecificExport()
 */


internal fun findMacros ( nativeIndex : NativeIndexImpl , compilation : CompilationWithPCH , translationUnits : List < CXTranslationUnit > , headers : Set < CXFile ? > )

{ <EOL> val names = collectMacroNames ( nativeIndex , translationUnits , headers ) <EOL> val macros = expandMacros ( compilation , names , typeConverter = { nativeIndex . convertType ( it ) } ) <EOL> macros . filterIsInstanceTo ( nativeIndex . macroConstants ) <EOL> macros . filterIsInstanceTo ( nativeIndex . wrappedMacros ) <EOL> }

/**
 * Finds all "macro constants" and registers them as [NativeIndex.constants] in given index.
 */


private fun expandMacros ( library : CompilationWithPCH , names : List < String > , typeConverter : TypeConverter ) : List < MacroDef >

{ <EOL> withIndex ( excludeDeclarationsFromPCH = true ) { index -> <EOL> val sourceFile = library . createTempSource ( ) <EOL> val compilerArgs = library . compilerArgs . toMutableList ( ) <EOL> compilerArgs += "<STR_LIT>" <EOL> compilerArgs += "<STR_LIT>" <EOL> val translationUnit = parseTranslationUnit ( index , sourceFile , compilerArgs , options = CXTranslationUnit_DetailedPreprocessingRecord ) <EOL> try { <EOL> val nameToMacroDef = mutableMapOf < String , MacroDef > ( ) <EOL> val unprocessedMacros = names . toMutableList ( ) <EOL> while ( unprocessedMacros . isNotEmpty ( ) ) { <EOL> val processedMacros = <EOL> tryExpandMacros ( library , translationUnit , sourceFile , unprocessedMacros , typeConverter ) <EOL> unprocessedMacros -= ( processedMacros . keys + unprocessedMacros . first ( ) ) <EOL> processedMacros . forEach { ( name , macroDef ) -> <EOL> if ( macroDef != null ) nameToMacroDef [ name ] = macroDef <EOL> } <EOL> } <EOL> return names . mapNotNull { nameToMacroDef [ it ] } <EOL> } finally { <EOL> clang_disposeTranslationUnit ( translationUnit ) <EOL> } <EOL> } <EOL> }

/**
 * For each name expands the macro with this name declared in the library,
 * checking if it gets expanded to a constant expression.
 *
 * Note: in the worst case this method parses the code against the library a lot of times,
 * so it requires library headers precompiled to significantly speed up the parsing and avoid visiting headers' AST.
 *
 * @return the list of constants.
 */


private fun tryExpandMacros ( library : CompilationWithPCH , translationUnit : CXTranslationUnit , sourceFile : File , names : List < String > , typeConverter : TypeConverter ) : Map < String , MacroDef ? >

{ <EOL> reparseWithCodeSnippets ( library , translationUnit , sourceFile , names ) <EOL> val macrosWithErrorsInSnippetFunctionHeader = mutableSetOf < String > ( ) <EOL> val macrosWithErrorsInSnippetFunctionBody = mutableSetOf < String > ( ) <EOL> val preambleSize = library . preambleLines . size <EOL> translationUnit . getErrorLineNumbers ( ) . map { it - preambleSize - <NUM_LIT:1> } . forEach { lineNumber -> <EOL> val index = lineNumber / CODE_SNIPPET_LINES_NUMBER <EOL> if ( index >= <NUM_LIT:0> && index < names . size ) { <EOL> when ( lineNumber % CODE_SNIPPET_LINES_NUMBER ) { <EOL> <NUM_LIT:0> -> macrosWithErrorsInSnippetFunctionHeader += names [ index ] <EOL> <NUM_LIT:1> -> macrosWithErrorsInSnippetFunctionBody += names [ index ] <EOL> else -> { } <EOL> } <EOL> } <EOL> } <EOL> val result = mutableMapOf < String , MacroDef ? > ( ) <EOL> visitChildren ( translationUnit ) { cursor , _ -> <EOL> if ( cursor . kind == CXCursorKind . CXCursor_FunctionDecl ) { <EOL> val functionName = getCursorSpelling ( cursor ) <EOL> if ( functionName . startsWith ( CODE_SNIPPET_FUNCTION_NAME_PREFIX ) ) { <EOL> val macroName = functionName . removePrefix ( CODE_SNIPPET_FUNCTION_NAME_PREFIX ) <EOL> if ( macroName in macrosWithErrorsInSnippetFunctionHeader ) { <EOL> } else { <EOL> result [ macroName ] = if ( macroName in macrosWithErrorsInSnippetFunctionBody ) { <EOL> null <EOL> } else { <EOL> processCodeSnippet ( cursor , macroName , typeConverter ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> CXChildVisitResult . CXChildVisit_Continue <EOL> } <EOL> return result <EOL> }

/**
 * Tries to expand macros [names] defined in [library].
 * Returns the map of successfully processed macros with resulting constant as a value
 * or `null` if the result is not a constant (expression).
 *
 * As a side effect, modifies the [sourceFile] and reparses the [translationUnit].
 */


private fun reparseWithCodeSnippets ( library : CompilationWithPCH , translationUnit : CXTranslationUnit , sourceFile : File , names : List < String > )

{ <EOL> sourceFile . bufferedWriter ( ) . use { writer -> <EOL> writer . appendPreamble ( library ) <EOL> names . forEach { name -> <EOL> val codeSnippetLines = when ( library . language ) { <EOL> Language . C , Language . CPP , Language . OBJECTIVE_C -> <EOL> listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:}>" ) <EOL> } <EOL> assert ( codeSnippetLines . size == CODE_SNIPPET_LINES_NUMBER ) <EOL> codeSnippetLines . forEach { writer . appendLine ( it ) } <EOL> } <EOL> } <EOL> clang_reparseTranslationUnit ( translationUnit , <NUM_LIT:0> , null , CXTranslationUnit_DetailedPreprocessingRecord ) <EOL> }

/**
 * Adds code snippets to be then processed with [processCodeSnippet] to the [sourceFile]
 * and reparses the [translationUnit].
 *
 * - If a code snippet allows extracting the constant value using libclang API, we'll add a [ConstantDef] in the
 * native index and generate a Kotlin constant for it.
 * - If the expression type can be inferred by libclang, we'll add a [WrappedMacroDef] in the native index and
 * generate a bridge for this macro.
 * - Otherwise the macro is skipped.
 */


private fun processCodeSnippet ( functionCursor : CValue < CXCursor > , name : String , typeConverter : TypeConverter ) : MacroDef ?

{ <EOL> val kindsToSkip = setOf ( CXCursorKind . CXCursor_CompoundStmt ) <EOL> var state = VisitorState . EXPECT_NODES_TO_SKIP <EOL> var evalResultOrNull : CXEvalResult ? = null <EOL> var typeOrNull : Type ? = null <EOL> val visitor : CursorVisitor = { cursor , _ -> <EOL> val kind = cursor . kind <EOL> when { <EOL> state == VisitorState . EXPECT_VARIABLE && kind == CXCursorKind . CXCursor_VarDecl -> { <EOL> evalResultOrNull = clang_Cursor_Evaluate ( cursor ) <EOL> state = VisitorState . EXPECT_VARIABLE_VALUE <EOL> CXChildVisitResult . CXChildVisit_Recurse <EOL> } <EOL> state == VisitorState . EXPECT_VARIABLE_VALUE && clang_isExpression ( kind ) != <NUM_LIT:0> -> { <EOL> typeOrNull = typeConverter ( clang_getCursorType ( cursor ) ) <EOL> state = VisitorState . EXPECT_END <EOL> CXChildVisitResult . CXChildVisit_Continue <EOL> } <EOL> state == VisitorState . EXPECT_NODES_TO_SKIP && kind in kindsToSkip -> <EOL> CXChildVisitResult . CXChildVisit_Recurse <EOL> state == VisitorState . EXPECT_NODES_TO_SKIP && kind == CXCursorKind . CXCursor_DeclStmt -> { <EOL> state = VisitorState . EXPECT_VARIABLE <EOL> CXChildVisitResult . CXChildVisit_Recurse <EOL> } <EOL> else -> { <EOL> state = VisitorState . INVALID <EOL> CXChildVisitResult . CXChildVisit_Break <EOL> } <EOL> } <EOL> } <EOL> try { <EOL> visitChildren ( functionCursor , visitor ) <EOL> if ( state != VisitorState . EXPECT_END ) { <EOL> return null <EOL> } <EOL> val type = typeOrNull ! ! <EOL> return if ( evalResultOrNull == null ) { <EOL> when ( type . unwrapTypedefs ( ) ) { <EOL> is PrimitiveType , <EOL> is PointerType , <EOL> is ObjCPointer -> WrappedMacroDef ( name , type ) <EOL> else -> null <EOL> } <EOL> } else { <EOL> val evalResult = evalResultOrNull ! ! <EOL> val evalResultKind = clang_EvalResult_getKind ( evalResult ) <EOL> when ( evalResultKind ) { <EOL> CXEvalResultKind . CXEval_Int -> <EOL> IntegerConstantDef ( name , type , clang_EvalResult_getAsLongLong ( evalResult ) ) <EOL> CXEvalResultKind . CXEval_Float -> <EOL> FloatingConstantDef ( name , type , clang_EvalResult_getAsDouble ( evalResult ) ) <EOL> CXEvalResultKind . CXEval_CFStr , <EOL> CXEvalResultKind . CXEval_ObjCStrLiteral , <EOL> CXEvalResultKind . CXEval_StrLiteral -> <EOL> if ( evalResultKind == CXEvalResultKind . CXEval_StrLiteral && ! type . canonicalIsPointerToChar ( ) ) { <EOL> null <EOL> } else { <EOL> StringConstantDef ( name , type , clang_EvalResult_getAsStr ( evalResult ) ! ! . toKString ( ) ) <EOL> } <EOL> CXEvalResultKind . CXEval_Other , <EOL> CXEvalResultKind . CXEval_UnExposed -> null <EOL> } <EOL> } <EOL> } finally { <EOL> evalResultOrNull ? . let { clang_EvalResult_dispose ( it ) } <EOL> } <EOL> }

/**
 * Checks that [functionCursor] is parsed exactly as expected for the code appended by [reparseWithCodeSnippets],
 * and returns the constant on success.
 */


public fun KtType . asPsiType ( useSitePosition : PsiElement , allowErrorTypes : Boolean , mode : KtTypeMappingMode = KtTypeMappingMode . DEFAULT , isAnnotationMethod : Boolean = false , suppressWildcards : Boolean ? = null , preserveAnnotations : Boolean = true , ) : PsiType ?

= withValidityAssertion { <EOL> analysisSession . psiTypeProvider . asPsiType ( type = this , useSitePosition = useSitePosition , allowErrorTypes = allowErrorTypes , mode = mode , isAnnotationMethod = isAnnotationMethod , suppressWildcards = suppressWildcards , preserveAnnotations = preserveAnnotations , ) <EOL> }

/**
 * Converts the given [KtType] to [PsiType] under [useSitePosition] context.
 *
 * Note: [PsiType] is JVM conception, so this method will return `null` for non-JVM platforms.
 *
 * @receiver type to convert
 *
 * @param useSitePosition is used to determine if the given [KtType] needs to be approximated.
 * For instance, if the given type is local yet available in the same scope of use site,
 * we can still use such a local type.
 * Otherwise, e.g., exposed to public as a return type, the resulting type will be approximated accordingly.
 *
 * @param allowErrorTypes if **false** the result will be null in the case of an error type inside the [type][this].
 * Erroneous types will be replaced with `error.NonExistentClass` type.
 *
 * @param suppressWildcards indicates whether wild cards in type arguments need to be suppressed or not,
 * e.g., according to the annotation on the containing declarations.
 * - `true` means they should be suppressed.
 * - `false` means they should appear.
 * - `null` is no-op by default, i.e., their suppression/appearance is determined by type annotations.
 *
 * @param preserveAnnotations if **true** the result [PsiType] will have converted annotations from the original [type][this]
 */


public fun PsiType . asKtType ( useSitePosition : PsiElement ) : KtType ?

= withValidityAssertion { <EOL> analysisSession . psiTypeProvider . asKtType ( this , useSitePosition ) <EOL> }

/**
 * Converts given [PsiType] to [KtType].
 *
 * [useSitePosition] may be used to clarify how to resolve some parts of [PsiType].
 * For instance, it can be used to collect type parameters and use them during the conversion.
 *
 * @receiver [PsiType] to be converted.
 * @return The converted [KtType], or null if conversion is not possible e.g., [PsiType] is not resolved
 */


private inline fun deserializeIrStatementOrigin ( hasOriginName : Boolean , protoName : ( ) -> Int ) : IrStatementOrigin ?

= <EOL> if ( hasOriginName ) deserializeIrStatementOrigin ( protoName ( ) ) else null

/**
 * This is more compact form of deserializeIrStatementOrigin() that allows writing
 * val origin = deserializeIrStatementOrigin(proto.hasOriginName()) { proto.originName }
 * instead of (as it was before)
 * val origin = if (proto.hasOriginName()) deserializeIrStatementOrigin(proto.originName) else null
 */


private inline fun < reified S : IrSymbol > deserializeTypedSymbol ( code : Long , fallbackSymbolKind : SymbolKind ? , remap : Boolean = true ) : S

= with ( declarationDeserializer ) { <EOL> val symbol = if ( remap ) deserializeIrSymbolAndRemap ( code ) else deserializeIrSymbol ( code ) <EOL> symbol . checkSymbolType ( fallbackSymbolKind ) <EOL> }

/**
 * This function allows to check deserialized symbols. If the deserialized symbol mismatches the symbol kind
 * at the call site in the deserializer then generate and reference another symbol with
 * the same signature. In case PL is off, just throw [IrSymbolTypeMismatchException].
 *
 * Note: [fallbackSymbolKind] must not completely match [S], but it should represent a subclass of [S].
 *
 * Example: [S] is [IrClassifierSymbol] and [fallbackSymbolKind] is [CLASS_SYMBOL],
 * which is only one possible option along with [TYPE_PARAMETER_SYMBOL].
 *
 * Note, that for local IR declarations such as [IrValueDeclaration] [fallbackSymbolKind] can be left null.
 */


{ <EOL> val ( train , test ) = fashionMnist ( ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . init ( ) <EOL> println ( it . kGraph ) <EOL> var accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( it . kGraph ) <EOL> println ( "<STR_LIT>" ) <EOL> it . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE ) <EOL> println ( it . kGraph ) <EOL> accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example shows how to do image classification from scratch using [model] with [BatchNorm] layer, without leveraging pre-trained weights or a pre-made model.
 * We demonstrate the workflow on the FashionMnist classification dataset.
 *
 * It includes:
 * - dataset loading from S3
 * - model compilation
 * - model training
 * - model evaluation
 */


private fun transformUrlToFile ( url : URL )

= url . toURI ( ) . toPath ( ) . toFile ( )

/**
 * Transforms a given URL to a File object with proper handling of escapable characters like whitespace, hashbang.
 *
 * Example: URL containing "some%20path" should be transformed to a File object pointing to "some path"
 */


private fun FirElementWithResolveState . shouldBeResolved ( )

= when ( this ) { <EOL> is FirDeclaration -> shouldBeResolved ( ) <EOL> else -> throwUnexpectedFirElementError ( this ) <EOL> }


@ Suppress ( "<STR_LIT:unused>" ) <EOL> fun registerDisposable ( disposable : PluginDisposable )

{ <EOL> _disposables += disposable <EOL> }

/**
 * Passed [disposable] will be called when the plugin is no longer needed:
 *
 * - In the CLI mode: At the end of the compilation process.
 * - In the IDE mode: When the whole project is closed, or when the module
 * with the corresponding compiler plugin enabled is removed from the project.
 */


@ Test <EOL> fun testOnCompletionBetweenLimitingOperators ( )

= runTest { <EOL> flowOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) <EOL> . zip ( flowOf ( <NUM_LIT:4> , <NUM_LIT:5> ) ) { a , b -> a + b } <EOL> . onCompletion { <EOL> expect ( <NUM_LIT:2> ) <EOL> assertNotNull ( it ) <EOL> } <EOL> . take ( <NUM_LIT:1> ) <EOL> . collect { <EOL> expect ( <NUM_LIT:1> ) <EOL> } <EOL> flowOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) <EOL> . take ( <NUM_LIT:2> ) <EOL> . onCompletion { <EOL> expect ( <NUM_LIT:4> ) <EOL> assertNotNull ( it ) <EOL> } <EOL> . zip ( flowOf ( <NUM_LIT:4> ) ) { a , b -> a + b } <EOL> . collect { <EOL> expect ( <NUM_LIT:3> ) <EOL> } <EOL> flowOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) <EOL> . take ( <NUM_LIT:2> ) <EOL> . onCompletion { <EOL> expect ( <NUM_LIT:5> ) <EOL> assertNotNull ( it ) <EOL> } <EOL> . first ( ) <EOL> flowOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) <EOL> . zip ( flowOf ( <NUM_LIT:4> , <NUM_LIT:5> ) ) { a , b -> a + b } <EOL> . onCompletion { <EOL> expect ( <NUM_LIT:6> ) <EOL> assertNotNull ( it ) <EOL> } <EOL> . first ( ) <EOL> flowOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) <EOL> . take ( <NUM_LIT:2> ) <EOL> . onCompletion { <EOL> expect ( <NUM_LIT:8> ) <EOL> assertNotNull ( it ) <EOL> } <EOL> . take ( <NUM_LIT:1> ) <EOL> . collect { <EOL> expect ( <NUM_LIT:7> ) <EOL> } <EOL> flowOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) <EOL> . zip ( flowOf ( <NUM_LIT:4> , <NUM_LIT:5> ) ) { a , b -> a + b } <EOL> . onCompletion { <EOL> expect ( <NUM_LIT:10> ) <EOL> assertNotNull ( it ) <EOL> } <EOL> . zip ( flowOf ( <NUM_LIT:6> ) ) { a , b -> a + b } <EOL> . collect { <EOL> expect ( <NUM_LIT:9> ) <EOL> } <EOL> finish ( <NUM_LIT:11> ) <EOL> }

/**
 * Tests that the operators that are used to limit the flow (like [take] and [zip]) faithfully propagate the
 * cancellation exception to the original owner.
 */


@ Test <EOL> fun testEmittingElementsAfterCancellation ( )

= runTest { <EOL> assertEquals ( <NUM_LIT:1> , flowOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) . take ( <NUM_LIT:100> ) . onCompletion { emit ( <NUM_LIT:4> ) } . first ( ) ) <EOL> }

/**
 * Tests that emitting new elements after completion doesn't overwrite the old elements.
 */


internal expect fun Double . format ( precision : Int , useGrouping : Boolean = true ) : String

/**
 * Pretty formats a number.
 *
 * The locale must be fixed, so that decimals will be consistently formatted.
 * - `.` - decimal separator
 * - `,` - thousands separator
 */


{ <EOL> }


@ Test <EOL> fun testChecksCorrectChangingStringMetricsVersion ( )

{ <EOL> val actualStringMetricsVersionAndHash = <EOL> Pair ( StringMetrics . VERSION , calculateFileChecksum ( STRING_METRICS_RELATIVE_PATH ) ) <EOL> assertEquals ( STRING_METRICS_EXPECTED_VERSION_AND_HASH , actualStringMetricsVersionAndHash , "<STR_LIT>" + "<STR_LIT>" ) <EOL> }

/**
 * Test checks for that the version of [StringMetrics] was increased after changes in this file
 */


@ Test <EOL> fun testChecksCorrectChangingBooleanMetricsVersion ( )

{ <EOL> val actualBooleanMetricsVersionAndHash = <EOL> Pair ( BooleanMetrics . VERSION , calculateFileChecksum ( BOOLEAN_METRICS_RELATIVE_PATH ) ) <EOL> assertEquals ( BOOLEAN_METRICS_EXPECTED_VERSION_AND_HASH , actualBooleanMetricsVersionAndHash , "<STR_LIT>" + "<STR_LIT>" ) <EOL> }

/**
 * Test checks for that the version of [BooleanMetrics] was increased after changes in this file
 */


@ Test <EOL> fun testChecksCorrectChangingNumericalMetricsVersion ( )

{ <EOL> val actualNumericalMetricsVersionAndHash = <EOL> Pair ( NumericalMetrics . VERSION , calculateFileChecksum ( NUMERICAL_METRICS_RELATIVE_PATH ) ) <EOL> assertEquals ( NUMERICAL_METRICS_EXPECTED_VERSION_AND_HASH , actualNumericalMetricsVersionAndHash , "<STR_LIT>" + "<STR_LIT>" ) <EOL> }

/**
 * Test checks for that the version of [NumericalMetrics] was increased after changes in this file
 */


fun < E > MutableList < E > . offer ( element : E )

= this . add ( element )

/**
 * Let's Walk Through a Maze.
 *
 * Imagine there is a maze whose walls are the big 'O' letters.
 * Now, I stand where a big 'I' stands and some cool prize lies
 * somewhere marked with a '$' sign. Like this:
 *
 * OOOOOOOOOOOOOOOOO
 * O O
 * O$ O O
 * OOOOO O
 * O O
 * O OOOOOOOOOOOOOO
 * O O I O
 * O O
 * OOOOOOOOOOOOOOOOO
 *
 * I want to get the prize, and this program helps me do so as soon
 * as I possibly can by finding a shortest path through the maze.
 */


fun findPath ( maze : Maze ) : List < Pair < Int , Int > > ?

{ <EOL> val previous = HashMap < Pair < Int , Int > , Pair < Int , Int > > ( ) <EOL> val queue = ArrayDeque < Pair < Int , Int > > ( ) <EOL> val visited = HashSet < Pair < Int , Int > > ( ) <EOL> queue . offer ( maze . start ) <EOL> visited . add ( maze . start ) <EOL> while ( ! queue . isEmpty ( ) ) { <EOL> val cell = queue . poll ( ) <EOL> if ( cell == maze . end ) break <EOL> for ( newCell in maze . neighbors ( cell . first , cell . second ) ) { <EOL> if ( newCell in visited ) continue <EOL> previous [ newCell ] = cell <EOL> queue . offer ( newCell ) <EOL> visited . add ( cell ) <EOL> } <EOL> } <EOL> if ( previous [ maze . end ] == null ) return null <EOL> val path = ArrayList < Pair < Int , Int > > ( ) <EOL> var current = previous [ maze . end ] <EOL> while ( current != maze . start ) { <EOL> path . add ( <NUM_LIT:0> , current ! ! ) <EOL> current = previous [ current ] <EOL> } <EOL> return path <EOL> }

/**
 * This function looks for a path from max.start to maze.end through
 * free space (a path does not go through walls). One can move only
 * straightly up, down, left or right, no diagonal moves allowed.
 */


fun Maze . neighbors ( i : Int , j : Int ) : List < Pair < Int , Int > >

{ <EOL> val result = ArrayList < Pair < Int , Int > > ( ) <EOL> addIfFree ( i - <NUM_LIT:1> , j , result ) <EOL> addIfFree ( i , j - <NUM_LIT:1> , result ) <EOL> addIfFree ( i + <NUM_LIT:1> , j , result ) <EOL> addIfFree ( i , j + <NUM_LIT:1> , result ) <EOL> return result <EOL> }

/**
 * Find neighbors of the (i, j) cell that are not walls
 */


{ <EOL> printMaze ( "<STR_LIT>" ) <EOL> printMaze ( "<STR_LIT>" ) <EOL> printMaze ( """<STR_LIT>""" . trimIndent ( ) ) <EOL> printMaze ( """<STR_LIT>""" . trimIndent ( ) ) <EOL> printMaze ( """<STR_LIT>""" . trimIndent ( ) ) <EOL> }


{ <EOL> val lines = s . split ( "<STR_LIT:\n>" ) ! ! <EOL> val w = lines . maxWithOrNull ( Comparator { o1 , o2 -> <EOL> val l1 : Int = o1 ? . length ? : <NUM_LIT:0> <EOL> val l2 = o2 ? . length ? : <NUM_LIT:0> <EOL> l1 - l2 <EOL> } ) ! ! <EOL> val data = Array < Array < Boolean > > ( lines . size ) { Array < Boolean > ( w . length ) { false } } <EOL> var start : Pair < Int , Int > ? = null <EOL> var end : Pair < Int , Int > ? = null <EOL> for ( line in lines . indices ) { <EOL> for ( x in lines [ line ] . indices ) { <EOL> val c = lines [ line ] ! ! [ x ] <EOL> data [ line ] [ x ] = c == '<CHAR_LIT>' <EOL> when ( c ) { <EOL> '<CHAR_LIT>' -> start = Pair ( line , x ) <EOL> '<CHAR_LIT:$>' -> end = Pair ( line , x ) <EOL> else -> { <EOL> } <EOL> } <EOL> } <EOL> } <EOL> if ( start == null ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> if ( end == null ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> return Maze ( w . length , lines . size , data , start ! ! , end ! ! ) <EOL> }

/**
 * A maze is encoded in the string s: the big 'O' letters are walls.
 * I stand where a big 'I' stands and the prize is marked with
 * a '$' sign.
 *
 * Example:
 *
 * OOOOOOOOOOOOOOOOO
 * O O
 * O$ O O
 * OOOOO O
 * O O
 * O OOOOOOOOOOOOOO
 * O O I O
 * O O
 * OOOOOOOOOOOOOOOOO
 */


private fun < A , B > matchSymmetricallyByNames ( containerA : NamedDomainObjectCollection < out A > , containerB : NamedDomainObjectCollection < out B > , whenMatched : ( A , B ) -> Unit )

{ <EOL> val matchedNames = mutableSetOf < String > ( ) <EOL> fun < T , R > NamedDomainObjectCollection < T > . matchAllWith ( other : NamedDomainObjectCollection < R > , match : ( T , R ) -> Unit ) { <EOL> this@matchAllWith . all { item -> <EOL> val itemName = this@matchAllWith . namer . determineName ( item ) <EOL> if ( itemName !in matchedNames ) { <EOL> val otherItem = other . findByName ( itemName ) <EOL> if ( otherItem != null ) { <EOL> matchedNames += itemName <EOL> match ( item , otherItem ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> containerA . matchAllWith ( containerB ) { a , b -> whenMatched ( a , b ) } <EOL> containerB . matchAllWith ( containerA ) { b , a -> whenMatched ( a , b ) } <EOL> }

/**
 * Applies [whenMatched] to pairs of items with the same name in [containerA] and [containerB],
 * regardless of the order in which they are added to the containers.
 */


{ <EOL> target . gradle . checkVersion ( ) <EOL> val context = prepare ( target ) <EOL> target . afterEvaluate { <EOL> context . prepareMerging ( ) <EOL> } <EOL> ProvidedVariantsLocator ( target ) { provided -> <EOL> context . finalizing ( provided ) <EOL> } <EOL> }

/**
 * Apply plugin to a given project.
 */


{ <EOL> val current = SemVer . ofVariableOrNull ( gradleVersion ) ! ! <EOL> val min = SemVer . ofVariableOrNull ( MINIMUM_GRADLE_VERSION ) ! ! <EOL> if ( current < min ) throw GradleException ( "<STR_LIT>" + "<STR_LIT>" ) <EOL> }

/**
 * Check supported Gradle versions.
 */


fun mdFile ( pathFromProjectRoot : String , fillFile : MarkdownTestDataFile . ( ) -> Unit )

/**
 * Creates an `.md` (Markdown) file.
 *
 * If you want to use this file for module and package documentation, it must be included
 * in [TestDokkaConfiguration.includes] or [TestDokkaSourceSet.includes].
 *
 * @param pathFromProjectRoot path relative to the root of the test project. Must begin
 * with `/` to not confuse it with relative paths. Example: `/docs/core-package.md`
 */


fun < T > enter ( part : String , block : ( ) -> T ) : T

{ <EOL> val prev = current <EOL> val prevSibling = sibling <EOL> val prevParent = parent <EOL> val next = PathPartInfo ( part ) <EOL> try { <EOL> when { <EOL> prevParent != null && prevSibling == null -> { <EOL> next . parent = prevParent <EOL> sibling = next <EOL> parent = null <EOL> } <EOL> prevParent != null && prevSibling != null -> { <EOL> next . prev = prevSibling <EOL> sibling = next <EOL> parent = null <EOL> } <EOL> else -> { <EOL> next . parent = prev <EOL> parent = null <EOL> } <EOL> } <EOL> current = next <EOL> return block ( ) <EOL> } finally { <EOL> current = prev <EOL> parent = prevParent <EOL> } <EOL> }

/**
 * Enter into a new scope with path part [part].
 */


fun < T > siblings ( block : ( ) -> T ) : T

{ <EOL> if ( parent != null ) { <EOL> return block ( ) <EOL> } <EOL> val prevSibling = sibling <EOL> val prevParent = parent <EOL> val prevCurrent = current <EOL> try { <EOL> parent = current <EOL> sibling = null <EOL> return block ( ) <EOL> } finally { <EOL> parent = prevParent <EOL> sibling = prevSibling <EOL> current = prevCurrent <EOL> } <EOL> }

/**
 * Inside this block, treat all entered path parts as siblings of the current path part.
 */


fun < T > siblings ( part : String , block : ( ) -> T ) : T

= enter ( part ) { siblings ( block ) }

/**
 * Enter into a new scope with path part [part] and assume entered paths to be children of
 * that path.
 *
 * This is shorthand for `enter(part) { siblings(block) } }`.
 */


fun < T > root ( keys : MutableSet < String > = mutableSetOf ( ) , block : ( ) -> T ) : T

{ <EOL> val prevKeys = this . keys <EOL> val prevCurrent = current <EOL> val prevParent = parent <EOL> val prevSibling = sibling <EOL> try { <EOL> this . keys = keys <EOL> current = <EOL> PathPartInfo . ROOT <EOL> parent = null <EOL> sibling = null <EOL> return siblings ( block ) <EOL> } finally { <EOL> this . keys = prevKeys <EOL> current = prevCurrent <EOL> parent = prevParent <EOL> sibling = prevSibling <EOL> } <EOL> }

/**
 * This API is meant to allow for a sub-hierarchy of the tree to be treated as its own scope.
 * This will use the provided [keys] Set as the container for keys that are built while in
 * this scope. Inside of this scope, the previous scope will be completely ignored.
 */


fun buildPath ( prefix : String , pathSeparator : String = "<STR_LIT:/>" , siblingSeparator : String = "<STR_LIT::>" ) : Pair < String , Boolean >

{ <EOL> return buildString { <EOL> append ( prefix ) <EOL> current . print ( this , pathSeparator , siblingSeparator ) <EOL> } . let { <EOL> it to keys . add ( it ) <EOL> } <EOL> }

/**
 * Build a path at the current position in the tree.
 *
 * @param prefix A string to prefix the path with
 * @param pathSeparator The string used to separate parts of the path
 * @param siblingSeparator When duplicate siblings are found an incrementing index is used to
 * make the path unique. This string will be used to separate the path part from the
 * incrementing index.
 *
 * @return A pair with `first` being the built key, and `second` being whether or not the key
 * was absent in the dictionary of already built keys. If `second` is false, this key is a
 * duplicate.
 */


private fun classDeclaredInUnexpectedPosition ( classOrObject : KtClassOrObject ) : Boolean

{ <EOL> if ( classOrObject is KtObjectDeclaration ) return false <EOL> val classParent = classOrObject . parent <EOL> return classParent !is KtBlockExpression && <EOL> classParent !is KtDeclarationContainer <EOL> }

/**
 * If class is declared in some strange context (for example, in expression like `10 < class A`),
 * we don't want to try to build a light class for it.
 *
 * The expression itself is incorrect and won't compile, but the parser is able the parse the class nonetheless.
 *
 * This does not concern objects, since object literals are expressions and can be used almost anywhere.
 */


inline fun Executor . runProcess ( executableAbsolutePath : String , vararg args : String , block : ExecuteRequest . ( ) -> Unit = { } , ) : RunProcessResult

{ <EOL> ByteArrayOutputStream ( ) . use { stdout -> <EOL> ByteArrayOutputStream ( ) . use { stderr -> <EOL> val request = ExecuteRequest ( executableAbsolutePath ) . apply { <EOL> this . args . addAll ( args ) <EOL> this . stdout = stdout <EOL> this . stderr = stderr <EOL> this . workingDirectory = File ( "<STR_LIT>" ) . absoluteFile <EOL> this . block ( ) <EOL> } <EOL> val response = this . execute ( request ) <EOL> val result = RunProcessResult ( executionTime = response . executionTime , stdout = stdout . toString ( "<STR_LIT>" ) . trim ( ) , stderr = stderr . toString ( "<STR_LIT>" ) . trim ( ) , ) <EOL> try { <EOL> response . assertSuccess ( ) <EOL> } catch ( e : IllegalStateException ) { <EOL> throw RunProcessException ( e . message ! ! , result , response . exitCode ) <EOL> } <EOL> return result <EOL> } <EOL> } <EOL> }

/**
 * Run [executableAbsolutePath] with [Executor] using current process' working directory with [args] and capture the full output.
 *
 * A simplified version of [Executor.execute].
 *
 * @param executableAbsolutePath Path to the executable
 * @param args Command line args
 * @param block optional block to additionally customize [ExecuteRequest]
 *
 * @throws RunProcessException if the process has failed or timed out.
 */


inline fun runProcess ( executableAbsolutePath : String , vararg args : String , block : ExecuteRequest . ( ) -> Unit = { } )

= <EOL> HostExecutor ( ) . runProcess ( executableAbsolutePath , * args , block = block )

/**
 * Run [executableAbsolutePath] on host using current process' working directory with [args] and capture the full output.
 *
 * A simplified version of [HostExecutor.execute].
 *
 * @param executableAbsolutePath Path to the executable
 * @param args Command line args
 * @param block optional block to additionally customize [ExecuteRequest]
 *
 * @throws RunProcessException if the process has failed or timed out.
 */


internal fun resolveKdocFqName ( analysisSession : KtAnalysisSession , selectedFqName : FqName , fullFqName : FqName , contextElement : KtElement , ) : Collection < KtSymbol >

{ <EOL> with ( analysisSession ) { <EOL> val fullSymbolsResolved = resolveKdocFqName ( fullFqName , contextElement ) <EOL> if ( selectedFqName == fullFqName ) return fullSymbolsResolved . mapTo ( mutableSetOf ( ) ) { it . symbol } <EOL> if ( fullSymbolsResolved . isEmpty ( ) ) { <EOL> val parent = fullFqName . parent ( ) <EOL> return resolveKdocFqName ( analysisSession , selectedFqName , parent , contextElement ) <EOL> } <EOL> val goBackSteps = fullFqName . pathSegments ( ) . size - selectedFqName . pathSegments ( ) . size <EOL> check ( goBackSteps > <NUM_LIT:0> ) { <EOL> "<STR_LIT>" <EOL> } <EOL> return fullSymbolsResolved . mapNotNullTo ( mutableSetOf ( ) ) { findParentSymbol ( it , goBackSteps , selectedFqName ) } <EOL> } <EOL> }

/**
 * Resolves the [selectedFqName] of KDoc
 *
 * To properly resolve qualifier parts in the middle,
 * we need to resolve the whole qualifier to understand which parts of the qualifier are package or class qualifiers.
 * And then we will be able to resolve the qualifier selected by the user to the proper class, package or callable.
 *
 * It's possible that the whole qualifier is invalid, in this case we still want to resolve our [selectedFqName].
 * To do this, we are trying to resolve the whole qualifier until we succeed.
 *
 * @param selectedFqName the selected fully qualified name of the KDoc
 * @param fullFqName the whole fully qualified name of the KDoc
 * @param contextElement the context element in which the KDoc is defined
 *
 * @return the collection of KtSymbol(s) resolved from the fully qualified name
 * based on the selected FqName and context element
 */


private fun KtAnalysisSession . findParentSymbol ( resolveResult : ResolveResult , goBackSteps : Int , selectedFqName : FqName ) : KtSymbol ?

{ <EOL> return if ( resolveResult . receiverClassReference != null ) { <EOL> findParentSymbol ( resolveResult . receiverClassReference , goBackSteps - <NUM_LIT:1> , selectedFqName ) <EOL> } else { <EOL> findParentSymbol ( resolveResult . symbol , goBackSteps , selectedFqName ) <EOL> } <EOL> }

/**
 * Finds the parent symbol of the given [ResolveResult] by traversing back up the symbol hierarchy a [goBackSteps] steps,
 * or until the containing class or object symbol is found.
 *
 * Knows about the [ResolveResult.receiverClassReference] field and uses it in case it's not empty.
 */


private fun KtAnalysisSession . findParentSymbol ( symbol : KtSymbol , goBackSteps : Int , selectedFqName : FqName ) : KtSymbol ?

{ <EOL> if ( symbol !is KtDeclarationSymbol && symbol !is KtPackageSymbol ) return null <EOL> if ( symbol is KtDeclarationSymbol ) { <EOL> goToNthParent ( symbol , goBackSteps ) ? . let { return it } <EOL> } <EOL> return getPackageSymbolIfPackageExists ( selectedFqName ) <EOL> }

/**
 * Finds the parent symbol of the given KtSymbol by traversing back up the symbol hierarchy a certain number of steps,
 * or until the containing class or object symbol is found.
 *
 * @param symbol The KtSymbol whose parent symbol needs to be found.
 * @param goBackSteps The number of steps to go back up the symbol hierarchy.
 * @param selectedFqName The fully qualified name of the selected package.
 * @return The [goBackSteps]-th parent [KtSymbol]
 */


private fun KtAnalysisSession . goToNthParent ( symbol : KtDeclarationSymbol , steps : Int ) : KtDeclarationSymbol ?

{ <EOL> var currentSymbol = symbol <EOL> repeat ( steps ) { <EOL> currentSymbol = currentSymbol . getContainingSymbol ( ) as? KtClassOrObjectSymbol ? : return null <EOL> } <EOL> return currentSymbol <EOL> }

/**
 * N.B. Works only for [KtClassOrObjectSymbol] parents chain.
 */


private fun KtAnalysisSession . getSymbolsFromParentMemberScopes ( fqName : FqName , contextElement : KtElement ) : Collection < KtSymbol >

{ <EOL> val declaration = PsiTreeUtil . getContextOfType ( contextElement , KtDeclaration :: class . java , false ) ? : return emptyList ( ) <EOL> for ( ktDeclaration in declaration . parentsOfType < KtDeclaration > ( withSelf = true ) ) { <EOL> if ( fqName . pathSegments ( ) . size == <NUM_LIT:1> ) { <EOL> getSymbolsFromDeclaration ( fqName . shortName ( ) , ktDeclaration ) . ifNotEmpty { return this } <EOL> } <EOL> if ( ktDeclaration is KtClassOrObject ) { <EOL> val symbol = ktDeclaration . getClassOrObjectSymbol ( ) ? : continue <EOL> val scope = getCompositeCombinedMemberAndCompanionObjectScope ( symbol ) <EOL> val symbolsFromScope = getSymbolsFromMemberScope ( fqName , scope ) <EOL> if ( symbolsFromScope . isNotEmpty ( ) ) return symbolsFromScope <EOL> } <EOL> } <EOL> return emptyList ( ) <EOL> }

/**
 * Returns the [KtSymbol]s called [fqName] found in the member scope and companion object's member scope of the [KtDeclaration]s that
 * contain the [contextElement].
 *
 * If [fqName] has two or more segments, e.g. `Foo.bar`, the member and companion object scope of the containing [KtDeclaration] will be
 * queried for a class `Foo` first, and then that class `Foo` will be queried for the member `bar` by short name.
 */


private fun KtAnalysisSession . getTypeQualifiedExtensions ( fqName : FqName , contextElement : KtElement ) : Collection < ResolveResult >

{ <EOL> if ( fqName . isRoot ) return emptyList ( ) <EOL> val extensionName = fqName . shortName ( ) <EOL> val receiverTypeName = fqName . parent ( ) <EOL> if ( receiverTypeName . isRoot ) return emptyList ( ) <EOL> val possibleExtensions = getExtensionCallableSymbolsByShortName ( extensionName , contextElement ) <EOL> if ( possibleExtensions . isEmpty ( ) ) return emptyList ( ) <EOL> val possibleReceivers = getReceiverTypeCandidates ( receiverTypeName , contextElement ) <EOL> return possibleReceivers . flatMap { receiverClassSymbol -> <EOL> val receiverType = buildClassType ( receiverClassSymbol ) <EOL> val applicableExtensions = possibleExtensions . filter { canBeReferencedAsExtensionOn ( it , receiverType ) } <EOL> applicableExtensions . map { it . toResolveResult ( receiverClassReference = receiverClassSymbol ) } <EOL> } <EOL> }

/**
 * Tries to resolve [fqName] into available extension callables (functions or properties)
 * prefixed with a suitable extension receiver type (like in `Foo.bar`, or `foo.Foo.bar`).
 *
 * Relies on the fact that in such references only the last qualifier refers to the
 * actual extension callable, and the part before that refers to the receiver type (either fully
 * or partially qualified).
 *
 * For example, `foo.Foo.bar` may only refer to the extension callable `bar` with
 * a `foo.Foo` receiver type, and this function will only look for such combinations.
 *
 * N.B. This function only searches for extension callables qualified by receiver types!
 * It does not try to resolve fully qualified or member functions, because they are dealt
 * with by the other parts of [KDocReferenceResolver].
 */


private fun KtAnalysisSession . canBeReferencedAsExtensionOn ( symbol : KtCallableSymbol , actualReceiverType : KtType ) : Boolean

{ <EOL> val extensionReceiverType = symbol . receiverParameter ? . type ? : return false <EOL> return isPossiblySuperTypeOf ( extensionReceiverType , actualReceiverType ) <EOL> }

/**
 * Returns true if we consider that [this] extension function prefixed with [actualReceiverType] in
 * a KDoc reference should be considered as legal and resolved, and false otherwise.
 *
 * This is **not** an actual type check, it is just an opinionated approximation.
 * The main guideline was K1 KDoc resolve.
 *
 * This check might change in the future, as Dokka team advances with KDoc rules.
 */


private fun KtAnalysisSession . isPossiblySuperTypeOf ( type : KtType , actualReceiverType : KtType ) : Boolean

{ <EOL> if ( actualReceiverType is KtTypeParameterType ) return false <EOL> if ( type is KtTypeParameterType ) { <EOL> return type . symbol . upperBounds . all { isPossiblySuperTypeOf ( it , actualReceiverType ) } <EOL> } <EOL> val receiverExpanded = actualReceiverType . expandedClassSymbol <EOL> val expectedExpanded = type . expandedClassSymbol <EOL> if ( receiverExpanded != null && receiverExpanded == expectedExpanded ) { <EOL> return true <EOL> } <EOL> return actualReceiverType . isSubTypeOf ( type ) <EOL> }

/**
 * Same constraints as in [canBeReferencedAsExtensionOn].
 *
 * For a similar function in the `intellij` repository, see `isPossiblySubTypeOf`.
 */


public fun ColumnsResolver < * > . isSingleColumnWithGroup ( cols : List < ColumnWithPath < * > > ) : Boolean

= <EOL> isSingleColumn ( ) && cols . singleOrNull ( ) ? . isColumnGroup ( ) == true

/**
 * Returns true if [this] is a [SingleColumn] and [cols] consists of a single column group.
 */


{ <EOL> val templateGroups = sequenceOf < TemplateGroup > ( Elements , Filtering , Ordering , ArrayOps , Snapshots , Mapping , SetOps , Aggregates , Guards , Generators , StringJoinOps , SequenceOps , RangeOps , Numeric , ComparableOps ) <EOL> val targetBaseDirs = mutableMapOf < KotlinTarget , File > ( ) <EOL> when ( args . size ) { <EOL> <NUM_LIT:1> -> { <EOL> val baseDir = File ( args . first ( ) ) <EOL> targetBaseDirs [ KotlinTarget . Common ] = baseDir . resolveExistingDir ( "<STR_LIT>" ) <EOL> targetBaseDirs [ KotlinTarget . JVM ] = baseDir . resolveExistingDir ( "<STR_LIT>" ) <EOL> targetBaseDirs [ KotlinTarget . JS ] = baseDir . resolveExistingDir ( "<STR_LIT>" ) <EOL> targetBaseDirs [ KotlinTarget . WASM ] = baseDir . resolveExistingDir ( "<STR_LIT>" ) <EOL> targetBaseDirs [ KotlinTarget . Native ] = baseDir . resolveExistingDir ( "<STR_LIT>" ) <EOL> } <EOL> else -> { <EOL> println ( """<STR_LIT>""" ) <EOL> exitProcess ( <NUM_LIT:1> ) <EOL> } <EOL> } <EOL> templateGroups . groupByFileAndWrite ( targetsToGenerate = targetBaseDirs . keys ) { ( target , source ) -> <EOL> val targetDir = targetBaseDirs [ target ] ? : error ( "<STR_LIT>" ) <EOL> val platformSuffix = when ( val platform = target . platform ) { <EOL> Platform . Common -> "<STR_LIT>" <EOL> Platform . Native -> if ( target . backend == Backend . Wasm ) "<STR_LIT>" else "<STR_LIT>" <EOL> else -> platform . name . lowercase ( ) . capitalize ( ) <EOL> } <EOL> targetDir . resolve ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Generates methods in the standard library which are mostly identical
 * but just using a different input kind.
 *
 * Kinda like mimicking source macros here, but this avoids the inefficiency of type conversions
 * at runtime.
 */


{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CVnoTop . VGG16 ( inputShape = intArrayOf ( IMAGE_SIZE , IMAGE_SIZE , <NUM_LIT:3> ) ) <EOL> val model = modelHub . loadModel ( modelType ) <EOL> val layers = mutableListOf < Layer > ( ) <EOL> layers . addAll ( model . layers ) <EOL> layers . add ( Flatten ( name = "<STR_LIT>" , ) ) <EOL> layers . add ( Dense ( name = "<STR_LIT>" , kernelInitializer = HeNormal ( ) , biasInitializer = HeNormal ( ) , outputSize = <NUM_LIT> , activation = Activations . Relu , ) ) <EOL> layers . add ( Dense ( name = "<STR_LIT>" , kernelInitializer = HeNormal ( ) , biasInitializer = HeNormal ( ) , outputSize = <NUM_LIT:2> , activation = Activations . Linear ) ) <EOL> val newModel = Sequential . of ( layers ) <EOL> val dataset = OnFlyImageDataset . create ( File ( dogsCatsSmallDatasetPath ( ) ) , FromFolders ( mapping = mapOf ( "<STR_LIT>" to <NUM_LIT:0> , "<STR_LIT>" to <NUM_LIT:1> ) ) , modelType . createPreprocessing ( newModel ) ) . shuffle ( ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> newModel . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> it . loadWeightsForFrozenLayers ( hdfFile ) <EOL> it . printSummary ( ) <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 VGG'16 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, 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.
 *
 * @see
 * Very Deep Convolutional Networks for Large-Scale Image Recognition (ICLR 2015).
 * @see
 * Detailed description of VGG'16 model and an approach to build it in Keras.
 */


= vgg16noTopAdditionalTraining ( )


fun < R > withDummyApplication ( action : ( ) -> R ) : R

{ <EOL> val previousApplication = ApplicationManager . getApplication ( ) <EOL> val disposable = Disposer . newDisposable ( "<STR_LIT>" ) <EOL> try { <EOL> MockApplication . setUp ( disposable ) <EOL> return action ( ) <EOL> } finally { <EOL> Disposer . dispose ( disposable ) <EOL> resetApplicationToNull ( previousApplication ) <EOL> require ( ApplicationManager . getApplication ( ) === previousApplication ) { <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> }

/**
 * Executes [action] with a dummy application available via [ApplicationManager.getApplication]. This function should **only** be used if
 * an application is needed to avoid null pointer exceptions from [ApplicationManager.getApplication] when used in simple situations. Do not
 * use this function if you need a properly set up application and project.
 */


fun RegisteredDirectives . ignoreExceptionIfIgnoreDirectivePresent ( ignoreDirective : Directive , action : ( ) -> Unit )

{ <EOL> var exception : Throwable ? = null <EOL> try { <EOL> action ( ) <EOL> } catch ( e : Throwable ) { <EOL> exception = e <EOL> } <EOL> if ( ignoreDirective in this ) { <EOL> if ( exception != null ) return <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> if ( exception != null ) { <EOL> throw exception <EOL> } <EOL> }

/**
 * [AfterAnalysisChecker][org.jetbrains.kotlin.test.model.AfterAnalysisChecker] should be the preferred option
 */


fun < T , R > Collection < T > . singleOrZeroValue ( transformer : ( T ) -> R ? , ambiguityValueRenderer : ( R ) -> String , ) : R ?

{ <EOL> val newCollection = mapNotNull ( transformer ) <EOL> return when ( newCollection . size ) { <EOL> <NUM_LIT:0> -> null <EOL> <NUM_LIT:1> -> newCollection . single ( ) <EOL> else -> error ( buildString { <EOL> appendLine ( "<STR_LIT>" ) <EOL> newCollection . joinTo ( this , separator = "<STR_LIT:\n>" , transform = ambiguityValueRenderer ) <EOL> } ) <EOL> } <EOL> }

/**
 * Transforms [this] collection with [transformer] and return single or null value. Throws [error] in the case of more than one element.
 */


public fun KtType . mapTypeToJvmType ( mode : TypeMappingMode = TypeMappingMode . DEFAULT ) : Type

= <EOL> withValidityAssertion { analysisSession . jvmTypeMapper . mapTypeToJvmType ( this , mode ) }

/**
 * Create ASM JVM type by corresponding KtType
 *
 * @see TypeMappingMode
 */


fun T . write ( parcel : Parcel , flags : Int )

/**
 * Writes the [T] instance state to the [parcel].
 */


fun create ( parcel : Parcel ) : T

/**
 * Reads the [T] instance state from the [parcel], constructs the new [T] instance and returns it.
 */


fun newArray ( size : Int ) : Array < T >

{ <EOL> throw NotImplementedError ( "<STR_LIT>" ) <EOL> }

/**
 * Returns a new [Array]<T> with the given array [size].
 */


@ ExperimentalBCVApi <EOL> public fun KLibDumpFilters ( builderAction : KlibDumpFilters . Builder . ( ) -> Unit ) : KlibDumpFilters

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

/**
 * Builds a new [KlibDumpFilters] instance by invoking a [builderAction] on a temporary
 * [KlibDumpFilters.Builder] instance and then converting it into filters.
 *
 * Supplied [KlibDumpFilters.Builder] is valid only during the scope of [builderAction] execution.
 */


fun unreachableBranch ( argument : Any ? ) : Nothing

{ <EOL> error ( "<STR_LIT>" ) <EOL> }

/**
 * Use this function to indicate that some when branch is semantically unreachable
 */


fun < T , A : Appendable > Iterable < T > . joinToWithBuffer ( buffer : A , separator : CharSequence = "<STR_LIT:U+002CU+0020>" , prefix : CharSequence = "<STR_LIT>" , postfix : CharSequence = "<STR_LIT>" , limit : Int = - <NUM_LIT:1> , truncated : CharSequence = "<STR_LIT:...>" , appendElement : A . ( T ) -> Unit , ) : A

{ <EOL> buffer . append ( prefix ) <EOL> var count = <NUM_LIT:0> <EOL> for ( element in this ) { <EOL> if ( ++ count > <NUM_LIT:1> ) buffer . append ( separator ) <EOL> if ( limit < <NUM_LIT:0> || count <= limit ) { <EOL> buffer . appendElement ( element ) <EOL> } else break <EOL> } <EOL> if ( limit in <NUM_LIT:0> ..< count ) buffer . append ( truncated ) <EOL> buffer . append ( postfix ) <EOL> return buffer <EOL> }

/**
 * Calls [appendElement] on [buffer] for all the elements, also appending [separator] between them and using the given [prefix]
 * and [postfix] if supplied.
 *
 * If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
 * elements will be appended, followed by the [truncated] string (which defaults to "...").
 */


{ <EOL> val rawDirective = parseDirective ( line ) ? : return false <EOL> val parsedDirective = convertToRegisteredDirective ( rawDirective ) ? : return false <EOL> addParsedDirective ( parsedDirective ) <EOL> return true <EOL> }

/**
 * returns true means that line contain directive
 */


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

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

/** Returns a buffered reader wrapping this Reader, or this Reader itself if it is already buffered. */


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

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

/** Returns a buffered writer wrapping this Writer, or this Writer itself if it is already buffered. */


public fun Reader . forEachLine ( action : ( String ) -> Unit ) : Unit

= useLines { it . forEach ( action ) }

/**
 * Iterates through each line of this reader, calls [action] for each line read
 * and closes the [Reader] when it's completed.
 *
 * @param action function to process file lines.
 */


public fun Reader . readLines ( ) : List < String >

{ <EOL> val result = arrayListOf < String > ( ) <EOL> forEachLine { result . add ( it ) } <EOL> return result <EOL> }

/**
 * Reads this reader content as a list of lines.
 *
 * Do not use this function for huge files.
 */


public inline fun < T > Reader . useLines ( block : ( Sequence < String > ) -> T ) : T

{ <EOL> contract { <EOL> callsInPlace ( block , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> return buffered ( ) . use { block ( it . lineSequence ( ) ) } <EOL> }

/**
 * Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once
 * the processing is complete.
 * @return the value returned by [block].
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun String . reader ( ) : StringReader

= StringReader ( this )

/** Creates a new reader for the string. */


public fun BufferedReader . lineSequence ( ) : Sequence < String >

= LinesSequence ( this ) . constrainOnce ( )

/**
 * Returns a sequence of corresponding file lines.
 *
 * *Note*: the caller must close the underlying `BufferedReader`
 * when the iteration is finished, as the user may not complete the iteration loop (e.g. using a method like find() or any() on the iterator
 * may terminate the iteration early).
 *
 * We suggest you try the method [useLines] instead which closes the stream when the processing is complete.
 *
 * @return a sequence of corresponding file lines. The sequence returned can be iterated only once.
 */


public fun Reader . readText ( ) : String

{ <EOL> val buffer = StringWriter ( ) <EOL> copyTo ( buffer ) <EOL> return buffer . toString ( ) <EOL> }

/**
 * Reads this reader completely as a String.
 *
 * *Note*: It is the caller's responsibility to close this reader.
 *
 * @return the string with corresponding file content.
 */


public fun Reader . copyTo ( out : Writer , bufferSize : Int = DEFAULT_BUFFER_SIZE ) : Long

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

/**
 * Copies this reader to the given [out] writer, returning the number of characters copied.
 *
 * **Note** it is the caller's responsibility to close both of these resources.
 *
 * @param out writer to write to.
 * @param bufferSize size of character buffer to use in process.
 * @return number of characters copied.
 */


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

= readBytes ( ) . toString ( charset )

/**
 * Reads the entire content of this URL as a String using UTF-8 or the specified [charset].
 *
 * This method is not recommended on huge files.
 *
 * @param charset a character set to use.
 * @return a string with this URL entire content.
 */


public fun URL . readBytes ( ) : ByteArray

= openStream ( ) . use { it . readBytes ( ) }

/**
 * Reads the entire content of the URL as byte array.
 *
 * This method is not recommended on huge files.
 *
 * @return a byte array with this URL entire content.
 */


override fun resolveAllSupertypesForOuterClass ( outerClass : FirClass )

{ <EOL> if ( outerClass !in visitedElements ) { <EOL> outerClass . asResolveTarget ( ) ? . let { resolveTarget -> <EOL> resolveToSupertypePhase ( resolveTarget ) <EOL> } <EOL> LLFirSupertypeLazyResolver . checkIsResolved ( outerClass ) <EOL> } <EOL> }

/**
 * We can do nothing here because at a call moment we've already resolved [outerClass]
 * because we resolve classes from top to down
 */


private inline fun < T : FirClassLikeDeclaration , S > performResolve ( declaration : T , superTypeRefsForTransformation : ( ) -> S , resolver : ( S ) -> List < FirResolvedTypeRef > , crossinline superTypeUpdater : ( List < FirTypeRef > ) -> Unit , )

{ <EOL> if ( declaration . resolvePhase >= resolverPhase ) return <EOL> declaration . lazyResolveToPhase ( resolverPhase . previous ) <EOL> var superTypeRefs : S ? = null <EOL> withReadLock ( declaration ) { <EOL> superTypeRefs = superTypeRefsForTransformation ( ) <EOL> } <EOL> if ( superTypeRefs == null ) return <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> val resolvedSuperTypeRefs = resolver ( superTypeRefs as S ) <EOL> val status = supertypeComputationSession . getSupertypesComputationStatus ( declaration ) <EOL> if ( status is SupertypeComputationStatus . Computed ) { <EOL> supertypeComputationSession . withDeclarationSession ( declaration ) { <EOL> for ( computedType in status . supertypeRefs ) { <EOL> crawlSupertype ( computedType . type ) <EOL> } <EOL> } <EOL> } <EOL> val loopedSuperTypeRefs = supertypeComputationSession . findLoopFor ( declaration ) <EOL> val resultedTypeRefs = loopedSuperTypeRefs ? : resolvedSuperTypeRefs <EOL> performCustomResolveUnderLock ( declaration ) { <EOL> superTypeUpdater ( resultedTypeRefs ) <EOL> } <EOL> }

/**
 * [superTypeRefsForTransformation] will be executed under [declaration] lock
 */


private fun crawlSupertype ( type : ConeKotlinType )

{ <EOL> for ( session in supertypeComputationSession . useSiteSessions . asReversed ( ) ) { <EOL> type . toSymbol ( session ) ? . let ( :: crawlSupertype ) <EOL> } <EOL> if ( type is ConeClassLikeType ) { <EOL> type . typeArguments . forEach { it . type ? . let { crawlSupertype ( it ) } } <EOL> } <EOL> }

/**
 * We want to apply resolved supertypes to as many designations as possible.
 * So we crawl the resolved supertypes of visited designations to find more designations to collect.
 */


fun findLoopFor ( declaration : FirClassLikeDeclaration ) : List < FirResolvedTypeRef > ?

{ <EOL> breakLoopFor ( declaration = declaration , session = declaration . llFirSession , visited = visited , looped = looped , pathSet = pathSet , path = path , ) <EOL> require ( path . isEmpty ( ) ) { "<STR_LIT>" } <EOL> require ( pathSet . isEmpty ( ) ) { "<STR_LIT>" } <EOL> visited . clear ( ) <EOL> looped . clear ( ) <EOL> return updatedTypesForDeclarationsWithLoop [ declaration ] <EOL> }

/**
 * @param declaration declaration to be checked for loops
 * @return list of resolved super type refs if at least one of them is [FirErrorTypeRef] due to cycle hierarchy
 */


override fun getResolvedSuperTypeRefsForOutOfSessionDeclaration ( classLikeDeclaration : FirClassLikeDeclaration ) : List < FirResolvedTypeRef > ?

{ <EOL> if ( classLikeDeclaration . resolvePhase < FirResolvePhase . SUPER_TYPES ) return emptyList ( ) <EOL> return super . getResolvedSuperTypeRefsForOutOfSessionDeclaration ( classLikeDeclaration ) <EOL> }

/**
 * We shouldn't try to iterate over unresolved class. Otherwise, it can lead to [ConcurrentModificationException]
 */


internal fun List < State > . wrap ( callInterceptor : CallInterceptor , irFunction : IrFunction , methodType : MethodType ? = null ) : List < Any ? >

{ <EOL> val name = irFunction . fqName <EOL> if ( name == eqeqName && this . any { it is Common } ) { <EOL> return mapIndexed { index , state -> <EOL> if ( state !is Common ) return@mapIndexed state <EOL> state . wrap ( callInterceptor , remainArraysAsIs = true , methodType ? . parameterType ( index ) ) <EOL> } <EOL> } <EOL> return this . mapIndexed { index , state -> <EOL> val unwrapArrays = ( name == "<STR_LIT>" && index != <NUM_LIT:0> ) || name == "<STR_LIT>" || name == checkNotNullName <EOL> state . wrap ( callInterceptor , unwrapArrays , methodType ? . parameterType ( index ) ) <EOL> } <EOL> }

/**
 * Prepare state object to be passed in outer world
 */


internal actual fun < T > createCache ( factory : ( KClass < * > ) -> KSerializer < T > ? ) : SerializerCache < T >

{ <EOL> return if ( useClassValue ) ClassValueCache ( factory ) else ConcurrentHashMapCache ( factory ) <EOL> }

/**
 * Creates a **strongly referenced** cache of values associated with [Class].
 * Serializers are computed using provided [factory] function.
 *
 * `null` values are not supported, though there aren't any technical limitations.
 */


internal actual fun < T > createParametrizedCache ( factory : ( KClass < Any > , List < KType > ) -> KSerializer < T > ? ) : ParametrizedSerializerCache < T >

{ <EOL> return if ( useClassValue ) ClassValueParametrizedCache ( factory ) else ConcurrentHashMapParametrizedCache ( factory ) <EOL> }


public inline fun LayerCollectorContext . tiles ( block : TilesContext . ( ) -> Unit )

{ <EOL> addLayer ( TilesContext ( this ) . apply ( block ) ) <EOL> }

/**
 * Adds a new `tiles` layer to the plot.
 *
 * The `tiles` layer is used for visualizing data in a grid format, useful for creating heatmaps or 2D binning plots.
 *
 * This function creates a context where you can set aesthetic mappings (`aes`) or aesthetic constants.
 * - Mappings are specified by calling methods that correspond to aesthetic names (`aes`).
 * - Constants are directly assigned using properties with the names corresponding to aesthetics.
 * For positional aesthetics, you can use the `.constant()` method.
 *
 * ## Tiles Aesthetics
 * * **`x`** - The X-coordinate for the bottom-left corner of the tile.
 * * **`y`** - The Y-coordinate for the bottom-left corner of the tile.
 * * **`fillColor`** - The fill color of the tile.
 * * **`alpha`** - The transparency of the tile.
 * * **`width`** - The width of the tile.
 * * **`height`** - The height of the tile.
 * * **`borderLine.color`** - The color of the borderLine.
 * * **`borderLine.width`** - The width of the borderLine.
 * * **`borderLine.type`** - The type of the borderLine (solid, dashed, etc.).
 *
 * ## Example Usage
 *
 * ```kotlin
 * val xCord by columnOf(1, 1, 2, 2, 3, 3)
 * val yCord by columnOf(1, 2, 1, 2, 1, 2)
 * val value by columnOf(5, 10, 15, 20, 25, 30)
 *
 * plot {
 * tiles {
 * // Positional mapping
 * x(xCord)
 * y(yCord)
 *
 * // Non-positional mapping
 * fillColor(value) {
 * scale = continuousColorGradient2(Color.WHITE, Color.BLUE, Color.RED, 0.5)
 * }
 *
 * // Non-positional settings
 * alpha = 0.8
 * borderLine {
 * color = Color.BLACK
 * width = 0.5
 * }
 *
 * width = 0.9
 * height = 0.9
 * }
 * }
 * ```
 */


@ OptIn ( ExperimentalContracts :: class , KtAnalysisApiInternals :: class ) <EOL> public inline fun KtAnalysisSession . buildSubstitutor ( build : KtSubstitutorBuilder . ( ) -> Unit ) : KtSubstitutor

{ <EOL> contract { <EOL> callsInPlace ( build , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> return analysisSession . substitutorFactory . buildSubstitutor ( KtSubstitutorBuilder ( token ) . apply ( build ) ) <EOL> }

/**
 * Creates new [KtSubstitutor] using substitutions specified inside [build] lambda
 */


public fun substitution ( typeParameter : KtTypeParameterSymbol , type : KtType )

{ <EOL> assertIsValidAndAccessible ( ) <EOL> _mapping [ typeParameter ] = type <EOL> }

/**
 * Adds a new [typeParameter] -> [type] substitution to the substitutor which is being built.
 * If there already was a substitution with a [typeParameter], replaces corresponding substitution with a new one.
 */


public fun substitutions ( substitutions : Map < KtTypeParameterSymbol , KtType > )

{ <EOL> assertIsValidAndAccessible ( ) <EOL> _mapping += substitutions <EOL> }

/**
 * Adds a new substitutions to the substitutor which is being built.
 * If there already was a substitution with a [KtTypeParameterSymbol] which is present in a [substitutions],
 * replaces corresponding substitution with a new one.
 */


abstract fun fileCached ( file : KtFile , createValue : ( ) -> FirFile ) : FirFile

/**
 * @return [FirFile] by [file] if it was previously built or runs [createValue] otherwise
 * The [createValue] is run under the lock so [createValue] is executed at most once for each [KtFile]
 */


fun < T : Number > reciprocal ( x : KtNDArray < T > ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x ) )

/**
 * Return the reciprocal of the argument, element-wise.
 */


fun < T : Number > positive ( x : KtNDArray < T > ) : KtNDArray < T >

/**
 * Numerical positive, element-wise.
 */


fun < T : Number > negative ( x : KtNDArray < T > ) : KtNDArray < T >

/**
 * Numerical negative, element-wise.
 */


fun < T : Number > power ( x1 : KtNDArray < T > , x2 : Byte ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x1 , x2 ) )

/**
 * First array elements raised to powers from second array, element-wise.
 */


fun < T : Number , E : Number > floatPower ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >


fun < T : Number , E : Number > fmod ( x1 : KtNDArray < T > , x2 : E ) : KtNDArray < T >

/**
 * Return the element-wise remainder of division.
 */


fun flush ( )

/** Writes any remaining in-memory changes to [storageFile]. */


override fun close ( )

/** Writes any remaining in-memory changes to [storageFile] ([flush]) and closes this map. */


fun append ( key : KEY , elements : Collection < E > )

/** Adds the given [elements] to the collection corresponding to the given [key]. */


{ <EOL> append ( key , listOf ( element ) ) <EOL> }

/** Adds the given [element] to the collection corresponding to the given [key]. */


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

{ <EOL> if ( size > <NUM_LIT:1> ) java . util . Collections . sort ( this ) <EOL> }

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


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

{ <EOL> if ( size > <NUM_LIT:1> ) java . util . Collections . sort ( this , comparator ) <EOL> }

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


@ kotlin . internal . InlineOnly <EOL> @ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual inline fun < T > MutableList < T > . fill ( value : T )

{ <EOL> java . util . Collections . fill ( this , value ) <EOL> }

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


@ kotlin . internal . InlineOnly <EOL> @ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public actual inline fun < T > MutableList < T > . shuffle ( )

{ <EOL> java . util . Collections . shuffle ( this ) <EOL> }

/**
 * Randomly shuffles elements in this mutable list.
 */


@ kotlin . internal . InlineOnly <EOL> @ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public inline fun < T > MutableList < T > . shuffle ( random : java . util . Random )

{ <EOL> java . util . Collections . shuffle ( this , random ) <EOL> }

/**
 * Randomly shuffles elements in this mutable list using the specified [random] instance as the source of randomness.
 */


internal fun DateTimeFormatBuilder . WithDate . yearOfEra ( padding : Padding )

{ <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> when ( this ) { <EOL> is AbstractWithDateBuilder -> addFormatStructureForDate ( BasicFormatStructure ( YearDirective ( padding , isYearOfEra = true ) ) ) <EOL> } <EOL> }

/**
 * A special directive for year-of-era that behaves equivalently to [DateTimeFormatBuilder.WithDate.year].
 * This is the result of calling [byUnicodePattern] on a pattern that uses the ubiquitous "y" symbol.
 * We need a separate directive so that, when using [DateTimeFormat.formatAsKotlinBuilderDsl], we can print an
 * additional comment and explain that the behavior was not preserved exactly.
 */


internal fun DateTimeFormatBuilder . WithDate . yearOfEraTwoDigits ( baseYear : Int )

{ <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> when ( this ) { <EOL> is AbstractWithDateBuilder -> addFormatStructureForDate ( BasicFormatStructure ( ReducedYearDirective ( baseYear , isYearOfEra = true ) ) ) <EOL> } <EOL> }


internal fun < T > MutableList < T > . replaceAll ( transformation : ( T ) -> T )

{ <EOL> val it = listIterator ( ) <EOL> while ( it . hasNext ( ) ) { <EOL> val element = it . next ( ) <EOL> it . set ( transformation ( element ) ) <EOL> } <EOL> }

/**
 * Replaces each element in the list with a result of a transformation specified.
 */


fun invalidateElement ( element : KtElement )

{ <EOL> val container = getContainerKtElement ( element ) <EOL> structureElements . remove ( container ) <EOL> }

/**
 * Must be called only under write-lock.
 *
 * This method is responsible for "invalidation" of re-analyzable declarations.
 *
 * @see LLFirDeclarationModificationService
 * @see getNonLocalReanalyzableContainingDeclaration
 */


fun getStructureElementFor ( element : KtElement ) : FileStructureElement

{ <EOL> val container = getContainerKtElement ( element ) <EOL> return structureElements . getOrPut ( container ) { createStructureElement ( container ) } <EOL> }

/**
 * @return [FileStructureElement] for the closest non-local declaration which contains this [element].
 */


private fun Project . registerVerifyModuleTask ( compileTask : KotlinCompile , sourceFile : File ) : TaskProvider < out KotlinJvmCompile >

{ <EOL> apply < KotlinApiPlugin > ( ) <EOL> val verifyModuleTaskName = "<STR_LIT>" <EOL> val kotlinApiPlugin = plugins . getPlugin ( KotlinApiPlugin :: class ) <EOL> val verifyModuleTask = kotlinApiPlugin . registerKotlinJvmCompileTask ( verifyModuleTaskName , compileTask . compilerOptions . moduleName . get ( ) ) <EOL> verifyModuleTask { <EOL> group = VERIFICATION_GROUP <EOL> description = "<STR_LIT>" <EOL> libraries . from ( compileTask . libraries ) <EOL> source ( compileTask . sources ) <EOL> source ( compileTask . javaSources ) <EOL> @ Suppress ( "<STR_LIT:INVISIBLE_MEMBER>" ) <EOL> source ( compileTask . scriptSources ) <EOL> source ( sourceFile ) <EOL> destinationDirectory . set ( temporaryDir ) <EOL> multiPlatformEnabled . set ( compileTask . multiPlatformEnabled ) <EOL> compilerOptions { <EOL> jvmTarget . set ( JvmTarget . JVM_9 ) <EOL> languageVersion . set ( compileTask . compilerOptions . languageVersion ) <EOL> freeCompilerArgs . addAll ( listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> optIn . addAll ( compileTask . kotlinOptions . options . optIn ) <EOL> } <EOL> inputs . files ( libraries . asFileTree . elements . map { libs -> <EOL> libs <EOL> . filter { it . asFile . exists ( ) } <EOL> . map { <EOL> zipTree ( it . asFile ) . filter { it . name == "<STR_LIT>" } <EOL> } <EOL> } ) . withPropertyName ( "<STR_LIT>" ) <EOL> this as KotlinCompile <EOL> val kotlinPluginVersion = KotlinToolingVersion ( kotlinApiPlugin . pluginVersion ) <EOL> if ( kotlinPluginVersion <= KotlinToolingVersion ( "<STR_LIT>" ) ) { <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> val ownModuleNameProp = ( this :: class . superclasses . first ( ) as KClass < AbstractKotlinCompile < * > > ) <EOL> . declaredMemberProperties <EOL> . find { it . name == "<STR_LIT>" } <EOL> ? . get ( this ) as? Property < String > <EOL> ownModuleNameProp ? . set ( compileTask . kotlinOptions . moduleName ) <EOL> } <EOL> val taskKotlinLanguageVersion = compilerOptions . languageVersion . orElse ( KotlinVersion . DEFAULT ) <EOL> @ OptIn ( InternalKotlinGradlePluginApi :: class ) <EOL> if ( taskKotlinLanguageVersion . get ( ) < KotlinVersion . KOTLIN_2_0 ) { <EOL> @ Suppress ( "<STR_LIT:INVISIBLE_MEMBER>" ) <EOL> commonSourceSet . from ( compileTask . commonSourceSet ) <EOL> } else { <EOL> multiplatformStructure . refinesEdges . set ( compileTask . multiplatformStructure . refinesEdges ) <EOL> multiplatformStructure . fragments . set ( compileTask . multiplatformStructure . fragments ) <EOL> } <EOL> incremental = false <EOL> } <EOL> return verifyModuleTask <EOL> }

/**
 * Add a Kotlin compile task that compiles `module-info.java` source file and Kotlin sources together,
 * the Kotlin compiler will parse and check module dependencies,
 * but it currently won't compile to a module-info.class file.
 */


protected abstract fun phaseSpecificCheckIsResolved ( target : FirElementWithResolveState )

/**
 * Check that phase-specific conditions are met
 * Will be performed to resolved declaration and its nested declarations
 * @see checkNestedDeclarationsAreResolved
 */


fun < T : Number > signbit ( x : KtNDArray < T > ) : KtNDArray < Boolean >

/**
 * Returns element-wise True where signbit is set (less than zero).
 */


fun < T : Number , E : Number > copysign ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x1 , x2 ) , dtype = Double :: class )

/**
 * Change the sign of x1 to that of x2, element-wise.
 */


fun < T : Any > frexp ( x : KtNDArray < T > ) : Pair < KtNDArray < Double > , KtNDArray < Int > >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x ) , kClass = Pair :: class ) as Pair < KtNDArray < Double > , KtNDArray < Int > >

/**
 * Decompose the elements of x into mantissa and twos exponent.
 */


fun < T : Number , E : Number > ldexp ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >

/**
 * Returns x1 * 2**x2, element-wise.
 */


fun < T : Number , E : Number > nextafter ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >

/**
 * Return the next floating-point value after x1 towards x2, element-wise.
 */


fun < T : Number > spacing ( x : KtNDArray < T > ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x ) , dtype = Double :: class )

/**
 * Return the distance between x and the nearest adjacent number.
 */


fun getIrClass ( firClass : FirClass ) : IrClass

{ <EOL> getCachedIrClass ( firClass ) ? . let { return it } <EOL> if ( firClass is FirAnonymousObject || firClass is FirRegularClass && firClass . visibility == Visibilities . Local ) { <EOL> return createAndCacheLocalIrClassOnTheFly ( firClass ) <EOL> } <EOL> require ( firClass is FirRegularClass ) <EOL> val symbol = createClassSymbol ( ) <EOL> val classId = firClass . symbol . classId <EOL> val parentId = classId . outerClassId <EOL> val parentClass = parentId ? . let { session . symbolProvider . getClassLikeSymbolByClassId ( it ) } <EOL> val irParent = declarationStorage . findIrParent ( classId . packageFqName , parentClass ? . toLookupTag ( ) , firClass . symbol , firClass . origin ) ! ! <EOL> classCache [ firClass ] = symbol <EOL> check ( irParent . isExternalParent ( ) ) { "<STR_LIT>" } <EOL> val irClass = lazyDeclarationsGenerator . createIrLazyClass ( firClass , irParent , symbol ) <EOL> irClass . prepareTypeParameters ( ) <EOL> return irClass <EOL> }

/**
 * FIR2IR looks over all non-local source classes and creates IR for them using [createAndCacheIrClass]
 * This means that after this phase all classes are either created and bound to their symbols or external classes,
 * which are created and bound at the first access anyway
 *
 * So, unlike callable declarations, it's safe to expose an API, which returns not just IrClassSymbol, but IrClass itself
 *
 * But on the first FIR2IR stage this API should not be used
 */


fun collectTailRecursionCalls ( irFunction : IrFunction , followFunctionReference : ( IrFunctionReference ) -> Boolean ) : TailCalls

{ <EOL> if ( ( irFunction as? IrSimpleFunction ) ? . isTailrec != true ) { <EOL> return TailCalls ( emptySet ( ) , false ) <EOL> } <EOL> class VisitorState ( val isTailExpression : Boolean , val inOtherFunction : Boolean ) <EOL> val isUnitReturn = irFunction . returnType . isUnit ( ) <EOL> val result = mutableSetOf < IrCall > ( ) <EOL> var someCallsAreInOtherFunctions = false <EOL> val visitor = object : IrElementVisitor < Unit , VisitorState > { <EOL> override fun visitElement ( element : IrElement , data : VisitorState ) { <EOL> element . acceptChildren ( this , VisitorState ( isTailExpression = false , data . inOtherFunction ) ) <EOL> } <EOL> override fun visitFunction ( declaration : IrFunction , data : VisitorState ) { <EOL> } <EOL> override fun visitClass ( declaration : IrClass , data : VisitorState ) { <EOL> } <EOL> override fun visitTry ( aTry : IrTry , data : VisitorState ) { <EOL> } <EOL> override fun visitReturn ( expression : IrReturn , data : VisitorState ) { <EOL> expression . value . accept ( this , VisitorState ( expression . returnTargetSymbol == irFunction . symbol , data . inOtherFunction ) ) <EOL> } <EOL> override fun visitExpressionBody ( body : IrExpressionBody , data : VisitorState ) = <EOL> body . acceptChildren ( this , data ) <EOL> override fun visitBlockBody ( body : IrBlockBody , data : VisitorState ) = <EOL> visitStatementContainer ( body , data ) <EOL> override fun visitContainerExpression ( expression : IrContainerExpression , data : VisitorState ) = <EOL> visitStatementContainer ( expression , data ) <EOL> private fun visitStatementContainer ( expression : IrStatementContainer , data : VisitorState ) { <EOL> expression . statements . forEachIndexed { index , irStatement -> <EOL> val isTailStatement = if ( index == expression . statements . lastIndex ) { <EOL> data . isTailExpression <EOL> } else { <EOL> isUnitReturn && expression . statements [ index + <NUM_LIT:1> ] . let { <EOL> it is IrReturn && it . returnTargetSymbol == irFunction . symbol && it . value . isUnitRead ( ) <EOL> } <EOL> } <EOL> irStatement . accept ( this , VisitorState ( isTailStatement , data . inOtherFunction ) ) <EOL> } <EOL> } <EOL> private fun IrExpression . isUnitRead ( ) : Boolean = <EOL> this is IrGetObjectValue && symbol . isClassWithFqName ( StandardNames . FqNames . unit ) <EOL> override fun visitWhen ( expression : IrWhen , data : VisitorState ) { <EOL> expression . branches . forEach { <EOL> it . condition . accept ( this , VisitorState ( isTailExpression = false , data . inOtherFunction ) ) <EOL> it . result . accept ( this , data ) <EOL> } <EOL> } <EOL> override fun visitCall ( expression : IrCall , data : VisitorState ) { <EOL> expression . acceptChildren ( this , VisitorState ( isTailExpression = false , data . inOtherFunction ) ) <EOL> if ( ! data . isTailExpression || expression . symbol != irFunction . symbol ) { <EOL> return <EOL> } <EOL> if ( irFunction . overriddenSymbols . isNotEmpty ( ) && expression . usesDefaultArguments ( ) ) { <EOL> return <EOL> } <EOL> val hasSameDispatchReceiver = <EOL> irFunction . dispatchReceiverParameter ? . type ? . classOrNull ? . owner ? . kind ? . isSingleton == true || <EOL> expression . dispatchReceiver ? . let { it is IrGetValue && it . symbol . owner == irFunction . dispatchReceiverParameter } != false <EOL> if ( ! hasSameDispatchReceiver ) { <EOL> return <EOL> } <EOL> if ( data . inOtherFunction ) { <EOL> someCallsAreInOtherFunctions = true <EOL> } <EOL> result . add ( expression ) <EOL> } <EOL> override fun visitFunctionReference ( expression : IrFunctionReference , data : VisitorState ) { <EOL> expression . acceptChildren ( this , VisitorState ( isTailExpression = false , data . inOtherFunction ) ) <EOL> if ( followFunctionReference ( expression ) ) { <EOL> expression . symbol . owner . body ? . accept ( this , VisitorState ( isTailExpression = false , inOtherFunction = true ) ) <EOL> } <EOL> } <EOL> } <EOL> irFunction . body ? . accept ( visitor , VisitorState ( isTailExpression = true , inOtherFunction = false ) ) <EOL> return TailCalls ( result , someCallsAreInOtherFunctions ) <EOL> }

/**
 * Collects calls to be treated as tail recursion.
 * The checks are partially based on the frontend implementation
 * in `ControlFlowInformationProvider.markAndCheckRecursiveTailCalls()`.
 *
 * This analysis is not very precise and can miss some calls.
 * It is also not guaranteed that each returned call is detected as tail recursion by the frontend.
 * However any returned call can be correctly optimized as tail recursion.
 */


public fun addLayer ( context : LayerContextInterface )

{ <EOL> checkRequiredAes ( context . requiredAes , context , if ( layersInheritMappings ) { <EOL> plotContext <EOL> } else null ) <EOL> layers . add ( context . toLayer ( layersInheritMappings ) ) <EOL> }

/**
 * Adds a new layer to the plot by converting the provided [LayerContextInterface] into a [Layer]
 * and appending it to the internal layers collection.
 *
 * @param context The [LayerContextInterface] that encapsulates the configurations,
 * aesthetic mappings, and other settings of the layer to be added.
 * The context provides all the necessary information to construct and visualize the layer within the plot.
 *
 * @throws IllegalArgumentException If the required aesthetics for the layer are not present.
 */


public fun < DomainType > addNonPositionalSetting ( aes : Aes , value : DomainType ) : NonPositionalSetting < DomainType >

{ <EOL> return NonPositionalSetting ( aes , value ) . also { <EOL> bindingCollector . settings [ aes ] = it <EOL> } <EOL> }

/**
 * Adds a [non-positional setting][NonPositionalSetting] with the given aes and value.
 *
 * @param aes the aesthetic attribute (aes) to associate with the non-positional setting.
 * @param value the value of the setting.
 * @return the newly created [NonPositionalSetting] object with the provided aes and value.
 */


public fun < DomainType > addPositionalSetting ( aes : Aes , value : DomainType ) : PositionalSetting < DomainType >

{ <EOL> return PositionalSetting ( aes , value ) . also { <EOL> bindingCollector . settings [ aes ] = it <EOL> } <EOL> }

/**
 * Adds a [positional setting][PositionalSetting] with the given aes and value.
 *
 * @param aes the aesthetic attribute (aes) to associate with the positional setting.
 * @param value the value of the setting.
 * @return the newly created [PositionalSetting] object with the provided aes and value.
 */