private fun repairNameIfRequired ( nameFromCell : String , columnNameCounters : MutableMap < String , Int > , nameRepairStrategy : NameRepairStrategy , ) : String

{ <EOL> return when ( nameRepairStrategy ) { <EOL> NameRepairStrategy . DO_NOTHING -> nameFromCell <EOL> NameRepairStrategy . CHECK_UNIQUE -> if ( columnNameCounters . contains ( nameFromCell ) ) throw DuplicateColumnNamesException ( columnNameCounters . keys . toList ( ) ) else nameFromCell <EOL> NameRepairStrategy . MAKE_UNIQUE -> if ( nameFromCell . isEmpty ( ) ) { <EOL> val emptyName = "<STR_LIT>" <EOL> if ( columnNameCounters . contains ( emptyName ) ) "<STR_LIT>" <EOL> else emptyName <EOL> } else { <EOL> if ( columnNameCounters . contains ( nameFromCell ) ) { <EOL> "<STR_LIT>" <EOL> } else { <EOL> nameFromCell <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * This is a universal function for name repairing
 * and should be moved to the API module later,
 * when the functionality will be enabled for all IO sources.
 *
 * TODO: https://github.com/Kotlin/dataframe/issues/387
 */


private fun Cell . setTime ( localDateTime : LocalDateTime )

{ <EOL> this . setCellValue ( DateUtil . getExcelDate ( localDateTime . plusDays ( <NUM_LIT:1> ) ) - <NUM_LIT:1.0> ) <EOL> }

/**
 * Set LocalDateTime value correctly also if date have zero value in Excel.
 * Zero dates are usually used for storing a time component only,
 * are displayed as 00.01.1900 in Excel and as 30.12.1899 in LibreOffice Calc and also in POI.
 * POI can not set 1899 year directly.
 */


private fun Cell . setDate ( date : Date )

{ <EOL> val calStart = LocaleUtil . getLocaleCalendar ( ) <EOL> calStart . time = date <EOL> this . setTime ( calStart . toInstant ( ) . atZone ( getUserTimeZone ( ) . toZoneId ( ) ) . toLocalDateTime ( ) ) <EOL> }

/**
 * Set Date value correctly also if date has zero value in Excel.
 * Zero dates are usually used for storing a time component only,
 * are displayed as 00.01.1900 in Excel and as 30.12.1899 in LibreOffice Calc and also in POI.
 * POI can not set 1899 year directly.
 */


private fun hasFlag ( flag : Int ) : Boolean

= flags and flag == flag

/** Return true if the pattern has the specified flag */


private fun processAlternations ( last : AbstractSet ) : AbstractSet

{ <EOL> val auxRange = CharClass ( hasFlag ( Pattern . CASE_INSENSITIVE ) ) <EOL> while ( ! lexemes . isEmpty ( ) && lexemes . isLetter ( ) && ( lexemes . lookAhead == <NUM_LIT:0> || lexemes . lookAhead == Lexer . CHAR_VERTICAL_BAR || lexemes . lookAhead == Lexer . CHAR_RIGHT_PARENTHESIS ) ) { <EOL> auxRange . add ( lexemes . next ( ) ) <EOL> if ( lexemes . currentChar == Lexer . CHAR_VERTICAL_BAR ) { <EOL> lexemes . next ( ) <EOL> } <EOL> } <EOL> val rangeSet = processRangeSet ( auxRange ) <EOL> rangeSet . next = last <EOL> return rangeSet <EOL> }


private fun processExpression ( ch : Int , newFlags : Int , last : AbstractSet ? ) : AbstractSet

{ <EOL> val children = ArrayList < AbstractSet > ( ) <EOL> val savedFlags = flags <EOL> var saveChangedFlags = false <EOL> if ( newFlags != flags ) { <EOL> flags = newFlags <EOL> } <EOL> val fSet : FSet <EOL> when ( ch ) { <EOL> Lexer . CHAR_NONCAP_GROUP -> fSet = NonCapFSet ( consumersCount ++ ) <EOL> Lexer . CHAR_POS_LOOKAHEAD , <EOL> Lexer . CHAR_NEG_LOOKAHEAD -> fSet = AheadFSet ( ) <EOL> Lexer . CHAR_POS_LOOKBEHIND , <EOL> Lexer . CHAR_NEG_LOOKBEHIND -> fSet = BehindFSet ( consumersCount ++ ) <EOL> Lexer . CHAR_ATOMIC_GROUP -> fSet = AtomicFSet ( consumersCount ++ ) <EOL> else -> { <EOL> if ( last == null ) { <EOL> fSet = FinalSet ( ) <EOL> saveChangedFlags = true <EOL> } else { <EOL> fSet = FSet ( capturingGroups . size ) <EOL> } <EOL> capturingGroups . add ( fSet ) <EOL> if ( ch == Lexer . CHAR_NAMED_GROUP ) { <EOL> val name = ( lexemes . curSpecialToken as NamedGroup ) . name <EOL> if ( groupNameToIndex . containsKey ( name ) ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , pattern , lexemes . curTokenIndex ) <EOL> } <EOL> groupNameToIndex [ name ] = fSet . groupIndex <EOL> } <EOL> } <EOL> } <EOL> if ( last != null ) { <EOL> lexemes . next ( ) <EOL> } <EOL> do { <EOL> val child : AbstractSet <EOL> when { <EOL> lexemes . isLetter ( ) && lexemes . lookAhead == Lexer . CHAR_VERTICAL_BAR -> child = processAlternations ( fSet ) <EOL> lexemes . currentChar == Lexer . CHAR_VERTICAL_BAR -> { <EOL> child = EmptySet ( fSet ) <EOL> lexemes . next ( ) <EOL> } <EOL> else -> { <EOL> child = processSubExpression ( fSet ) <EOL> if ( lexemes . currentChar == Lexer . CHAR_VERTICAL_BAR ) { <EOL> lexemes . next ( ) <EOL> } <EOL> } <EOL> } <EOL> children . add ( child ) <EOL> } while ( ! ( lexemes . isEmpty ( ) || lexemes . currentChar == Lexer . CHAR_RIGHT_PARENTHESIS ) ) <EOL> if ( lexemes . lookBack == Lexer . CHAR_VERTICAL_BAR ) { <EOL> children . add ( EmptySet ( fSet ) ) <EOL> } <EOL> if ( flags != savedFlags && ! saveChangedFlags ) { <EOL> flags = savedFlags <EOL> lexemes . restoreFlags ( flags ) <EOL> } <EOL> when ( ch ) { <EOL> Lexer . CHAR_NONCAP_GROUP -> return NonCapturingJointSet ( children , fSet ) <EOL> Lexer . CHAR_POS_LOOKAHEAD -> return PositiveLookAheadSet ( children , fSet ) <EOL> Lexer . CHAR_NEG_LOOKAHEAD -> return NegativeLookAheadSet ( children , fSet ) <EOL> Lexer . CHAR_POS_LOOKBEHIND -> return PositiveLookBehindSet ( children , fSet ) <EOL> Lexer . CHAR_NEG_LOOKBEHIND -> return NegativeLookBehindSet ( children , fSet ) <EOL> Lexer . CHAR_ATOMIC_GROUP -> return AtomicJointSet ( children , fSet ) <EOL> else -> when ( children . size ) { <EOL> <NUM_LIT:0> -> return EmptySet ( fSet ) <EOL> <NUM_LIT:1> -> return SingleSet ( children [ <NUM_LIT:0> ] , fSet ) <EOL> else -> return JointSet ( children , fSet ) <EOL> } <EOL> } <EOL> }


@ OptIn ( ExperimentalNativeApi :: class ) <EOL> private fun processSequence ( ) : AbstractSet

{ <EOL> val substring = StringBuilder ( ) <EOL> while ( ! lexemes . isEmpty ( ) && lexemes . isLetter ( ) && ! lexemes . isSurrogate ( ) && ( ! lexemes . isNextSpecial && lexemes . lookAhead == <NUM_LIT:0> || ! lexemes . isNextSpecial && Lexer . isLetter ( lexemes . lookAhead ) || lexemes . lookAhead == Lexer . CHAR_RIGHT_PARENTHESIS || lexemes . lookAhead and <NUM_LIT> . toInt ( ) == Lexer . CHAR_LEFT_PARENTHESIS || lexemes . lookAhead == Lexer . CHAR_VERTICAL_BAR || lexemes . lookAhead == Lexer . CHAR_DOLLAR ) ) { <EOL> val ch = lexemes . next ( ) <EOL> if ( Char . isSupplementaryCodePoint ( ch ) ) { <EOL> substring . append ( Char . toChars ( ch ) ) <EOL> } else { <EOL> substring . append ( ch . toChar ( ) ) <EOL> } <EOL> } <EOL> return SequenceSet ( substring , hasFlag ( CASE_INSENSITIVE ) ) <EOL> }


private fun processDecomposedChar ( ) : AbstractSet

{ <EOL> val codePoints = IntArray ( Lexer . MAX_DECOMPOSITION_LENGTH ) <EOL> val codePointsHangul : CharArray <EOL> var readCodePoints = <NUM_LIT:0> <EOL> var curSymb = - <NUM_LIT:1> <EOL> var curSymbIndex = - <NUM_LIT:1> <EOL> if ( ! lexemes . isEmpty ( ) && lexemes . isLetter ( ) ) { <EOL> curSymb = lexemes . next ( ) <EOL> codePoints [ readCodePoints ] = curSymb <EOL> curSymbIndex = curSymb - Lexer . LBase <EOL> } <EOL> if ( curSymbIndex >= <NUM_LIT:0> && curSymbIndex < Lexer . LCount ) { <EOL> codePointsHangul = CharArray ( Lexer . MAX_HANGUL_DECOMPOSITION_LENGTH ) <EOL> codePointsHangul [ readCodePoints ++ ] = curSymb . toChar ( ) <EOL> curSymb = lexemes . currentChar <EOL> curSymbIndex = curSymb - Lexer . VBase <EOL> if ( curSymbIndex >= <NUM_LIT:0> && curSymbIndex < Lexer . VCount ) { <EOL> codePointsHangul [ readCodePoints ++ ] = curSymb . toChar ( ) <EOL> lexemes . next ( ) <EOL> curSymb = lexemes . currentChar <EOL> curSymbIndex = curSymb - Lexer . TBase <EOL> if ( curSymbIndex >= <NUM_LIT:0> && curSymbIndex < Lexer . TCount ) { <EOL> codePointsHangul [ @ Suppress ( "<STR_LIT>" ) readCodePoints ++ ] = curSymb . toChar ( ) <EOL> lexemes . next ( ) <EOL> return HangulDecomposedCharSet ( codePointsHangul , <NUM_LIT:3> ) <EOL> } else { <EOL> return HangulDecomposedCharSet ( codePointsHangul , <NUM_LIT:2> ) <EOL> } <EOL> } else { <EOL> return CharSet ( codePointsHangul [ <NUM_LIT:0> ] , hasFlag ( CASE_INSENSITIVE ) ) <EOL> } <EOL> } else { <EOL> readCodePoints ++ <EOL> while ( readCodePoints < Lexer . MAX_DECOMPOSITION_LENGTH && ! lexemes . isEmpty ( ) && lexemes . isLetter ( ) && ! Lexer . isDecomposedCharBoundary ( lexemes . currentChar ) ) { <EOL> codePoints [ readCodePoints ++ ] = lexemes . next ( ) <EOL> } <EOL> if ( readCodePoints == <NUM_LIT:1> && ! Lexer . hasSingleCodepointDecomposition ( codePoints [ <NUM_LIT:0> ] ) ) { <EOL> return processCharSet ( codePoints [ <NUM_LIT:0> ] ) <EOL> } else { <EOL> return DecomposedCharSet ( codePoints , readCodePoints ) <EOL> } <EOL> } <EOL> }


private fun processSubExpression ( last : AbstractSet ) : AbstractSet

{ <EOL> var cur : AbstractSet <EOL> when { <EOL> lexemes . isLetter ( ) && ! lexemes . isNextSpecial && Lexer . isLetter ( lexemes . lookAhead ) -> { <EOL> when { <EOL> hasFlag ( Pattern . CANON_EQ ) -> { <EOL> cur = processDecomposedChar ( ) <EOL> if ( ! lexemes . isEmpty ( ) && ( lexemes . currentChar != Lexer . CHAR_RIGHT_PARENTHESIS || last is FinalSet ) && lexemes . currentChar != Lexer . CHAR_VERTICAL_BAR && ! lexemes . isLetter ( ) ) { <EOL> cur = processQuantifier ( last , cur ) <EOL> } <EOL> } <EOL> lexemes . isHighSurrogate ( ) || lexemes . isLowSurrogate ( ) -> { <EOL> val term = processTerminal ( last ) <EOL> cur = processQuantifier ( last , term ) <EOL> } <EOL> else -> { <EOL> cur = processSequence ( ) <EOL> } <EOL> } <EOL> } <EOL> lexemes . currentChar == Lexer . CHAR_RIGHT_PARENTHESIS -> { <EOL> if ( last is FinalSet ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , pattern , lexemes . curTokenIndex ) <EOL> } <EOL> cur = EmptySet ( last ) <EOL> } <EOL> else -> { <EOL> val term = processTerminal ( last ) <EOL> cur = processQuantifier ( last , term ) <EOL> } <EOL> } <EOL> if ( ! lexemes . isEmpty ( ) && ( lexemes . currentChar != Lexer . CHAR_RIGHT_PARENTHESIS || last is FinalSet ) && lexemes . currentChar != Lexer . CHAR_VERTICAL_BAR ) { <EOL> val next = processSubExpression ( last ) <EOL> if ( cur is LeafQuantifierSet && cur . max == Quantifier . INF && cur . min == <NUM_LIT:0> && ! next . first ( cur . innerSet ) ) { <EOL> cur = UnifiedQuantifierSet ( cur ) <EOL> } <EOL> cur . next = next <EOL> } else { <EOL> cur . next = last <EOL> } <EOL> return cur <EOL> }


private fun processQuantifier ( last : AbstractSet , term : AbstractSet ) : AbstractSet

{ <EOL> val quant = lexemes . currentChar <EOL> if ( term . type == AbstractSet . TYPE_DOTSET && ( quant == Lexer . QUANT_STAR || quant == Lexer . QUANT_PLUS ) ) { <EOL> lexemes . next ( ) <EOL> return DotQuantifierSet ( term , last , quant , AbstractLineTerminator . getInstance ( flags ) , hasFlag ( Pattern . DOTALL ) ) <EOL> } <EOL> return when ( quant ) { <EOL> Lexer . QUANT_STAR , Lexer . QUANT_PLUS , Lexer . QUANT_ALT , Lexer . QUANT_COMP -> { <EOL> val quantifier = quantifierFromLexerToken ( quant ) <EOL> when { <EOL> term is LeafSet -> <EOL> LeafQuantifierSet ( quantifier , term , last , quant ) <EOL> term . consumesFixedLength -> <EOL> FixedLengthQuantifierSet ( quantifier , term , last , quant ) <EOL> else -> <EOL> GroupQuantifierSet ( quantifier , term , last , quant , groupQuantifierCount ++ ) <EOL> } <EOL> } <EOL> Lexer . QUANT_STAR_R , Lexer . QUANT_PLUS_R , Lexer . QUANT_ALT_R , Lexer . QUANT_COMP_R -> { <EOL> val quantifier = quantifierFromLexerToken ( quant ) <EOL> when { <EOL> term is LeafSet -> <EOL> ReluctantLeafQuantifierSet ( quantifier , term , last , quant ) <EOL> term . consumesFixedLength -> <EOL> ReluctantFixedLengthQuantifierSet ( quantifier , term , last , quant ) <EOL> else -> <EOL> ReluctantGroupQuantifierSet ( quantifier , term , last , quant , groupQuantifierCount ++ ) <EOL> } <EOL> } <EOL> Lexer . QUANT_PLUS_P , Lexer . QUANT_STAR_P , Lexer . QUANT_ALT_P , Lexer . QUANT_COMP_P -> { <EOL> val quantifier = quantifierFromLexerToken ( quant ) <EOL> when { <EOL> term is LeafSet -> <EOL> PossessiveLeafQuantifierSet ( quantifier , term , last , quant ) <EOL> term . consumesFixedLength -> <EOL> PossessiveFixedLengthQuantifierSet ( quantifier , term , last , quant ) <EOL> else -> <EOL> PossessiveGroupQuantifierSet ( quantifier , term , last , quant , groupQuantifierCount ++ ) <EOL> } <EOL> } <EOL> else -> term <EOL> } <EOL> }

/**
 * Q->T(*|+|?...) also do some optimizations.
 */


private fun processTerminal ( last : AbstractSet ) : AbstractSet

{ <EOL> val term : AbstractSet <EOL> var char = lexemes . currentChar <EOL> while ( char and <NUM_LIT> . toInt ( ) == Lexer . CHAR_FLAGS ) { <EOL> lexemes . next ( ) <EOL> flags = ( char shr <NUM_LIT:16> ) and flagsBitMask <EOL> char = lexemes . currentChar <EOL> } <EOL> if ( char and <NUM_LIT> . toInt ( ) == Lexer . CHAR_LEFT_PARENTHESIS ) { <EOL> var newFlags = flags <EOL> if ( char and <NUM_LIT> . toInt ( ) == Lexer . CHAR_NONCAP_GROUP ) { <EOL> newFlags = ( char shr <NUM_LIT:16> ) and flagsBitMask <EOL> } <EOL> term = processExpression ( char and <NUM_LIT> . toInt ( ) , newFlags , last ) <EOL> if ( lexemes . currentChar != Lexer . CHAR_RIGHT_PARENTHESIS ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , pattern , lexemes . curTokenIndex ) <EOL> } <EOL> lexemes . next ( ) <EOL> } else { <EOL> when ( char ) { <EOL> Lexer . CHAR_LEFT_SQUARE_BRACKET -> { <EOL> lexemes . next ( ) <EOL> var negative = false <EOL> if ( lexemes . currentChar == Lexer . CHAR_CARET ) { <EOL> negative = true <EOL> lexemes . next ( ) <EOL> } <EOL> term = processRange ( negative , last ) <EOL> if ( lexemes . currentChar != Lexer . CHAR_RIGHT_SQUARE_BRACKET ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , pattern , lexemes . curTokenIndex ) <EOL> } <EOL> lexemes . setModeWithReread ( Lexer . Mode . PATTERN ) <EOL> lexemes . next ( ) <EOL> } <EOL> Lexer . CHAR_DOT -> { <EOL> lexemes . next ( ) <EOL> term = DotSet ( AbstractLineTerminator . getInstance ( flags ) , hasFlag ( DOTALL ) ) <EOL> } <EOL> Lexer . CHAR_CARET -> { <EOL> lexemes . next ( ) <EOL> term = SOLSet ( AbstractLineTerminator . getInstance ( flags ) , hasFlag ( MULTILINE ) ) <EOL> consumersCount ++ <EOL> } <EOL> Lexer . CHAR_DOLLAR -> { <EOL> lexemes . next ( ) <EOL> term = EOLSet ( consumersCount ++ , AbstractLineTerminator . getInstance ( flags ) , hasFlag ( MULTILINE ) ) <EOL> } <EOL> Lexer . CHAR_WORD_BOUND -> { <EOL> lexemes . next ( ) <EOL> term = WordBoundarySet ( true ) <EOL> } <EOL> Lexer . CHAR_NONWORD_BOUND -> { <EOL> lexemes . next ( ) <EOL> term = WordBoundarySet ( false ) <EOL> } <EOL> Lexer . CHAR_END_OF_INPUT -> { <EOL> lexemes . next ( ) <EOL> term = EOISet ( ) <EOL> } <EOL> Lexer . CHAR_END_OF_LINE -> { <EOL> lexemes . next ( ) <EOL> term = EOLSet ( consumersCount ++ , AbstractLineTerminator . getInstance ( flags ) ) <EOL> } <EOL> Lexer . CHAR_START_OF_INPUT -> { <EOL> lexemes . next ( ) <EOL> term = SOLSet ( AbstractLineTerminator . getInstance ( flags ) ) <EOL> } <EOL> Lexer . CHAR_LINEBREAK -> { <EOL> lexemes . next ( ) <EOL> val fSet = NonCapFSet ( consumersCount ++ ) <EOL> val lineBreakSequence = SequenceSet ( "<STR_LIT>" ) . apply { <EOL> next = fSet <EOL> } <EOL> val lineBreakChars = RangeSet ( CharClass ( ) . addAll ( listOf ( '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' , '<CHAR_LIT>' ) ) ) . apply { <EOL> next = fSet <EOL> } <EOL> term = NonCapturingJointSet ( listOf ( lineBreakSequence , lineBreakChars ) , fSet ) <EOL> } <EOL> Lexer . CHAR_PREVIOUS_MATCH -> { <EOL> lexemes . next ( ) <EOL> term = PreviousMatchSet ( ) <EOL> } <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT:1>' . toInt ( ) , <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT:2>' . toInt ( ) , <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT:3>' . toInt ( ) , <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT:4>' . toInt ( ) , <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT>' . toInt ( ) , <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT>' . toInt ( ) , <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT>' . toInt ( ) , <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT>' . toInt ( ) , <EOL> <NUM_LIT> . toInt ( ) or '<CHAR_LIT:9>' . toInt ( ) -> { <EOL> var groupIndex = ( char and <NUM_LIT> ) - '<CHAR_LIT:0>' . code <EOL> while ( lexemes . lookAhead in '<CHAR_LIT:0>' . code .. '<CHAR_LIT:9>' . code ) { <EOL> val newGroupIndex = ( groupIndex * <NUM_LIT:10> ) + ( lexemes . lookAhead - '<CHAR_LIT:0>' . code ) <EOL> if ( newGroupIndex in <NUM_LIT:0> until capturingGroups . size ) { <EOL> groupIndex = newGroupIndex <EOL> lexemes . next ( ) <EOL> } else { <EOL> break <EOL> } <EOL> } <EOL> term = createBackReference ( groupIndex ) <EOL> lexemes . next ( ) <EOL> } <EOL> Lexer . CHAR_NAMED_GROUP_REF -> { <EOL> val name = ( lexemes . curSpecialToken as NamedGroup ) . name <EOL> val groupIndex = groupNameToIndex [ name ] ? : - <NUM_LIT:1> <EOL> term = createBackReference ( groupIndex ) <EOL> lexemes . next ( ) <EOL> } <EOL> <NUM_LIT:0> -> { <EOL> val cc : AbstractCharClass ? = lexemes . curSpecialToken as AbstractCharClass ? <EOL> when { <EOL> cc != null -> { <EOL> term = processRangeSet ( cc ) <EOL> lexemes . next ( ) <EOL> } <EOL> ! lexemes . isEmpty ( ) -> { <EOL> term = CharSet ( char . toChar ( ) ) <EOL> lexemes . next ( ) <EOL> } <EOL> else -> term = EmptySet ( last ) <EOL> } <EOL> } <EOL> else -> { <EOL> when { <EOL> char >= <NUM_LIT:0> && ! lexemes . isSpecial -> { <EOL> term = processCharSet ( char ) <EOL> lexemes . next ( ) <EOL> } <EOL> char == Lexer . CHAR_VERTICAL_BAR -> { <EOL> term = EmptySet ( last ) <EOL> } <EOL> char == Lexer . CHAR_RIGHT_PARENTHESIS -> { <EOL> if ( last is FinalSet ) { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , pattern , lexemes . curTokenIndex ) <EOL> } <EOL> term = EmptySet ( last ) <EOL> } <EOL> else -> { <EOL> val current = if ( lexemes . isSpecial ) lexemes . curSpecialToken . toString ( ) else char . toString ( ) <EOL> throw PatternSyntaxException ( "<STR_LIT>" , pattern , lexemes . curTokenIndex ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> return term <EOL> }

/**
 * T-> letter|[range]|{char-class}|(E)
 */


private fun createBackReference ( groupIndex : Int ) : BackReferenceSet

{ <EOL> if ( groupIndex >= <NUM_LIT:0> && groupIndex < capturingGroups . size ) { <EOL> capturingGroups [ groupIndex ] . isBackReferenced = true <EOL> needsBackRefReplacement = true <EOL> return BackReferenceSet ( groupIndex , consumersCount ++ , hasFlag ( CASE_INSENSITIVE ) ) <EOL> } else { <EOL> throw PatternSyntaxException ( "<STR_LIT>" , pattern , lexemes . curTokenIndex ) <EOL> } <EOL> }

/** Creates a back reference to the group with specified [groupIndex], or throws if the group doesn't exist yet. */


private fun processRange ( negative : Boolean , last : AbstractSet ) : AbstractSet

{ <EOL> val res = processRangeExpression ( negative ) <EOL> val rangeSet = processRangeSet ( res ) <EOL> rangeSet . next = last <EOL> return rangeSet <EOL> }


{ <EOL> return StringBuilder ( ) <EOL> . append ( "<STR_LIT>" ) <EOL> . append ( s . replace ( "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> . append ( "<STR_LIT>" ) . toString ( ) <EOL> }

/**
 * Quotes a given string using "\Q" and "\E", so that all other meta-characters lose their special meaning.
 * If the string is used for a `Pattern` afterwards, it can only be matched literally.
 */


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

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


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

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


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

/**
 * Tests property dispatching of `withTimeoutOrNull` blocks
 */


@ Test <EOL> fun testYieldBlockingWithTimeout ( )

= runTest { <EOL> expect ( <NUM_LIT:1> ) <EOL> val result = withTimeoutOrNull ( <NUM_LIT:100> ) { <EOL> while ( true ) { <EOL> yield ( ) <EOL> } <EOL> } <EOL> assertNull ( result ) <EOL> finish ( <NUM_LIT:2> ) <EOL> }

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


override fun dispatch ( context : CoroutineContext , block : Runnable )

{ <EOL> checkSchedulerInContext ( scheduler , context ) <EOL> if ( dispatchImmediately ) { <EOL> scheduler . sendDispatchEvent ( context ) <EOL> block . run ( ) <EOL> } else { <EOL> post ( block , context ) <EOL> } <EOL> }


override fun dispatchYield ( context : CoroutineContext , block : Runnable )

{ <EOL> checkSchedulerInContext ( scheduler , context ) <EOL> post ( block , context ) <EOL> }


= "<STR_LIT>"


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . ERROR ) <EOL> override suspend fun pauseDispatcher ( block : suspend ( ) -> Unit )

{ <EOL> val previous = dispatchImmediately <EOL> dispatchImmediately = false <EOL> try { <EOL> block ( ) <EOL> } finally { <EOL> dispatchImmediately = previous <EOL> } <EOL> }


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . ERROR ) <EOL> override fun pauseDispatcher ( )

{ <EOL> dispatchImmediately = false <EOL> }


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . ERROR ) <EOL> override fun resumeDispatcher ( )

{ <EOL> dispatchImmediately = true <EOL> }


@ ExternalKotlinTargetApi <EOL> fun IdeDependencyResolver . withTransformer ( transformer : IdeDependencyTransformer )

= IdeDependencyResolver { sourceSet -> <EOL> transformer . transform ( sourceSet , this @ withTransformer . resolve ( sourceSet ) ) <EOL> }

/**
 * Creates a [IdeDependencyResolver] which will invoke the given [transformer] right after resolving the dependencies from the
 * receiver.
 */


@ ExternalKotlinTargetApi <EOL> fun IdeDependencyTransformer ( transformers : List < IdeDependencyTransformer ? > ) : IdeDependencyTransformer

= IdeCompositeDependencyTransformer ( transformers . filterNotNull ( ) )

/**
 * Create a composite [IdeDependencyTransformer]
 * `null` instances will just be ignored.
 * The transformers will be invoked in the same order as specified to this function.
 */


@ ExternalKotlinTargetApi <EOL> fun IdeDependencyTransformer ( vararg transformers : IdeDependencyTransformer ? <EOL> ) : IdeDependencyTransformer

= IdeDependencyTransformer ( transformers . toList ( ) )


fun collectAllCandidates ( qualifiedAccess : FirQualifiedAccessExpression , name : Name , containingDeclarations : List < FirDeclaration > = transformer . components . containingDeclarations , resolutionContext : ResolutionContext = transformer . resolutionContext , resolutionMode : ResolutionMode , ) : List < OverloadCandidate >

{ <EOL> val collector = AllCandidatesCollector ( components , components . resolutionStageRunner ) <EOL> val origin = ( qualifiedAccess as? FirFunctionCall ) ? . origin ? : FirFunctionCallOrigin . Regular <EOL> val result = <EOL> collectCandidates ( qualifiedAccess , name , forceCallKind = null , isUsedAsGetClassReceiver = false , origin , containingDeclarations , resolutionContext , collector , resolutionMode = resolutionMode ) <EOL> return collector . allCandidates . map { OverloadCandidate ( it , isInBestCandidates = it in result . candidates ) } <EOL> }

/** WARNING: This function is public for the analysis API and should only be used there. */


private fun reduceCandidates ( collector : CandidateCollector , explicitReceiver : FirExpression ? = null , resolutionContext : ResolutionContext = transformer . resolutionContext , ) : Pair < Set < Candidate > , CandidateApplicability ? >

{ <EOL> fun chooseMostSpecific ( list : List < Candidate > ) : Set < Candidate > { <EOL> val onSuperReference = ( explicitReceiver as? FirQualifiedAccessExpression ) ? . calleeReference is FirSuperReference <EOL> return conflictResolver . chooseMaximallySpecificCandidates ( list , discriminateAbstracts = onSuperReference ) <EOL> } <EOL> val candidates = collector . bestCandidates ( ) <EOL> if ( collector . isSuccess ) { <EOL> return chooseMostSpecific ( candidates ) to null <EOL> } <EOL> if ( candidates . size > <NUM_LIT:1> ) { <EOL> val groupedByDiagnosticCount = candidates . groupBy { <EOL> components . resolutionStageRunner . fullyProcessCandidate ( it , resolutionContext ) <EOL> it . diagnostics . minOf ( ResolutionDiagnostic :: applicability ) <EOL> } <EOL> groupedByDiagnosticCount . maxBy { it . key } . let { <EOL> return chooseMostSpecific ( it . value ) to it . key <EOL> } <EOL> } <EOL> return candidates . toSet ( ) to null <EOL> }

/**
 * Returns a [Pair] consisting of the reduced candidates and the new applicability if it has changed and `null` otherwise.
 */


public fun < K , V > PairSerializer ( keySerializer : KSerializer < K > , valueSerializer : KSerializer < V > ) : KSerializer < Pair < K , V > >

= kotlinx . serialization . internal . PairSerializer ( keySerializer , valueSerializer )

/**
 * Returns built-in serializer for Kotlin [Pair].
 * Resulting serializer represents pair as a structure of two key-value pairs.
 */


public fun < K , V > MapEntrySerializer ( keySerializer : KSerializer < K > , valueSerializer : KSerializer < V > ) : KSerializer < Map . Entry < K , V > >

= kotlinx . serialization . internal . MapEntrySerializer ( keySerializer , valueSerializer )

/**
 * Returns built-in serializer for [Map.Entry].
 * Resulting serializer represents entry as a structure with a single key-value pair.
 * E.g. `Pair(1, 2)` and `Map.Entry(1, 2)` will be serialized to JSON as
 * `{"first": 1, "second": 2}` and `{"1": 2}` respectively.
 */


public fun < A , B , C > TripleSerializer ( aSerializer : KSerializer < A > , bSerializer : KSerializer < B > , cSerializer : KSerializer < C > ) : KSerializer < Triple < A , B , C > >

= kotlinx . serialization . internal . TripleSerializer ( aSerializer , bSerializer , cSerializer )

/**
 * Returns built-in serializer for Kotlin [Triple].
 * Resulting serializer represents triple as a structure of three key-value pairs.
 */


public fun Char . Companion . serializer ( ) : KSerializer < Char >

= CharSerializer

/**
 * Returns serializer for [Char] with [descriptor][SerialDescriptor] of [PrimitiveKind.CHAR] kind.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun CharArraySerializer ( ) : KSerializer < CharArray >

= CharArraySerializer

/**
 * Returns serializer for [CharArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [Char.Companion.serializer].
 */


public fun Byte . Companion . serializer ( ) : KSerializer < Byte >

= ByteSerializer

/**
 * Returns serializer for [Byte] with [descriptor][SerialDescriptor] of [PrimitiveKind.BYTE] kind.
 */


public fun ByteArraySerializer ( ) : KSerializer < ByteArray >

= ByteArraySerializer

/**
 * Returns serializer for [ByteArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [Byte.Companion.serializer].
 */


@ ExperimentalSerializationApi <EOL> @ ExperimentalUnsignedTypes <EOL> public fun UByteArraySerializer ( ) : KSerializer < UByteArray >

= UByteArraySerializer

/**
 * Returns serializer for [UByteArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [UByte.Companion.serializer].
 */


public fun Short . Companion . serializer ( ) : KSerializer < Short >

= ShortSerializer

/**
 * Returns serializer for [Short] with [descriptor][SerialDescriptor] of [PrimitiveKind.SHORT] kind.
 */


public fun ShortArraySerializer ( ) : KSerializer < ShortArray >

= ShortArraySerializer

/**
 * Returns serializer for [ShortArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [Short.Companion.serializer].
 */


@ ExperimentalSerializationApi <EOL> @ ExperimentalUnsignedTypes <EOL> public fun UShortArraySerializer ( ) : KSerializer < UShortArray >

= UShortArraySerializer

/**
 * Returns serializer for [UShortArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [UShort.Companion.serializer].
 */


public fun Int . Companion . serializer ( ) : KSerializer < Int >

= IntSerializer

/**
 * Returns serializer for [Int] with [descriptor][SerialDescriptor] of [PrimitiveKind.INT] kind.
 */


public fun IntArraySerializer ( ) : KSerializer < IntArray >

= IntArraySerializer

/**
 * Returns serializer for [IntArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [Int.Companion.serializer].
 */


@ ExperimentalSerializationApi <EOL> @ ExperimentalUnsignedTypes <EOL> public fun UIntArraySerializer ( ) : KSerializer < UIntArray >

= UIntArraySerializer

/**
 * Returns serializer for [UIntArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [UInt.Companion.serializer].
 */


public fun Long . Companion . serializer ( ) : KSerializer < Long >

= LongSerializer

/**
 * Returns serializer for [Long] with [descriptor][SerialDescriptor] of [PrimitiveKind.LONG] kind.
 */


public fun LongArraySerializer ( ) : KSerializer < LongArray >

= LongArraySerializer

/**
 * Returns serializer for [LongArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [Long.Companion.serializer].
 */


@ ExperimentalSerializationApi <EOL> @ ExperimentalUnsignedTypes <EOL> public fun ULongArraySerializer ( ) : KSerializer < ULongArray >

= ULongArraySerializer

/**
 * Returns serializer for [ULongArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [ULong.Companion.serializer].
 */


public fun Float . Companion . serializer ( ) : KSerializer < Float >

= FloatSerializer

/**
 * Returns serializer for [Float] with [descriptor][SerialDescriptor] of [PrimitiveKind.FLOAT] kind.
 */


public fun FloatArraySerializer ( ) : KSerializer < FloatArray >

= FloatArraySerializer

/**
 * Returns serializer for [FloatArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [Float.Companion.serializer].
 */


public fun Double . Companion . serializer ( ) : KSerializer < Double >

= DoubleSerializer

/**
 * Returns serializer for [Double] with [descriptor][SerialDescriptor] of [PrimitiveKind.DOUBLE] kind.
 */


public fun DoubleArraySerializer ( ) : KSerializer < DoubleArray >

= DoubleArraySerializer

/**
 * Returns serializer for [DoubleArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [Double.Companion.serializer].
 */


public fun Boolean . Companion . serializer ( ) : KSerializer < Boolean >

= BooleanSerializer

/**
 * Returns serializer for [Boolean] with [descriptor][SerialDescriptor] of [PrimitiveKind.BOOLEAN] kind.
 */


public fun BooleanArraySerializer ( ) : KSerializer < BooleanArray >

= BooleanArraySerializer

/**
 * Returns serializer for [BooleanArray] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized one by one with [Boolean.Companion.serializer].
 */


@ Suppress ( "<STR_LIT:unused>" ) <EOL> public fun Unit . serializer ( ) : KSerializer < Unit >

= UnitSerializer

/**
 * Returns serializer for [Unit] with [descriptor][SerialDescriptor] of [StructureKind.OBJECT] kind.
 */


public fun String . Companion . serializer ( ) : KSerializer < String >

= StringSerializer

/**
 * Returns serializer for [String] with [descriptor][SerialDescriptor] of [PrimitiveKind.STRING] kind.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> @ ExperimentalSerializationApi <EOL> public inline fun < reified T : Any , reified E : T ? > ArraySerializer ( elementSerializer : KSerializer < E > ) : KSerializer < Array < E > >

= <EOL> ArraySerializer < T , E > ( T :: class , elementSerializer )

/**
 * Returns serializer for reference [Array] of type [E] with [descriptor][SerialDescriptor] of [StructureKind.LIST] kind.
 * Each element of the array is serialized with the given [elementSerializer].
 */


@ ExperimentalSerializationApi <EOL> public fun < T : Any , E : T ? > ArraySerializer ( kClass : KClass < T > , elementSerializer : KSerializer < E > ) : KSerializer < Array < E > >

= ReferenceArraySerializer < T , E > ( kClass , elementSerializer )


public fun < T > ListSerializer ( elementSerializer : KSerializer < T > ) : KSerializer < List < T > >

= <EOL> ArrayListSerializer ( elementSerializer )

/**
 * Creates a serializer for [`List<T>`][List] for the given serializer of type [T].
 */


public fun < T > SetSerializer ( elementSerializer : KSerializer < T > ) : KSerializer < Set < T > >

= <EOL> LinkedHashSetSerializer ( elementSerializer )

/**
 * Creates a serializer for [`Set<T>`][Set] for the given serializer of type [T].
 */


public fun < K , V > MapSerializer ( keySerializer : KSerializer < K > , valueSerializer : KSerializer < V > ) : KSerializer < Map < K , V > >

= LinkedHashMapSerializer ( keySerializer , valueSerializer )

/**
 * Creates a serializer for [`Map<K, V>`][Map] for the given serializers for
 * its ket type [K] and value type [V].
 */


public fun UInt . Companion . serializer ( ) : KSerializer < UInt >

= UIntSerializer

/**
 * Returns serializer for [UInt].
 */


public fun ULong . Companion . serializer ( ) : KSerializer < ULong >

= ULongSerializer

/**
 * Returns serializer for [ULong].
 */


public fun UByte . Companion . serializer ( ) : KSerializer < UByte >

= UByteSerializer

/**
 * Returns serializer for [UByte].
 */


public fun UShort . Companion . serializer ( ) : KSerializer < UShort >

= UShortSerializer

/**
 * Returns serializer for [UShort].
 */


public fun Duration . Companion . serializer ( ) : KSerializer < Duration >

= DurationSerializer

/**
 * Returns serializer for [Duration].
 * It is serialized as a string that represents a duration in the ISO-8601-2 format.
 *
 * The result of serialization is similar to calling [Duration.toIsoString], for deserialization is [Duration.parseIsoString].
 */


@ ExperimentalSerializationApi <EOL> public fun NothingSerializer ( ) : KSerializer < Nothing >

= NothingSerializer

/**
 * Returns serializer for [Nothing].
 * Throws an exception when trying to encode or decode.
 *
 * It is used as a dummy in case it is necessary to pass a type to a parameterized class. At the same time, it is expected that this generic type will not participate in serialization.
 */


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . ERROR ) <EOL> public fun Any . asDynamic ( ) : JsAny

= this . toJsReference ( )

/**
 * Reinterprets this value as a value of the Dynamic type.
 */


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . ERROR , replaceWith = ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ kotlin . internal . InlineOnly <EOL> public fun String . asDynamic ( ) : JsString

= this . toJsString ( )


public fun JsAny . toThrowableOrNull ( ) : Throwable ?

{ <EOL> val thisAny : Any = this <EOL> if ( thisAny is Throwable ) return thisAny <EOL> var result : Throwable ? = null <EOL> jsCatch { <EOL> try { <EOL> jsThrow ( this ) <EOL> } catch ( e : Throwable ) { <EOL> result = e <EOL> } <EOL> } <EOL> return result <EOL> }

/**
 * For a Dynamic value caught in JS, returns the corresponding [Throwable]
 * if it was thrown from Kotlin, or null otherwise.
 */


fun orthographicProjectionMatrix ( left : Float , right : Float , bottom : Float , top : Float , near : Float , far : Float ) : Matrix4

{ <EOL> val m3 = diagonalMatrix ( <NUM_LIT:2> / ( right - left ) , <NUM_LIT:2> / ( top - bottom ) , - <NUM_LIT:2> / ( far - near ) ) <EOL> val tx = - ( right + left ) / ( right - left ) <EOL> val ty = - ( top + bottom ) / ( top - bottom ) <EOL> val tz = - ( far + near ) / ( far - near ) <EOL> return Matrix4 ( m3 , col4 = Vector4 ( tx , ty , tz , <NUM_LIT> ) ) <EOL> }

/**
 * The matrix to perform the orthographic projection from the world coordinate system to the clip space,
 * as described in [glOrtho documentation](https://www.khronos.org/registry/OpenGL-Refpages/es1.1/xhtml/glOrtho.xml)
 */


private fun IrType . exploreType ( visitedSymbols : MutableSet < IrClassifierSymbol > ) : ExploredClassifier

{ <EOL> return when ( this ) { <EOL> is IrSimpleType -> classifier . exploreSymbol ( visitedSymbols ) . asUnusable ( ) <EOL> ? : arguments . firstUnusable { it . typeOrNull ? . exploreType ( visitedSymbols ) } <EOL> ? : Usable <EOL> is IrDynamicType -> Usable <EOL> else -> { <EOL> if ( this is IrErrorType && allowErrorTypes ) <EOL> Usable <EOL> else <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/** Explore the IR type to find the first cause why this type should be considered as unusable. */


private fun IrClassifierSymbol . exploreSymbol ( visitedSymbols : MutableSet < IrClassifierSymbol > ) : ExploredClassifier

{ <EOL> exploredSymbols [ this ] ? . let { result -> <EOL> return result <EOL> } <EOL> if ( ! isBound ) { <EOL> stubGenerator . getDeclaration ( this ) <EOL> return exploredSymbols . registerUnusable ( this , MissingClassifier ( this ) ) <EOL> } <EOL> ( owner as? IrLazyClass ) ? . let { lazyIrClass -> <EOL> val isEffectivelyMissingClassifier = <EOL> lazyIrClass . descriptor is NotFoundClasses . MockClassDescriptor <EOL> || lazyIrClass . isEffectivelyMissingLazyIrDeclaration ( ) <EOL> if ( isEffectivelyMissingClassifier ) <EOL> return exploredSymbols . registerUnusable ( this , MissingClassifier ( this ) ) <EOL> } <EOL> if ( ! visitedSymbols . add ( this ) ) { <EOL> return Usable <EOL> } <EOL> val cause : Unusable ? = when ( val classifier = owner ) { <EOL> is IrClass -> when ( PLModule . determineModuleFor ( owner as IrClass ) ) { <EOL> is PLModule . MissingDeclarations -> return exploredSymbols . registerUnusable ( this , MissingClassifier ( this ) ) <EOL> stdlibModule , PLModule . SyntheticBuiltInFunctions -> { <EOL> null <EOL> } <EOL> else -> { <EOL> val directSuperTypeSymbols = hashSetOf < IrClassSymbol > ( ) <EOL> classifier . annotationConstructorsIfApplicable ? . firstUnusable { it . exploreAnnotationConstructor ( visitedSymbols ) } <EOL> ? : classifier . outerClassSymbolIfApplicable ? . exploreSymbol ( visitedSymbols ) . asUnusable ( ) <EOL> ? : classifier . typeParameters . firstUnusable { it . symbol . exploreSymbol ( visitedSymbols ) } <EOL> ? : classifier . superTypes . firstUnusable { superType -> <EOL> directSuperTypeSymbols . addIfNotNull ( superType . asSimpleType ( ) ? . classifier as? IrClassSymbol ) <EOL> superType . exploreType ( visitedSymbols ) <EOL> } <EOL> ? : classifier . exploreSuperClasses ( directSuperTypeSymbols ) <EOL> } <EOL> } <EOL> is IrTypeParameter -> classifier . superTypes . firstUnusable { it . exploreType ( visitedSymbols ) } <EOL> else -> null <EOL> } <EOL> val rootCause = when { <EOL> cause == null -> return exploredSymbols . registerUsable ( this ) <EOL> cause . symbol == this -> return exploredSymbols . registerUnusable ( this , cause ) <EOL> else -> when ( cause ) { <EOL> is DueToOtherClassifier -> cause . rootCause <EOL> is CanBeRootCause -> cause <EOL> } <EOL> } <EOL> return exploredSymbols . registerUnusable ( this , DueToOtherClassifier ( this , rootCause ) ) <EOL> }

/** Explore the IR classifier symbol to find the first cause why this symbol should be considered as unusable. */


private fun IrValueParameter . exploreAnnotationConstructorParameter ( visitedSymbols : MutableSet < IrClassifierSymbol > , annotationClass : IrClass ) : Unusable ?

{ <EOL> val parameterType = type . asSimpleType ( ) ? : return null <EOL> val parameterClassSymbol = parameterType . classifier as IrClassSymbol <EOL> val parameterClass = parameterClassSymbol . owner <EOL> when { <EOL> parameterClass . isAnnotationClass -> { <EOL> parameterClassSymbol . exploreSymbol ( visitedSymbols ) . asUnusable ( ) ? . let { return it } <EOL> } <EOL> parameterClass . isEnumClass || parameterClassSymbol in permittedAnnotationParameterSymbols -> return null <EOL> parameterClassSymbol == builtIns . arrayClass -> { <EOL> for ( argument in parameterType . arguments ) { <EOL> val argumentClassSymbol = ( argument . typeOrNull ? . asSimpleType ( ) ? : continue ) . classifier as IrClassSymbol <EOL> val argumentClass = argumentClassSymbol . owner <EOL> when { <EOL> argumentClass . isAnnotationClass -> { <EOL> argumentClassSymbol . exploreSymbol ( visitedSymbols ) . asUnusable ( ) ? . let { return it } <EOL> } <EOL> argumentClass . isEnumClass || argumentClassSymbol in permittedAnnotationArrayParameterSymbols -> continue <EOL> else -> return AnnotationWithUnacceptableParameter ( annotationClass . symbol , argumentClassSymbol ) <EOL> } <EOL> } <EOL> } <EOL> else -> return AnnotationWithUnacceptableParameter ( annotationClass . symbol , parameterClassSymbol ) <EOL> } <EOL> return null <EOL> }

/** See also [org.jetbrains.kotlin.resolve.CompileTimeConstantUtils.isAcceptableTypeForAnnotationParameter] */


private inline fun < T > Iterable < T > . firstUnusable ( transform : ( T ) -> ExploredClassifier ? ) : Unusable ?

= <EOL> firstNotNullOfOrNull { transform ( it ) . asUnusable ( ) }

/** Iterate the collection and find the first unusable classifier. */


public expect fun < T > runBlocking ( context : CoroutineContext = EmptyCoroutineContext , block : suspend CoroutineScope . ( ) -> T ) : T

/**
 * Runs a new coroutine and **blocks** the current thread until its completion.
 *
 * It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in
 * `main` functions and in tests.
 *
 * Calling [runBlocking] from a suspend function is redundant.
 * For example, the following code is incorrect:
 * ```
 * suspend fun loadConfiguration() {
 * // DO NOT DO THIS:
 * val data = runBlocking { // <- redundant and blocks the thread, do not do that
 * fetchConfigurationData() // suspending function
 * }
 * ```
 *
 * Here, instead of releasing the thread on which `loadConfiguration` runs if `fetchConfigurationData` suspends, it will
 * block, potentially leading to thread starvation issues.
 */


@ ExperimentalMultikApi <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public fun LinAlg . svd ( mat : MultiArray < Float , D2 > ) : Triple < D2Array < Float > , D1Array < Float > , D2Array < Float > >

= this . linAlgEx . svdF ( mat )

/**
 * Returns SVD decomposition of the float matrix
 */


@ ExperimentalMultikApi <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public fun < T : Number > LinAlg . svd ( mat : MultiArray < T , D2 > ) : Triple < D2Array < Double > , D1Array < Double > , D2Array < Double > >

= this . linAlgEx . svd ( mat )

/**
 * Returns SVD decomposition of the numeric matrix
 */


@ ExperimentalMultikApi <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public fun < T : Complex > LinAlg . svd ( mat : MultiArray < T , D2 > ) : Triple < D2Array < T > , D1Array < T > , D2Array < T > >

= this . linAlgEx . svdC ( mat )

/**
 * Returns SVD decomposition of the complex matrix
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < reified T : Number > JavaRDD < T > . toJavaDoubleRDD ( ) : JavaDoubleRDD

= <EOL> JavaDoubleRDD . fromRDD ( when ( T :: class ) { <EOL> Double :: class -> this <EOL> else -> map ( Number :: toDouble ) <EOL> } . rdd ( ) as RDD < Any > )

/** Utility method to convert [JavaRDD]<[Number]> to [JavaDoubleRDD]. */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> fun JavaDoubleRDD . toDoubleRDD ( ) : JavaRDD < Double >

= <EOL> JavaDoubleRDD . toRDD ( this ) . toJavaRDD ( ) as JavaRDD < Double >

/** Utility method to convert [JavaDoubleRDD] to [JavaRDD]<[Double]>. */


inline fun < reified T : Number > JavaRDD < T > . sum ( ) : Double

= toJavaDoubleRDD ( ) . sum ( )


inline fun < reified T : Number > JavaRDD < T > . stats ( ) : StatCounter

= toJavaDoubleRDD ( ) . stats ( )

/**
 * Return a [org.apache.spark.util.StatCounter] object that captures the mean, variance and
 * count of the RDD's elements in one operation.
 */


inline fun < reified T : Number > JavaRDD < T > . mean ( ) : Double

= toJavaDoubleRDD ( ) . mean ( )

/** Compute the mean of this RDD's elements. */


inline fun < reified T : Number > JavaRDD < T > . variance ( ) : Double

= toJavaDoubleRDD ( ) . variance ( )

/** Compute the population variance of this RDD's elements. */


inline fun < reified T : Number > JavaRDD < T > . stdev ( ) : Double

= toJavaDoubleRDD ( ) . stdev ( )

/** Compute the population standard deviation of this RDD's elements. */


inline fun < reified T : Number > JavaRDD < T > . sampleStdev ( ) : Double

= toJavaDoubleRDD ( ) . sampleStdev ( )

/**
 * Compute the sample standard deviation of this RDD's elements (which corrects for bias in
 * estimating the standard deviation by dividing by N-1 instead of N).
 */


inline fun < reified T : Number > JavaRDD < T > . sampleVariance ( ) : Double

= toJavaDoubleRDD ( ) . sampleVariance ( )

/**
 * Compute the sample variance of this RDD's elements (which corrects for bias in
 * estimating the variance by dividing by N-1 instead of N).
 */


inline fun < reified T : Number > JavaRDD < T > . popStdev ( ) : Double

= toJavaDoubleRDD ( ) . popStdev ( )


inline fun < reified T : Number > JavaRDD < T > . popVariance ( ) : Double

= toJavaDoubleRDD ( ) . popVariance ( )


inline fun < reified T : Number > JavaRDD < T > . meanApprox ( timeout : Long , confidence : Double = <NUM_LIT> , ) : PartialResult < BoundedDouble >

= toJavaDoubleRDD ( ) . meanApprox ( timeout , confidence )

/** Approximate operation to return the mean within a timeout. */


inline fun < reified T : Number > JavaRDD < T > . sumApprox ( timeout : Long , confidence : Double = <NUM_LIT> , ) : PartialResult < BoundedDouble >

= toJavaDoubleRDD ( ) . sumApprox ( timeout , confidence )

/** Approximate operation to return the sum within a timeout. */


inline fun < reified T : Number > JavaRDD < T > . histogram ( bucketCount : Int ) : Tuple2 < DoubleArray , LongArray >

= <EOL> toJavaDoubleRDD ( ) . histogram ( bucketCount )

/**
 * Compute a histogram of the data using bucketCount number of buckets evenly
 * spaced between the minimum and maximum of the RDD. For example if the min
 * value is 0 and the max is 100 and there are two buckets the resulting
 * buckets will be `[0, 50)` `[50, 100]`. bucketCount must be at least 1
 * If the RDD contains infinity, NaN throws an exception
 * If the elements in RDD do not vary (max == min) always returns a single bucket.
 */


inline fun < reified T : Number > JavaRDD < T > . histogram ( buckets : Array < Double > , evenBuckets : Boolean = false , ) : LongArray

= toJavaDoubleRDD ( ) . histogram ( buckets , evenBuckets )

/**
 * Compute a histogram using the provided buckets. The buckets are all open
 * to the right except for the last which is closed.
 * e.g. for the array
 * `[1, 10, 20, 50]` the buckets are `[1, 10) [10, 20) [20, 50]`
 * e.g. ` <=x<10, 10<=x<20, 20<=x<=50`
 * And on the input of 1 and 50 we would have a histogram of 1, 0, 1
 *
 * Note: If your histogram is evenly spaced (e.g. `[0, 10, 20, 30]`) this can be switched
 * from an O(log n) insertion to O(1) per element. (where n = # buckets) if you set evenBuckets
 * to true.
 * buckets must be sorted and not contain any duplicates.
 * buckets array must be at least two elements
 * All NaN entries are treated the same. If you have a NaN bucket it must be
 * the maximum value of the last position and all NaN entries will be counted
 * in that bucket.
 */


fun DependencyHandler . module ( dependency : ProjectDependency , moduleName : String ) : ProjectDependency

= dependency . copy ( ) . apply { <EOL> capabilities { <EOL> requireCapability ( CppConsumerPlugin . moduleCapability ( dependencyProject , moduleName ) ) <EOL> } <EOL> }

/**
 * Depend on [CompileToBitcodePlugin]'s module named [moduleName] defined in [dependency].
 */


fun DependencyHandler . moduleTestFixtures ( dependency : ProjectDependency , moduleName : String ) : ProjectDependency

= dependency . copy ( ) . apply { <EOL> capabilities { <EOL> requireCapability ( CppConsumerPlugin . moduleTestFixturesCapability ( dependencyProject , moduleName ) ) <EOL> } <EOL> }

/**
 * Depend on [CompileToBitcodePlugin]'s module (testFixtures part) named [moduleName] defined in [dependency].
 */


fun DependencyHandler . moduleTest ( dependency : ProjectDependency , moduleName : String ) : ProjectDependency

= dependency . copy ( ) . apply { <EOL> capabilities { <EOL> requireCapability ( CppConsumerPlugin . moduleTestCapability ( dependencyProject , moduleName ) ) <EOL> } <EOL> }

/**
 * Depend on [CompileToBitcodePlugin]'s module (test part) named [moduleName] defined in [dependency].
 */


fun annotationInfos ( ) : List < KtAnnotationApplicationInfo >

/**
 * @return a list of [KtAnnotationApplicationInfo] applicable for this provider
 */


fun ownerClassId ( ) : ClassId ?

/**
 * Example:
 * ```
 * package one
 *
 * @Ann1 @Ann2
 * class Foo
 * ```
 * If this provider provides annotations from `Foo` class then the result of the function will be [ClassId] for `one.Foo`
 *
 * @return [ClassId] of an owner of annotations from this provider
 */


public fun ColumnSet < * > . valueCols ( filter : Predicate < ValueColumn < * > > = { true } ) : TransformableColumnSet < * >

= <EOL> valueColumnsInternal ( filter )

/**
 * @include [CommonValueColsDocs]
 * @set [CommonValueColsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") }.`[valueCols][ColumnSet.valueCols]`() }`
 *
 * `// NOTE: This can be shortened to just:`
 *
 * `df.`[select][DataFrame.select]` { `[valueCols][ColumnsSelectionDsl.valueCols]` { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun ColumnsSelectionDsl < * > . valueCols ( filter : Predicate < ValueColumn < * > > = { true } ) : TransformableColumnSet < * >

= <EOL> asSingleColumn ( ) . valueColumnsInternal ( filter )

/**
 * @include [CommonValueColsDocs]
 * @set [CommonValueColsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[valueCols][ColumnsSelectionDsl.valueCols]`() }`
 *
 * `df.`[select][DataFrame.select]` { `[valueCols][ColumnsSelectionDsl.valueCols]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 */


public fun SingleColumn < DataRow < * > > . valueCols ( filter : Predicate < ValueColumn < * > > = { true } ) : TransformableColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . valueColumnsInternal ( filter )

/**
 * @include [CommonValueColsDocs]
 * @set [CommonValueColsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { myColGroup.`[valueCols][SingleColumn.valueCols]`() }`
 *
 * `df.`[select][DataFrame.select]` { myColGroup.`[valueCols][SingleColumn.valueCols]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 */


public fun String . valueCols ( filter : Predicate < ValueColumn < * > > = { true } ) : TransformableColumnSet < * >

= <EOL> columnGroup ( this ) . valueCols ( filter )

/**
 * @include [CommonValueColsDocs]
 * @set [CommonValueColsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "myColGroup".`[valueCols][String.valueCols]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 *
 * `df.`[select][DataFrame.select]` { "myColGroup".`[valueCols][String.valueCols]`() }`
 */


public fun KProperty < * > . valueCols ( filter : Predicate < ValueColumn < * > > = { true } ) : TransformableColumnSet < * >

/**
 * @include [CommonValueColsDocs]
 * @set [CommonValueColsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { Type::myColumnGroup.`[valueCols][KProperty.valueCols]` { it.`[any][ColumnWithPath.any]` { it == "Alice" } } }`
 *
 * `df.`[select][DataFrame.select]` { Type::myColumnGroup.`[valueCols][KProperty.valueCols]`() }`
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColumnGroup.`[valueCols][KProperty.valueCols]`() }`
 */


public fun ColumnPath . valueCols ( filter : Predicate < ValueColumn < * > > = { true } ) : TransformableColumnSet < * >

/**
 * @include [CommonValueColsDocs]
 * @set [CommonValueColsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["myGroupCol"].`[valueCols][ColumnPath.valueCols]`() }`
 */


internal fun ColumnsResolver < * > . valueColumnsInternal ( filter : ( ValueColumn < * > ) -> Boolean ) : TransformableColumnSet < * >

= <EOL> colsInternal { it . isValueColumn ( ) && filter ( it . asValueColumn ( ) ) }

/**
 * Returns a TransformableColumnSet containing the value columns that satisfy the given filter.
 *
 * @param filter The filter function to apply on each value column. Must accept a ValueColumn object and return a Boolean.
 * @return A [TransformableColumnSet] containing the value columns that satisfy the filter.
 */


@ OptIn ( SessionConfiguration :: class ) <EOL> fun FirSession . registerDefaultComponents ( )

{ <EOL> register ( FirVisibilityChecker :: class , FirVisibilityChecker . Default ) <EOL> register ( ConeCallConflictResolverFactory :: class , DefaultCallConflictResolverFactory ) <EOL> register ( FirPlatformClassMapper :: class , FirPlatformClassMapper . Default ) <EOL> register ( FirOverridesBackwardCompatibilityHelper :: class , FirDefaultOverridesBackwardCompatibilityHelper ) <EOL> register ( FirDelegatedMembersFilter :: class , FirDelegatedMembersFilter . Default ) <EOL> register ( FirPlatformSpecificCastChecker :: class , FirPlatformSpecificCastChecker . Default ) <EOL> register ( FirDefaultImportProviderHolder :: class , FirDefaultImportProviderHolder ( CommonPlatformAnalyzerServices ) ) <EOL> }

/**
 * Registers default components for [FirSession]
 * They could be overridden by calling a function that registers specific platform components
 */


fun fromSystemProperty ( key : String ) : DebugMode

= when ( System . getProperty ( key ) ) { <EOL> "<STR_LIT:2>" , "<STR_LIT>" -> SUPER_DEBUG <EOL> "<STR_LIT:1>" , "<STR_LIT:true>" , "<STR_LIT>" -> DEBUG <EOL> "<STR_LIT:0>" , "<STR_LIT:false>" , "<STR_LIT>" , null -> NONE <EOL> else -> NONE <EOL> }

/**
 * Obtains a [DebugMode] from the system property with the given [key].
 * If the property is not defined, returns [NONE].
 */


public external fun eval ( expr : String ) : dynamic

/**
 * Exposes the JavaScript [eval function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) to Kotlin.
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> fun display ( value : Any )

= display ( value , null )

/**
 * Try to display the given value. It is only displayed if it's an instance of [Renderable]
 * or may be converted to it
 *
 * Left for binary compatibility
 */


fun display ( value : Any , id : String ? = null , )

/**
 * Try to display the given value. It is only displayed if it's an instance of [Renderable]
 * or may be converted to it
 */


fun updateDisplay ( value : Any , id : String ? = null , )

/**
 * Updates display data with given [id] with the new [value]
 */


fun scheduleExecution ( execution : ExecutionCallback < * > )

/**
 * Schedules execution of the given [execution] after the completing of execution of the current cell
 */


fun execute ( code : Code ) : FieldValue

/**
 * Executes code immediately. Note that it may lead to breaking the kernel state in some cases
 */


fun addLibraries ( libraries : Collection < LibraryDefinition > )

/**
 * Adds new libraries via their definition. Fully interchangeable with `%use` approach
 */


fun acceptsIntegrationTypeName ( typeName : String ) : Boolean ?

/**
 * Says whether this [typeName] should be loaded as integration based on loaded libraries.
 * `null` means that loaded libraries don't care about this [typeName].
 */


fun loadKotlinArtifacts ( artifacts : Collection < String > , version : String ? = null , )

/**
 * Loads Kotlin standard artifacts (org.jetbrains.kotlin:kotlin-$name:$version)
 *
 * @param artifacts Names of the artifacts substituted to the above line
 * @param version Version of the artifacts to load. Current Kotlin version will be used by default
 */


fun loadStdlibJdkExtensions ( version : String ? = null )

/**
 * Loads Kotlin standard library extensions for a current JDK
 *
 * @param version Version of the artifact to load. Current Kotlin version will be used by default
 */


fun declare ( variables : Iterable < VariableDeclaration > )

/**
 * Declares global variables for notebook
 */


private fun hackExceptions ( constructor : IrConstructor )

{ <EOL> val setPropertiesSymbol = context . setPropertiesToThrowableInstanceSymbol <EOL> val statements = ( constructor . body as? IrBlockBody ) ? . statements ? : return <EOL> var callIndex = - <NUM_LIT:1> <EOL> var superCallIndex = - <NUM_LIT:1> <EOL> for ( i in statements . indices ) { <EOL> val s = statements [ i ] <EOL> if ( s is IrCall && s . symbol === setPropertiesSymbol ) { <EOL> callIndex = i <EOL> } <EOL> if ( s is IrDelegatingConstructorCall && s . symbol . owner . origin === PrimaryConstructorLowering . SYNTHETIC_PRIMARY_CONSTRUCTOR ) { <EOL> superCallIndex = i <EOL> } <EOL> } <EOL> if ( callIndex != - <NUM_LIT:1> && superCallIndex != - <NUM_LIT:1> ) { <EOL> val tmp = statements [ callIndex ] <EOL> statements [ callIndex ] = statements [ superCallIndex ] <EOL> statements [ superCallIndex ] = tmp <EOL> } <EOL> }

/**
 * Swap call synthetic primary ctor and call extendThrowable
 */


fun < T1 , T2 > Pair < T1 , T2 > . toTuple ( ) : Tuple2 < T1 , T2 >

= Tuple2 < T1 , T2 > ( first , second )

/**
 * Returns a new [Tuple2] based on the arguments in the current [Pair].
 */


fun < T1 , T2 > Tuple2 < T1 , T2 > . toPair ( ) : Pair < T1 , T2 >

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

/**
 * Returns a new [Pair] based on the arguments in the current [Tuple2].
 */


fun < T1 , T2 , T3 > Triple < T1 , T2 , T3 > . toTuple ( ) : Tuple3 < T1 , T2 , T3 >

= Tuple3 < T1 , T2 , T3 > ( first , second , third )

/**
 * Returns a new [Tuple3] based on the arguments in the current [Triple].
 */


fun < T1 , T2 , T3 > Tuple3 < T1 , T2 , T3 > . toTriple ( ) : Triple < T1 , T2 , T3 >

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

/**
 * Returns a new [Triple] based on the arguments in the current [Tuple3].
 */


@ InternalCoroutinesApi <EOL> public fun Job . cancelFutureOnCompletion ( future : Future < * > ) : DisposableHandle

= <EOL> invokeOnCompletion ( handler = CancelFutureOnCompletion ( future ) )

/**
 * Cancels a specified [future] when this job is cancelled.
 * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created).
 * ```
 * invokeOnCompletion { if (it != null) future.cancel(false) }
 * ```
 *
 * @suppress **This an internal API and should not be used from general code.**
 */


public fun CancellableContinuation < * > . cancelFutureOnCancellation ( future : Future < * > ) : Unit

= <EOL> invokeOnCancellation ( handler = CancelFutureOnCancel ( future ) )

/**
 * Cancels a specified [future] when this job is cancelled.
 * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created).
 * ```
 * invokeOnCancellation { if (it != null) future.cancel(false) }
 * ```
 */


fun setPythonConfig ( pythonPath : String )

{ <EOL> val pyHome = File ( pythonPath ) <EOL> if ( ! pyHome . exists ( ) ) throw FileNotFoundException ( "<STR_LIT>" ) <EOL> val os = getOS ( ) <EOL> val pythonExePath = when ( os ) { <EOL> OSType . WINDOWS -> Pair ( File ( "<STR_LIT>" ) , File ( "<STR_LIT>" ) ) <EOL> OSType . LINUX , OSType . MACOS -> Pair ( File ( "<STR_LIT>" ) , File ( "<STR_LIT>" ) ) <EOL> OSType . UNKNOWN -> throw Exception ( "<STR_LIT>" ) <EOL> } <EOL> val python = when { <EOL> pythonExePath . first . exists ( ) -> pythonExePath . first . absolutePath <EOL> pythonExePath . second . exists ( ) -> pythonExePath . second . absolutePath <EOL> else -> throw FileNotFoundException ( "<STR_LIT>" ) <EOL> } <EOL> val pythonLibPath = getPythonEnv ( pythonScriptName , "<STR_LIT>" , python ) <EOL> pythonConf = PythonConf ( os , pyHome . absolutePath , pythonLibPath , python ) <EOL> }

/**
 * Sets paths to python executable and python std lib.
 *
 * NOTE: by default, directory specified in `PYTHONHOME` is used or directory returned from
 * `sysconfig.get_config_var('prefix')` command.
 *
 * @param pythonPath PYTHONHOME, directory where python is installed
 * @exception FileNotFoundException
 */


{ <EOL> if ( pythonConf == null ) { <EOL> val osType = getOS ( ) <EOL> val pythonHome = System . getenv ( "<STR_LIT>" ) ? : getPythonEnv ( pythonScriptName , "<STR_LIT>" ) <EOL> pythonConf = PythonConf ( osType = osType , pythonHome = pythonHome , pythonLibPath = getPythonEnv ( pythonScriptName , "<STR_LIT>" ) , "<STR_LIT>" ) <EOL> } <EOL> val locationLib : String <EOL> val exceptionMessage = StringBuilder ( ) <EOL> try { <EOL> System . loadLibrary ( baseNameNativeLib ) <EOL> return <EOL> } catch ( e : UnsatisfiedLinkError ) { <EOL> exceptionMessage <EOL> . append ( e . message ) <EOL> . append ( "<STR_LIT:\n>" ) <EOL> } <EOL> val pypiURL = <EOL> if ( version != null && version ! ! . contains ( "<STR_LIT>" ) ) "<STR_LIT>" else "<STR_LIT>" <EOL> var pipOut = execCommand ( pythonConf ! ! . python , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) <EOL> if ( pipOut . isEmpty ( ) || "<STR_LIT>" in pipOut ) { <EOL> execCommand ( pythonConf ! ! . python , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , pypiURL , "<STR_LIT>" ) <EOL> pipOut = execCommand ( pythonConf ! ! . python , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) <EOL> } <EOL> if ( version != null && pipOut . substringAfter ( "<STR_LIT>" ) . substringBefore ( "<STR_LIT:\n>" ) != version ) { <EOL> execCommand ( pythonConf ! ! . python , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , pypiURL , "<STR_LIT>" , "<STR_LIT>" ) <EOL> } <EOL> locationLib = if ( pythonConf ! ! . osType == OSType . WINDOWS ) { <EOL> buildString { <EOL> append ( pythonConf ! ! . pythonHome ) <EOL> append ( "<STR_LIT>" ) <EOL> } <EOL> } else { <EOL> buildString { <EOL> append ( pipOut . substringAfter ( "<STR_LIT>" ) . substringBefore ( "<STR_LIT:\n>" ) ) <EOL> append ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> try { <EOL> System . load ( locationLib ) <EOL> } catch ( e : UnsatisfiedLinkError ) { <EOL> exceptionMessage <EOL> . append ( e . message ) <EOL> . append ( "<STR_LIT:\n>" ) <EOL> throw UnsatisfiedLinkError ( exceptionMessage . toString ( ) ) <EOL> } <EOL> }

/**
 * Load *ktnumpy* and *pythonlib*.
 *
 * Pip is used to search for *ktnumpy*, if *ktnumpy* is not installed, pip installs the appropriate version.
 */


{ <EOL> val jsonConfigFile = getVGG16JSONConfigFile ( ) <EOL> val model = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> val imageNetClassLabels = Imagenet . V1k . labels ( ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . MAE , metric = Metrics . ACCURACY ) <EOL> println ( it . kGraph ) <EOL> it . logSummary ( ) <EOL> it . loadWeights ( getVGG16WeightsFile ( ) ) <EOL> val fileLoader = pipeline < BufferedImage > ( ) <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . call ( InputType . CAFFE . preprocessing ( ) ) <EOL> . fileLoader ( ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:8> ) { <EOL> val inputData = fileLoader . load ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val res = it . predict ( inputData , "<STR_LIT>" ) <EOL> println ( "<STR_LIT>" ) <EOL> val top5 = it . predictTop5Labels ( inputData , imageNetClassLabels ) <EOL> println ( top5 . toString ( ) ) <EOL> } <EOL> } <EOL> }

/**
 * This example demonstrates the inference concept on VGG'16 model and weights loading from KotlinDL txt format:
 * - Weights are loaded from txt files, configuration is loaded from .json file.
 * - Model predicts on a few images located in resources.
 * - Special preprocessing (used in VGG'16 during training on ImageNet dataset) is applied to each image before prediction.
 * - No additional training.
 * - No new layers are added.
 *
 * @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.
 */


private fun getVGG16JSONConfigFile ( ) : File

{ <EOL> val properties = Properties ( ) <EOL> val reader = FileReader ( "<STR_LIT>" ) <EOL> properties . load ( reader ) <EOL> val vgg16JSONModelPath = properties [ "<STR_LIT>" ] as String <EOL> return File ( vgg16JSONModelPath ) <EOL> }

/** Returns JSON file with model configuration, saved from Keras 2.x. */


private fun getVGG16WeightsFile ( ) : File

{ <EOL> val properties = Properties ( ) <EOL> val reader = FileReader ( "<STR_LIT>" ) <EOL> properties . load ( reader ) <EOL> val vgg16h5TxtWeightsPath = properties [ "<STR_LIT>" ] as String <EOL> return File ( vgg16h5TxtWeightsPath ) <EOL> }

/** Returns .h5 file with model weights, saved from Keras 2.x. */


fun toolOptions ( configure : TO . ( ) -> Unit )

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

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


fun toolOptions ( configure : Action < in TO > )

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


fun < F > prepareJvmSessions ( files : List < F > , configuration : CompilerConfiguration , projectEnvironment : AbstractProjectEnvironment , rootModuleName : Name , extensionRegistrars : List < FirExtensionRegistrar > , librariesScope : AbstractProjectFileSearchScope , libraryList : DependencyListForCliModule , isCommonSource : ( F ) -> Boolean , isScript : ( F ) -> Boolean , fileBelongsToModule : ( F , String ) -> Boolean , createProviderAndScopeForIncrementalCompilation : ( List < F > ) -> IncrementalCompilationContext ? , ) : List < SessionWithSources < F > >

{ <EOL> val javaSourcesScope = projectEnvironment . getSearchScopeForProjectJavaSources ( ) <EOL> val predefinedJavaComponents = FirSharableJavaComponents ( firCachesFactoryForCliMode ) <EOL> var firJvmIncrementalCompilationSymbolProviders : FirJvmIncrementalCompilationSymbolProviders ? = null <EOL> var firJvmIncrementalCompilationSymbolProvidersIsInitialized = false <EOL> return prepareSessions ( files , configuration , rootModuleName , JvmPlatforms . unspecifiedJvmPlatform , metadataCompilationMode = false , libraryList , isCommonSource , isScript , fileBelongsToModule , createLibrarySession = { sessionProvider -> <EOL> FirJvmSessionFactory . createLibrarySession ( rootModuleName , sessionProvider , libraryList . moduleDataProvider , projectEnvironment , extensionRegistrars , librariesScope , projectEnvironment . getPackagePartProvider ( librariesScope ) , configuration . languageVersionSettings , predefinedJavaComponents = predefinedJavaComponents , registerExtraComponents = { } , ) <EOL> } , ) { moduleFiles , moduleData , sessionProvider , sessionConfigurator -> <EOL> FirJvmSessionFactory . createModuleBasedSession ( moduleData , sessionProvider , javaSourcesScope , projectEnvironment , createIncrementalCompilationSymbolProviders = { session -> <EOL> if ( firJvmIncrementalCompilationSymbolProvidersIsInitialized ) firJvmIncrementalCompilationSymbolProviders <EOL> else { <EOL> firJvmIncrementalCompilationSymbolProvidersIsInitialized = true <EOL> createProviderAndScopeForIncrementalCompilation ( moduleFiles ) ? . createSymbolProviders ( session , moduleData , projectEnvironment ) ? . also { <EOL> firJvmIncrementalCompilationSymbolProviders = it <EOL> } <EOL> } <EOL> } , extensionRegistrars , configuration . languageVersionSettings , configuration . get ( JVMConfigurationKeys . JVM_TARGET , JvmTarget . DEFAULT ) , configuration . get ( CommonConfigurationKeys . LOOKUP_TRACKER ) , configuration . get ( CommonConfigurationKeys . ENUM_WHEN_TRACKER ) , configuration . get ( CommonConfigurationKeys . IMPORT_TRACKER ) , predefinedJavaComponents = predefinedJavaComponents , needRegisterJavaElementFinder = true , registerExtraComponents = { } , sessionConfigurator , ) <EOL> } <EOL> }

/**
 * Creates library session and sources session for JVM platform
 * Number of created session depends on mode of MPP:
 * - disabled
 * - legacy (one platform and one common module)
 * - HMPP (multiple number of modules)
 */


fun < F > prepareJsSessions ( files : List < F > , configuration : CompilerConfiguration , rootModuleName : Name , resolvedLibraries : List < KotlinLibrary > , libraryList : DependencyListForCliModule , extensionRegistrars : List < FirExtensionRegistrar > , isCommonSource : ( F ) -> Boolean , fileBelongsToModule : ( F , String ) -> Boolean , lookupTracker : LookupTracker ? , icData : KlibIcData ? , ) : List < SessionWithSources < F > >

{ <EOL> return prepareSessions ( files , configuration , rootModuleName , JsPlatforms . defaultJsPlatform , metadataCompilationMode = false , libraryList , isCommonSource , isScript = { false } , fileBelongsToModule , createLibrarySession = { sessionProvider -> <EOL> FirJsSessionFactory . createLibrarySession ( rootModuleName , resolvedLibraries , sessionProvider , libraryList . moduleDataProvider , extensionRegistrars , configuration , registerExtraComponents = { } , ) <EOL> } ) { _ , moduleData , sessionProvider , sessionConfigurator -> <EOL> FirJsSessionFactory . createModuleBasedSession ( moduleData , sessionProvider , extensionRegistrars , configuration , lookupTracker , icData = icData , registerExtraComponents = { } , init = sessionConfigurator , ) <EOL> } <EOL> }

/**
 * Creates library session and sources session for JS platform
 * Number of created session depends on mode of MPP:
 * - disabled
 * - legacy (one platform and one common module)
 * - HMPP (multiple number of modules)
 */


fun < F > prepareNativeSessions ( files : List < F > , configuration : CompilerConfiguration , rootModuleName : Name , resolvedLibraries : List < KotlinResolvedLibrary > , libraryList : DependencyListForCliModule , extensionRegistrars : List < FirExtensionRegistrar > , metadataCompilationMode : Boolean , isCommonSource : ( F ) -> Boolean , fileBelongsToModule : ( F , String ) -> Boolean , registerExtraComponents : ( ( FirSession ) -> Unit ) = { } , ) : List < SessionWithSources < F > >

{ <EOL> return prepareSessions ( files , configuration , rootModuleName , NativePlatforms . unspecifiedNativePlatform , metadataCompilationMode , libraryList , isCommonSource , isScript = { false } , fileBelongsToModule , createLibrarySession = { sessionProvider -> <EOL> FirNativeSessionFactory . createLibrarySession ( rootModuleName , resolvedLibraries , sessionProvider , libraryList . moduleDataProvider , extensionRegistrars , configuration . languageVersionSettings , registerExtraComponents , ) <EOL> } ) { _ , moduleData , sessionProvider , sessionConfigurator -> <EOL> FirNativeSessionFactory . createModuleBasedSession ( moduleData , sessionProvider , extensionRegistrars , configuration . languageVersionSettings , sessionConfigurator , registerExtraComponents , ) <EOL> } <EOL> }

/**
 * Creates library session and sources session for Native platform
 * Number of created session depends on mode of MPP:
 * - disabled
 * - legacy (one platform and one common module)
 * - HMPP (multiple number of modules)
 */


fun < F > prepareWasmSessions ( files : List < F > , configuration : CompilerConfiguration , rootModuleName : Name , resolvedLibraries : List < KotlinLibrary > , libraryList : DependencyListForCliModule , extensionRegistrars : List < FirExtensionRegistrar > , isCommonSource : ( F ) -> Boolean , fileBelongsToModule : ( F , String ) -> Boolean , lookupTracker : LookupTracker ? , icData : KlibIcData ? , ) : List < SessionWithSources < F > >

{ <EOL> return prepareSessions ( files , configuration , rootModuleName , WasmPlatforms . Default , metadataCompilationMode = false , libraryList , isCommonSource , isScript = { false } , fileBelongsToModule , createLibrarySession = { sessionProvider -> <EOL> FirWasmSessionFactory . createLibrarySession ( rootModuleName , resolvedLibraries , sessionProvider , libraryList . moduleDataProvider , extensionRegistrars , configuration . languageVersionSettings , registerExtraComponents = { } , ) <EOL> } ) { _ , moduleData , sessionProvider , sessionConfigurator -> <EOL> FirWasmSessionFactory . createModuleBasedSession ( moduleData , sessionProvider , extensionRegistrars , configuration . languageVersionSettings , configuration . wasmTarget , lookupTracker , icData = icData , registerExtraComponents = { } , init = sessionConfigurator , ) <EOL> } <EOL> }

/**
 * Creates library session and sources session for Wasm platform
 * Number of created session depends on mode of MPP:
 * - disabled
 * - legacy (one platform and one common module)
 * - HMPP (multiple number of modules)
 */


fun < F > prepareCommonSessions ( files : List < F > , configuration : CompilerConfiguration , projectEnvironment : AbstractProjectEnvironment , rootModuleName : Name , extensionRegistrars : List < FirExtensionRegistrar > , librariesScope : AbstractProjectFileSearchScope , libraryList : DependencyListForCliModule , resolvedLibraries : List < KotlinResolvedLibrary > , isCommonSource : ( F ) -> Boolean , fileBelongsToModule : ( F , String ) -> Boolean , createProviderAndScopeForIncrementalCompilation : ( List < F > ) -> IncrementalCompilationContext ? , ) : List < SessionWithSources < F > >

{ <EOL> return prepareSessions ( files , configuration , rootModuleName , CommonPlatforms . defaultCommonPlatform , metadataCompilationMode = true , libraryList , isCommonSource , isScript = { false } , fileBelongsToModule , createLibrarySession = { sessionProvider -> <EOL> FirCommonSessionFactory . createLibrarySession ( rootModuleName , sessionProvider , libraryList . moduleDataProvider , projectEnvironment , extensionRegistrars , librariesScope , resolvedLibraries , projectEnvironment . getPackagePartProvider ( librariesScope ) as PackageAndMetadataPartProvider , configuration . languageVersionSettings , registerExtraComponents = { } , ) <EOL> } ) { moduleFiles , moduleData , sessionProvider , sessionConfigurator -> <EOL> FirCommonSessionFactory . createModuleBasedSession ( moduleData , sessionProvider , projectEnvironment , incrementalCompilationContext = createProviderAndScopeForIncrementalCompilation ( moduleFiles ) , extensionRegistrars , configuration . languageVersionSettings , lookupTracker = configuration . get ( CommonConfigurationKeys . LOOKUP_TRACKER ) , enumWhenTracker = configuration . get ( CommonConfigurationKeys . ENUM_WHEN_TRACKER ) , importTracker = configuration . get ( CommonConfigurationKeys . IMPORT_TRACKER ) , registerExtraComponents = { } , init = sessionConfigurator ) <EOL> } <EOL> }

/**
 * Creates library session and sources session for Common platform (for metadata compilation)
 * Number of created sessions is always one, in this mode modules are compiled against compiled
 * metadata of dependent modules
 */


internal fun createLTOPipelineConfigForRuntime ( generationState : NativeGenerationState ) : LlvmPipelineConfig

{ <EOL> val config = generationState . config <EOL> val configurables : Configurables = config . platform . configurables <EOL> return LlvmPipelineConfig ( generationState . llvm . targetTriple , getCpuModel ( generationState ) , getCpuFeatures ( generationState ) , LlvmOptimizationLevel . AGGRESSIVE , LlvmSizeLevel . NONE , LLVMCodeGenOptLevel . LLVMCodeGenLevelAggressive , configurables . currentRelocationMode ( generationState ) . translateToLlvmRelocMode ( ) , LLVMCodeModel . LLVMCodeModelDefault , globalDce = false , internalize = false , objCPasses = configurables is AppleConfigurables , makeDeclarationsHidden = false , inlineThreshold = tryGetInlineThreshold ( generationState ) , ) <EOL> }

/**
 * Creates [LlvmPipelineConfig] that is used for [RuntimeLinkageStrategy.LinkAndOptimize].
 * There is no DCE or internalization here because optimized module will be linked later.
 * Still, runtime is not intended to be debugged by user, and we can optimize it pretty aggressively
 * even in debug compilation.
 */


internal fun createLTOFinalPipelineConfig ( context : PhaseContext , targetTriple : String , closedWorld : Boolean , timePasses : Boolean = false , ) : LlvmPipelineConfig

{ <EOL> val config = context . config <EOL> val target = config . target <EOL> val configurables : Configurables = config . platform . configurables <EOL> val cpuModel = getCpuModel ( context ) <EOL> val cpuFeatures = getCpuFeatures ( context ) <EOL> val optimizationLevel : LlvmOptimizationLevel = when { <EOL> context . shouldOptimize ( ) -> LlvmOptimizationLevel . AGGRESSIVE <EOL> context . shouldContainDebugInfo ( ) -> LlvmOptimizationLevel . NONE <EOL> else -> LlvmOptimizationLevel . DEFAULT <EOL> } <EOL> val sizeLevel : LlvmSizeLevel = when { <EOL> context . shouldOptimize ( ) -> LlvmSizeLevel . NONE <EOL> context . shouldContainDebugInfo ( ) -> LlvmSizeLevel . NONE <EOL> else -> LlvmSizeLevel . NONE <EOL> } <EOL> val codegenOptimizationLevel : LLVMCodeGenOptLevel = when { <EOL> context . shouldOptimize ( ) -> LLVMCodeGenOptLevel . LLVMCodeGenLevelAggressive <EOL> context . shouldContainDebugInfo ( ) -> LLVMCodeGenOptLevel . LLVMCodeGenLevelNone <EOL> else -> LLVMCodeGenOptLevel . LLVMCodeGenLevelDefault <EOL> } <EOL> val relocMode : LLVMRelocMode = configurables . currentRelocationMode ( context ) . translateToLlvmRelocMode ( ) <EOL> val codeModel : LLVMCodeModel = LLVMCodeModel . LLVMCodeModelDefault <EOL> val globalDce = true <EOL> val internalize = closedWorld <EOL> val makeDeclarationsHidden = config . produce == CompilerOutputKind . STATIC_CACHE <EOL> val objcPasses = configurables is AppleConfigurables <EOL> val inlineThreshold : Int ? = when { <EOL> context . shouldOptimize ( ) -> tryGetInlineThreshold ( context ) <EOL> context . shouldContainDebugInfo ( ) -> null <EOL> else -> null <EOL> } <EOL> return LlvmPipelineConfig ( targetTriple , cpuModel , cpuFeatures , optimizationLevel , sizeLevel , codegenOptimizationLevel , relocMode , codeModel , globalDce , internalize , makeDeclarationsHidden , objcPasses , inlineThreshold , timePasses = timePasses , ) <EOL> }

/**
 * In the end, Kotlin/Native generates a single LLVM module during compilation.
 * It won't be linked with any other LLVM module, so we can hide and DCE unused symbols.
 *
 * The set of optimizations relies on current compiler configuration.
 * In case of debug we do almost nothing (that's why we need [createLTOPipelineConfigForRuntime]),
 * but for release binaries we rely on "closed" world and enable a lot of optimizations.
 */


@ GCUnsafeCall ( "<STR_LIT>" ) <EOL> internal external fun < T > undefined ( ) : T

/**
 * Returns undefined value of type `T`.
 * This method is unsafe and should be used with care.
 */


internal fun LLFirResolveTarget . resolve ( phase : FirResolvePhase )

{ <EOL> val session = target . llFirResolvableSession <EOL> ? : errorWithAttachment ( "<STR_LIT>" ) { <EOL> withEntry ( "<STR_LIT>" , target . llFirSession ) { it . toString ( ) } <EOL> } <EOL> val lazyDeclarationResolver = session . moduleComponents . firModuleLazyDeclarationResolver <EOL> lazyDeclarationResolver . lazyResolveTarget ( this , phase ) <EOL> }

/**
 * Resolves the target to the specified [phase].
 * The owning session must be a resolvable one.
 */


private fun ensureCapacity ( index : Int )

{ <EOL> if ( index < <NUM_LIT:0> ) { <EOL> throw IndexOutOfBoundsException ( ) <EOL> } <EOL> if ( index >= size ) { <EOL> size = index + <NUM_LIT:1> <EOL> if ( index . elementIndex >= bits . size ) { <EOL> bits = bits . copyOf ( bitToElementSize ( index + <NUM_LIT:1> ) ) <EOL> } <EOL> clearUnusedTail ( ) <EOL> } <EOL> }

/**
 * Checks if index is valid and extends the `bits` array if the index exceeds its size.
 * @throws [IndexOutOfBoundsException] if [index] < 0.
 */


fun set ( index : Int , value : Boolean = true )

{ <EOL> ensureCapacity ( index ) <EOL> val ( elementIndex , offset ) = index . asBitCoordinates <EOL> setBitsWithMask ( elementIndex , offset . asMask , value ) <EOL> }

/** Set the bit specified to the specified value. */


fun set ( from : Int , to : Int , value : Boolean = true )

= set ( from until to , value )

/** Sets the bits with indices between [from] (inclusive) and [to] (exclusive) to the specified value. */


fun set ( range : IntRange , value : Boolean = true )

{ <EOL> if ( range . start < <NUM_LIT:0> || range . endInclusive < <NUM_LIT:0> ) { <EOL> throw IndexOutOfBoundsException ( ) <EOL> } <EOL> if ( range . start > range . endInclusive ) { <EOL> return <EOL> } <EOL> ensureCapacity ( range . endInclusive ) <EOL> val ( fromIndex , fromOffset ) = range . start . asBitCoordinates <EOL> val ( toIndex , toOffset ) = range . endInclusive . asBitCoordinates <EOL> if ( toIndex == fromIndex ) { <EOL> val mask = getMaskBetween ( fromOffset , toOffset ) <EOL> setBitsWithMask ( fromIndex , mask , value ) <EOL> } else { <EOL> setBitsWithMask ( fromIndex , fromOffset . asMaskAfter , value ) <EOL> for ( index in fromIndex + <NUM_LIT:1> until toIndex ) { <EOL> bits [ index ] = if ( value ) ALL_TRUE else ALL_FALSE <EOL> } <EOL> setBitsWithMask ( toIndex , toOffset . asMaskBefore , value ) <EOL> } <EOL> }

/** Sets the bits from the range specified to the specified value. */


private fun nextBit ( startIndex : Int , lookFor : Boolean ) : Int

{ <EOL> if ( startIndex < <NUM_LIT:0> ) { <EOL> throw IndexOutOfBoundsException ( ) <EOL> } <EOL> if ( startIndex >= size ) { <EOL> return if ( lookFor ) - <NUM_LIT:1> else startIndex <EOL> } <EOL> val ( startElementIndex , startOffset ) = startIndex . asBitCoordinates <EOL> var element = bits [ startElementIndex ] <EOL> for ( offset in startOffset .. MAX_BIT_OFFSET ) { <EOL> val bit = element and ( <NUM_LIT> shl offset ) != <NUM_LIT:0L> <EOL> if ( bit == lookFor ) { <EOL> return bitIndex ( startElementIndex , offset ) <EOL> } <EOL> } <EOL> for ( index in startElementIndex + <NUM_LIT:1> .. bits . lastIndex ) { <EOL> element = bits [ index ] <EOL> for ( offset in <NUM_LIT:0> .. MAX_BIT_OFFSET ) { <EOL> val bit = element and ( <NUM_LIT> shl offset ) != <NUM_LIT:0L> <EOL> if ( bit == lookFor ) { <EOL> return bitIndex ( index , offset ) <EOL> } <EOL> } <EOL> } <EOL> return if ( lookFor ) - <NUM_LIT:1> else size <EOL> }

/**
 * Returns an index of a next set (if [lookFor] == true) or clear
 * (if [lookFor] == false) bit after [startIndex] (inclusive).
 * Returns -1 (for [lookFor] == true) or [size] (for lookFor == false)
 * if there is no such bits between [startIndex] and [size] - 1.
 * @throws IndexOutOfBoundException if [startIndex] < 0.
 */


fun nextSetBit ( startIndex : Int = <NUM_LIT:0> ) : Int

= nextBit ( startIndex , true )

/**
 * Returns an index of a next bit which value is `true` after [startIndex] (inclusive).
 * Returns -1 if there is no such bits after [startIndex].
 * @throws IndexOutOfBoundException if [startIndex] < 0.
 */


fun nextClearBit ( startIndex : Int = <NUM_LIT:0> ) : Int

= nextBit ( startIndex , false )

/**
 * Returns an index of a next bit which value is `false` after [startIndex] (inclusive).
 * Returns [size] if there is no such bits between [startIndex] and [size] - 1 assuming that the set has an infinite
 * sequence of `false` bits after (size - 1)-th.
 * @throws IndexOutOfBoundException if [startIndex] < 0.
 */


operator fun get ( index : Int ) : Boolean

{ <EOL> if ( index < <NUM_LIT:0> ) { <EOL> throw IndexOutOfBoundsException ( ) <EOL> } <EOL> if ( index >= size ) { <EOL> return false <EOL> } <EOL> val ( elementIndex , offset ) = index . asBitCoordinates <EOL> return bits [ elementIndex ] and offset . asMask != <NUM_LIT:0L> <EOL> }

/** Returns a value of a bit with the [index] specified. */


= doOperation ( another , Long :: and )

/** Performs a logical and operation over corresponding bits of this and [another] BitSets. The result is saved in this BitSet. */


= doOperation ( another , Long :: or )

/** Performs a logical or operation over corresponding bits of this and [another] BitSets. The result is saved in this BitSet. */


= doOperation ( another , Long :: xor )

/** Performs a logical xor operation over corresponding bits of this and [another] BitSets. The result is saved in this BitSet. */


{ <EOL> ensureCapacity ( another . lastIndex ) <EOL> var index = <NUM_LIT:0> <EOL> while ( index < another . bits . size ) { <EOL> bits [ index ] = bits [ index ] and another . bits [ index ] . inv ( ) <EOL> index ++ <EOL> } <EOL> while ( index < bits . size ) { <EOL> bits [ index ] = bits [ index ] and ALL_TRUE <EOL> index ++ <EOL> } <EOL> }

/** Performs a logical and + not operations over corresponding bits of this and [another] BitSets. The result is saved in this BitSet. */


fun intersects ( another : BitSet ) : Boolean

= <EOL> ( <NUM_LIT:0> until minOf ( bits . size , another . bits . size ) ) . any { bits [ it ] and another . bits [ it ] != <NUM_LIT:0L> }

/** Returns true if the specified BitSet has any bits set to true that are also set to true in this BitSet. */


fun evalUnaryOp ( name : String , type : CompileTimeType , value : Any ) : Any ?

{ <EOL> when ( type ) { <EOL> BOOLEAN -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as Boolean ) . not ( ) <EOL> "<STR_LIT:toString>" -> return ( value as Boolean ) . toString ( ) <EOL> } <EOL> BYTE -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as Byte ) . toByte ( ) <EOL> "<STR_LIT>" -> return ( value as Byte ) . toChar ( ) <EOL> "<STR_LIT>" -> return ( value as Byte ) . toDouble ( ) <EOL> "<STR_LIT>" -> return ( value as Byte ) . toFloat ( ) <EOL> "<STR_LIT>" -> return ( value as Byte ) . toInt ( ) <EOL> "<STR_LIT>" -> return ( value as Byte ) . toLong ( ) <EOL> "<STR_LIT>" -> return ( value as Byte ) . toShort ( ) <EOL> "<STR_LIT:toString>" -> return ( value as Byte ) . toString ( ) <EOL> "<STR_LIT>" -> return ( value as Byte ) . unaryMinus ( ) <EOL> "<STR_LIT>" -> return ( value as Byte ) . unaryPlus ( ) <EOL> } <EOL> CHAR -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as Char ) . toByte ( ) <EOL> "<STR_LIT>" -> return ( value as Char ) . toChar ( ) <EOL> "<STR_LIT>" -> return ( value as Char ) . toDouble ( ) <EOL> "<STR_LIT>" -> return ( value as Char ) . toFloat ( ) <EOL> "<STR_LIT>" -> return ( value as Char ) . toInt ( ) <EOL> "<STR_LIT>" -> return ( value as Char ) . toLong ( ) <EOL> "<STR_LIT>" -> return ( value as Char ) . toShort ( ) <EOL> "<STR_LIT:toString>" -> return ( value as Char ) . toString ( ) <EOL> "<STR_LIT>" -> return ( value as Char ) . code <EOL> } <EOL> DOUBLE -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as Double ) . toByte ( ) <EOL> "<STR_LIT>" -> return ( value as Double ) . toChar ( ) <EOL> "<STR_LIT>" -> return ( value as Double ) . toDouble ( ) <EOL> "<STR_LIT>" -> return ( value as Double ) . toFloat ( ) <EOL> "<STR_LIT>" -> return ( value as Double ) . toInt ( ) <EOL> "<STR_LIT>" -> return ( value as Double ) . toLong ( ) <EOL> "<STR_LIT>" -> return ( value as Double ) . toShort ( ) <EOL> "<STR_LIT:toString>" -> return ( value as Double ) . toString ( ) <EOL> "<STR_LIT>" -> return ( value as Double ) . unaryMinus ( ) <EOL> "<STR_LIT>" -> return ( value as Double ) . unaryPlus ( ) <EOL> } <EOL> FLOAT -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as Float ) . toByte ( ) <EOL> "<STR_LIT>" -> return ( value as Float ) . toChar ( ) <EOL> "<STR_LIT>" -> return ( value as Float ) . toDouble ( ) <EOL> "<STR_LIT>" -> return ( value as Float ) . toFloat ( ) <EOL> "<STR_LIT>" -> return ( value as Float ) . toInt ( ) <EOL> "<STR_LIT>" -> return ( value as Float ) . toLong ( ) <EOL> "<STR_LIT>" -> return ( value as Float ) . toShort ( ) <EOL> "<STR_LIT:toString>" -> return ( value as Float ) . toString ( ) <EOL> "<STR_LIT>" -> return ( value as Float ) . unaryMinus ( ) <EOL> "<STR_LIT>" -> return ( value as Float ) . unaryPlus ( ) <EOL> } <EOL> INT -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as Int ) . inv ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . toByte ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . toChar ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . toDouble ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . toFloat ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . toInt ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . toLong ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . toShort ( ) <EOL> "<STR_LIT:toString>" -> return ( value as Int ) . toString ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . unaryMinus ( ) <EOL> "<STR_LIT>" -> return ( value as Int ) . unaryPlus ( ) <EOL> } <EOL> LONG -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as Long ) . inv ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . toByte ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . toChar ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . toDouble ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . toFloat ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . toInt ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . toLong ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . toShort ( ) <EOL> "<STR_LIT:toString>" -> return ( value as Long ) . toString ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . unaryMinus ( ) <EOL> "<STR_LIT>" -> return ( value as Long ) . unaryPlus ( ) <EOL> } <EOL> SHORT -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as Short ) . toByte ( ) <EOL> "<STR_LIT>" -> return ( value as Short ) . toChar ( ) <EOL> "<STR_LIT>" -> return ( value as Short ) . toDouble ( ) <EOL> "<STR_LIT>" -> return ( value as Short ) . toFloat ( ) <EOL> "<STR_LIT>" -> return ( value as Short ) . toInt ( ) <EOL> "<STR_LIT>" -> return ( value as Short ) . toLong ( ) <EOL> "<STR_LIT>" -> return ( value as Short ) . toShort ( ) <EOL> "<STR_LIT:toString>" -> return ( value as Short ) . toString ( ) <EOL> "<STR_LIT>" -> return ( value as Short ) . unaryMinus ( ) <EOL> "<STR_LIT>" -> return ( value as Short ) . unaryPlus ( ) <EOL> } <EOL> STRING -> when ( name ) { <EOL> "<STR_LIT>" -> return ( value as String ) . length <EOL> "<STR_LIT:toString>" -> return ( value as String ) . toString ( ) <EOL> } <EOL> else -> { } <EOL> } <EOL> return null <EOL> }

