• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright (C) 2025 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.turbine
18 
19 import com.android.tools.metalava.model.item.DefaultCodebase
20 import com.google.turbine.diag.SourceFile
21 import com.google.turbine.tree.Tree.CompUnit
22 
23 /**
24  * Creates [TurbineSourceFile]s on demand for a [SourceFile] and caches the result for reuse.
25  *
26  * @param codebase the [DefaultCodebase] of which any created [TurbineSourceFile]s are part.
27  * @param units the [CompUnit]s from which the [TurbineSourceFile]s will be created.
28  */
29 internal class TurbineSourceFileCache(
30     private val codebase: DefaultCodebase,
31     units: List<CompUnit>,
32 ) {
33     /** Map from [SourceFile.path] to [CompUnit]. */
34     private val pathToCompUnit = units.associateBy { it.source().path() }
35 
36     /** Map from file path to the [TurbineSourceFile]. */
37     private val turbineSourceFiles = mutableMapOf<String, TurbineSourceFile>()
38 
39     /**
40      * Get the [TurbineSourceFile] for a [SourceFile].
41      *
42      * If none exists then find the [CompUnit] for [sourceFile] by [SourceFile.path], failing if it
43      * could not be found. Then create a [TurbineSourceFile] from that, cache it for future use and
44      * return it.
45      */
46     internal fun turbineSourceFile(sourceFile: SourceFile): TurbineSourceFile =
47         turbineSourceFiles.computeIfAbsent(sourceFile.path()) { path ->
48             val unit = pathToCompUnit[path] ?: error("cannot find CompUnit for $path")
49             TurbineSourceFile(codebase, unit)
50         }
51 }
52