private fun verifyTokens ( text : String , vararg tokens : Token )

{ <EOL> val lexer = Lexer ( StringReader ( text ) ) <EOL> for ( expectedToken in tokens ) { <EOL> assertEquals ( expectedToken , lexer . nextToken ( ) ) <EOL> } <EOL> assertNull ( lexer . nextToken ( ) , "<STR_LIT>" ) <EOL> }


private fun verifyMalformed ( text : String )

{ <EOL> assertFailsWith < MalformedJSONException > { <EOL> Lexer ( StringReader ( text ) ) . nextToken ( ) <EOL> } <EOL> }


{ <EOL> val originalBindingContext = bindingContext as? CleanableBindingContext <EOL> ? : error ( "<STR_LIT>" ) <EOL> originalBindingContext . clear ( ) <EOL> }


= true


fun test ( mh : MethodHandle ? , mt : MethodType ? )

{ <EOL> val constable = if ( cond ( ) ) mh else mt <EOL> }


{ <EOL> test ( null , null ) <EOL> return "<STR_LIT:OK>" <EOL> }


fun foo ( )


fun bar ( )


{ throw UnsupportedOperationException ( ) }


private fun checkSerializationException ( action : ( ) -> Unit , assertions : SerializationException . ( String ) -> Unit )

{ <EOL> val e = assertFailsWith ( SerializationException :: class , action ) <EOL> assertNotNull ( e . message ) <EOL> e . assertions ( e . message ! ! ) <EOL> }


@ Test <EOL> fun testNotRegisteredMessage ( )

= parametrizedTest { mode -> <EOL> val input = """<STR_LIT>""" <EOL> checkSerializationException ( { <EOL> default . decodeFromString < Holder > ( input , mode ) <EOL> } , { message -> <EOL> if ( mode == JsonTestingMode . STREAMING ) <EOL> assertContains ( message , "<STR_LIT>" ) <EOL> else <EOL> assertContains ( message , "<STR_LIT>" ) <EOL> } ) <EOL> }


@ Test <EOL> fun testDiscriminatorMissingNoDefaultMessage ( )

= parametrizedTest { mode -> <EOL> val input = """<STR_LIT>""" <EOL> checkSerializationException ( { <EOL> default . decodeFromString < Holder > ( input , mode ) <EOL> } , { message -> <EOL> assertContains ( message , "<STR_LIT>" ) <EOL> } ) <EOL> }


@ Test <EOL> fun testClassDiscriminatorIsNull ( )


= object : Iterator < Int > { <EOL> var i = <NUM_LIT:0> <EOL> override fun next ( ) = i ++ <EOL> override fun hasNext ( ) = i < n <EOL> }


fun < T > Iterable < T > . stringify ( ) : String

{ <EOL> var s = "<STR_LIT>" <EOL> for ( i in this ) s += i <EOL> return s <EOL> }


{ <EOL> val a = FromAny ( ) <EOL> val it = FromIterable ( <NUM_LIT:3> ) <EOL> val s = it . stringify ( ) <EOL> if ( s != "<STR_LIT>" ) return "<STR_LIT>" <EOL> var ao = object : Any ( ) { <EOL> } <EOL> var ito = object : Iterable < Int > { <EOL> override public fun iterator ( ) = object : Iterator < Int > { <EOL> var i = <NUM_LIT:0> <EOL> override fun next ( ) : Int { <EOL> var r = i <EOL> i += <NUM_LIT:2> <EOL> return r <EOL> } <EOL> override fun hasNext ( ) = i < <NUM_LIT:9> <EOL> } <EOL> } <EOL> val so = ito . stringify ( ) <EOL> if ( so != "<STR_LIT>" ) return "<STR_LIT>" <EOL> return "<STR_LIT:OK>" <EOL> }


fun < StringifyTP > stringify ( collection : StringifyTP , size : ( StringifyTP ) -> Int , get : StringifyTP . ( Int ) -> Any ? ) : String

{ <EOL> var res = "<STR_LIT:[>" <EOL> for ( i in <NUM_LIT:0> until size ( collection ) ) { <EOL> if ( i > <NUM_LIT:0> ) res += "<STR_LIT:U+002CU+0020>" <EOL> res += collection . get ( i ) . toString ( ) <EOL> } <EOL> res += "<STR_LIT:]>" <EOL> return res <EOL> }


fun < StringifyArrayTP : I > stringifyArray ( array : Array < StringifyArrayTP > )

= <EOL> stringify ( array , { it . size } , Array < * > :: get )


fun stringifyIntArray ( array : Array < Int > )

= <EOL> stringify ( array , { it . size } , Array < Int > :: get )


= v . toString ( )


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" ) <EOL> fun < BazTP0 , BazTP1 > foo ( p1 : BazTP0 , p2 : BazTP1 )


{ <EOL> val ref : KFunction2 < QuxTP , QuxTP , Unit > = :: foo <EOL> println ( ref ) <EOL> }


{ <EOL> println ( stringifyArray ( arrayOf ( N ( <NUM_LIT:2> ) , N ( <NUM_LIT> ) ) ) ) <EOL> println ( stringifyIntArray ( arrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) ) ) <EOL> bar < Int > ( ) <EOL> bar < String > ( ) <EOL> val ref : KFunction2 < Int , Int , Unit > = :: foo <EOL> println ( ref ) <EOL> return "<STR_LIT:OK>" <EOL> }


{ <EOL> val i : Int = <NUM_LIT:1> <EOL> foo ( i ) <EOL> }


{ <EOL> report ( "<STR_LIT>" ) <EOL> processSubmodules ( ) <EOL> report ( "<STR_LIT>" ) <EOL> finishProcessing ( ) <EOL> }


= <EOL> templatingPlugin . querySingle { submoduleTemplateProcessor } . process ( context . configuration . modules )


= <EOL> templatingPlugin . query { templateProcessingStrategy } . forEach { it . finish ( context . configuration . outputDir ) }


= "<STR_LIT:OK>"


= A ( ) . foo


@ Test <EOL> fun `test - regular class` ( )

{ <EOL> val file = inlineSourceCodeAnalysis . createKtFile ( """<STR_LIT>""" . trimIndent ( ) ) <EOL> analyze ( file ) { <EOL> val fooSymbol = file . getClassOrFail ( "<STR_LIT:Foo>" ) <EOL> assertEquals ( listOf ( "<STR_LIT:bar>" , "<STR_LIT>" ) , fooSymbol . getCallableSymbolsForObjCMemberTranslation ( ) . map { it as KtFunctionSymbol } . map { it . name . asString ( ) } ) <EOL> } <EOL> }


@ Test <EOL> fun `test - data class` ( )

