1 /*
2  * Copyright (C) 2023 The Android Open Source Project
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  *      http://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.android.hoststubgen.filters
17 
18 import com.android.hoststubgen.HostStubGenInternalException
19 
20 
21 /**
22  * [OutputFilter] with a given policy. Used to represent the default policy.
23  *
24  * This is used as the last fallback filter.
25  *
26  * @param policy the policy. Cannot be a "substitute" policy.
27  */
28 class ConstantFilter(
29         policy: FilterPolicy,
30         val reason: String
31 ) : OutputFilter() {
32     val classPolicy: FilterPolicy
33     val fieldPolicy: FilterPolicy
34     val methodPolicy: FilterPolicy
35 
36     init {
37         if (policy.isSubstitute) {
38             throw HostStubGenInternalException(
39                     "ConstantFilter doesn't allow substitution policies.")
40         }
41         if (policy.isClassWidePolicy) {
42             // We prevent it, because there's no point in using class-wide policies because
43             // all members get othe same policy too anyway.
44             throw HostStubGenInternalException(
45                     "ConstantFilter doesn't allow class-wide policies.")
46         }
47         methodPolicy = policy
48 
49         // If the default policy is "throw", we convert it to "keep" for classes and fields.
50         classPolicy = when (policy) {
51             FilterPolicy.Throw -> FilterPolicy.Keep
52             else -> policy
53         }
54         fieldPolicy = classPolicy
55     }
56 
getPolicyForClassnull57     override fun getPolicyForClass(className: String): FilterPolicyWithReason {
58         return classPolicy.withReason(reason)
59     }
60 
getPolicyForFieldnull61     override fun getPolicyForField(className: String, fieldName: String): FilterPolicyWithReason {
62         return fieldPolicy.withReason(reason)
63     }
64 
getPolicyForMethodnull65     override fun getPolicyForMethod(
66             className: String,
67             methodName: String,
68             descriptor: String,
69             ): FilterPolicyWithReason {
70         return methodPolicy.withReason(reason)
71     }
72 }
73