/** This file is generated by `./gradlew generateOperationsMap`. DO NOT MODIFY MANUALLY */


public fun < E > SendChannel < E > . trySendBlocking ( element : E ) : ChannelResult < Unit >

{ <EOL> trySend ( element ) . onSuccess { return ChannelResult . success ( Unit ) } <EOL> return runBlocking { <EOL> val r = runCatching { send ( element ) } <EOL> if ( r . isSuccess ) ChannelResult . success ( Unit ) <EOL> else ChannelResult . closed ( r . exceptionOrNull ( ) ) <EOL> } <EOL> }

/**
 * Adds [element] to this channel, **blocking** the caller while this channel is full,
 * and returning either [successful][ChannelResult.isSuccess] result when the element was added, or
 * failed result representing closed channel with a corresponding exception.
 *
 * This is a way to call [Channel.send] method in a safe manner inside a blocking code using [runBlocking] and catching,
 * so this function should not be used from coroutine.
 *
 * Example of usage:
 *
 * ```
 * // From callback API
 * channel.trySendBlocking(element)
 * .onSuccess { /* request next element or debug log */ }
 * .onFailure { t: Throwable? -> /* throw or log */ }
 * ```
 *
 * For this operation it is guaranteed that [failure][ChannelResult.failed] always contains an exception in it.
 *
 * @throws `InterruptedException` on JVM if the current thread is interrupted during the blocking send operation.
 */


@ Deprecated ( level = DeprecationLevel . HIDDEN , message = "<STR_LIT>" + "<STR_LIT>" , replaceWith = ReplaceWith ( "<STR_LIT>" ) ) <EOL> public fun < E > SendChannel < E > . sendBlocking ( element : E )

{ <EOL> if ( trySend ( element ) . isSuccess ) <EOL> return <EOL> runBlocking { <EOL> send ( element ) <EOL> } <EOL> }


internal fun Path . findInPath ( name : String ) : Path ?

= Files <EOL> . walk ( this ) . use { stream -> stream . asSequence ( ) . find { it . fileName . toString ( ) == name } }

/**
 * Find the file with given [name] in current [Path].
 *
 * @return `null` if file is absent in current [Path]
 */


internal fun createTempDirDeleteOnExit ( prefix : String ) : Path

= Files <EOL> . createTempDirectory ( prefix ) <EOL> . apply { toFile ( ) . deleteOnExit ( ) }

/**
 * Create a temporary directory that will be cleaned up on normal JVM termination, but will be left on non-zero exit status.
 *
 * Prefer using JUnit5 `@TempDir` over this method when possible.
 */


internal fun Path . allFilesWithExtension ( ext : String ) : List < Path >

= <EOL> Files . walk ( this ) . use { stream -> stream . filter { it . extension . equals ( ext , ignoreCase = true ) } . toList ( ) }

/**
 * Returns list of all files whose name ends with [ext] extension. The comparison is case-insensitive.
 */


fun TestProject . sourceFilesRelativeToProject ( expectedSourceFiles : List < String > , sourcesDir : GradleProject . ( ) -> Path = { javaSourcesDir ( ) } , subProjectName : String ? = null ) : Iterable < Path >

{ <EOL> return expectedSourceFiles <EOL> . map { <EOL> if ( subProjectName != null ) { <EOL> subProject ( subProjectName ) . sourcesDir ( ) . resolve ( it ) <EOL> } else { <EOL> sourcesDir ( ) . resolve ( it ) <EOL> } <EOL> } <EOL> . map { <EOL> it . relativeTo ( projectPath ) <EOL> } <EOL> }

/**
 * Convert list of [expectedSourceFiles] to relate to [TestProject] paths.
 */


fun Path . getSingleFileInDir ( relativePath : String ) : Path

{ <EOL> val path = resolve ( relativePath ) <EOL> return Files . list ( path ) . use { <EOL> val files = it . asSequence ( ) . toList ( ) <EOL> files . singleOrNull ( ) ? : fail ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Returns a single file located in the [relativePath] subdirectory. If no file or more than one file is found an assertion error will be thrown.
 */


override suspend fun collect ( collector : FlowCollector < T > ) : Nothing

/**
 * Accepts the given [collector] and [emits][FlowCollector.emit] values into it.
 * To emit values from a shared flow into a specific collector, either `collector.emitAll(flow)` or `collect { ... }`
 * SAM-conversion can be used.
 *
 * **A shared flow never completes**. A call to [Flow.collect] or any other terminal operator
 * on a shared flow never completes normally.
 *
 * It is guaranteed that, by the time the first suspension happens, [collect] has already subscribed to the
 * [SharedFlow] and is eligible for receiving emissions. In particular, the following code will always print `1`:
 * ```
 * val flow = MutableSharedFlow<Int>()
 * launch(start = CoroutineStart.UNDISPATCHED) {
 * flow.collect { println(1) }
 * }
 * flow.emit(1)
 * ```
 *
 * @see [Flow.collect] for implementation and inheritance details.
 */


override suspend fun emit ( value : T )

/**
 * Emits a [value] to this shared flow, suspending on buffer overflow.
 *
 * This call can suspend only when the [BufferOverflow] strategy is
 * [SUSPEND][BufferOverflow.SUSPEND] **and** there are subscribers collecting this shared flow.
 *
 * If there are no subscribers, the buffer is not used.
 * Instead, the most recently emitted value is simply stored into
 * the replay cache if one was configured, displacing the older elements there,
 * or dropped if no replay cache was configured.
 *
 * See [tryEmit] for a non-suspending variant of this function.
 *
 * This method is **thread-safe** and can be safely invoked from concurrent coroutines without
 * external synchronization.
 */


public fun tryEmit ( value : T ) : Boolean

/**
 * Tries to emit a [value] to this shared flow without suspending. It returns `true` if the value was
 * emitted successfully (see below). When this function returns `false`, it means that a call to a plain [emit]
 * function would suspend until there is buffer space available.
 *
 * This call can return `false` only when the [BufferOverflow] strategy is
 * [SUSPEND][BufferOverflow.SUSPEND] **and** there are subscribers collecting this shared flow.
 *
 * If there are no subscribers, the buffer is not used.
 * Instead, the most recently emitted value is simply stored into
 * the replay cache if one was configured, displacing the older elements there,
 * or dropped if no replay cache was configured. In any case, `tryEmit` returns `true`.
 *
 * This method is **thread-safe** and can be safely invoked from concurrent coroutines without
 * external synchronization.
 */


@ ExperimentalCoroutinesApi <EOL> public fun resetReplayCache ( )

/**
 * Resets the [replayCache] of this shared flow to an empty state.
 * New subscribers will be receiving only the values that were emitted after this call,
 * while old subscribers will still be receiving previously buffered values.
 * To reset a shared flow to an initial value, emit the value after this call.
 *
 * On a [MutableStateFlow], which always contains a single value, this function is not
 * supported, and throws an [UnsupportedOperationException]. To reset a [MutableStateFlow]
 * to an initial value, just update its [value][MutableStateFlow.value].
 *
 * This method is **thread-safe** and can be safely invoked from concurrent coroutines without
 * external synchronization.
 *
 * **Note: This is an experimental api.** This function may be removed or renamed in the future.
 */