{ <EOL> val file = inlineSourceCodeAnalysis . createKtFile ( """<STR_LIT>""" . trimIndent ( ) ) <EOL> analyze ( file ) { <EOL> val foo = file . getClassOrFail ( "<STR_LIT:Foo>" ) <EOL> assertEquals ( listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:equals>" , "<STR_LIT:hashCode>" , "<STR_LIT:toString>" , "<STR_LIT:a>" ) , foo . getCallableSymbolsForObjCMemberTranslation ( ) . sortedWith ( StableCallableOrder ) . map { it as KtNamedSymbol } . map { it . name . asString ( ) } ) <EOL> } <EOL> }


@ Test <EOL> fun `test - enum class` ( )

{ <EOL> val file = inlineSourceCodeAnalysis . createKtFile ( """<STR_LIT>""" . trimIndent ( ) ) <EOL> analyze ( file ) { <EOL> val foo = file . getClassOrFail ( "<STR_LIT:Foo>" ) <EOL> assertEquals ( emptyList ( ) , foo . getCallableSymbolsForObjCMemberTranslation ( ) . sortedWith ( StableCallableOrder ) . map { it as KtNamedSymbol } . map { it . name . asString ( ) } ) <EOL> } <EOL> }


{ <EOL> val aTree = createCirTreeFromSourceCode ( "<STR_LIT>" ) <EOL> val bTree = createCirTreeFromSourceCode ( "<STR_LIT>" ) <EOL> val merged = mergeCirTree ( "<STR_LIT:a>" to aTree , "<STR_LIT:b>" to bTree ) <EOL> val typeAlias = merged . assertSingleModule ( ) . assertSinglePackage ( ) . assertSingleTypeAlias ( ) <EOL> typeAlias . assertNoMissingTargetDeclaration ( ) <EOL> }


fun `test missing target declarations` ( )

{ <EOL> val aTree = createCirTreeFromSourceCode ( "<STR_LIT>" ) <EOL> val bTree = createCirTreeFromSourceCode ( "<STR_LIT>" ) <EOL> val merged = mergeCirTree ( "<STR_LIT:a>" to aTree , "<STR_LIT:b>" to bTree ) <EOL> val pkg = merged . assertSingleModule ( ) . assertSinglePackage ( ) <EOL> assertEquals ( <NUM_LIT:2> , pkg . typeAliases . size , "<STR_LIT>" ) <EOL> val a = pkg . typeAliases [ CirName . create ( "<STR_LIT:a>" ) ] ? : kotlin . test . fail ( "<STR_LIT>" ) <EOL> val b = pkg . typeAliases [ CirName . create ( "<STR_LIT:b>" ) ] ? : kotlin . test . fail ( "<STR_LIT>" ) <EOL> kotlin . test . assertNotNull ( a . targetDeclarations [ <NUM_LIT:0> ] , "<STR_LIT>" ) <EOL> kotlin . test . assertNotNull ( b . targetDeclarations [ <NUM_LIT:1> ] , "<STR_LIT>" ) <EOL> kotlin . test . assertNull ( a . targetDeclarations [ <NUM_LIT:1> ] , "<STR_LIT>" ) <EOL> kotlin . test . assertNull ( b . targetDeclarations [ <NUM_LIT:0> ] , "<STR_LIT>" ) <EOL> }


public fun ColumnSet < * > . colGroups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >

= <EOL> columnGroupsInternal ( filter )

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


public fun ColumnsSelectionDsl < * > . colGroups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >

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

/**
 * @include [CommonColGroupsDocs]
 * @set [CommonColGroupsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[colGroups][ColumnsSelectionDsl.colGroups]`() }`
 *
 * `df.`[select][DataFrame.select]` { `[colGroups][ColumnsSelectionDsl.colGroups]` { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun SingleColumn < DataRow < * > > . colGroups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >

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

/**
 * @include [CommonColGroupsDocs]
 * @set [CommonColGroupsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { myColGroup.`[colGroups][SingleColumn.colGroups]`() }`
 *
 * `df.`[select][DataFrame.select]` { myColGroup.`[colGroups][SingleColumn.colGroups]` { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }`
 */


public fun String . colGroups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >

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

/**
 * @include [CommonColGroupsDocs]
 * @set [CommonColGroupsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "myColGroup".`[colGroups][String.colGroups]` { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }`
 *
 * `df.`[select][DataFrame.select]` { "myColGroup".`[colGroups][String.colGroups]`() }`
 */


public fun KProperty < * > . colGroups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >

/**
 * @include [CommonColGroupsDocs]
 * @set [CommonColGroupsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[colGroup][ColumnsSelectionDsl.colGroup]`(Type::myColGroup).`[colGroups][SingleColumn.colGroups]` { it.`[name][ColumnReference.name]`.`[startsWith][String.startsWith]`("my") } }`
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColGroup.`[colGroups][KProperty.colGroups]`() }`
 */


public fun ColumnPath . colGroups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >

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


@ Deprecated ( COLS_SELECT_DSL_GROUP , ReplaceWith ( COLS_SELECT_DSL_GROUP_REPLACE ) , DeprecationLevel . ERROR ) <EOL> public fun ColumnSet < * > . groups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >

= <EOL> columnGroupsInternal ( filter )


@ Deprecated ( COLS_SELECT_DSL_GROUP , ReplaceWith ( COLS_SELECT_DSL_GROUP_REPLACE ) , DeprecationLevel . ERROR ) <EOL> public fun SingleColumn < DataRow < * > > . groups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >


@ Deprecated ( COLS_SELECT_DSL_GROUP , ReplaceWith ( COLS_SELECT_DSL_GROUP_REPLACE ) , DeprecationLevel . ERROR ) <EOL> public fun ColumnsSelectionDsl < * > . groups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >

= <EOL> this . asSingleColumn ( ) . columnGroupsInternal ( filter )


@ Deprecated ( COLS_SELECT_DSL_GROUP , ReplaceWith ( COLS_SELECT_DSL_GROUP_REPLACE ) , DeprecationLevel . ERROR ) <EOL> public fun String . groups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >


@ Deprecated ( COLS_SELECT_DSL_GROUP , ReplaceWith ( COLS_SELECT_DSL_GROUP_REPLACE ) , DeprecationLevel . ERROR ) <EOL> public fun KProperty < * > . groups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >


@ Deprecated ( COLS_SELECT_DSL_GROUP , ReplaceWith ( COLS_SELECT_DSL_GROUP_REPLACE ) , DeprecationLevel . ERROR ) <EOL> public fun ColumnPath . groups ( filter : Predicate < ColumnGroup < * > > = { true } ) : TransformableColumnSet < AnyRow >


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> internal fun ColumnsResolver < * > . columnGroupsInternal ( filter : ( ColumnGroup < * > ) -> Boolean ) : TransformableColumnSet < AnyRow >

= <EOL> colsInternal { it . isColumnGroup ( ) && filter ( it . asColumnGroup ( ) ) } as TransformableColumnSet < AnyRow >

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


{ <EOL> null ? . run { return } <EOL> }


{ <EOL> test ( ) <EOL> return "<STR_LIT:OK>" <EOL> }


fun useFieldMissingOptimization ( ) : Boolean

{ <EOL> return throwMissedFieldExceptionFunc != null && throwMissedFieldExceptionArrayFunc != null <EOL> }


fun IrDeclaration . excludeFromJsExport ( )

{ <EOL> if ( ! compilerContext . platform . isJs ( ) ) { <EOL> return <EOL> } <EOL> val jsExportIgnore = compilerContext . jsExportIgnoreClass ? : return <EOL> val jsExportIgnoreCtor = jsExportIgnore . primaryConstructor ? : return <EOL> annotations += IrConstructorCallImpl ( UNDEFINED_OFFSET , UNDEFINED_OFFSET , jsExportIgnore . defaultType , jsExportIgnoreCtor . symbol , jsExportIgnore . typeParameters . size , jsExportIgnoreCtor . typeParameters . size , jsExportIgnoreCtor . valueParameters . size , ) <EOL> }


private fun getClassListFromFileAnnotation ( annotationFqName : FqName ) : List < IrClassSymbol >

{ <EOL> val annotation = currentClass . fileParent . annotations . findAnnotation ( annotationFqName ) ? : return emptyList ( ) <EOL> val vararg = annotation . getValueArgument ( <NUM_LIT:0> ) as? IrVararg ? : return emptyList ( ) <EOL> return vararg . elements <EOL> . mapNotNull { ( it as? IrClassReference ) ? . symbol as? IrClassSymbol } <EOL> }


fun IrBlockBodyBuilder . generateGoldenMaskCheck ( seenVars : List < IrValueDeclaration > , properties : IrSerializableProperties , serialDescriptor : IrExpression )

{ <EOL> val fieldsMissedTest : IrExpression <EOL> val throwErrorExpr : IrExpression <EOL> val maskSlotCount = seenVars . size <EOL> if ( maskSlotCount == <NUM_LIT:1> ) { <EOL> val goldenMask = properties . goldenMask <EOL> throwErrorExpr = irInvoke ( null , throwMissedFieldExceptionFunc ! ! , irGet ( seenVars [ <NUM_LIT:0> ] ) , irInt ( goldenMask ) , serialDescriptor , typeHint = compilerContext . irBuiltIns . unitType ) <EOL> fieldsMissedTest = irNotEquals ( irInt ( goldenMask ) , irBinOp ( OperatorNameConventions . AND , irInt ( goldenMask ) , irGet ( seenVars [ <NUM_LIT:0> ] ) ) ) <EOL> } else { <EOL> val goldenMaskList = properties . goldenMaskList <EOL> var compositeExpression : IrExpression ? = null <EOL> for ( i in goldenMaskList . indices ) { <EOL> val singleCheckExpr = irNotEquals ( irInt ( goldenMaskList [ i ] ) , irBinOp ( OperatorNameConventions . AND , irInt ( goldenMaskList [ i ] ) , irGet ( seenVars [ i ] ) ) ) <EOL> compositeExpression = if ( compositeExpression == null ) { <EOL> singleCheckExpr <EOL> } else { <EOL> irBinOp ( OperatorNameConventions . OR , compositeExpression , singleCheckExpr ) <EOL> } <EOL> } <EOL> fieldsMissedTest = compositeExpression ! ! <EOL> throwErrorExpr = irBlock { <EOL> + irInvoke ( null , throwMissedFieldExceptionArrayFunc ! ! , createIntArrayOfExpression ( goldenMaskList . indices . map { irGet ( seenVars [ it ] ) } ) , createIntArrayOfExpression ( goldenMaskList . map { irInt ( it ) } ) , serialDescriptor , typeHint = compilerContext . irBuiltIns . unitType ) <EOL> } <EOL> } <EOL> + irIfThen ( compilerContext . irBuiltIns . unitType , fieldsMissedTest , throwErrorExpr ) <EOL> }


fun IrBlockBodyBuilder . serializeAllProperties ( serializableProperties : List < IrSerializableProperty > , objectToSerialize : IrValueDeclaration , localOutput : IrValueDeclaration , localSerialDesc : IrValueDeclaration , kOutputClass : IrClassSymbol , ignoreIndexTo : Int , initializerAdapter : ( IrExpressionBody ) -> IrExpression , cachedChildSerializerByIndex : ( Int ) -> IrExpression ? , genericGetter : ( ( Int , IrType ) -> IrExpression ) ? <EOL> )

{ <EOL> fun IrSerializableProperty . irGet ( ) : IrExpression { <EOL> val ownerType = objectToSerialize . symbol . owner . type <EOL> return getProperty ( irGet ( type = ownerType , variable = objectToSerialize . symbol ) , ir ) <EOL> } <EOL> for ( ( index , property ) in serializableProperties . withIndex ( ) ) { <EOL> if ( index < ignoreIndexTo ) continue <EOL> val elementCall = formEncodeDecodePropertyCall ( irGet ( localOutput ) , property , { innerSerial , sti -> <EOL> val f = <EOL> kOutputClass . functionByName ( "<STR_LIT>" ) <EOL> f to listOf ( irGet ( localSerialDesc ) , irInt ( index ) , innerSerial , property . irGet ( ) ) <EOL> } , { <EOL> val f = <EOL> kOutputClass . functionByName ( "<STR_LIT>" ) <EOL> val args : MutableList < IrExpression > = mutableListOf ( irGet ( localSerialDesc ) , irInt ( index ) ) <EOL> if ( it . elementMethodPrefix != "<STR_LIT>" ) args . add ( property . irGet ( ) ) <EOL> f to args <EOL> } , cachedChildSerializerByIndex ( index ) , genericGetter ) <EOL> val encodeDefaults = property . ir . getEncodeDefaultAnnotationValue ( ) <EOL> val field = <EOL> property . ir . backingField <EOL> val initializer = field ? . initializer <EOL> if ( ! property . optional || encodeDefaults == true || field == null || initializer == null ) { <EOL> + elementCall <EOL> } else { <EOL> val partB = irNotEquals ( property . irGet ( ) , initializerAdapter ( initializer ) ) <EOL> val condition = if ( encodeDefaults == false ) { <EOL> partB <EOL> } else { <EOL> val shouldEncodeFunc = kOutputClass . functionByName ( CallingConventions . shouldEncodeDefault ) <EOL> val partA = irInvoke ( irGet ( localOutput ) , shouldEncodeFunc , irGet ( localSerialDesc ) , irInt ( index ) ) <EOL> irIfThenElse ( compilerContext . irBuiltIns . booleanType , partA , irTrue ( ) , partB ) <EOL> } <EOL> + irIfThen ( condition , elementCall ) <EOL> } <EOL> } <EOL> }


fun IrBlockBodyBuilder . formEncodeDecodePropertyCall ( encoder : IrExpression , property : IrSerializableProperty , whenHaveSerializer : ( serializer : IrExpression , sti : IrSerialTypeInfo ) -> FunctionWithArgs , whenDoNot : ( sti : IrSerialTypeInfo ) -> FunctionWithArgs , cachedSerializer : IrExpression ? , genericGetter : ( ( Int , IrType ) -> IrExpression ) ? = null , returnTypeHint : IrType ? = null ) : IrExpression

{ <EOL> val sti = getIrSerialTypeInfo ( property , compilerContext ) <EOL> val innerSerial = cachedSerializer ? : serializerInstance ( sti . serializer , compilerContext , property . type , property . genericIndex , property . ir . parentClassOrNull , genericGetter ) <EOL> val ( functionToCall , args : List < IrExpression > ) = if ( innerSerial != null ) whenHaveSerializer ( innerSerial , sti ) else whenDoNot ( sti ) <EOL> val typeArgs = if ( functionToCall . owner . typeParameters . isNotEmpty ( ) ) listOf ( property . type ) else listOf ( ) <EOL> return irInvoke ( encoder , functionToCall , typeArguments = typeArgs , valueArguments = args , returnTypeHint = returnTypeHint ) <EOL> }


private fun IrBuilderWithScope . callSerializerFromCompanion ( thisIrType : IrSimpleType , typeArgs : List < IrType > , args : List < IrExpression > , expectedSerializer : ClassId ? <EOL> ) : IrExpression ?

{ <EOL> val baseClass = thisIrType . getClass ( ) ? : return null <EOL> val companionClass = baseClass . companionObject ( ) ? : return null <EOL> val serializerProviderFunction = companionClass . declarations . singleOrNull { <EOL> it is IrFunction && it . name == SerialEntityNames . SERIALIZER_PROVIDER_NAME && it . valueParameters . size == baseClass . typeParameters . size <EOL> } ? : return null <EOL> val replaceArgsWithUnitSerializer = expectedSerializer == polymorphicSerializerId || expectedSerializer == sealedSerializerId <EOL> val adjustedArgs : List < IrExpression > = <EOL> if ( replaceArgsWithUnitSerializer ) { <EOL> val serializer = findStandardKotlinTypeSerializer ( compilerContext , context . irBuiltIns . unitType ) ! ! <EOL> List ( baseClass . typeParameters . size ) { irGetObject ( serializer ) } <EOL> } else { <EOL> args <EOL> } <EOL> val adjustedTypeArgs : List < IrType > = if ( replaceArgsWithUnitSerializer ) thisIrType . argumentTypesOrUpperBounds ( ) else typeArgs <EOL> with ( serializerProviderFunction as IrFunction ) { <EOL> return irInvoke ( irGetObject ( companionClass ) , symbol , adjustedTypeArgs . takeIf { it . size == typeParameters . size } . orEmpty ( ) , adjustedArgs . takeIf { it . size == valueParameters . size } . orEmpty ( ) ) <EOL> } <EOL> }


private fun IrBuilderWithScope . callSerializerFromObject ( thisIrType : IrSimpleType , args : List < IrExpression > , ) : IrExpression ?

{ <EOL> val baseClass = thisIrType . getClass ( ) ? : return null <EOL> val serializerProviderFunction = baseClass . declarations . singleOrNull { <EOL> it is IrFunction && it . name == SerialEntityNames . SERIALIZER_PROVIDER_NAME && it . valueParameters . size == baseClass . typeParameters . size <EOL> } ? : return null <EOL> with ( serializerProviderFunction as IrFunction ) { <EOL> return irInvoke ( irGetObject ( baseClass ) , symbol , emptyList ( ) , args . takeIf { it . size == valueParameters . size } . orEmpty ( ) ) <EOL> } <EOL> }


fun IrBuilderWithScope . serializerTower ( generator : SerializerIrGenerator , dispatchReceiverParameter : IrValueParameter , property : IrSerializableProperty , cachedSerializer : IrExpression ? <EOL> ) : IrExpression ?

{ <EOL> val nullableSerClass = compilerContext . referenceProperties ( SerialEntityNames . wrapIntoNullableCallableId ) . single ( ) <EOL> val serializerExpression = if ( cachedSerializer != null ) { <EOL> cachedSerializer <EOL> } else { <EOL> val serializerClassSymbol = <EOL> property . serializableWith ( compilerContext ) <EOL> ? : if ( ! property . type . isTypeParameter ( ) ) generator . findTypeSerializerOrContext ( compilerContext , property . type ) else null <EOL> serializerInstance ( serializerClassSymbol , compilerContext , property . type , genericIndex = property . genericIndex , property . ir . parentClassOrNull , ) { it , _ -> <EOL> val ir = generator . localSerializersFieldsDescriptors [ it ] <EOL> irGetField ( irGet ( dispatchReceiverParameter ) , ir . backingField ! ! ) <EOL> } <EOL> } <EOL> return serializerExpression ? . let { expr -> wrapWithNullableSerializerIfNeeded ( property . type , expr , nullableSerClass ) } <EOL> }


private fun IrBuilderWithScope . wrapWithNullableSerializerIfNeeded ( type : IrType , expression : IrExpression , nullableProp : IrPropertySymbol ) : IrExpression

= if ( type . isMarkedNullable ( ) ) { <EOL> val resultType = type . makeNotNull ( ) <EOL> val typeArguments = listOf ( resultType ) <EOL> val callee = nullableProp . owner . getter ! ! <EOL> val returnType = callee . returnType . substitute ( callee . typeParameters , typeArguments ) <EOL> irInvoke ( callee = callee . symbol , typeArguments = typeArguments , valueArguments = emptyList ( ) , returnTypeHint = returnType ) . apply { extensionReceiver = expression } <EOL> } else { <EOL> expression <EOL> }


fun wrapIrTypeIntoKSerializerIrType ( type : IrType , variance : Variance = Variance . INVARIANT ) : IrType

{ <EOL> val kSerClass = compilerContext . referenceClass ( ClassId ( SerializationPackages . packageFqName , SerialEntityNames . KSERIALIZER_NAME ) ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> return IrSimpleTypeImpl ( kSerClass , hasQuestionMark = false , arguments = listOf ( makeTypeProjection ( type , variance ) ) , annotations = emptyList ( ) ) <EOL> }


internal fun IrClass . addCachedChildSerializersProperty ( cacheableSerializers : List < IrExpression ? > ) : IrProperty ?

{ <EOL> cacheableSerializers . firstOrNull { it != null } ? : return null <EOL> val kSerializerClass = compilerContext . kSerializerClass <EOL> ? : error ( "<STR_LIT>" ) <EOL> val kSerializerType = kSerializerClass . typeWith ( compilerContext . irBuiltIns . anyType ) <EOL> val arrayType = compilerContext . irBuiltIns . arrayClass . typeWith ( kSerializerType ) <EOL> val property = addValPropertyWithJvmFieldInitializer ( arrayType , SerialEntityNames . CACHED_CHILD_SERIALIZERS_PROPERTY_NAME ) { <EOL> createArrayOfExpression ( kSerializerType , cacheableSerializers . map { it ? : irNull ( ) } ) <EOL> } <EOL> if ( declarations . removeIf { declaration -> declaration === property } ) { <EOL> declarations . add ( <NUM_LIT:0> , property ) <EOL> } <EOL> return property <EOL> }


internal fun IrStatementsBuilder < * > . createCacheableChildSerializersFactory ( cacheProperty : IrProperty ? , cacheableSerializers : List < Boolean > , containingClassProducer : ( ) -> IrClass ) : ( Int ) -> IrExpression ?

{ <EOL> cacheProperty ? : return { null } <EOL> val variable = <EOL> irTemporary ( irInvoke ( irGetObject ( containingClassProducer ( ) ) , cacheProperty . getter ! ! . symbol ) , "<STR_LIT>" ) <EOL> return { index : Int -> <EOL> if ( cacheableSerializers [ index ] ) { <EOL> irInvoke ( irGet ( variable ) , compilerContext . arrayValueGetter . symbol , irInt ( index ) ) <EOL> } else { <EOL> null <EOL> } <EOL> } <EOL> }

/**
 * Factory to getting cached serializers via variable.
 * Must be used only in one place because for each factory creates one variable.
 *
 * Class from [containingClassProducer] used only if [cacheProperty] is not null.
 */


fun IrClass . createCachedChildSerializers ( serializableClass : IrClass , serializableProperties : List < IrSerializableProperty > ) : List < IrExpression ? >

{ <EOL> return DeclarationIrBuilder ( compilerContext , symbol ) . run { <EOL> serializableProperties . map { cacheableChildSerializerInstance ( serializableClass , it ) } <EOL> } <EOL> }


private fun IrBuilderWithScope . cacheableChildSerializerInstance ( serializableClass : IrClass , property : IrSerializableProperty ) : IrExpression ?

{ <EOL> if ( serializableClass . symbol == property . type . classifier ) { <EOL> return null <EOL> } <EOL> if ( property . type . checkTypeArgumentsHasSelf ( serializableClass . symbol ) ) { <EOL> return null <EOL> } <EOL> val serializer = getIrSerialTypeInfo ( property , compilerContext ) . serializer ? : return null <EOL> if ( serializer . owner . kind == ClassKind . OBJECT ) return null <EOL> return serializerInstance ( serializer , compilerContext , property . type , null , serializableClass , null ) <EOL> }


private fun IrSimpleType . checkTypeArgumentsHasSelf ( itselfClass : IrClassSymbol ) : Boolean

{ <EOL> arguments . forEach { typeArgument -> <EOL> if ( typeArgument . typeOrNull ? . classifierOrNull == itselfClass ) return true <EOL> if ( typeArgument is IrSimpleType ) { <EOL> if ( typeArgument . checkTypeArgumentsHasSelf ( itselfClass ) ) return true <EOL> } <EOL> } <EOL> return false <EOL> }


fun IrBuilderWithScope . serializerInstance ( serializerClassOriginal : IrClassSymbol ? , pluginContext : SerializationPluginContext , kType : IrType , genericIndex : Int ? = null , rootSerializableClass : IrClass ? = null , genericGetter : ( ( Int , IrType ) -> IrExpression ) ? = null , ) : IrExpression ?

{ <EOL> val nullableSerClass = compilerContext . referenceProperties ( SerialEntityNames . wrapIntoNullableCallableId ) . single ( ) <EOL> if ( serializerClassOriginal == null ) { <EOL> if ( genericIndex == null ) return null <EOL> return genericGetter ? . invoke ( genericIndex , kType ) <EOL> } <EOL> if ( serializerClassOriginal . owner . kind == ClassKind . OBJECT ) { <EOL> val serializerClass = serializerClassOriginal . owner <EOL> val samePackage = serializerClass . packageFqName == rootSerializableClass ? . packageFqName <EOL> return if ( rootSerializableClass == null || serializerClass . visibility != DescriptorVisibilities . PRIVATE || samePackage ) { <EOL> irGetObject ( serializerClassOriginal ) <EOL> } else { <EOL> val simpleType = ( kType as? IrSimpleType ) ? : error ( "<STR_LIT>" ) <EOL> if ( simpleType . getClass ( ) ? . isObject == true ) { <EOL> callSerializerFromObject ( simpleType , emptyList ( ) ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> } else { <EOL> callSerializerFromCompanion ( simpleType , emptyList ( ) , emptyList ( ) , serializerClassOriginal . owner . classId ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> fun instantiate ( serializer : IrClassSymbol ? , type : IrType ) : IrExpression ? { <EOL> val expr = serializerInstance ( serializer , pluginContext , type , type . genericIndex , rootSerializableClass , genericGetter ) ? : return null <EOL> return wrapWithNullableSerializerIfNeeded ( type , expr , nullableSerClass ) <EOL> } <EOL> var serializerClass = serializerClassOriginal <EOL> var args : List < IrExpression > <EOL> var typeArgs : List < IrType > <EOL> @ Suppress ( "<STR_LIT>" ) val kType = ( kType as? IrSimpleType ) ? : error ( "<STR_LIT>" ) <EOL> val typeArgumentsAsTypes = kType . argumentTypesOrUpperBounds ( ) <EOL> var needToCopyAnnotations = false <EOL> when ( serializerClassOriginal . owner . classId ) { <EOL> polymorphicSerializerId -> { <EOL> needToCopyAnnotations = true <EOL> args = listOf ( classReference ( kType . classOrUpperBound ( ) ! ! ) ) <EOL> typeArgs = listOf ( kType ) <EOL> } <EOL> contextSerializerId -> { <EOL> if ( genericIndex == null && kType . genericIndex != null ) { <EOL> return null <EOL> } <EOL> args = listOf ( classReference ( kType . classOrUpperBound ( ) ! ! ) ) <EOL> typeArgs = listOf ( kType ) <EOL> val hasNewCtxSerCtor = compilerContext . referenceConstructors ( contextSerializerId ) . any { it . owner . valueParameters . size == <NUM_LIT:3> } <EOL> if ( hasNewCtxSerCtor ) { <EOL> args = args + mutableListOf < IrExpression > ( ) . apply { <EOL> val fallbackDefaultSerializer = findTypeSerializer ( pluginContext , kType ) <EOL> . takeIf { it ? . owner ? . classId != contextSerializerId } <EOL> add ( instantiate ( fallbackDefaultSerializer , kType ) ? : irNull ( ) ) <EOL> add ( createArrayOfExpression ( wrapIrTypeIntoKSerializerIrType ( kType , variance = Variance . OUT_VARIANCE ) , typeArgumentsAsTypes . map { <EOL> val argSer = findTypeSerializerOrContext ( compilerContext , it ) <EOL> instantiate ( argSer , it ) ? : return null <EOL> } ) ) <EOL> } <EOL> } <EOL> } <EOL> objectSerializerId -> { <EOL> needToCopyAnnotations = true <EOL> args = listOf ( irString ( kType . serialName ( ) ) , irGetObject ( kType . classOrUpperBound ( ) ! ! ) ) <EOL> typeArgs = listOf ( kType ) <EOL> } <EOL> sealedSerializerId -> { <EOL> needToCopyAnnotations = true <EOL> args = mutableListOf < IrExpression > ( ) . apply { <EOL> add ( irString ( kType . serialName ( ) ) ) <EOL> add ( classReference ( kType . classOrUpperBound ( ) ! ! ) ) <EOL> val ( subclasses , subSerializers ) = allSealedSerializableSubclassesFor ( kType . classOrUpperBound ( ) ! ! . owner , pluginContext ) <EOL> val projectedOutCurrentKClass = <EOL> compilerContext . irBuiltIns . kClassClass . typeWithArguments ( listOf ( makeTypeProjection ( kType , Variance . OUT_VARIANCE ) ) ) <EOL> add ( createArrayOfExpression ( projectedOutCurrentKClass , subclasses . map { classReference ( it . classOrUpperBound ( ) ! ! ) } ) ) <EOL> add ( createArrayOfExpression ( wrapIrTypeIntoKSerializerIrType ( kType , variance = Variance . OUT_VARIANCE ) , subSerializers . mapIndexed { i , serializer -> <EOL> val type = subclasses [ i ] <EOL> val expr = serializerInstance ( serializer , pluginContext , type , type . genericIndex , rootSerializableClass ) { _ , genericType -> <EOL> serializerInstance ( pluginContext . referenceClass ( polymorphicSerializerId ) , pluginContext , ( genericType . classifierOrNull as IrTypeParameterSymbol ) . owner . representativeUpperBound ) ! ! <EOL> } ! ! <EOL> wrapWithNullableSerializerIfNeeded ( type , expr , nullableSerClass ) <EOL> } ) ) <EOL> } <EOL> typeArgs = listOf ( kType ) <EOL> } <EOL> enumSerializerId -> { <EOL> serializerClass = pluginContext . referenceClass ( enumSerializerId ) <EOL> val enumDescriptor = kType . classOrNull ! ! <EOL> typeArgs = listOf ( kType ) <EOL> if ( this @ BaseIrGenerator !is SerializableCompanionIrGenerator ) { <EOL> callSerializerFromCompanion ( kType , typeArgs , emptyList ( ) , enumSerializerId ) ? . let { return it } <EOL> } <EOL> val enumArgs = mutableListOf ( irString ( kType . serialName ( ) ) , irCall ( enumDescriptor . owner . findEnumValuesMethod ( ) ) , ) <EOL> if ( enumSerializerFactoryFunc != null && annotatedEnumSerializerFactoryFunc != null ) { <EOL> val factoryFunc : IrSimpleFunctionSymbol = if ( enumDescriptor . owner . isEnumWithSerialInfoAnnotation ( ) ) { <EOL> val enumEntries = enumDescriptor . owner . enumEntries ( ) <EOL> val entriesNames = enumEntries . map { it . annotations . serialNameValue ? . let { n -> irString ( n ) } ? : irNull ( ) } <EOL> val entriesAnnotations = enumEntries . map { <EOL> val annotationsConstructors = copyAnnotationsFrom ( it . annotations ) <EOL> if ( annotationsConstructors . isEmpty ( ) ) { <EOL> irNull ( ) <EOL> } else { <EOL> createArrayOfExpression ( compilerContext . irBuiltIns . annotationType , annotationsConstructors ) <EOL> } <EOL> } <EOL> val classAnnotationsConstructors = copyAnnotationsFrom ( enumDescriptor . owner . annotations ) <EOL> val classAnnotations = if ( classAnnotationsConstructors . isEmpty ( ) ) { <EOL> irNull ( ) <EOL> } else { <EOL> createArrayOfExpression ( compilerContext . irBuiltIns . annotationType , classAnnotationsConstructors ) <EOL> } <EOL> val annotationArrayType = <EOL> compilerContext . irBuiltIns . arrayClass . typeWith ( compilerContext . irBuiltIns . annotationType . makeNullable ( ) ) <EOL> enumArgs += createArrayOfExpression ( compilerContext . irBuiltIns . stringType . makeNullable ( ) , entriesNames ) <EOL> enumArgs += createArrayOfExpression ( annotationArrayType , entriesAnnotations ) <EOL> enumArgs += classAnnotations <EOL> annotatedEnumSerializerFactoryFunc <EOL> } else { <EOL> enumSerializerFactoryFunc <EOL> } <EOL> val factoryReturnType = factoryFunc . owner . returnType . substitute ( factoryFunc . owner . typeParameters , typeArgs ) <EOL> return irInvoke ( null , factoryFunc , typeArgs , enumArgs , factoryReturnType ) <EOL> } else { <EOL> args = enumArgs <EOL> } <EOL> } <EOL> else -> { <EOL> args = typeArgumentsAsTypes . map { <EOL> val argSer = findTypeSerializerOrContext ( pluginContext , it ) <EOL> instantiate ( argSer , it ) ? : return null <EOL> } <EOL> typeArgs = typeArgumentsAsTypes <EOL> } <EOL> } <EOL> if ( serializerClassOriginal . owner . classId == referenceArraySerializerId ) { <EOL> args = listOf ( wrapperClassReference ( typeArgumentsAsTypes . single ( ) ) ) + args <EOL> typeArgs = listOf ( typeArgs [ <NUM_LIT:0> ] . makeNotNull ( ) ) + typeArgs <EOL> } <EOL> if ( ! kType . isInterface ( ) && serializerClassOriginal == kType . classOrUpperBound ( ) ? . owner . classSerializer ( pluginContext ) && this @ BaseIrGenerator !is SerializableCompanionIrGenerator ) { <EOL> callSerializerFromCompanion ( kType , typeArgs , args , serializerClassOriginal . owner . classId ) ? . let { return it } <EOL> } <EOL> val serializable = serializerClass ? . owner ? . let { compilerContext . getSerializableClassDescriptorBySerializer ( it ) } <EOL> requireNotNull ( serializerClass ) <EOL> val ctor = if ( serializable ? . typeParameters ? . isNotEmpty ( ) == true ) { <EOL> requireNotNull ( findSerializerConstructorForTypeArgumentsSerializers ( serializerClass . owner ) ) { "<STR_LIT>" } <EOL> } else { <EOL> val constructors = serializerClass . constructors <EOL> if ( ! needToCopyAnnotations ) { <EOL> constructors . single { it . owner . isPrimary } <EOL> } else { <EOL> constructors . find { it . owner . lastArgumentIsAnnotationArray ( ) } ? : run { <EOL> needToCopyAnnotations = false <EOL> constructors . single { it . owner . isPrimary } <EOL> } <EOL> } <EOL> } <EOL> assert ( ctor . isBound ) <EOL> val ctorDecl = ctor . owner <EOL> if ( needToCopyAnnotations ) { <EOL> val classAnnotations = copyAnnotationsFrom ( kType . getClass ( ) ? . let { collectSerialInfoAnnotations ( it ) } . orEmpty ( ) ) <EOL> args = args + createArrayOfExpression ( compilerContext . irBuiltIns . annotationType , classAnnotations ) <EOL> } <EOL> val typeParameters = ctorDecl . parentAsClass . typeParameters <EOL> val substitutedReturnType = ctorDecl . returnType . substitute ( typeParameters , typeArgs ) <EOL> return irInvoke ( null , ctor , typeArguments = typeArgs . takeIf { it . size == ctorDecl . typeParameters . size } . orEmpty ( ) , valueArguments = args . takeIf { it . size == ctorDecl . valueParameters . size } . orEmpty ( ) , returnTypeHint = substitutedReturnType ) <EOL> }


fun File . getFileByName ( name : String ) : File

= <EOL> findFileByName ( name ) ? : throw AssertionError ( "<STR_LIT>" )


fun File . getFilesByNames ( vararg names : String ) : List < File >

= <EOL> names . map { getFileByName ( it ) }


fun File . findFileByName ( name : String ) : File ?

= <EOL> walk ( ) . filter { it . isFile && it . name . equals ( name , ignoreCase = true ) } . firstOrNull ( )


fun File . allKotlinFiles ( ) : Iterable < File >

= <EOL> allFilesWithExtension ( "<STR_LIT:kt>" )


fun File . allJavaFiles ( ) : Iterable < File >

= <EOL> allFilesWithExtension ( "<STR_LIT:java>" )


fun File . allFilesWithExtension ( ext : String ) : Iterable < File >

= <EOL> walk ( ) . filter { it . isFile && it . extension . equals ( ext , ignoreCase = true ) } . toList ( )


fun File . modify ( transform : ( String ) -> String )

{ <EOL> writeText ( transform ( readText ( ) ) ) <EOL> }


{ <EOL> modify { "<STR_LIT>" } <EOL> }


fun createTempDir ( prefix : String ) : File

= createTempDirDeleteOnExit ( prefix ) . toFile ( )


fun normalizePath ( path : String ) : String

{ <EOL> var start = <NUM_LIT:0> <EOL> var separator = false <EOL> if ( isWindows ) { <EOL> if ( path . startsWith ( "<STR_LIT>" ) ) { <EOL> start = <NUM_LIT:2> <EOL> separator = true <EOL> } else if ( path . startsWith ( "<STR_LIT>" ) ) { <EOL> return normalizeTail ( <NUM_LIT:0> , path , false ) <EOL> } <EOL> } <EOL> for ( i in start until path . length ) { <EOL> val c = path [ i ] <EOL> if ( c == '<CHAR_LIT:/>' ) { <EOL> if ( separator ) { <EOL> return normalizeTail ( i , path , true ) <EOL> } <EOL> separator = true <EOL> } else if ( c == '<CHAR_LIT:\\>' ) { <EOL> return normalizeTail ( i , path , separator ) <EOL> } else { <EOL> separator = false <EOL> } <EOL> } <EOL> return path <EOL> }

/**
 * converts back slashes to forward slashes
 * removes double slashes inside the path, e.g. "x/y//z" => "x/y/z"
 *
 * Converted from com.intellij.openapi.util.io.FileUtil.normalize
 */


private fun normalizeTail ( prefixEnd : Int , path : String , separator : Boolean ) : String

{ <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> var separator = separator <EOL> val result = StringBuilder ( path . length ) <EOL> result . append ( path , <NUM_LIT:0> , prefixEnd ) <EOL> var start = prefixEnd <EOL> if ( start == <NUM_LIT:0> && isWindows && ( path . startsWith ( "<STR_LIT>" ) || path . startsWith ( "<STR_LIT>" ) ) ) { <EOL> start = <NUM_LIT:2> <EOL> result . append ( "<STR_LIT>" ) <EOL> separator = true <EOL> } <EOL> for ( i in start until path . length ) { <EOL> val c = path [ i ] <EOL> if ( c == '<CHAR_LIT:/>' || c == '<CHAR_LIT:\\>' ) { <EOL> if ( ! separator ) result . append ( '<CHAR_LIT:/>' ) <EOL> separator = true <EOL> } else { <EOL> result . append ( c ) <EOL> separator = false <EOL> } <EOL> } <EOL> return result . toString ( ) <EOL> }


fun Path . replaceText ( oldValue : String , newValue : String )

{ <EOL> writeText ( readText ( ) . replace ( oldValue , newValue ) ) <EOL> }


fun File . replaceText ( oldValue : String , newValue : String )


fun File . replaceText ( regex : Regex , replacement : String )

{ <EOL> writeText ( readText ( ) . replace ( regex , replacement ) ) <EOL> }


fun Path . replaceFirst ( oldValue : String , newValue : String )

{ <EOL> writeText ( readText ( ) . replaceFirst ( oldValue , newValue ) ) <EOL> }


fun Path . replaceWithVersion ( versionSuffix : String ) : Path

{ <EOL> val otherVersion = resolveSibling ( "<STR_LIT>" ) <EOL> otherVersion . copyTo ( this , overwrite = true ) <EOL> return this <EOL> }


{ <EOL> c . startCoroutine ( handleExceptionContinuation { <EOL> result = it . message ! ! <EOL> } ) <EOL> }


= suspendCoroutine { <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> c = it as Continuation < Any > <EOL> }


fun suspendFunId ( block : suspend ( ) -> IC )

= block


= value


= IC ( ss . s )


= t


{ <EOL> return suspendFunId { foo ( qux ( quz ( suspendMe ( ) ) ) ) } ( ) <EOL> }


= bar ( ) . s


{ <EOL> builder { <EOL> Test1 ( ) . test ( ) <EOL> } <EOL> c ? . resumeWithException ( IllegalStateException ( "<STR_LIT:OK>" ) ) <EOL> if ( result != "<STR_LIT:OK>" ) return "<STR_LIT>" <EOL> return result <EOL> }


= Content ( value )


@ ExperimentalContracts <EOL> inline fun < R , T : R > Content < T > . getOrElse ( onException : ( exception : Exception ) -> R , ) : R

= fold ( { it } , onException )


@ ExperimentalContracts <EOL> inline fun < R , T > Content < T > . fold ( onContent : ( value : T ) -> R , onException : ( exception : Exception ) -> R , ) : R

{ <EOL> contract { <EOL> callsInPlace ( onContent , InvocationKind . AT_MOST_ONCE ) <EOL> callsInPlace ( onException , InvocationKind . AT_MOST_ONCE ) <EOL> } <EOL> return onContent ( value ) <EOL> }


@ ExperimentalContracts <EOL> fun box ( ) : String

{ <EOL> val t = content ( <NUM_LIT:1> ) . getOrElse { <NUM_LIT:2> } <EOL> if ( t != <NUM_LIT:1> ) return "<STR_LIT>" <EOL> return "<STR_LIT:OK>" <EOL> }


= "<STR_LIT:OK>"


override fun < E : FirElement > transformElement ( element : E , data : D ) : E

{ <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return ( element . transformChildren ( this , data ) as E ) <EOL> }


open fun beforeCollectingForElement ( element : FirElement )


open fun beforeGoingNestedDeclaration ( declaration : FirDeclaration , context : CheckerContext )


@ Suppress ( "<STR_LIT:NOTHING_TO_INLINE>" ) <EOL> inline fun < T > foo ( i1 : T , i2 : T ) : List < T >

{ <EOL> val j1 = i1 <EOL> val j2 = i2 <EOL> return listOf ( j1 , j2 ) <EOL> }


{ <EOL> return foo < Int > ( <NUM_LIT:1> , <NUM_LIT:2> ) <EOL> }


{ <EOL> assertEquals ( "<STR_LIT>" , bar ( ) . toString ( ) ) <EOL> return "<STR_LIT:OK>" <EOL> }


fun getImplementation ( context : Context ) : IrSimpleFunction ?

{ <EOL> val target = function . target <EOL> val implementation = if ( ! needBridge ) <EOL> target <EOL> else { <EOL> val bridgeOwner = if ( inheritsBridge ) { <EOL> target <EOL> } else { <EOL> function <EOL> } <EOL> context . bridgesSupport . getBridge ( OverriddenFunctionInfo ( bridgeOwner , overriddenFunction ) ) <EOL> } <EOL> return if ( implementation . modality == Modality . ABSTRACT ) null else implementation <EOL> }


{ <EOL> return "<STR_LIT>" <EOL> }


override fun equals ( other : Any ? ) : Boolean

{ <EOL> if ( this === other ) return true <EOL> if ( other !is OverriddenFunctionInfo ) return false <EOL> if ( function != other . function ) return false <EOL> if ( overriddenFunction != other . overriddenFunction ) return false <EOL> return true <EOL> }


{ <EOL> var result = function . hashCode ( ) <EOL> result = <NUM_LIT:31> * result + overriddenFunction . hashCode ( ) <EOL> return result <EOL> }


{ <EOL> val interfaceColors = assignColorsToInterfaces ( ) <EOL> val maxColor = interfaceColors . values . maxOrNull ( ) ? : <NUM_LIT:0> <EOL> var bitsPerColor = <NUM_LIT:0> <EOL> var x = maxColor <EOL> while ( x > <NUM_LIT:0> ) { <EOL> ++ bitsPerColor <EOL> x /= <NUM_LIT:2> <EOL> } <EOL> val maxInterfaceId = Int . MAX_VALUE shr bitsPerColor <EOL> val colorCounts = IntArray ( maxColor + <NUM_LIT:1> ) <EOL> val root = context . irBuiltIns . anyClass . owner <EOL> val immediateInheritors = mutableMapOf < IrClass , MutableList < IrClass > > ( ) <EOL> val allClasses = mutableListOf < IrClass > ( ) <EOL> irModule . acceptVoid ( object : IrElementVisitorVoid { <EOL> override fun visitElement ( element : IrElement ) { <EOL> element . acceptChildrenVoid ( this ) <EOL> } <EOL> override fun visitClass ( declaration : IrClass ) { <EOL> if ( declaration . isInterface ) { <EOL> val color = interfaceColors [ declaration ] ! ! <EOL> val interfaceId = ++ colorCounts [ color ] <EOL> assert ( interfaceId <= maxInterfaceId ) { <EOL> "<STR_LIT>" <EOL> } <EOL> context . getLayoutBuilder ( declaration ) . hierarchyInfo = <EOL> ClassGlobalHierarchyInfo ( <NUM_LIT:0> , <NUM_LIT:0> , color or ( interfaceId shl bitsPerColor ) ) <EOL> } else { <EOL> allClasses += declaration <EOL> if ( declaration != root ) { <EOL> val superClass = declaration . getSuperClassNotAny ( ) ? : root <EOL> val inheritors = immediateInheritors . getOrPut ( superClass ) { mutableListOf ( ) } <EOL> inheritors . add ( declaration ) <EOL> } <EOL> } <EOL> super . visitClass ( declaration ) <EOL> } <EOL> } ) <EOL> var time = <NUM_LIT:0> <EOL> fun dfs ( irClass : IrClass ) { <EOL> ++ time <EOL> val enterTime = if ( irClass == root ) - <NUM_LIT:1> else time <EOL> immediateInheritors [ irClass ] ? . forEach { dfs ( it ) } <EOL> val exitTime = time <EOL> context . getLayoutBuilder ( irClass ) . hierarchyInfo = ClassGlobalHierarchyInfo ( enterTime , exitTime , <NUM_LIT:0> ) <EOL> } <EOL> dfs ( root ) <EOL> context . globalHierarchyAnalysisResult = GlobalHierarchyAnalysisResult ( bitsPerColor ) <EOL> }


fun computeColoringGreedy ( ) : IntArray

{ <EOL> val colors = IntArray ( nodes . size ) { - <NUM_LIT:1> } <EOL> var numberOfColors = <NUM_LIT:0> <EOL> val usedColors = BooleanArray ( nodes . size ) <EOL> for ( v in nodes . indices ) { <EOL> for ( c in <NUM_LIT:0> until numberOfColors ) <EOL> usedColors [ c ] = false <EOL> for ( u in forbidden [ v ] ) <EOL> if ( colors [ u ] >= <NUM_LIT:0> ) <EOL> usedColors [ colors [ u ] ] = true <EOL> var found = false <EOL> for ( c in <NUM_LIT:0> until numberOfColors ) <EOL> if ( ! usedColors [ c ] ) { <EOL> colors [ v ] = c <EOL> found = true <EOL> break <EOL> } <EOL> if ( ! found ) <EOL> colors [ v ] = numberOfColors ++ <EOL> } <EOL> return colors <EOL> }


fun build ( irModuleFragment : IrModuleFragment ) : InterfacesForbiddennessGraph

{ <EOL> val interfaceIndices = mutableMapOf < IrClass , Int > ( ) <EOL> val interfaces = mutableListOf < IrClass > ( ) <EOL> val forbidden = mutableListOf < MutableList < Int > > ( ) <EOL> irModuleFragment . acceptVoid ( object : IrElementVisitorVoid { <EOL> override fun visitElement ( element : IrElement ) { <EOL> element . acceptChildrenVoid ( this ) <EOL> } <EOL> fun registerInterface ( iface : IrClass ) { <EOL> interfaceIndices . getOrPut ( iface ) { <EOL> forbidden . add ( mutableListOf ( ) ) <EOL> interfaces . add ( iface ) <EOL> interfaces . size - <NUM_LIT:1> <EOL> } <EOL> } <EOL> override fun visitClass ( declaration : IrClass ) { <EOL> if ( declaration . isInterface ) <EOL> registerInterface ( declaration ) <EOL> else { <EOL> val implementedInterfaces = declaration . implementedInterfaces <EOL> implementedInterfaces . forEach { registerInterface ( it ) } <EOL> for ( i in <NUM_LIT:0> until implementedInterfaces . size ) <EOL> for ( j in i + <NUM_LIT:1> until implementedInterfaces . size ) { <EOL> val v = interfaceIndices [ implementedInterfaces [ i ] ] ! ! <EOL> val u = interfaceIndices [ implementedInterfaces [ j ] ] ! ! <EOL> forbidden [ v ] . add ( u ) <EOL> forbidden [ u ] . add ( v ) <EOL> } <EOL> } <EOL> super . visitClass ( declaration ) <EOL> } <EOL> } ) <EOL> return InterfacesForbiddennessGraph ( interfaces , forbidden ) <EOL> }


private fun assignColorsToInterfaces ( ) : Map < IrClass , Int >

{ <EOL> val graph = InterfacesForbiddennessGraph . build ( irModule ) <EOL> val coloring = graph . computeColoringGreedy ( ) <EOL> return graph . nodes . mapIndexed { v , irClass -> irClass to coloring [ v ] } . toMap ( ) <EOL> }


internal fun IrField . requiredAlignment ( llvm : CodegenLlvmHelpers ) : Int

{ <EOL> val llvmType = type . toLLVMType ( llvm ) <EOL> val abiAlignment = if ( llvmType == llvm . vector128Type ) { <EOL> <NUM_LIT:8> <EOL> } else { <EOL> LLVMABIAlignmentOfType ( llvm . runtime . targetData , llvmType ) <EOL> } <EOL> return if ( hasAnnotation ( KonanFqNames . volatile ) ) { <EOL> val size = LLVMABISizeOfType ( llvm . runtime . targetData , llvmType ) . toInt ( ) <EOL> val alignment = maxOf ( size , abiAlignment ) <EOL> require ( alignment % size == <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> require ( alignment % abiAlignment == <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> alignment <EOL> } else { <EOL> abiAlignment <EOL> } <EOL> }


private fun IrField . toFieldInfo ( llvm : CodegenLlvmHelpers ) : FieldInfo

{ <EOL> val isConst = correspondingPropertySymbol ? . owner ? . isConst ? : false <EOL> require ( ! isConst || initializer ? . expression is IrConst < * > ) { "<STR_LIT>" } <EOL> return FieldInfo ( name . asString ( ) , type , isConst , symbol , requiredAlignment ( llvm ) ) <EOL> }


fun vtableIndex ( function : IrSimpleFunction ) : Int

{ <EOL> val bridgeDirections = function . target . bridgeDirectionsTo ( function ) <EOL> val index = vtableEntries . indexOfFirst { it . function == function && it . bridgeDirections == bridgeDirections } <EOL> require ( index >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> return index <EOL> }


fun overridingOf ( function : IrSimpleFunction )

= <EOL> overridableOrOverridingMethods . firstOrNull { function in it . allOverriddenFunctions } ? . let { <EOL> OverriddenFunctionInfo ( it , function ) . getImplementation ( context ) <EOL> }


fun itablePlace ( function : IrSimpleFunction ) : InterfaceTablePlace

{ <EOL> require ( irClass . isInterface ) { "<STR_LIT>" } <EOL> val interfaceVTable = interfaceVTableEntries <EOL> val index = interfaceVTable . indexOf ( function ) <EOL> if ( index >= <NUM_LIT:0> ) <EOL> return InterfaceTablePlace ( classId , interfaceVTable . size , index ) <EOL> val superFunction = function . overriddenSymbols . first ( ) . owner <EOL> return context . getLayoutBuilder ( superFunction . parentAsClass ) . itablePlace ( superFunction ) <EOL> }


fun getFields ( llvm : CodegenLlvmHelpers ) : List < FieldInfo >

= getFieldsInternal ( llvm ) . map { fieldInfo -> <EOL> val mappedField = fieldInfo . irField ? . let { context . mapping . lateInitFieldToNullableField [ it ] ? : it } <EOL> if ( mappedField == fieldInfo . irField ) <EOL> fieldInfo <EOL> else <EOL> mappedField ! ! . toFieldInfo ( llvm ) <EOL> }

/**
 * All fields of the class instance.
 * The order respects the class hierarchy, i.e. a class [fields] contains superclass [fields] as a prefix.
 */


private fun getFieldsInternal ( llvm : CodegenLlvmHelpers ) : List < FieldInfo >

{ <EOL> fields ? . let { return it } <EOL> val superClass = irClass . getSuperClassNotAny ( ) <EOL> val superFields = if ( superClass != null ) context . getLayoutBuilder ( superClass ) . getFieldsInternal ( llvm ) else emptyList ( ) <EOL> val declaredFields = getDeclaredFields ( llvm ) <EOL> val sortedDeclaredFields = if ( irClass . hasAnnotation ( KonanFqNames . noReorderFields ) ) <EOL> declaredFields <EOL> else <EOL> declaredFields . sortedByDescending { <EOL> with ( llvm ) { LLVMStoreSizeOfType ( runtime . targetData , it . type . toLLVMType ( this ) ) } <EOL> } <EOL> return ( superFields + sortedDeclaredFields ) . also { fields = it } <EOL> }


fun getDeclaredFields ( llvm : CodegenLlvmHelpers ) : List < FieldInfo >

{ <EOL> val outerThisField = if ( irClass . isInner ) <EOL> context . innerClassesSupport . getOuterThisField ( irClass ) <EOL> else null <EOL> val moduleDeserializer = context . irLinker . getCachedDeclarationModuleDeserializer ( irClass ) <EOL> if ( moduleDeserializer != null ) <EOL> return moduleDeserializer . deserializeClassFields ( irClass , outerThisField ? . toFieldInfo ( llvm ) ) <EOL> val declarations = irClass . declarations . toMutableList ( ) <EOL> outerThisField ? . let { <EOL> if ( ! declarations . contains ( it ) ) <EOL> declarations += it <EOL> } <EOL> return declarations . mapNotNull { <EOL> when ( it ) { <EOL> is IrField -> it . takeIf { it . isReal && ! it . isStatic } ? . toFieldInfo ( llvm ) <EOL> is IrProperty -> it . takeIf { it . isReal } ? . backingField ? . takeIf { ! it . isStatic } ? . toFieldInfo ( llvm ) <EOL> else -> null <EOL> } <EOL> } <EOL> }

/**
 * Fields declared in the class.
 */


fun IrSimpleFunction . getLoweredVersion ( )

= when { <EOL> isSuspend -> this . getOrCreateFunctionWithContinuationStub ( context ) <EOL> else -> this <EOL> }

/**
 * Normally, function should be already replaced. But if the function come from LazyIr, it can be not replaced.
 */


override fun check ( expression : FirFunctionCall , context : CheckerContext , reporter : DiagnosticReporter )

{ <EOL> val resolvedCalleeSymbol = expression . calleeReference . toResolvedNamedFunctionSymbol ( ) ? : return <EOL> val resolvedCalleeName = resolvedCalleeSymbol . name <EOL> if ( expression . origin != FirFunctionCallOrigin . Operator || resolvedCalleeName !in FirOperationNameConventions . ASSIGNMENT_NAMES ) { <EOL> return <EOL> } <EOL> if ( ! expression . resolvedType . isUnit ) { <EOL> reporter . reportOn ( expression . source , FirErrors . ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT , resolvedCalleeSymbol , FirOperationNameConventions . ASSIGNMENT_NAMES [ resolvedCalleeName ] ! ! . operator , context ) <EOL> } <EOL> }


@ OptIn ( kotlin . contracts . ExperimentalContracts :: class ) <EOL> fun check ( actual : Boolean )

{ <EOL> contract { returns ( ) implies actual } <EOL> assertTrue ( actual ) <EOL> }


{ <EOL> val s : S = P ( ) <EOL> check ( s is P ) <EOL> assertEquals ( s . str , "<STR_LIT>" ) <EOL> return "<STR_LIT:OK>" <EOL> }


inline fun foo ( i1 : Int , i2 : Double ) : Int

{ <EOL> val o = object : Comparable < Int > { <EOL> override fun compareTo ( other : Int ) = i1 - other <EOL> } <EOL> return o . compareTo ( i2 . toInt ( ) ) <EOL> }


{ <EOL> class Cmp2 ( ) : Comparable < Int > { <EOL> override fun compareTo ( other : Int ) = - other <EOL> } <EOL> return Cmp2 ( ) . compareTo ( i ) <EOL> }


{ <EOL> if ( foo ( <NUM_LIT:10> , <NUM_LIT> ) + bar ( - <NUM_LIT:10> ) != <NUM_LIT:0> ) return "<STR_LIT:FAIL>" <EOL> return "<STR_LIT:OK>" <EOL> }


{ <EOL> c . startCoroutine ( handleExceptionContinuation { <EOL> result = it . message ! ! <EOL> } ) <EOL> }


suspend fun < T > call ( fn : suspend ( ) -> T )

= fn ( )


= if ( r . x == "<STR_LIT:OK>" ) "<STR_LIT:OK>" else "<STR_LIT>"


{ <EOL> var c : Continuation < R > ? = null <EOL> builder { <EOL> useR ( call { suspendCoroutine { c = it } } ) <EOL> } <EOL> c ? . resumeWithException ( IllegalStateException ( "<STR_LIT:OK>" ) ) <EOL> return result <EOL> }


{ <EOL> val frameMapAtStart = codegen . frameMap . mark ( ) <EOL> prepareConfiguration ( ) <EOL> val hasElse = expression . elseExpression != null <EOL> defaultLabel = if ( hasElse || ! isStatement || isExhaustive ) elseLabel else endLabel <EOL> generateSubjectValue ( ) <EOL> generateSubjectValueToIndex ( ) <EOL> val beginLabel = Label ( ) <EOL> v . mark ( beginLabel ) <EOL> generateSwitchInstructionByTransitionsTable ( ) <EOL> generateEntries ( ) <EOL> if ( ! hasElse && ( ! isStatement || isExhaustive ) ) { <EOL> v . visitLabel ( elseLabel ) <EOL> codegen . putUnitInstanceOntoStackForNonExhaustiveWhen ( expression , isStatement ) <EOL> } <EOL> codegen . markLineNumber ( expression , isStatement ) <EOL> v . mark ( endLabel ) <EOL> frameMapAtStart . dropTo ( ) <EOL> subjectVariableDescriptor ? . let { <EOL> v . visitLocalVariable ( it . name . asString ( ) , subjectType . descriptor , null , beginLabel , endLabel , subjectLocal ) <EOL> } <EOL> }

/**
 * Generates bytecode for entire when expression
 */


{ <EOL> for ( entry in expression . entries ) { <EOL> val entryLabel = Label ( ) <EOL> for ( constant in switchCodegenProvider . getConstantsFromEntry ( entry ) ) { <EOL> if ( constant is NullValue || constant == null ) continue <EOL> processConstant ( constant , entryLabel , entry ) <EOL> } <EOL> if ( entry . isElse ) { <EOL> elseLabel = entryLabel <EOL> } <EOL> entryLabels . add ( entryLabel ) <EOL> } <EOL> }

/**
 * Sets up transitionsTable and maybe something else needed in a special case
 * Behaviour may be changed by overriding processConstant
 */


protected abstract fun processConstant ( constant : ConstantValue < * > , entryLabel : Label , entry : KtWhenEntry )


protected fun putTransitionOnce ( value : Int , entryLabel : Label )

{ <EOL> if ( ! transitionsTable . containsKey ( value ) ) { <EOL> transitionsTable [ value ] = entryLabel <EOL> } <EOL> }


{ <EOL> if ( subjectVariable != null ) { <EOL> val mySubjectVariable = bindingContext [ BindingContext . VARIABLE , subjectVariable ] <EOL> ? : throw AssertionError ( "<STR_LIT>" ) <EOL> subjectLocal = codegen . frameMap . enter ( mySubjectVariable , subjectType ) <EOL> codegen . visitProperty ( subjectVariable , null ) <EOL> StackValue . local ( subjectLocal , subjectType , subjectKotlinType ) . put ( subjectType , subjectKotlinType , codegen . v ) <EOL> subjectVariableDescriptor = mySubjectVariable <EOL> } else { <EOL> codegen . gen ( subjectExpression , subjectType , subjectKotlinType ) <EOL> subjectVariableDescriptor = null <EOL> } <EOL> }

/**
 * Generates subject value on top of the stack.
 * If the subject is a variable, it's stored and loaded.
 */


protected abstract fun generateSubjectValueToIndex ( )

/**
 * Given a subject value on stack (after [generateSubjectValue]),
 * produces int value to be used in switch.
 */


protected fun generateNullCheckIfNeeded ( )

{ <EOL> if ( TypeUtils . isNullableType ( subjectKotlinType ) ) { <EOL> val nullEntryIndex = findNullEntryIndex ( expression ) <EOL> val nullLabel = if ( nullEntryIndex == - <NUM_LIT:1> ) defaultLabel else entryLabels [ nullEntryIndex ] <EOL> val notNullLabel = Label ( ) <EOL> with ( v ) { <EOL> dup ( ) <EOL> ifnonnull ( notNullLabel ) <EOL> pop ( ) <EOL> goTo ( nullLabel ) <EOL> visitLabel ( notNullLabel ) <EOL> } <EOL> } <EOL> }


private fun findNullEntryIndex ( expression : KtWhenExpression )

= <EOL> expression . entries . withIndex ( ) . firstOrNull { ( _ , entry ) -> <EOL> switchCodegenProvider . getConstantsFromEntry ( entry ) . any { it is NullValue } <EOL> } ? . index ? : - <NUM_LIT:1>


private fun generateSwitchInstructionByTransitionsTable ( )

{ <EOL> val keys = transitionsTable . keys . toIntArray ( ) <EOL> val labelsNumber = keys . size <EOL> val maxValue = keys . last ( ) <EOL> val minValue = keys . first ( ) <EOL> val rangeLength = maxValue . toLong ( ) - minValue . toLong ( ) + <NUM_LIT:1L> <EOL> if ( preferLookupOverSwitch ( labelsNumber , rangeLength ) ) { <EOL> val labels = transitionsTable . values . toTypedArray ( ) <EOL> v . lookupswitch ( defaultLabel , keys , labels ) <EOL> return <EOL> } <EOL> val sparseLabels = Array ( rangeLength . toInt ( ) ) { index -> <EOL> transitionsTable [ index + minValue ] ? : defaultLabel <EOL> } <EOL> v . tableswitch ( minValue , maxValue , defaultLabel , * sparseLabels ) <EOL> }


{ <EOL> val entryLabelsIterator = entryLabels . iterator ( ) <EOL> for ( entry in expression . entries ) { <EOL> v . visitLabel ( entryLabelsIterator . next ( ) ) <EOL> val mark = codegen . myFrameMap . mark ( ) <EOL> codegen . gen ( entry . expression , resultType , resultKotlinType ) <EOL> mark . dropTo ( ) <EOL> if ( ! entry . isElse ) { <EOL> v . goTo ( endLabel ) <EOL> } <EOL> } <EOL> }


fun preferLookupOverSwitch ( labelsNumber : Int , rangeLength : Long )

= rangeLength > <NUM_LIT> * labelsNumber || rangeLength > Int . MAX_VALUE


{ <EOL> if ( v == <NUM_LIT:0> ) { <EOL> try { <EOL> foo ( ) <EOL> } catch ( e : Exception ) { <EOL> } <EOL> } <EOL> }


{ <EOL> try { <EOL> if ( v == <NUM_LIT:0> ) { <EOL> foo ( ) <EOL> } <EOL> } catch ( e : Exception ) { <EOL> } <EOL> }


{ <EOL> if ( v ) { <EOL> try { <EOL> foo ( ) <EOL> } catch ( e : Exception ) { <EOL> } <EOL> } <EOL> }


{ <EOL> try { <EOL> if ( v ) { <EOL> foo ( ) <EOL> } <EOL> } catch ( e : Exception ) { <EOL> } <EOL> }


{ <EOL> test1 ( <NUM_LIT:1> ) <EOL> test2 ( <NUM_LIT:1> ) <EOL> test3 ( false ) <EOL> test4 ( false ) <EOL> return "<STR_LIT:OK>" <EOL> }


@ JsName ( "<STR_LIT:bar>" ) <EOL> fun foo ( ) : String


override fun foo ( ) : String


{ <EOL> val c = js ( "<STR_LIT>" ) <EOL> val a : A = c <EOL> val b : B = c <EOL> assertEquals ( a . name , "<STR_LIT>" ) <EOL> assertEquals ( a . asDynamic ( ) . __name , "<STR_LIT>" ) <EOL> assertEquals ( b . name , "<STR_LIT>" ) <EOL> assertEquals ( b . asDynamic ( ) . __name , "<STR_LIT>" ) <EOL> assertEquals ( a . foo ( ) , "<STR_LIT>" ) <EOL> assertEquals ( a . asDynamic ( ) . bar ( ) , "<STR_LIT>" ) <EOL> assertEquals ( b . foo ( ) , "<STR_LIT>" ) <EOL> assertEquals ( b . asDynamic ( ) . bar ( ) , "<STR_LIT>" ) <EOL> return "<STR_LIT:OK>" <EOL> }


operator fun Any ? . getValue ( thisRef : Any ? , property : Any ? )

= <EOL> if ( this == <NUM_LIT> && thisRef == null ) "<STR_LIT:OK>" else "<STR_LIT>"


= s


= <EOL> membersDiffList . isEmpty ( ) <EOL> && functionReports . areAllEmpty ( ) <EOL> && propertyReports . areAllEmpty ( ) <EOL> && typeAliasReports . areAllEmpty ( ) <EOL> && localDelegatedPropertyReport . areAllEmpty ( )


override fun writeAsHtml ( output : PrintWriter )

{ <EOL> if ( isEmpty ( ) ) return <EOL> output . tag ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> output . listDiff ( header1 , header2 , membersDiffList ) <EOL> for ( report in listOf ( functionReports , propertyReports , typeAliasReports , localDelegatedPropertyReport ) . flatten ( ) ) { <EOL> report . writeAsHtml ( output ) <EOL> } <EOL> }


fun addMembersListDiffs ( diffs : List < ListEntryDiff > )

{ <EOL> for ( diff in diffs ) { <EOL> membersDiffList . add ( diff . toDiffEntry ( ) ) <EOL> } <EOL> }


= MetadataPropertyReport ( "<STR_LIT>" , header1 , header2 ) . also { functionReports . add ( it ) }


= MetadataPropertyReport ( "<STR_LIT>" , header1 , header2 ) . also { propertyReports . add ( it ) }


= MetadataPropertyReport ( "<STR_LIT>" , header1 , header2 ) . also { typeAliasReports . add ( it ) }


fun localDelegatedPropertyReport ( id : String )

= <EOL> MetadataPropertyReport ( "<STR_LIT>" , header1 , header2 ) . also { localDelegatedPropertyReport . add ( it ) }


fun TextTreeBuilderContext . appendPackageMetadataReport ( )

{ <EOL> if ( isNotEmpty ( ) ) { <EOL> node ( "<STR_LIT>" ) { <EOL> appendDiffEntries ( header1 , header2 , membersDiffList ) <EOL> for ( report in listOf ( functionReports , propertyReports , typeAliasReports , localDelegatedPropertyReport ) . flatten ( ) ) { <EOL> with ( report ) { appendReport ( ) } <EOL> } <EOL> } <EOL> } <EOL> }


public fun write ( arg : String = "<STR_LIT:default>" )


{ <EOL> }


override fun write ( arg : String )


public actual fun write ( arg : String ) : Unit


override fun getClasses ( nameFilter : ( Name ) -> Boolean )

= <EOL> javac . findClassesFromPackage ( fqName ) . filter { nameFilter ( it . fqName ! ! . shortName ( ) ) }


= ( other as? TreeBasedPackage ) ? . name == name


= name . hashCode ( )


= name


= TypeParameterCommonizer ( TypeCommonizer ( MOCK_CLASSIFIERS , DefaultCommonizerSettings ) )


= doTestSuccess ( expected = mockTypeParam ( isReified = true ) , mockTypeParam ( isReified = true ) , mockTypeParam ( isReified = true ) , mockTypeParam ( isReified = true ) )


= doTestSuccess ( expected = mockTypeParam ( isReified = false ) , mockTypeParam ( isReified = false ) , mockTypeParam ( isReified = false ) , mockTypeParam ( isReified = false ) )


@ Test ( expected = IllegalCommonizerStateException :: class ) <EOL> fun someAreReified1 ( )

= doTestFailure ( mockTypeParam ( isReified = true ) , mockTypeParam ( isReified = true ) , mockTypeParam ( isReified = false ) )


@ Test ( expected = IllegalCommonizerStateException :: class ) <EOL> fun someAreReified2 ( )

= doTestFailure ( mockTypeParam ( isReified = false ) , mockTypeParam ( isReified = false ) , mockTypeParam ( isReified = true ) )


@ Test ( expected = IllegalCommonizerStateException :: class ) <EOL> fun differentVariance1 ( )

= doTestFailure ( mockTypeParam ( variance = Variance . IN_VARIANCE ) , mockTypeParam ( variance = Variance . IN_VARIANCE ) , mockTypeParam ( variance = Variance . OUT_VARIANCE ) )


@ Test ( expected = IllegalCommonizerStateException :: class ) <EOL> fun differentVariance2 ( )

= doTestFailure ( mockTypeParam ( variance = Variance . OUT_VARIANCE ) , mockTypeParam ( variance = Variance . OUT_VARIANCE ) , mockTypeParam ( variance = Variance . INVARIANT ) )


@ Test ( expected = IllegalCommonizerStateException :: class ) <EOL> fun differentUpperBounds1 ( )

= doTestFailure ( mockTypeParam ( upperBounds = listOf ( "<STR_LIT:kotlin/String>" ) ) , mockTypeParam ( upperBounds = listOf ( "<STR_LIT:kotlin/String>" ) ) , mockTypeParam ( upperBounds = listOf ( "<STR_LIT>" ) ) )


@ Test ( expected = IllegalCommonizerStateException :: class ) <EOL> fun differentUpperBounds2 ( )

= doTestFailure ( mockTypeParam ( upperBounds = listOf ( "<STR_LIT:kotlin/String>" , "<STR_LIT>" ) ) , mockTypeParam ( upperBounds = listOf ( "<STR_LIT:kotlin/String>" , "<STR_LIT>" ) ) , mockTypeParam ( upperBounds = listOf ( "<STR_LIT:kotlin/String>" ) ) )


@ Test ( expected = IllegalCommonizerStateException :: class ) <EOL> fun differentUpperBounds3 ( )

= doTestFailure ( mockTypeParam ( upperBounds = listOf ( "<STR_LIT:kotlin/String>" , "<STR_LIT>" ) ) , mockTypeParam ( upperBounds = listOf ( "<STR_LIT:kotlin/String>" , "<STR_LIT>" ) ) , mockTypeParam ( upperBounds = listOf ( "<STR_LIT>" , "<STR_LIT:kotlin/String>" ) ) )


fun mockTypeParam ( name : String = "<STR_LIT:T>" , isReified : Boolean = false , variance : Variance = Variance . INVARIANT , upperBounds : List < String > = listOf ( "<STR_LIT>" ) )

= CirTypeParameter ( annotations = emptyList ( ) , name = CirName . create ( name ) , isReified = isReified , variance = variance , upperBounds = upperBounds . map ( :: mockClassType ) )


private fun initKotlinMultiplatformProject ( config : GradleProjectTest . ( ) -> Unit = { } , ) : GradleProjectTest

{ <EOL> return gradleKtsProjectTest ( "<STR_LIT>" ) { <EOL> settingsGradleKts += """<STR_LIT>""" . trimMargin ( ) <EOL> buildGradleKts = """<STR_LIT>""" . trimMargin ( ) <EOL> dir ( "<STR_LIT>" ) { <EOL> createKotlinFile ( "<STR_LIT>" , """<STR_LIT>""" . trimMargin ( ) ) <EOL> createKotlinFile ( "<STR_LIT>" , """<STR_LIT>""" . trimMargin ( ) ) <EOL> } <EOL> dir ( "<STR_LIT>" ) { <EOL> createKotlinFile ( "<STR_LIT>" , """<STR_LIT>""" . trimMargin ( ) ) <EOL> } <EOL> dir ( "<STR_LIT>" ) { <EOL> createKotlinFile ( "<STR_LIT>" , """<STR_LIT>""" . trimMargin ( ) ) <EOL> } <EOL> config ( ) <EOL> } <EOL> }


override fun deserialize ( decoder : Decoder ) : CustomULong

= <EOL> CustomULong ( decoder . decodeInline ( descriptor ) . decodeSerializableValue ( ULong . serializer ( ) ) )


override fun serialize ( encoder : Encoder , value : CustomULong )

{ <EOL> encoder . encodeInline ( descriptor ) . encodeSerializableValue ( ULong . serializer ( ) , value . value ) <EOL> }


@ Test <EOL> fun testInlineClassAsMapKey ( )

{ <EOL> println ( Long . MAX_VALUE . toULong ( ) + <NUM_LIT> ) <EOL> val c = Carrier ( mapOf ( <NUM_LIT:1L> to <NUM_LIT:1L> ) , mapOf ( Long . MAX_VALUE . toULong ( ) + <NUM_LIT> to <NUM_LIT> ) , mapOf ( WrappedLong ( <NUM_LIT:3L> ) to <NUM_LIT:3L> ) , mapOf ( WrappedULong ( Long . MAX_VALUE . toULong ( ) + <NUM_LIT> ) to <NUM_LIT> ) , mapOf ( CustomULong ( Long . MAX_VALUE . toULong ( ) + <NUM_LIT> ) to <NUM_LIT> ) ) <EOL> assertJsonFormAndRestored ( serializer < Carrier > ( ) , c , """<STR_LIT>""" ) <EOL> }


fun getProvider ( project : Project ) : SyntheticJavaPartsProvider

{ <EOL> val instances = getInstances ( project ) <EOL> val providers = instances . map { it . buildProvider ( ) } <EOL> return if ( providers . isEmpty ( ) ) { <EOL> SyntheticJavaPartsProvider . EMPTY <EOL> } else { <EOL> CompositeSyntheticJavaPartsProvider ( providers ) <EOL> } <EOL> }


fun buildProvider ( ) : SyntheticJavaPartsProvider


public fun foo ( p0 : IntArray ? )


public fun dummy ( )


override fun foo ( p0 : IntArray ? )


= name . baseId ( )


= name . reflectId ( )


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> fun FunctionN ( n : Int ) : ClassId

{ <EOL> return "<STR_LIT>" . baseId ( ) <EOL> }


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> fun SuspendFunctionN ( n : Int ) : ClassId

{ <EOL> return "<STR_LIT>" . coroutinesId ( ) <EOL> }


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> fun KFunctionN ( n : Int ) : ClassId

{ <EOL> return "<STR_LIT>" . reflectId ( ) <EOL> }


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> fun KSuspendFunctionN ( n : Int ) : ClassId


= ClassId ( StandardClassIds . BASE_KOTLIN_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_KOTLIN_PACKAGE , Name . identifier ( "<STR_LIT>" + shortClassName . identifier ) )


= ClassId ( StandardClassIds . BASE_REFLECT_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . Array . packageFqName , Name . identifier ( identifier + StandardClassIds . Array . shortClassName . identifier ) )


= ClassId ( StandardClassIds . BASE_COLLECTIONS_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_RANGES_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_ANNOTATION_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_JVM_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_JVM_INTERNAL_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_JVM_FUNCTIONS_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_INTERNAL_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_INTERNAL_IR_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_COROUTINES_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_ENUMS_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_CONCURRENT_PACKAGE , Name . identifier ( this ) )


= ClassId ( StandardClassIds . BASE_TEST_PACKAGE , Name . identifier ( this ) )


private fun String . callableId ( packageName : FqName )

= CallableId ( packageName , Name . identifier ( this ) )


private fun String . callableId ( classId : ClassId )

= CallableId ( classId , Name . identifier ( this ) )


private fun < K , V > Map < K , V > . inverseMap ( ) : Map < V , K >

= entries . associate { ( k , v ) -> v to k }


{ <EOL> val mockGeom = mockk < Geom > ( ) <EOL> val layersInheritMappings = true <EOL> val layerContextInterface = object : LayerContextInterface { <EOL> override val geom : Geom = mockGeom <EOL> override val layerFeatures : MutableMap < FeatureName , LayerFeature > = mutableMapOf ( ) <EOL> override val requiredAes : Set < Aes > = setOf ( ) <EOL> override fun toLayer ( layersInheritMappings : Boolean ) : Layer { <EOL> return Layer ( <NUM_LIT:0> , geom , bindingCollector . mappings , bindingCollector . settings , layerFeatures , bindingCollector . freeScales , layersInheritMappings ) <EOL> } <EOL> override val bindingCollector : BindingCollector = BindingCollector ( ) <EOL> } <EOL> val layer = layerContextInterface . toLayer ( layersInheritMappings ) <EOL> assertEquals ( mockGeom , layer . geom ) <EOL> assertEquals ( layerContextInterface . bindingCollector . mappings , layer . mappings ) <EOL> assertEquals ( layerContextInterface . bindingCollector . settings , layer . settings ) <EOL> assertEquals ( layerContextInterface . bindingCollector . freeScales , layer . freeScales ) <EOL> assertEquals ( layerContextInterface . layerFeatures , layer . features ) <EOL> assertEquals ( layersInheritMappings , layer . inheritsBindings ) <EOL> }


override fun doRawFirTest ( filePath : String )

{ <EOL> val ignoreTreeAccess = InTextDirectivesUtils . isDirectiveDefined ( File ( filePath ) . readText ( ) , "<STR_LIT>" ) <EOL> var treeAccessFound = false <EOL> try { <EOL> super . doRawFirTest ( filePath ) <EOL> } catch ( e : Throwable ) { <EOL> if ( ! ignoreTreeAccess || e . message ? . startsWith ( "<STR_LIT>" ) != true ) { <EOL> throw e <EOL> } <EOL> treeAccessFound = true <EOL> } <EOL> assertEquals ( "<STR_LIT>" , ignoreTreeAccess , treeAccessFound ) <EOL> }


override fun createKtFile ( filePath : String ) : KtFile

{ <EOL> val originalFile = super . createKtFile ( filePath ) <EOL> val originalProvider = originalFile . viewProvider <EOL> val updatedProvider = object : SingleRootFileViewProvider ( originalProvider . manager , originalProvider . virtualFile , originalProvider . isEventSystemEnabled , originalProvider . fileType , ) { <EOL> override fun isPhysical ( ) : Boolean = true <EOL> } <EOL> updatedProvider . manager . setAssertOnFileLoadingFilter ( VirtualFileFilter . ALL , testRootDisposable ) <EOL> val fileWithStub = object : KtFile ( updatedProvider , false ) { <EOL> override fun getStub ( ) : KotlinFileStub ? = stubTree ? . root as? KotlinFileStub <EOL> } <EOL> updatedProvider . forceCachedPsi ( fileWithStub ) <EOL> assertNotNull ( "<STR_LIT>" , fileWithStub . stub ) <EOL> return fileWithStub <EOL> }


{ <EOL> return if ( ( p == <NUM_LIT:1> ) && ( c == <NUM_LIT:0> ) ) "<STR_LIT:OK>" else "<STR_LIT:fail>" <EOL> }


= "<STR_LIT:OK>"


fun getVariablesWithConstraintsContainingGivenTypeVariable ( variableConstructorMarker : TypeConstructorMarker , ) : Collection < VariableWithConstraints >


fun getTypeVariable ( typeConstructor : TypeConstructorMarker ) : TypeVariableMarker ?


fun getConstraintsForVariable ( typeVariable : TypeVariableMarker ) : List < Constraint >


fun addNewIncorporatedConstraint ( lowerType : KotlinTypeMarker , upperType : KotlinTypeMarker , shouldTryUseDifferentFlexibilityForUpperType : Boolean , isFromNullabilityConstraint : Boolean = false , isFromDeclaredUpperBound : Boolean = false , )


fun addNewIncorporatedConstraint ( typeVariable : TypeVariableMarker , type : KotlinTypeMarker , constraintContext : ConstraintContext )


fun incorporate ( c : Context , typeVariable : TypeVariableMarker , constraint : Constraint )

{ <EOL> ProgressIndicatorAndCompilationCanceledStatus . checkCanceled ( ) <EOL> if ( c . areThereRecursiveConstraints ( typeVariable , constraint ) ) return <EOL> c . directWithVariable ( typeVariable , constraint ) <EOL> c . insideOtherConstraint ( typeVariable , constraint ) <EOL> }


private fun Context . areThereRecursiveConstraints ( typeVariable : TypeVariableMarker , constraint : Constraint )

= <EOL> constraint . type . contains { it . typeConstructor ( ) . unwrapStubTypeVariableConstructor ( ) == typeVariable . freshTypeConstructor ( ) }


private fun Context . directWithVariable ( typeVariable : TypeVariableMarker , constraint : Constraint , )

{ <EOL> val shouldBeTypeVariableFlexible = <EOL> if ( useRefinedBoundsForTypeVariableInFlexiblePosition ( ) ) <EOL> false <EOL> else <EOL> with ( utilContext ) { typeVariable . shouldBeFlexible ( ) } <EOL> if ( constraint . kind != ConstraintKind . LOWER ) { <EOL> forEachConstraint ( typeVariable ) { <EOL> if ( it . kind != ConstraintKind . UPPER ) { <EOL> addNewIncorporatedConstraint ( it . type , constraint . type , shouldBeTypeVariableFlexible , it . isNullabilityConstraint ) <EOL> } <EOL> } <EOL> } <EOL> if ( constraint . kind != ConstraintKind . UPPER ) { <EOL> forEachConstraint ( typeVariable ) { <EOL> if ( it . kind != ConstraintKind . LOWER ) { <EOL> val isFromDeclaredUpperBound = <EOL> it . position . from is DeclaredUpperBoundConstraintPosition < * > && ! it . type . typeConstructor ( ) . isTypeVariable ( ) <EOL> addNewIncorporatedConstraint ( constraint . type , it . type , shouldBeTypeVariableFlexible , isFromDeclaredUpperBound = isFromDeclaredUpperBound ) <EOL> } <EOL> } <EOL> } <EOL> }


private inline fun Context . forEachConstraint ( typeVariable : TypeVariableMarker , action : ( Constraint ) -> Unit )

{ <EOL> val constraints = getConstraintsForVariable ( typeVariable ) <EOL> var i = <NUM_LIT:0> <EOL> while ( i < constraints . size ) { <EOL> action ( constraints [ i ++ ] ) <EOL> } <EOL> }


private fun Context . insideOtherConstraint ( typeVariable : TypeVariableMarker , constraint : Constraint , )

{ <EOL> val freshTypeConstructor = typeVariable . freshTypeConstructor ( ) <EOL> for ( storageForOtherVariable in getVariablesWithConstraintsContainingGivenTypeVariable ( freshTypeConstructor ) ) { <EOL> for ( otherConstraint in storageForOtherVariable . getConstraintsContainedSpecifiedTypeVariable ( freshTypeConstructor ) ) { <EOL> generateNewConstraint ( typeVariable , constraint , storageForOtherVariable . typeVariable , otherConstraint ) <EOL> } <EOL> } <EOL> }


private fun Context . generateNewConstraint ( causeOfIncorporationVariable : TypeVariableMarker , causeOfIncorporationConstraint : Constraint , otherVariable : TypeVariableMarker , otherConstraint : Constraint , )

{ <EOL> val isBaseGenericType = otherConstraint . type . argumentsCount ( ) != <NUM_LIT:0> <EOL> val isBaseOrOtherCapturedType = otherConstraint . type . isCapturedType ( ) || causeOfIncorporationConstraint . type . isCapturedType ( ) <EOL> val ( type , needApproximation ) = when ( causeOfIncorporationConstraint . kind ) { <EOL> ConstraintKind . EQUALITY -> { <EOL> causeOfIncorporationConstraint . type to false <EOL> } <EOL> ConstraintKind . UPPER -> { <EOL> if ( otherConstraint . kind == ConstraintKind . LOWER && ! isBaseGenericType && ! isBaseOrOtherCapturedType ) { <EOL> nothingType ( ) to false <EOL> } else if ( otherConstraint . kind == ConstraintKind . UPPER && ! isBaseGenericType && ! isBaseOrOtherCapturedType ) { <EOL> causeOfIncorporationConstraint . type to false <EOL> } else { <EOL> createCapturedType ( createTypeArgument ( causeOfIncorporationConstraint . type , TypeVariance . OUT ) , listOf ( causeOfIncorporationConstraint . type ) , null , CaptureStatus . FOR_INCORPORATION ) to true <EOL> } <EOL> } <EOL> ConstraintKind . LOWER -> { <EOL> if ( otherConstraint . kind == ConstraintKind . UPPER && ! isBaseGenericType && ! isBaseOrOtherCapturedType ) { <EOL> nullableAnyType ( ) to false <EOL> } else if ( otherConstraint . kind == ConstraintKind . LOWER && ! isBaseGenericType && ! isBaseOrOtherCapturedType ) { <EOL> causeOfIncorporationConstraint . type to false <EOL> } else { <EOL> createCapturedType ( createTypeArgument ( causeOfIncorporationConstraint . type , TypeVariance . IN ) , emptyList ( ) , causeOfIncorporationConstraint . type , CaptureStatus . FOR_INCORPORATION ) to true <EOL> } <EOL> } <EOL> } <EOL> approximateIfNeededAndAddNewConstraint ( causeOfIncorporationVariable , causeOfIncorporationConstraint , otherVariable , otherConstraint , type , needApproximation ) <EOL> }


private fun Context . approximateIfNeededAndAddNewConstraint ( causeOfIncorporationVariable : TypeVariableMarker , causeOfIncorporationConstraint : Constraint , targetVariable : TypeVariableMarker , otherConstraint : Constraint , type : KotlinTypeMarker , needApproximation : Boolean = true , )

{ <EOL> val typeWithSubstitution = otherConstraint . type . substitute ( this , causeOfIncorporationVariable , type ) <EOL> val prepareType = { toSuper : Boolean -> <EOL> if ( needApproximation ) approximateCapturedTypes ( typeWithSubstitution , toSuper ) else typeWithSubstitution <EOL> } <EOL> if ( otherConstraint . kind != ConstraintKind . LOWER ) { <EOL> addNewConstraint ( causeOfIncorporationVariable , causeOfIncorporationConstraint , targetVariable , otherConstraint , prepareType ( true ) , isSubtype = false ) <EOL> } <EOL> if ( otherConstraint . kind != ConstraintKind . UPPER ) { <EOL> addNewConstraint ( causeOfIncorporationVariable , causeOfIncorporationConstraint , targetVariable , otherConstraint , prepareType ( false ) , isSubtype = true ) <EOL> } <EOL> }


private fun Context . addNewConstraint ( causeOfIncorporationVariable : TypeVariableMarker , causeOfIncorporationConstraint : Constraint , targetVariable : TypeVariableMarker , otherConstraint : Constraint , newConstraintType : KotlinTypeMarker , isSubtype : Boolean , )

{ <EOL> if ( targetVariable in getNestedTypeVariables ( newConstraintType ) ) return <EOL> val isUsefulForNullabilityConstraint = <EOL> isPotentialUsefulNullabilityConstraint ( newConstraintType , causeOfIncorporationConstraint . type , causeOfIncorporationConstraint . kind , ) <EOL> val isFromVariableFixation = otherConstraint . position . from is FixVariableConstraintPosition < * > <EOL> || causeOfIncorporationConstraint . position . from is FixVariableConstraintPosition < * > <EOL> if ( ! causeOfIncorporationConstraint . kind . isEqual ( ) && ! isUsefulForNullabilityConstraint && ! isFromVariableFixation && ! containsConstrainingTypeWithoutProjection ( newConstraintType , causeOfIncorporationConstraint ) ) return <EOL> if ( trivialConstraintTypeInferenceOracle . isGeneratedConstraintTrivial ( otherConstraint , causeOfIncorporationConstraint , newConstraintType , isSubtype ) ) return <EOL> val derivedFrom = SmartSet . create ( otherConstraint . derivedFrom ) . also { it . addAll ( causeOfIncorporationConstraint . derivedFrom ) } <EOL> if ( causeOfIncorporationVariable in derivedFrom ) return <EOL> derivedFrom . add ( causeOfIncorporationVariable ) <EOL> val kind = if ( isSubtype ) ConstraintKind . LOWER else ConstraintKind . UPPER <EOL> val inputTypePosition = <EOL> otherConstraint . position . from as? OnlyInputTypeConstraintPosition ? : otherConstraint . inputTypePositionBeforeIncorporation <EOL> val isNewConstraintUsefulForNullability = isUsefulForNullabilityConstraint && newConstraintType . isNullableNothing ( ) <EOL> val isOtherConstraintUsefulForNullability = <EOL> causeOfIncorporationConstraint . isNullabilityConstraint && causeOfIncorporationConstraint . type . isNullableNothing ( ) <EOL> val isNullabilityConstraint = isNewConstraintUsefulForNullability || isOtherConstraintUsefulForNullability <EOL> val constraintContext = ConstraintContext ( kind , derivedFrom , inputTypePosition , isNullabilityConstraint ) <EOL> addNewIncorporatedConstraint ( targetVariable , newConstraintType , constraintContext ) <EOL> }


private fun Context . containsConstrainingTypeWithoutProjection ( newConstraint : KotlinTypeMarker , otherConstraint : Constraint , ) : Boolean

{ <EOL> return getNestedArguments ( newConstraint ) . any { <EOL> it . getType ( ) . typeConstructor ( ) == otherConstraint . type . typeConstructor ( ) && it . getVariance ( ) == TypeVariance . INV <EOL> } <EOL> }


private fun Context . isPotentialUsefulNullabilityConstraint ( newConstraint : KotlinTypeMarker , otherConstraint : KotlinTypeMarker , kind : ConstraintKind , ) : Boolean

{ <EOL> if ( trivialConstraintTypeInferenceOracle . isSuitableResultedType ( newConstraint ) ) return false <EOL> val otherConstraintCanAddNullabilityToNewOne = <EOL> ! newConstraint . isNullableType ( ) && otherConstraint . isNullableType ( ) && kind == ConstraintKind . LOWER <EOL> val newConstraintCanAddNullabilityToOtherOne = <EOL> newConstraint . isNullableType ( ) && ! otherConstraint . isNullableType ( ) && kind == ConstraintKind . UPPER <EOL> return otherConstraintCanAddNullabilityToNewOne || newConstraintCanAddNullabilityToOtherOne <EOL> }


private fun Context . getNestedTypeVariables ( type : KotlinTypeMarker ) : List < TypeVariableMarker >

= <EOL> getNestedArguments ( type ) . mapNotNullTo ( SmartList ( ) ) { <EOL> getTypeVariable ( it . getType ( ) . typeConstructor ( ) . unwrapStubTypeVariableConstructor ( ) ) <EOL> }


private fun KotlinTypeMarker . substitute ( c : Context , typeVariable : TypeVariableMarker , value : KotlinTypeMarker ) : KotlinTypeMarker

{ <EOL> val substitutor = c . typeSubstitutorByTypeConstructor ( mapOf ( typeVariable . freshTypeConstructor ( c ) to value ) ) <EOL> return substitutor . safeSubstitute ( c , this ) <EOL> }


private fun approximateCapturedTypes ( type : KotlinTypeMarker , toSuper : Boolean ) : KotlinTypeMarker

= <EOL> if ( toSuper ) typeApproximator . approximateToSuperType ( type , TypeApproximatorConfiguration . IncorporationConfiguration ) ? : type <EOL> else typeApproximator . approximateToSubType ( type , TypeApproximatorConfiguration . IncorporationConfiguration ) ? : type


private fun TypeSystemInferenceExtensionContext . getNestedArguments ( type : KotlinTypeMarker ) : List < TypeArgumentMarker >

{ <EOL> val result = SmartList < TypeArgumentMarker > ( ) <EOL> val stack = ArrayDeque < TypeArgumentMarker > ( ) <EOL> when ( type ) { <EOL> is FlexibleTypeMarker -> { <EOL> stack . push ( createTypeArgument ( type . lowerBound ( ) , TypeVariance . INV ) ) <EOL> stack . push ( createTypeArgument ( type . upperBound ( ) , TypeVariance . INV ) ) <EOL> } <EOL> else -> stack . push ( createTypeArgument ( type , TypeVariance . INV ) ) <EOL> } <EOL> stack . push ( createTypeArgument ( type , TypeVariance . INV ) ) <EOL> val addArgumentsToStack = { projectedType : KotlinTypeMarker -> <EOL> for ( argumentIndex in <NUM_LIT:0> until projectedType . argumentsCount ( ) ) { <EOL> stack . add ( projectedType . getArgument ( argumentIndex ) ) <EOL> } <EOL> } <EOL> while ( ! stack . isEmpty ( ) ) { <EOL> val typeProjection = stack . pop ( ) <EOL> if ( typeProjection . isStarProjection ( ) ) continue <EOL> result . add ( typeProjection ) <EOL> when ( val projectedType = typeProjection . getType ( ) ) { <EOL> is FlexibleTypeMarker -> { <EOL> addArgumentsToStack ( projectedType . lowerBound ( ) ) <EOL> addArgumentsToStack ( projectedType . upperBound ( ) ) <EOL> } <EOL> else -> addArgumentsToStack ( projectedType ) <EOL> } <EOL> } <EOL> return result <EOL> }


override fun getInstance ( project : Project ) : JavaSourceSetsAccessor

= JavaSourceSetsAccessorG70 ( project . convention )


override fun lower ( module : IrModuleFragment )

{ <EOL> if ( context . platform . isJvm ( ) ) { <EOL> module . transformChildrenVoid ( this ) <EOL> } <EOL> }


override fun visitTypeOperator ( expression : IrTypeOperatorCall ) : IrExpression

{ <EOL> val functionExpr = expression . findSamFunctionExpr ( ) <EOL> if ( functionExpr != null && expression . typeOperand . isComposableFunInterface ( ) ) { <EOL> val argument = functionExpr . transform ( this , null ) as IrFunctionExpression <EOL> val superType = expression . typeOperand <EOL> val superClass = superType . classOrNull ? : error ( "<STR_LIT>" ) <EOL> return FunctionReferenceBuilder ( argument , superClass , superType , currentDeclarationParent ! ! , context , currentScope ! ! . scope . scopeOwnerSymbol , IrTypeSystemContextImpl ( context . irBuiltIns ) ) . build ( ) <EOL> } <EOL> return super . visitTypeOperator ( expression ) <EOL> }


private fun IrType . isComposableFunInterface ( ) : Boolean

= <EOL> classOrNull <EOL> ? . functions <EOL> ? . single { it . owner . modality == Modality . ABSTRACT } <EOL> ? . owner <EOL> ? . hasComposableAnnotation ( ) == true


internal fun IrTypeOperatorCall . findSamFunctionExpr ( ) : IrFunctionExpression ?

{ <EOL> val argument = argument <EOL> val operator = operator <EOL> val type = typeOperand <EOL> val functionClass = type . classOrNull <EOL> val isFunInterfaceConversion = operator == SAM_CONVERSION && <EOL> functionClass != null && <EOL> functionClass . owner . isFun <EOL> return if ( isFunInterfaceConversion ) { <EOL> when { <EOL> argument is IrFunctionExpression && argument . origin . isLambda -> argument <EOL> argument is IrTypeOperatorCall && argument . operator == IMPLICIT_CAST -> { <EOL> val functionExpr = argument . argument <EOL> functionExpr as? IrFunctionExpression <EOL> } <EOL> else -> null <EOL> } <EOL> } else { <EOL> null <EOL> } <EOL> }


{ <EOL> strong . dispose ( ) <EOL> }


= ReferenceWrapper ( Data ( ) )


private fun ReferenceWrapper . stress ( )

= ( <NUM_LIT:1> .. REPEAT_COUNT ) . sumOf { <EOL> this . value <EOL> }


{ <EOL> assertNotEquals ( <NUM_LIT:0> , aliveRef . stress ( ) ) <EOL> }


{ <EOL> assertEquals ( <NUM_LIT:0> , deadRef . stress ( ) ) <EOL> }


{ <EOL> val ref = ReferenceWrapper . create ( ) <EOL> ref . dispose ( ) <EOL> GC . schedule ( ) <EOL> Blackhole . consume ( ref . stress ( ) ) <EOL> }


{ <EOL> weight . forEach { it . dispose ( ) } <EOL> }


{ <EOL> list . plusAssign ( mutableListOf ( "<STR_LIT>" ) ) <EOL> with ( a ) { <EOL> list . plusAssign ( mutableListOf ( "<STR_LIT>" ) ) <EOL> list += mutableListOf ( "<STR_LIT>" ) <EOL> } <EOL> }


{ <EOL> main ( ) <EOL> hello ( ) <EOL> console . log ( "<STR_LIT>" ) <EOL> }


abstract fun f ( ) : String


= f ( )


abstract fun bar ( ) : Any


{ <EOL> return object : G ( ) { <EOL> override fun bar ( ) : Any { <EOL> return object : A < T > ( ) { <EOL> override fun f ( ) : String = "<STR_LIT:OK>" <EOL> } <EOL> } <EOL> } <EOL> }


{ <EOL> val y = foo < String > ( ) . bar ( ) ; <EOL> assertEquals ( "<STR_LIT:OK>" , y . toString ( ) ) <EOL> assertEquals ( "<STR_LIT>" , y . javaClass . getGenericSuperclass ( ) ? . toString ( ) ) <EOL> return "<STR_LIT:OK>" <EOL> }


public suspend fun < S , T : S > Flow < T > . reduce ( operation : suspend ( accumulator : S , value : T ) -> S ) : S

{ <EOL> var accumulator : Any ? = NULL <EOL> collect { value -> <EOL> accumulator = if ( accumulator !== NULL ) { <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> operation ( accumulator as S , value ) <EOL> } else { <EOL> value <EOL> } <EOL> } <EOL> if ( accumulator === NULL ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return accumulator as S <EOL> }

/**
 * Accumulates value starting with the first element and applying [operation] to current accumulator value and each element.
 * Throws [NoSuchElementException] if flow was empty.
 */


public suspend inline fun < T , R > Flow < T > . fold ( initial : R , crossinline operation : suspend ( acc : R , value : T ) -> R ) : R

{ <EOL> var accumulator = initial <EOL> collect { value -> <EOL> accumulator = operation ( accumulator , value ) <EOL> } <EOL> return accumulator <EOL> }

/**
 * Accumulates value starting with [initial] value and applying [operation] current accumulator value and each element
 */


public suspend fun < T > Flow < T > . single ( ) : T

{ <EOL> var result : Any ? = NULL <EOL> collect { value -> <EOL> require ( result === NULL ) { "<STR_LIT>" } <EOL> result = value <EOL> } <EOL> if ( result === NULL ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> return result as T <EOL> }

/**
 * The terminal operator that awaits for one and only one value to be emitted.
 * Throws [NoSuchElementException] for empty flow and [IllegalArgumentException] for flow
 * that contains more than one element.
 */


public suspend fun < T > Flow < T > . singleOrNull ( ) : T ?

{ <EOL> var result : Any ? = NULL <EOL> collectWhile { <EOL> if ( result === NULL ) { <EOL> result = it <EOL> true <EOL> } else { <EOL> result = NULL <EOL> false <EOL> } <EOL> } <EOL> return if ( result === NULL ) null else result as T <EOL> }

/**
 * The terminal operator that awaits for one and only one value to be emitted.
 * Returns the single value or `null`, if the flow was empty or emitted more than one value.
 */


public suspend fun < T > Flow < T > . first ( ) : T

{ <EOL> var result : Any ? = NULL <EOL> collectWhile { <EOL> result = it <EOL> false <EOL> } <EOL> if ( result === NULL ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> return result as T <EOL> }

/**
 * The terminal operator that returns the first element emitted by the flow and then cancels flow's collection.
 * Throws [NoSuchElementException] if the flow was empty.
 */


public suspend fun < T > Flow < T > . first ( predicate : suspend ( T ) -> Boolean ) : T

{ <EOL> var result : Any ? = NULL <EOL> collectWhile { <EOL> if ( predicate ( it ) ) { <EOL> result = it <EOL> false <EOL> } else { <EOL> true <EOL> } <EOL> } <EOL> if ( result === NULL ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> return result as T <EOL> }

/**
 * The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
 * Throws [NoSuchElementException] if the flow has not contained elements matching the [predicate].
 */


public suspend fun < T > Flow < T > . firstOrNull ( ) : T ?

{ <EOL> var result : T ? = null <EOL> collectWhile { <EOL> result = it <EOL> false <EOL> } <EOL> return result <EOL> }

/**
 * The terminal operator that returns the first element emitted by the flow and then cancels flow's collection.
 * Returns `null` if the flow was empty.
 */


public suspend fun < T > Flow < T > . firstOrNull ( predicate : suspend ( T ) -> Boolean ) : T ?

{ <EOL> var result : T ? = null <EOL> collectWhile { <EOL> if ( predicate ( it ) ) { <EOL> result = it <EOL> false <EOL> } else { <EOL> true <EOL> } <EOL> } <EOL> return result <EOL> }

/**
 * The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
 * Returns `null` if the flow did not contain an element matching the [predicate].
 */


public suspend fun < T > Flow < T > . last ( ) : T

{ <EOL> var result : Any ? = NULL <EOL> collect { <EOL> result = it <EOL> } <EOL> if ( result === NULL ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> return result as T <EOL> }

/**
 * The terminal operator that returns the last element emitted by the flow.
 *
 * Throws [NoSuchElementException] if the flow was empty.
 */


public suspend fun < T > Flow < T > . lastOrNull ( ) : T ?

{ <EOL> var result : T ? = null <EOL> collect { <EOL> result = it <EOL> } <EOL> return result <EOL> }

/**
 * The terminal operator that returns the last element emitted by the flow or `null` if the flow was empty.
 */


private fun Json ( discriminator : String , useArrayPolymorphism : Boolean = false )

= Json { <EOL> classDiscriminator = discriminator <EOL> this . useArrayPolymorphism = useArrayPolymorphism <EOL> }


@ Test <EOL> fun testCollisionWithDiscriminator ( )

{ <EOL> assertFailsWith < IllegalStateException > { Json ( "<STR_LIT:type>" ) . encodeToString ( Base . serializer ( ) , Base . Child ( "<STR_LIT:a>" ) ) } <EOL> assertFailsWith < IllegalStateException > { Json ( "<STR_LIT>" ) . encodeToString ( Base . serializer ( ) , Base . Child ( "<STR_LIT:a>" ) ) } <EOL> Json ( "<STR_LIT:f>" ) . encodeToString ( Base . serializer ( ) , Base . Child ( "<STR_LIT:a>" ) ) <EOL> }


@ Test <EOL> fun testNoCollisionWithArrayPolymorphism ( )

{ <EOL> Json ( "<STR_LIT:type>" , true ) . encodeToString ( Base . serializer ( ) , Base . Child ( "<STR_LIT:a>" ) ) <EOL> }


@ Test <EOL> fun testDescriptorInitializerFailure ( )

{ <EOL> BaseCollision . Child ( ) <EOL> BaseCollision . ChildCollided ( ) <EOL> BaseCollision . ChildCollided . serializer ( ) . descriptor <EOL> assertFailsWith < IllegalStateException > { BaseCollision . serializer ( ) . descriptor } <EOL> }


abstract fun interestedIn ( key : GeneratedDeclarationKey ? ) : Boolean


abstract fun generateBodyForFunction ( function : IrSimpleFunction , key : GeneratedDeclarationKey ? ) : IrBody ?


abstract fun generateBodyForConstructor ( constructor : IrConstructor , key : GeneratedDeclarationKey ? ) : IrBody ?


final override fun visitElement ( element : IrElement )

{ <EOL> if ( visitBodies ) { <EOL> element . acceptChildrenVoid ( this ) <EOL> } else { <EOL> when ( element ) { <EOL> is IrDeclaration , <EOL> is IrFile , <EOL> is IrModuleFragment -> element . acceptChildrenVoid ( this ) <EOL> else -> { } <EOL> } <EOL> } <EOL> }


final override fun visitSimpleFunction ( declaration : IrSimpleFunction )

{ <EOL> val origin = declaration . origin <EOL> if ( origin !is GeneratedByPlugin || ! interestedIn ( origin . pluginKey ) ) { <EOL> if ( visitBodies ) { <EOL> visitElement ( declaration ) <EOL> } <EOL> return <EOL> } <EOL> require ( declaration . body == null ) <EOL> declaration . body = generateBodyForFunction ( declaration , origin . pluginKey ) <EOL> }


final override fun visitConstructor ( declaration : IrConstructor )

{ <EOL> val origin = declaration . origin <EOL> if ( origin !is GeneratedByPlugin || ! interestedIn ( origin . pluginKey ) || declaration . body != null ) { <EOL> if ( visitBodies ) { <EOL> visitElement ( declaration ) <EOL> } <EOL> return <EOL> } <EOL> declaration . body = generateBodyForConstructor ( declaration , origin . pluginKey ) <EOL> }


protected fun generateDefaultBodyForMaterializeFunction ( function : IrSimpleFunction ) : IrBody ?

{ <EOL> val constructedType = function . returnType as? IrSimpleType ? : return null <EOL> val constructedClassSymbol = constructedType . classifier <EOL> val constructedClass = constructedClassSymbol . owner as? IrClass ? : return null <EOL> val constructor = constructedClass . primaryConstructor ? : return null <EOL> val constructorCall = IrConstructorCallImpl ( - <NUM_LIT:1> , - <NUM_LIT:1> , constructedType , constructor . symbol , typeArgumentsCount = <NUM_LIT:0> , constructorTypeArgumentsCount = <NUM_LIT:0> , valueArgumentsCount = <NUM_LIT:0> ) <EOL> val returnStatement = IrReturnImpl ( - <NUM_LIT:1> , - <NUM_LIT:1> , irBuiltIns . nothingType , function . symbol , constructorCall ) <EOL> return irFactory . createBlockBody ( - <NUM_LIT:1> , - <NUM_LIT:1> , listOf ( returnStatement ) ) <EOL> }


protected fun generateBodyForDefaultConstructor ( declaration : IrConstructor ) : IrBody ?

{ <EOL> val type = declaration . returnType as? IrSimpleType ? : return null <EOL> val delegatingAnyCall = IrDelegatingConstructorCallImpl ( - <NUM_LIT:1> , - <NUM_LIT:1> , irBuiltIns . anyType , irBuiltIns . anyClass . owner . primaryConstructor ? . symbol ? : return null , typeArgumentsCount = <NUM_LIT:0> , valueArgumentsCount = <NUM_LIT:0> ) <EOL> val initializerCall = IrInstanceInitializerCallImpl ( - <NUM_LIT:1> , - <NUM_LIT:1> , ( declaration . parent as? IrClass ) ? . symbol ? : return null , type ) <EOL> return irFactory . createBlockBody ( - <NUM_LIT:1> , - <NUM_LIT:1> , listOf ( delegatingAnyCall , initializerCall ) ) <EOL> }


override fun create ( entries : Array < out Map . Entry < String , String > > ) : Map < String , String >

{ <EOL> return persistentHashMapOf ( * entries . map { it . key to it . value } . toTypedArray ( ) ) <EOL> }


{ <EOL> val map = mutableMapOf < String , String > ( ) . apply { entries . forEach { this [ it . key ] = it . value } } <EOL> return persistentHashMapOf < String , String > ( ) . putAll ( map ) <EOL> }


{ <EOL> return entries . fold ( persistentHashMapOf ( ) ) { map , entry -> map . put ( entry . key , entry . value ) } <EOL> }


{ <EOL> val map = mutableMapOf < String , String > ( ) . apply { entries . forEach { this [ it . key ] = it . value } } <EOL> return persistentHashMapOf < String , String > ( ) . mutate { it . putAll ( map ) } <EOL> }


{ <EOL> return persistentHashMapOf < String , String > ( ) . mutate { builder -> entries . forEach { builder [ it . key ] = it . value } } <EOL> }


override fun create ( entries : Array < out Map . Entry < String , String > > ) : MutableMap < String , String >

{ <EOL> return persistentHashMapOf ( * entries . map { it . key to it . value } . toTypedArray ( ) ) . builder ( ) <EOL> }


{ <EOL> val map = mutableMapOf < String , String > ( ) . apply { entries . forEach { this [ it . key ] = it . value } } <EOL> return persistentHashMapOf < String , String > ( ) . builder ( ) . apply { putAll ( map ) } <EOL> }


{ <EOL> return persistentHashMapOf < String , String > ( ) . builder ( ) . apply { entries . forEach { this [ it . key ] = it . value } } <EOL> }


{ <EOL> return persistentMapOf ( * entries . map { it . key to it . value } . toTypedArray ( ) ) <EOL> }