1 /*
2  * Copyright (C) 2022 Square, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.squareup.kotlinpoet
17 
18 /** A KotlinPoet spec type that can have a context receiver. */
19 public interface ContextReceivable {
20 
21   /** The originating elements of this type. */
22   @ExperimentalKotlinPoetApi
23   public val contextReceiverTypes: List<TypeName>
24 
25   /** The builder analogue to [ContextReceivable] types. */
26   public interface Builder<out T : Builder<T>> {
27 
28     /** Mutable map of the current originating elements this builder contains. */
29     @ExperimentalKotlinPoetApi
30     public val contextReceiverTypes: MutableList<TypeName>
31 
32     /** Adds the given [receiverTypes] to this type's list of originating elements. */
33     @Suppress("UNCHECKED_CAST")
34     @ExperimentalKotlinPoetApi
<lambda>null35     public fun contextReceivers(receiverTypes: Iterable<TypeName>): T = apply {
36       contextReceiverTypes += receiverTypes
37     } as T
38 
39     /** Adds the given [receiverTypes] to this type's list of originating elements. */
40     @ExperimentalKotlinPoetApi
contextReceiversnull41     public fun contextReceivers(vararg receiverTypes: TypeName): T =
42       contextReceivers(receiverTypes.toList())
43   }
44 }
45 
46 @ExperimentalKotlinPoetApi
47 internal fun ContextReceivable.Builder<*>.buildContextReceivers() =
48   ContextReceivers(contextReceiverTypes.toImmutableList())
49 
50 @JvmInline
51 @ExperimentalKotlinPoetApi
52 internal value class ContextReceivers(
53   override val contextReceiverTypes: List<TypeName>,
54 ) : ContextReceivable
55