2 * Copyright 2000-2017 JetBrains s.r.o.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.jetbrains.uast.evaluation
18 import com.intellij.openapi.util.Key
19 import org.jetbrains.uast.*
20 import org.jetbrains.uast.values.UValue
21 import java.lang.ref.SoftReference
23 interface UEvaluationContext {
24 val uastContext: UastContext
26 val extensions: List<UEvaluatorExtension>
28 fun analyzeAll(file: UFile, state: UEvaluationState = file.createEmptyState()): UEvaluationContext
30 fun analyze(declaration: UDeclaration, state: UEvaluationState = declaration.createEmptyState()): UEvaluator
32 fun valueOf(expression: UExpression): UValue
34 fun getEvaluator(declaration: UDeclaration): UEvaluator
37 fun UFile.analyzeAll(context: UastContext = getUastContext(), extensions: List<UEvaluatorExtension> = emptyList()): UEvaluationContext =
38 MapBasedEvaluationContext(context, extensions).analyzeAll(this)
41 fun UExpression.uValueOf(extensions: List<UEvaluatorExtension> = emptyList()): UValue? {
42 val declaration = getContainingDeclaration() ?: return null
43 val context = declaration.getEvaluationContextWithCaching(extensions)
44 context.analyze(declaration)
45 return context.valueOf(this)
48 fun UExpression.uValueOf(vararg extensions: UEvaluatorExtension): UValue? = uValueOf(extensions.asList())
50 fun UDeclaration.getEvaluationContextWithCaching(extensions: List<UEvaluatorExtension> = emptyList()): UEvaluationContext {
51 return containingFile?.let { file ->
52 val cachedContext = file.getUserData(EVALUATION_CONTEXT_KEY)?.get()
53 if (cachedContext != null && cachedContext.extensions == extensions)
56 MapBasedEvaluationContext(getUastContext(), extensions).apply {
57 file.putUserData(EVALUATION_CONTEXT_KEY, SoftReference(this))
60 } ?: MapBasedEvaluationContext(getUastContext(), extensions)
63 val EVALUATION_CONTEXT_KEY = Key<SoftReference<out UEvaluationContext>>("uast.EvaluationContext")