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 
17 package com.android.tools.metalava.model.psi
18 
19 import com.android.tools.lint.UastEnvironment
20 import com.android.tools.metalava.model.AnnotationManager
21 import com.android.tools.metalava.model.ClassItem
22 import com.android.tools.metalava.model.ClassResolver
23 import com.android.tools.metalava.reporter.Reporter
24 import com.intellij.psi.JavaPsiFacade
25 import com.intellij.psi.search.GlobalSearchScope
26 import java.io.File
27 
28 internal class PsiBasedClassResolver(
29     uastEnvironment: UastEnvironment,
30     annotationManager: AnnotationManager,
31     reporter: Reporter,
32     allowReadingComments: Boolean,
33 ) : ClassResolver {
34     private val javaPsiFacade: JavaPsiFacade
35     private val searchScope: GlobalSearchScope
36     private val classpathCodebase: PsiBasedCodebase
37 
38     init {
39         // Properties used to resolve classes from the classpath
40         val project = uastEnvironment.ideaProject
41         javaPsiFacade = JavaPsiFacade.getInstance(project)
42         searchScope = GlobalSearchScope.everythingScope(project)
43 
44         classpathCodebase =
45             PsiBasedCodebase(
46                 location = File("classpath"),
47                 description = "Codebase from classpath",
48                 annotationManager = annotationManager,
49                 reporter = reporter,
50                 fromClasspath = true,
51                 allowReadingComments = allowReadingComments,
52             )
53         val emptyPackageDocs = PackageDocs(mutableMapOf(), mutableMapOf(), mutableSetOf())
54         classpathCodebase.initializeFromSources(uastEnvironment, emptyList(), emptyPackageDocs)
55     }
56 
resolveClassnull57     override fun resolveClass(erasedName: String): ClassItem? {
58         // If the class cannot be found on the class path then return null, otherwise create a
59         // PsiClassItem for it.
60         val psiClass = javaPsiFacade.findClass(erasedName, searchScope) ?: return null
61         return classpathCodebase.findOrCreateClass(psiClass)
62     }
63 }
64