Remove 172 bunchset

This commit is contained in:
Vyacheslav Gerasimov
2018-08-02 19:08:04 +03:00
parent 0c867b4804
commit a2bf417d75
338 changed files with 0 additions and 26220 deletions
@@ -1,13 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.uast.kotlin
import org.jetbrains.uast.UElement
/**
* Actual only for 173-bunch, please remove when 173 is over
*/
typealias JvmDeclarationUElementPlaceholder = UElement
@@ -1,192 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.asJava.toLightGetter
import org.jetbrains.kotlin.asJava.toLightSetter
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.expressions.KotlinUElvisExpression
import org.jetbrains.uast.kotlin.internal.KotlinUElementWithComments
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable
abstract class KotlinAbstractUElement(private val givenParent: UElement?) : KotlinUElementWithComments,
JvmDeclarationUElementPlaceholder {
override val uastParent: UElement? by lz {
givenParent ?: convertParent()
}
protected open fun convertParent(): UElement? {
val psi = psi
var parent = psi?.parent ?: psi?.containingFile
if (psi is KtAnnotationEntry) {
val parentUnwrapped = KotlinConverter.unwrapElements(parent) ?: return null
val target = psi.useSiteTarget?.getAnnotationUseSiteTarget()
when (target) {
AnnotationUseSiteTarget.PROPERTY_GETTER ->
parent = (parentUnwrapped as? KtProperty)?.getter
?: (parentUnwrapped as? KtParameter)?.toLightGetter()
?: parent
AnnotationUseSiteTarget.PROPERTY_SETTER ->
parent = (parentUnwrapped as? KtProperty)?.setter
?: (parentUnwrapped as? KtParameter)?.toLightSetter()
?: parent
}
}
if (psi is UastKotlinPsiVariable && parent != null) {
parent = parent.parent
}
while (parent is KtStringTemplateEntryWithExpression ||
parent is KtStringTemplateExpression && parent.entries.size == 1) {
parent = parent.parent
}
if (parent is KtWhenConditionWithExpression) {
parent = parent.parent
}
if (parent is KtImportList) {
parent = parent.parent
}
if (psi is KtFunctionLiteral && parent is KtLambdaExpression) {
parent = parent.parent
}
if (parent is KtLambdaArgument) {
parent = parent.parent
}
if (psi is KtSuperTypeCallEntry) {
parent = parent?.parent
}
val result = doConvertParent(this, parent)
if (result == this) {
throw IllegalStateException("Loop in parent structure when converting a $psi of type ${psi?.javaClass} with parent $parent of type ${parent?.javaClass} text: [${parent?.text}]")
}
return result
}
override fun equals(other: Any?): Boolean {
if (other !is UElement) {
return false
}
return this.psi == other.psi
}
override fun hashCode() = psi?.hashCode() ?: 0
}
fun doConvertParent(element: UElement, parent: PsiElement?): UElement? {
val parentUnwrapped = KotlinConverter.unwrapElements(parent) ?: return null
if (parent is KtValueArgument && parentUnwrapped is KtAnnotationEntry) {
return (KotlinUastLanguagePlugin().convertElementWithParent(parentUnwrapped, null) as? KotlinUAnnotation)
?.findAttributeValueExpression(parent)
}
if (parent is KtParameter) {
val annotationClass = findAnnotationClassFromConstructorParameter(parent)
if (annotationClass != null) {
return annotationClass.methods.find { it.name == parent.name }
}
}
if (parent is KtClassInitializer) {
val containingClass = parent.containingClassOrObject
if (containingClass != null) {
val containingUClass = KotlinUastLanguagePlugin().convertElementWithParent(containingClass, null) as? KotlinUClass
containingUClass?.methods?.filterIsInstance<KotlinConstructorUMethod>()?.firstOrNull { it.isPrimary }?.let {
return it.uastBody
}
}
}
val result = KotlinUastLanguagePlugin().convertElementWithParent(parentUnwrapped, null)
if (result is UEnumConstant && element is UDeclaration) {
return result.initializingClass
}
if (result is UCallExpression && result.uastParent is UEnumConstant) {
return result.uastParent
}
if (result is USwitchClauseExpressionWithBody && !isInConditionBranch(element, result)) {
return result.body
}
if (result is KotlinUDestructuringDeclarationExpression &&
element.psi == (parent as KtDestructuringDeclaration).initializer) {
return result.tempVarAssignment
}
if (result is KotlinUElvisExpression && parent is KtBinaryExpression) {
when (element.psi) {
parent.left -> return result.lhsDeclaration
parent.right -> return result.rhsIfExpression
}
}
if (result is UMethod
&& result !is KotlinConstructorUMethod // no sense to wrap super calls with `return`
&& element is UExpression
&& element !is UBlockExpression
&& element !is UTypeReferenceExpression // when element is a type in extension methods
) {
return KotlinUBlockExpression.KotlinLazyUBlockExpression(result, { block ->
listOf(KotlinUImplicitReturnExpression(block).apply { returnExpression = element })
}).expressions.single()
}
return result
}
private fun isInConditionBranch(element: UElement, result: USwitchClauseExpressionWithBody) =
element.psi?.parentsWithSelf?.takeWhile { it !== result.psi }?.any { it is KtWhenCondition } ?: false
private fun findAnnotationClassFromConstructorParameter(parameter: KtParameter): UClass? {
val primaryConstructor = parameter.getStrictParentOfType<KtPrimaryConstructor>() ?: return null
val containingClass = primaryConstructor.getContainingClassOrObject()
if (containingClass.isAnnotation()) {
return KotlinUastLanguagePlugin().convertElementWithParent(containingClass, null) as? UClass
}
return null
}
abstract class KotlinAbstractUExpression(givenParent: UElement?)
: KotlinAbstractUElement(givenParent), UExpression {
override val annotations: List<UAnnotation>
get() {
val annotatedExpression = psi?.parent as? KtAnnotatedExpression ?: return emptyList()
return annotatedExpression.annotationEntries.map { KotlinUAnnotation(it, this) }
}
}
@@ -1,541 +0,0 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.lang.Language
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.*
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
import org.jetbrains.uast.*
import org.jetbrains.uast.java.JavaUastLanguagePlugin
import org.jetbrains.uast.kotlin.declarations.KotlinUMethod
import org.jetbrains.uast.kotlin.expressions.*
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable
interface KotlinUastResolveProviderService {
fun getBindingContext(element: KtElement): BindingContext
fun getTypeMapper(element: KtElement): KotlinTypeMapper?
fun getLanguageVersionSettings(element: KtElement): LanguageVersionSettings
fun isJvmElement(psiElement: PsiElement): Boolean
}
var PsiElement.destructuringDeclarationInitializer: Boolean? by UserDataProperty(Key.create("kotlin.uast.destructuringDeclarationInitializer"))
class KotlinUastLanguagePlugin : UastLanguagePlugin {
override val priority = 10
private val javaPlugin by lz { UastLanguagePlugin.getInstances().first { it is JavaUastLanguagePlugin } }
override val language: Language
get() = KotlinLanguage.INSTANCE
override fun isFileSupported(fileName: String): Boolean {
return fileName.endsWith(".kt", false) || fileName.endsWith(".kts", false)
}
private val PsiElement.isJvmElement: Boolean
get() {
val resolveProvider = ServiceManager.getService(project, KotlinUastResolveProviderService::class.java)
return resolveProvider.isJvmElement(this)
}
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? {
if (!element.isJvmElement) return null
return convertDeclarationOrElement(element, parent, requiredType)
}
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? {
if (!element.isJvmElement) return null
if (element is PsiFile) return convertDeclaration(element, null, requiredType)
if (element is KtLightClassForFacade) return convertDeclaration(element, null, requiredType)
return convertDeclarationOrElement(element, null, requiredType)
}
private fun convertDeclarationOrElement(element: PsiElement, givenParent: UElement?, requiredType: Class<out UElement>?): UElement? {
if (element is UElement) return element
if (element.isValid) {
element.getUserData(KOTLIN_CACHED_UELEMENT_KEY)?.get()?.let { cachedUElement ->
return if (requiredType == null || requiredType.isInstance(cachedUElement)) cachedUElement else null
}
}
val uElement = convertDeclaration(element, givenParent, requiredType)
?: KotlinConverter.convertPsiElement(element, givenParent, requiredType)
/*
if (uElement != null) {
element.putUserData(KOTLIN_CACHED_UELEMENT_KEY, WeakReference(uElement))
}
*/
return uElement
}
override fun getMethodCallExpression(
element: PsiElement,
containingClassFqName: String?,
methodName: String
): UastLanguagePlugin.ResolvedMethod? {
if (element !is KtCallExpression) return null
val resolvedCall = element.getResolvedCall(element.analyze()) ?: return null
val resultingDescriptor = resolvedCall.resultingDescriptor
if (resultingDescriptor !is FunctionDescriptor || resultingDescriptor.name.asString() != methodName) return null
val parent = element.parent
val parentUElement = convertElementWithParent(parent, null) ?: return null
val uExpression = KotlinUFunctionCallExpression(element, parentUElement, resolvedCall)
val method = uExpression.resolve() ?: return null
if (method.name != methodName) return null
return UastLanguagePlugin.ResolvedMethod(uExpression, method)
}
override fun getConstructorCallExpression(
element: PsiElement,
fqName: String
): UastLanguagePlugin.ResolvedConstructor? {
if (element !is KtCallExpression) return null
val resolvedCall = element.getResolvedCall(element.analyze()) ?: return null
val resultingDescriptor = resolvedCall.resultingDescriptor
if (resultingDescriptor !is ConstructorDescriptor
|| resultingDescriptor.returnType.constructor.declarationDescriptor?.name?.asString() != fqName) {
return null
}
val parent = KotlinConverter.unwrapElements(element.parent) ?: return null
val parentUElement = convertElementWithParent(parent, null) ?: return null
val uExpression = KotlinUFunctionCallExpression(element, parentUElement, resolvedCall)
val method = uExpression.resolve() ?: return null
val containingClass = method.containingClass ?: return null
return UastLanguagePlugin.ResolvedConstructor(uExpression, method, containingClass)
}
internal fun convertDeclaration(element: PsiElement,
givenParent: UElement?,
requiredType: Class<out UElement>?): UElement? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? {
return { ctor(element as P, givenParent) }
}
val original = element.originalElement
return with(requiredType) {
when (original) {
is KtLightMethod -> el<UMethod>(build(KotlinUMethod.Companion::create)) // .Companion is needed because of KT-13934
is KtLightClass -> when (original.kotlinOrigin) {
is KtEnumEntry -> el<UEnumConstant> {
convertEnumEntry(original.kotlinOrigin as KtEnumEntry, givenParent)
}
else -> el<UClass> { KotlinUClass.create(original, givenParent) }
}
is KtLightFieldImpl.KtLightEnumConstant -> el<UEnumConstant>(build(::KotlinUEnumConstant))
is KtLightField -> el<UField>(build(::KotlinUField))
is KtLightParameter, is UastKotlinPsiParameter -> el<UParameter>(build(::KotlinUParameter))
is UastKotlinPsiVariable -> el<UVariable>(build(::KotlinUVariable))
is KtEnumEntry -> el<UEnumConstant> {
convertEnumEntry(original, givenParent)
}
is KtClassOrObject -> el<UClass> {
original.toLightClass()?.let { lightClass ->
KotlinUClass.create(lightClass, givenParent)
}
}
is KtFunction ->
if (original.isLocal) {
el<ULambdaExpression> {
val parent = original.parent
if (parent is KtLambdaExpression) {
KotlinULambdaExpression(parent, givenParent) // your parent is the ULambdaExpression
} else if (original.name.isNullOrEmpty()) {
createLocalFunctionLambdaExpression(original, givenParent)
}
else {
val uDeclarationsExpression = createLocalFunctionDeclaration(original, givenParent)
val localFunctionVar = uDeclarationsExpression.declarations.single() as KotlinLocalFunctionUVariable
localFunctionVar.uastInitializer
}
}
}
else {
el<UMethod> {
val lightMethod = LightClassUtil.getLightClassMethod(original) ?: return null
convertDeclaration(lightMethod, givenParent, requiredType)
}
}
is KtPropertyAccessor -> el<UMethod> {
val lightMethod = LightClassUtil.getLightClassAccessorMethod(original) ?: return null
convertDeclaration(lightMethod, givenParent, requiredType)
}
is KtProperty ->
if (original.isLocal) {
KotlinConverter.convertPsiElement(element, givenParent, requiredType)
}
else {
convertNonLocalProperty(original, givenParent, requiredType)
}
is KtParameter -> el<UParameter> {
val ownerFunction = original.ownerFunction as? KtFunction ?: return null
val lightMethod = LightClassUtil.getLightClassMethod(ownerFunction) ?: return null
val lightParameter = lightMethod.parameterList.parameters.find { it.name == original.name } ?: return null
KotlinUParameter(lightParameter, givenParent)
}
is KtFile -> el<UFile> { KotlinUFile(original, this@KotlinUastLanguagePlugin) }
is FakeFileForLightClass -> el<UFile> { KotlinUFile(original.navigationElement, this@KotlinUastLanguagePlugin) }
is KtAnnotationEntry -> el<UAnnotation>(build(::KotlinUAnnotation))
is KtLightAnnotationForSourceEntry -> convertElement(original.kotlinOrigin, givenParent, requiredType)
else -> null
}
}
}
private fun convertEnumEntry(original: KtEnumEntry, givenParent: UElement?): UElement? {
return LightClassUtil.getLightClassBackingField(original)?.let { psiField ->
if (psiField is KtLightFieldImpl.KtLightEnumConstant) {
KotlinUEnumConstant(psiField, givenParent)
}
else {
null
}
}
}
override fun isExpressionValueUsed(element: UExpression): Boolean {
return when (element) {
is KotlinUSimpleReferenceExpression.KotlinAccessorCallExpression -> element.setterValue != null
is KotlinAbstractUExpression -> {
val ktElement = element.psi as? KtElement ?: return false
ktElement.analyze()[BindingContext.USED_AS_EXPRESSION, ktElement] ?: false
}
else -> false
}
}
}
internal inline fun <reified ActualT : UElement> Class<out UElement>?.el(f: () -> UElement?): UElement? {
return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null
}
internal inline fun <reified ActualT : UElement> Class<out UElement>?.expr(f: () -> UExpression?): UExpression? {
return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null
}
private fun convertNonLocalProperty(property: KtProperty,
givenParent: UElement?,
requiredType: Class<out UElement>?): UElement? {
val methods = LightClassUtil.getLightClassPropertyMethods(property)
return methods.backingField?.let { backingField ->
with(requiredType) {
el<UField> { KotlinUField(backingField, givenParent) }
}
} ?: methods.getter?.let { getter ->
KotlinUastLanguagePlugin().convertDeclaration(getter, givenParent, requiredType)
}
}
internal object KotlinConverter {
internal tailrec fun unwrapElements(element: PsiElement?): PsiElement? = when (element) {
is KtValueArgumentList -> unwrapElements(element.parent)
is KtValueArgument -> unwrapElements(element.parent)
is KtDeclarationModifierList -> unwrapElements(element.parent)
is KtContainerNode -> unwrapElements(element.parent)
is KtSimpleNameStringTemplateEntry -> unwrapElements(element.parent)
is KtLightParameterList -> unwrapElements(element.parent)
else -> element
}
internal fun convertPsiElement(element: PsiElement?,
givenParent: UElement?,
requiredType: Class<out UElement>?): UElement? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? {
return { ctor(element as P, givenParent) }
}
return with (requiredType) { when (element) {
is KtParameterList -> el<UDeclarationsExpression> {
val declarationsExpression = KotlinUDeclarationsExpression(givenParent)
declarationsExpression.apply {
declarations = element.parameters.mapIndexed { i, p ->
KotlinUParameter(UastKotlinPsiParameter.create(p, element, declarationsExpression, i), this)
}
}
}
is KtClassBody -> el<UExpressionList>(build(KotlinUExpressionList.Companion::createClassBody))
is KtCatchClause -> el<UCatchClause>(build(::KotlinUCatchClause))
is KtVariableDeclaration ->
if (element is KtProperty && !element.isLocal) {
el<UField> {
LightClassUtil.getLightClassBackingField(element)?.let {
KotlinUField(it, givenParent)
}
}
}
else {
el<UVariable> {
convertVariablesDeclaration(element, givenParent).declarations.singleOrNull()
}
}
is KtExpression -> KotlinConverter.convertExpression(element, givenParent, requiredType)
is KtLambdaArgument -> element.getLambdaExpression()?.let { KotlinConverter.convertExpression(it, givenParent, requiredType) }
is KtLightElementBase -> {
val expression = element.kotlinOrigin
when (expression) {
is KtExpression -> KotlinConverter.convertExpression(expression, givenParent, requiredType)
else -> el<UExpression> { UastEmptyExpression }
}
}
is KtLiteralStringTemplateEntry, is KtEscapeStringTemplateEntry -> el<ULiteralExpression>(build(::KotlinStringULiteralExpression))
is KtStringTemplateEntry -> element.expression?.let { convertExpression(it, givenParent, requiredType) } ?: expr<UExpression> { UastEmptyExpression }
is KtWhenEntry -> el<USwitchClauseExpressionWithBody>(build(::KotlinUSwitchEntry))
is KtWhenCondition -> convertWhenCondition(element, givenParent, requiredType)
is KtTypeReference -> el<UTypeReferenceExpression> { LazyKotlinUTypeReferenceExpression(element, givenParent) }
is KtConstructorDelegationCall ->
el<UCallExpression> { KotlinUFunctionCallExpression(element, givenParent) }
is KtSuperTypeCallEntry ->
el<UExpression> {
(element.getParentOfType<KtClassOrObject>(true)?.parent as? KtObjectLiteralExpression)
?.toUElementOfType<UExpression>()
?: KotlinUFunctionCallExpression(element, givenParent)
}
is KtImportDirective -> el<UImportStatement>(build(::KotlinUImportStatement))
else -> {
if (element is LeafPsiElement) {
if (element.elementType == KtTokens.IDENTIFIER)
el<UIdentifier>(build(::UIdentifier))
else if (element.elementType == KtTokens.LBRACKET && element.parent is KtCollectionLiteralExpression)
el<UIdentifier> {
UIdentifier(
element,
KotlinUCollectionLiteralExpression(
element.parent as KtCollectionLiteralExpression,
null
)
)
}
else null
} else {
null
}
}
}}
}
internal fun convertEntry(entry: KtStringTemplateEntry,
givenParent: UElement?,
requiredType: Class<out UElement>? = null): UExpression? {
return with(requiredType) {
if (entry is KtStringTemplateEntryWithExpression) {
expr<UExpression> {
KotlinConverter.convertOrEmpty(entry.expression, givenParent)
}
}
else {
expr<ULiteralExpression> {
if (entry is KtEscapeStringTemplateEntry)
KotlinStringULiteralExpression(entry, givenParent, entry.unescapedValue)
else
KotlinStringULiteralExpression(entry, givenParent)
}
}
}
}
internal fun convertExpression(expression: KtExpression,
givenParent: UElement?,
requiredType: Class<out UElement>? = null): UExpression? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? {
return { ctor(expression as P, givenParent) }
}
return with (requiredType) { when (expression) {
is KtVariableDeclaration -> expr<UDeclarationsExpression>(build(::convertVariablesDeclaration))
is KtStringTemplateExpression -> {
when {
expression.entries.isEmpty() -> {
expr<ULiteralExpression> { KotlinStringULiteralExpression(expression, givenParent, "") }
}
expression.entries.size == 1 -> convertEntry(expression.entries[0], givenParent, requiredType)
else -> {
expr<UExpression> { KotlinStringTemplateUPolyadicExpression(expression, givenParent) }
}
}
}
is KtDestructuringDeclaration -> expr<UDeclarationsExpression> {
val declarationsExpression = KotlinUDestructuringDeclarationExpression(givenParent, expression)
declarationsExpression.apply {
val tempAssignment = KotlinULocalVariable(UastKotlinPsiVariable.create(expression, declarationsExpression), declarationsExpression)
val destructuringAssignments = expression.entries.mapIndexed { i, entry ->
val psiFactory = KtPsiFactory(expression.project)
val initializer = psiFactory.createAnalyzableExpression("${tempAssignment.name}.component${i + 1}()",
expression.containingFile)
initializer.destructuringDeclarationInitializer = true
KotlinULocalVariable(UastKotlinPsiVariable.create(entry, tempAssignment.psi, declarationsExpression, initializer), declarationsExpression)
}
declarations = listOf(tempAssignment) + destructuringAssignments
}
}
is KtLabeledExpression -> expr<ULabeledExpression>(build(::KotlinULabeledExpression))
is KtClassLiteralExpression -> expr<UClassLiteralExpression>(build(::KotlinUClassLiteralExpression))
is KtObjectLiteralExpression -> expr<UObjectLiteralExpression>(build(::KotlinUObjectLiteralExpression))
is KtDotQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUQualifiedReferenceExpression))
is KtSafeQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUSafeQualifiedExpression))
is KtSimpleNameExpression -> expr<USimpleNameReferenceExpression>(build(::KotlinUSimpleReferenceExpression))
is KtCallExpression -> expr<UCallExpression>(build(::KotlinUFunctionCallExpression))
is KtCollectionLiteralExpression -> expr<UCallExpression>(build(::KotlinUCollectionLiteralExpression))
is KtBinaryExpression -> {
if (expression.operationToken == KtTokens.ELVIS) {
expr<UExpressionList>(build(::createElvisExpression))
}
else expr<UBinaryExpression>(build(::KotlinUBinaryExpression))
}
is KtParenthesizedExpression -> expr<UParenthesizedExpression>(build(::KotlinUParenthesizedExpression))
is KtPrefixExpression -> expr<UPrefixExpression>(build(::KotlinUPrefixExpression))
is KtPostfixExpression -> expr<UPostfixExpression>(build(::KotlinUPostfixExpression))
is KtThisExpression -> expr<UThisExpression>(build(::KotlinUThisExpression))
is KtSuperExpression -> expr<USuperExpression>(build(::KotlinUSuperExpression))
is KtCallableReferenceExpression -> expr<UCallableReferenceExpression>(build(::KotlinUCallableReferenceExpression))
is KtIsExpression -> expr<UBinaryExpressionWithType>(build(::KotlinUTypeCheckExpression))
is KtIfExpression -> expr<UIfExpression>(build(::KotlinUIfExpression))
is KtWhileExpression -> expr<UWhileExpression>(build(::KotlinUWhileExpression))
is KtDoWhileExpression -> expr<UDoWhileExpression>(build(::KotlinUDoWhileExpression))
is KtForExpression -> expr<UForEachExpression>(build(::KotlinUForEachExpression))
is KtWhenExpression -> expr<USwitchExpression>(build(::KotlinUSwitchExpression))
is KtBreakExpression -> expr<UBreakExpression>(build(::KotlinUBreakExpression))
is KtContinueExpression -> expr<UContinueExpression>(build(::KotlinUContinueExpression))
is KtReturnExpression -> expr<UReturnExpression>(build(::KotlinUReturnExpression))
is KtThrowExpression -> expr<UThrowExpression>(build(::KotlinUThrowExpression))
is KtBlockExpression -> expr<UBlockExpression>(build(::KotlinUBlockExpression))
is KtConstantExpression -> expr<ULiteralExpression>(build(::KotlinULiteralExpression))
is KtTryExpression -> expr<UTryExpression>(build(::KotlinUTryExpression))
is KtArrayAccessExpression -> expr<UArrayAccessExpression>(build(::KotlinUArrayAccessExpression))
is KtLambdaExpression -> expr<ULambdaExpression>(build(::KotlinULambdaExpression))
is KtBinaryExpressionWithTypeRHS -> expr<UBinaryExpressionWithType>(build(::KotlinUBinaryExpressionWithType))
is KtClassOrObject -> expr<UDeclarationsExpression> {
expression.toLightClass()?.let { lightClass ->
KotlinUDeclarationsExpression(givenParent).apply {
declarations = listOf(KotlinUClass.create(lightClass, this))
}
} ?: UastEmptyExpression
}
is KtFunction -> if (expression.name.isNullOrEmpty()) {
expr<ULambdaExpression>(build(::createLocalFunctionLambdaExpression))
}
else {
expr<UDeclarationsExpression>(build(::createLocalFunctionDeclaration))
}
else -> expr<UExpression>(build(::UnknownKotlinExpression))
}}
}
internal fun convertWhenCondition(condition: KtWhenCondition,
givenParent: UElement?,
requiredType: Class<out UElement>? = null): UExpression? {
return with(requiredType) {
when (condition) {
is KtWhenConditionInRange -> expr<UBinaryExpression> {
KotlinCustomUBinaryExpression(condition, givenParent).apply {
leftOperand = KotlinStringUSimpleReferenceExpression("it", this)
operator = when {
condition.isNegated -> KotlinBinaryOperators.NOT_IN
else -> KotlinBinaryOperators.IN
}
rightOperand = KotlinConverter.convertOrEmpty(condition.rangeExpression, this)
}
}
is KtWhenConditionIsPattern -> expr<UBinaryExpression> {
KotlinCustomUBinaryExpressionWithType(condition, givenParent).apply {
operand = KotlinStringUSimpleReferenceExpression("it", this)
operationKind = when {
condition.isNegated -> KotlinBinaryExpressionWithTypeKinds.NEGATED_INSTANCE_CHECK
else -> UastBinaryExpressionWithTypeKind.INSTANCE_CHECK
}
val typeRef = condition.typeReference
typeReference = typeRef?.let {
LazyKotlinUTypeReferenceExpression(it, this) { typeRef.toPsiType(this, boxed = true) }
}
}
}
is KtWhenConditionWithExpression ->
condition.expression?.let { KotlinConverter.convertExpression(it, givenParent, requiredType) }
else -> expr<UExpression> { UastEmptyExpression }
}
}
}
internal fun convertOrEmpty(expression: KtExpression?, parent: UElement?): UExpression {
return expression?.let { convertExpression(it, parent, null) } ?: UastEmptyExpression
}
internal fun convertOrNull(expression: KtExpression?, parent: UElement?): UExpression? {
return if (expression != null) convertExpression(expression, parent, null) else null
}
internal fun KtPsiFactory.createAnalyzableExpression(text: String, context: PsiElement): KtExpression =
createAnalyzableProperty("val x = $text", context).initializer ?: error("Failed to create expression from text: '$text'")
internal fun KtPsiFactory.createAnalyzableProperty(text: String, context: PsiElement): KtProperty =
createAnalyzableDeclaration(text, context)
internal fun <TDeclaration : KtDeclaration> KtPsiFactory.createAnalyzableDeclaration(text: String, context: PsiElement): TDeclaration {
val file = createAnalyzableFile("dummy.kt", text, context)
val declarations = file.declarations
assert(declarations.size == 1) { "${declarations.size} declarations in $text" }
return declarations.first() as TDeclaration
}
}
private fun convertVariablesDeclaration(
psi: KtVariableDeclaration,
parent: UElement?
): UDeclarationsExpression {
val declarationsExpression = KotlinUDeclarationsExpression(null, parent, psi)
val parentPsiElement = parent?.psi
val variable = KotlinUAnnotatedLocalVariable(
UastKotlinPsiVariable.create(psi, parentPsiElement, declarationsExpression), declarationsExpression) { annotationParent ->
psi.annotationEntries.map { KotlinUAnnotation(it, annotationParent) }
}
return declarationsExpression.apply { declarations = listOf(variable) }
}
@@ -1,76 +0,0 @@
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiClass
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.ValueArgument
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.uast.*
class KotlinUAnnotation(
override val psi: KtAnnotationEntry,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UAnnotation {
private val resolvedAnnotation: AnnotationDescriptor? by lz { psi.analyze()[BindingContext.ANNOTATION, psi] }
private val resolvedCall: ResolvedCall<*>? by lz { psi.getResolvedCall(psi.analyze()) }
override val qualifiedName: String?
get() = resolvedAnnotation?.fqName?.asString()
override val attributeValues: List<UNamedExpression> by lz {
resolvedCall?.valueArguments?.entries?.mapNotNull {
val arguments = it.value.arguments
val name = it.key.name.asString()
when {
arguments.size == 1 ->
KotlinUNamedExpression.create(name, arguments.first(), this)
arguments.size > 1 ->
KotlinUNamedExpression.create(name, arguments, this)
else -> null
}
} ?: emptyList()
}
override fun resolve(): PsiClass? {
val descriptor = resolvedAnnotation?.annotationClass ?: return null
return descriptor.toSource()?.getMaybeLightElement(this) as? PsiClass
}
override fun findAttributeValue(name: String?): UExpression? =
findDeclaredAttributeValue(name) ?: findAttributeDefaultValue(name ?: "value")
fun findAttributeValueExpression(arg: ValueArgument): UExpression? {
val mapping = resolvedCall?.getArgumentMapping(arg)
return (mapping as? ArgumentMatch)?.let { match ->
val namedExpression = attributeValues.find { it.name == match.valueParameter.name.asString() }
namedExpression?.expression as? KotlinUVarargExpression ?: namedExpression
}
}
override fun findDeclaredAttributeValue(name: String?): UExpression? {
return attributeValues.find {
it.name == name ||
(name == null && it.name == "value") ||
(name == "value" && it.name == null)
}?.expression
}
private fun findAttributeDefaultValue(name: String): UExpression? {
val parameter = resolvedAnnotation
?.annotationClass
?.unsubstitutedPrimaryConstructor
?.valueParameters
?.find { it.name.asString() == name } ?: return null
val defaultValue = (parameter.source.getPsi() as? KtParameter)?.defaultValue ?: return null
return getLanguagePlugin().convertWithParent(defaultValue)
}
}
@@ -1,258 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForLocalDeclaration
import org.jetbrains.kotlin.asJava.classes.KtLightClassForScript
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.uast.*
import org.jetbrains.uast.java.AbstractJavaUClass
import org.jetbrains.uast.kotlin.declarations.KotlinUMethod
import org.jetbrains.uast.kotlin.declarations.UastLightIdentifier
abstract class AbstractKotlinUClass(private val givenParent: UElement?) : AbstractJavaUClass() {
override val uastParent: UElement? by lz { givenParent ?: convertParent() }
//TODO: should be merged with KotlinAbstractUElement.convertParent() after detaching from AbstractJavaUClass
open fun convertParent(): UElement? =
(this.psi as? KtLightClassForLocalDeclaration)?.kotlinOrigin?.parent?.let {
when (it) {
is KtClassBody -> it.parent.toUElement() // TODO: it seems that `class_body`-s are never created in kotlin uast in top-down walk, probably they should be completely skipped and always unwrapped
else -> it.toUElement()
}
} ?: (psi.parent ?: psi.containingFile).toUElement()
}
open class KotlinUClass private constructor(
psi: KtLightClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
val ktClass = psi.kotlinOrigin
override val psi = unwrap<UClass, PsiClass>(psi)
override fun getOriginalElement(): PsiElement? = super.getOriginalElement()
override fun getNameIdentifier(): PsiIdentifier? = UastLightIdentifier(psi, ktClass)
override fun getContainingFile(): PsiFile? = unwrapFakeFileForLightClass(psi.containingFile)
override val annotations: List<UAnnotation>
get() = ktClass?.annotationEntries?.map { KotlinUAnnotation(it, this) } ?: emptyList()
override val uastAnchor: UElement
get() = UIdentifier(nameIdentifier, this)
override fun getInnerClasses(): Array<UClass> {
// filter DefaultImpls to avoid processing same methods from original interface multiple times
// filter Enum entry classes to avoid duplication with PsiEnumConstant initializer class
return psi.innerClasses.filter {
it.name != JvmAbi.DEFAULT_IMPLS_CLASS_NAME && !it.isEnumEntryLightClass()
}.mapNotNull {
getLanguagePlugin().convertOpt<UClass>(it, this)
}.toTypedArray()
}
override fun getSuperClass(): UClass? = super.getSuperClass()
override fun getFields(): Array<UField> = super.getFields()
override fun getInitializers(): Array<UClassInitializer> = super.getInitializers()
override fun getMethods(): Array<UMethod> {
val hasPrimaryConstructor = ktClass?.hasPrimaryConstructor() ?: false
var secondaryConstructorsCount = 0
fun createUMethod(psiMethod: PsiMethod): UMethod {
return if (psiMethod is KtLightMethod &&
psiMethod.isConstructor) {
if (!hasPrimaryConstructor && secondaryConstructorsCount++ == 0)
KotlinSecondaryConstructorWithInitializersUMethod(ktClass, psiMethod, this)
else
KotlinConstructorUMethod(ktClass, psiMethod, this)
} else {
getLanguagePlugin().convertOpt(psiMethod, this) ?: reportConvertFailure(psiMethod)
}
}
fun isDelegatedMethod(psiMethod: PsiMethod) = psiMethod is KtLightMethod && psiMethod.isDelegated
return psi.methods.asSequence()
.filterNot(::isDelegatedMethod)
.map(::createUMethod)
.toList()
.toTypedArray()
}
private fun PsiClass.isEnumEntryLightClass() = (this as? KtLightClass)?.kotlinOrigin is KtEnumEntry
companion object {
fun create(psi: KtLightClass, containingElement: UElement?): UClass = when (psi) {
is PsiAnonymousClass -> KotlinUAnonymousClass(psi, containingElement)
is KtLightClassForScript -> KotlinScriptUClass(psi, containingElement)
else -> KotlinUClass(psi, containingElement)
}
}
}
open class KotlinConstructorUMethod(
private val ktClass: KtClassOrObject?,
override val psi: KtLightMethod,
givenParent: UElement?
) : KotlinUMethod(psi, givenParent) {
val isPrimary: Boolean
get() = psi.kotlinOrigin.let { it is KtPrimaryConstructor || it is KtClassOrObject }
override val uastBody: UExpression? by lz {
val delegationCall: KtCallElement? = psi.kotlinOrigin.let {
when {
isPrimary -> ktClass?.superTypeListEntries?.firstIsInstanceOrNull<KtSuperTypeCallEntry>()
it is KtSecondaryConstructor -> it.getDelegationCall()
else -> null
}
}
val bodyExpressions = getBodyExpressions()
if (delegationCall == null && bodyExpressions.isEmpty()) return@lz null
KotlinUBlockExpression.KotlinLazyUBlockExpression(this) { uastParent ->
SmartList<UExpression>().apply {
delegationCall?.let {
add(KotlinUFunctionCallExpression(it, uastParent))
}
bodyExpressions.forEach {
add(KotlinConverter.convertOrEmpty(it, uastParent))
}
}
}
}
open protected fun getBodyExpressions(): List<KtExpression> {
if (isPrimary) return getInitializers()
val bodyExpression = (psi.kotlinOrigin as? KtFunction)?.bodyExpression ?: return emptyList()
if (bodyExpression is KtBlockExpression) return bodyExpression.statements
return listOf(bodyExpression)
}
protected fun getInitializers() = ktClass?.getAnonymousInitializers()?.mapNotNull { it.body } ?: emptyList()
}
// This class was created as a workaround for KT-21617 to be the only constructor which includes `init` block
// when there is no primary constructors in the class.
// It is expected to have only one constructor of this type in a UClass.
class KotlinSecondaryConstructorWithInitializersUMethod(
ktClass: KtClassOrObject?,
psi: KtLightMethod,
givenParent: UElement?
) : KotlinConstructorUMethod(ktClass, psi, givenParent) {
override fun getBodyExpressions(): List<KtExpression> = getInitializers() + super.getBodyExpressions()
}
class KotlinUAnonymousClass(
psi: PsiAnonymousClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), UAnonymousClass, PsiAnonymousClass by psi {
override val psi: PsiAnonymousClass = unwrap<UAnonymousClass, PsiAnonymousClass>(psi)
override fun getOriginalElement(): PsiElement? = super<AbstractKotlinUClass>.getOriginalElement()
override fun getSuperClass(): UClass? = super<AbstractKotlinUClass>.getSuperClass()
override fun getFields(): Array<UField> = super<AbstractKotlinUClass>.getFields()
override fun getMethods(): Array<UMethod> = super<AbstractKotlinUClass>.getMethods()
override fun getInitializers(): Array<UClassInitializer> = super<AbstractKotlinUClass>.getInitializers()
override fun getInnerClasses(): Array<UClass> = super<AbstractKotlinUClass>.getInnerClasses()
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override val uastAnchor: UElement?
get() {
val ktClassOrObject = (psi.originalElement as? KtLightClass)?.kotlinOrigin as? KtObjectDeclaration ?: return null
return UIdentifier(ktClassOrObject.getObjectKeyword(), this)
}
}
class KotlinScriptUClass(
psi: KtLightClassForScript,
override val uastParent: UElement?
) : AbstractJavaUClass(), PsiClass by psi {
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override fun getNameIdentifier(): PsiIdentifier? = UastLightIdentifier(psi, psi.kotlinOrigin)
override val uastAnchor: UElement
get() = UIdentifier(nameIdentifier, this)
override val psi = unwrap<UClass, KtLightClassForScript>(psi)
override fun getSuperClass(): UClass? = super.getSuperClass()
override fun getFields(): Array<UField> = super.getFields()
override fun getInitializers(): Array<UClassInitializer> = super.getInitializers()
override fun getInnerClasses(): Array<UClass> =
psi.innerClasses.mapNotNull { getLanguagePlugin().convertOpt<UClass>(it, this) }.toTypedArray()
override fun getMethods(): Array<UMethod> = psi.methods.map(this::createUMethod).toTypedArray()
private fun createUMethod(method: PsiMethod): UMethod {
return if (method.isConstructor) {
KotlinScriptConstructorUMethod(psi.script, method as KtLightMethod, this)
}
else {
getLanguagePlugin().convertOpt(method, this) ?: reportConvertFailure(method)
}
}
override fun getOriginalElement(): PsiElement? = psi.originalElement
class KotlinScriptConstructorUMethod(
script: KtScript,
override val psi: KtLightMethod,
override val uastParent: UElement?
) : KotlinUMethod(psi, uastParent) {
override val uastBody: UExpression? by lz {
val initializers = script.declarations.filterIsInstance<KtScriptInitializer>()
KotlinUBlockExpression.create(initializers, this)
}
}
}
private fun reportConvertFailure(psiMethod: PsiMethod): Nothing {
val isValid = psiMethod.isValid
val report = KotlinExceptionWithAttachments(
"cant convert $psiMethod of ${psiMethod.javaClass} to UMethod"
+ if (!isValid) " (method is not valid)" else ""
)
if (isValid) {
report.withAttachment("method", psiMethod.text)
psiMethod.containingFile?.let {
report.withAttachment("file", it.text)
}
}
throw report
}
@@ -1,56 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.uast.*
import java.util.*
class KotlinUFile(override val psi: KtFile, override val languagePlugin: UastLanguagePlugin) : UFile {
override val packageName: String
get() = psi.packageFqName.asString()
override val annotations: List<UAnnotation>
get() = psi.annotationEntries.map { KotlinUAnnotation(it, this) }
override val allCommentsInFile by lz {
val comments = ArrayList<UComment>(0)
psi.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitComment(comment: PsiComment) {
comments += UComment(comment, this@KotlinUFile)
}
})
comments
}
override val imports by lz { psi.importDirectives.map { KotlinUImportStatement(it, this) } }
override val classes by lz {
val facadeOrScriptClass = if (psi.isScript()) psi.script?.toLightClass() else psi.findFacadeClass()
val classes = psi.declarations.mapNotNull { (it as? KtClassOrObject)?.toLightClass()?.toUClass() }
(facadeOrScriptClass?.toUClass()?.let { listOf(it) } ?: emptyList()) + classes
}
private fun PsiClass.toUClass() = languagePlugin.convertOpt<UClass>(this, this@KotlinUFile)
}
@@ -1,65 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UImportStatement
import org.jetbrains.uast.USimpleNameReferenceExpression
class KotlinUImportStatement(
override val psi: KtImportDirective,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UImportStatement {
override val isOnDemand: Boolean
get() = psi.isAllUnder
private val importRef by lz {
psi.importedReference?.let {
ImportReference(it, psi.name ?: psi.text, this, psi)
}
}
override val importReference: UElement?
get() = importRef
override fun resolve() = importRef?.resolve()
private class ImportReference(
override val psi: KtExpression,
override val identifier: String,
givenParent: UElement?,
private val importDirective: KtImportDirective
) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression {
override val resolvedName: String?
get() = identifier
override fun asRenderString(): String = importDirective.importedFqName?.asString() ?: psi.text
override fun resolve(): PsiElement? {
val reference = psi.getQualifiedElementSelector() as? KtReferenceExpression ?: return null
val bindingContext = reference.analyze()
val referenceTarget = bindingContext[BindingContext.REFERENCE_TARGET, reference] ?: return null
return referenceTarget.toSource()?.getMaybeLightElement(this)
}
}
}
@@ -1,115 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin.declarations
import com.intellij.psi.PsiCodeBlock
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.isGetter
import org.jetbrains.kotlin.asJava.elements.isSetter
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.uast.*
import org.jetbrains.uast.java.annotations
import org.jetbrains.uast.java.internal.JavaUElementWithComments
import org.jetbrains.uast.kotlin.*
open class KotlinUMethod(
psi: KtLightMethod,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UAnnotationMethod, JavaUElementWithComments, PsiMethod by psi {
override val comments: List<UComment>
get() = super<KotlinAbstractUElement>.comments
override val psi: KtLightMethod = unwrap<UMethod, KtLightMethod>(psi)
override val uastDefaultValue by lz {
val annotationParameter = psi.kotlinOrigin as? KtParameter ?: return@lz null
val defaultValue = annotationParameter.defaultValue ?: return@lz null
getLanguagePlugin().convertElement(defaultValue, this) as? UExpression
}
private val kotlinOrigin = (psi.originalElement as KtLightElement<*, *>).kotlinOrigin
override fun getContainingFile(): PsiFile? = unwrapFakeFileForLightClass(psi.containingFile)
override fun getNameIdentifier() = UastLightIdentifier(psi, kotlinOrigin as KtNamedDeclaration?)
override val annotations by lz {
psi.annotations
.mapNotNull { (it as? KtLightElement<*, *>)?.kotlinOrigin as? KtAnnotationEntry }
.map { KotlinUAnnotation(it, this) }
}
override val uastParameters by lz {
psi.parameterList.parameters.map { KotlinUParameter(it, this) }
}
override val uastAnchor: UElement
get() = UIdentifier(nameIdentifier, this)
override val uastBody by lz {
val bodyExpression = when (kotlinOrigin) {
is KtFunction -> kotlinOrigin.bodyExpression
is KtProperty -> when {
psi.isGetter -> kotlinOrigin.getter?.bodyExpression
psi.isSetter -> kotlinOrigin.setter?.bodyExpression
else -> null
}
else -> null
} ?: return@lz null
when (bodyExpression) {
!is KtBlockExpression -> {
KotlinUBlockExpression.KotlinLazyUBlockExpression(this, { block ->
val implicitReturn = KotlinUImplicitReturnExpression(block)
val uBody = getLanguagePlugin().convertElement(bodyExpression, implicitReturn) as? UExpression
?: return@KotlinLazyUBlockExpression emptyList()
listOf(implicitReturn.apply { returnExpression = uBody })
})
}
else -> getLanguagePlugin().convertElement(bodyExpression, this) as? UExpression
}
}
override val isOverride: Boolean
get() = (kotlinOrigin as? KtCallableDeclaration)?.hasModifier(KtTokens.OVERRIDE_KEYWORD) ?: false
override fun getBody(): PsiCodeBlock? = super.getBody()
override fun getOriginalElement(): PsiElement? = super.getOriginalElement()
override fun equals(other: Any?) = other is KotlinUMethod && psi == other.psi
companion object {
fun create(psi: KtLightMethod, containingElement: UElement?) =
if (psi.kotlinOrigin is KtConstructor<*>) {
KotlinConstructorUMethod(
psi.kotlinOrigin?.containingClassOrObject,
psi, containingElement
)
}
else
KotlinUMethod(psi, containingElement)
}
}
@@ -1,285 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.java.JavaAbstractUExpression
import org.jetbrains.uast.java.JavaUAnnotation
import org.jetbrains.uast.java.annotations
import org.jetbrains.uast.kotlin.declarations.UastLightIdentifier
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable
import org.jetbrains.uast.visitor.UastVisitor
abstract class AbstractKotlinUVariable(givenParent: UElement?)
: KotlinAbstractUElement(givenParent), PsiVariable, UVariable {
override val uastInitializer: UExpression?
get() {
val psi = psi
val initializerExpression = when (psi) {
is UastKotlinPsiVariable -> psi.ktInitializer
is UastKotlinPsiParameter -> psi.ktDefaultValue
is KtLightElement<*, *> -> {
val origin = psi.kotlinOrigin
when (origin) {
is KtVariableDeclaration -> origin.initializer
is KtParameter -> origin.defaultValue
else -> null
}
}
else -> null
} ?: return null
return getLanguagePlugin().convertElement(initializerExpression, this) as? UExpression ?: UastEmptyExpression
}
val delegateExpression: UExpression? by lz {
val psi = psi
val expression = when (psi) {
is KtLightElement<*, *> -> (psi.kotlinOrigin as? KtProperty)?.delegateExpression
is UastKotlinPsiVariable -> (psi.ktElement as? KtProperty)?.delegateExpression
else -> null
}
expression?.let { getLanguagePlugin().convertElement(it, this) as? UExpression }
}
override fun getNameIdentifier(): PsiIdentifier {
val kotlinOrigin = (psi as? KtLightElement<*, *>)?.kotlinOrigin
return UastLightIdentifier(psi, kotlinOrigin as KtNamedDeclaration?)
}
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override val annotations: List<UAnnotation> by lz { psi.annotations.map { JavaUAnnotation(it, this) } }
override val typeReference by lz { getLanguagePlugin().convertOpt<UTypeReferenceExpression>(psi.typeElement, this) }
override val uastAnchor: UElement?
get() = UIdentifier(nameIdentifier, this)
override fun equals(other: Any?) = other is AbstractKotlinUVariable && psi == other.psi
}
class KotlinUVariable(
psi: PsiVariable,
givenParent: UElement?
) : AbstractKotlinUVariable(givenParent), UVariable, PsiVariable by psi {
override val psi = unwrap<UVariable, PsiVariable>(psi)
override val annotations by lz { psi.annotations.map { JavaUAnnotation(it, this) } }
override val typeReference by lz { getLanguagePlugin().convertOpt<UTypeReferenceExpression>(psi.typeElement, this) }
override fun getInitializer(): PsiExpression? {
return super<AbstractKotlinUVariable>.getInitializer()
}
override fun getOriginalElement(): PsiElement? {
return super<AbstractKotlinUVariable>.getOriginalElement()
}
override fun getNameIdentifier(): PsiIdentifier {
return super.getNameIdentifier()
}
override fun getContainingFile(): PsiFile {
return super.getContainingFile()
}
}
open class KotlinUParameter(
psi: PsiParameter,
givenParent: UElement?
) : AbstractKotlinUVariable(givenParent), UParameter, PsiParameter by psi {
override val psi = unwrap<UParameter, PsiParameter>(psi)
override fun getInitializer(): PsiExpression? {
return super<AbstractKotlinUVariable>.getInitializer()
}
override fun getOriginalElement(): PsiElement? {
return super<AbstractKotlinUVariable>.getOriginalElement()
}
override fun getNameIdentifier(): PsiIdentifier {
return super.getNameIdentifier()
}
override fun getContainingFile(): PsiFile {
return super.getContainingFile()
}
}
open class KotlinUField(
psi: PsiField,
givenParent: UElement?
) : AbstractKotlinUVariable(givenParent), UField, PsiField by psi {
override val psi = unwrap<UField, PsiField>(psi)
override fun getInitializer(): PsiExpression? {
return super<AbstractKotlinUVariable>.getInitializer()
}
override fun getOriginalElement(): PsiElement? {
return super<AbstractKotlinUVariable>.getOriginalElement()
}
override fun getNameIdentifier(): PsiIdentifier {
return super.getNameIdentifier()
}
override fun getContainingFile(): PsiFile {
return super.getContainingFile()
}
override fun isPhysical(): Boolean {
return true
}
override fun accept(visitor: UastVisitor) {
if (visitor.visitField(this)) return
annotations.acceptList(visitor)
uastInitializer?.accept(visitor)
delegateExpression?.accept(visitor)
visitor.afterVisitField(this)
}
}
open class KotlinULocalVariable(
psi: PsiLocalVariable,
givenParent: UElement?
) : AbstractKotlinUVariable(givenParent), ULocalVariable, PsiLocalVariable by psi {
override val psi = unwrap<ULocalVariable, PsiLocalVariable>(psi)
override fun getInitializer(): PsiExpression? {
return super<AbstractKotlinUVariable>.getInitializer()
}
override fun getOriginalElement(): PsiElement? {
return super<AbstractKotlinUVariable>.getOriginalElement()
}
override fun getNameIdentifier(): PsiIdentifier {
return super.getNameIdentifier()
}
override fun getContainingFile(): PsiFile {
return super.getContainingFile()
}
override fun accept(visitor: UastVisitor) {
if (visitor.visitLocalVariable(this)) return
annotations.acceptList(visitor)
uastInitializer?.accept(visitor)
delegateExpression?.accept(visitor)
visitor.afterVisitLocalVariable(this)
}
}
open class KotlinUAnnotatedLocalVariable(
psi: PsiLocalVariable,
uastParent: UElement?,
computeAnnotations: (parent: UElement) -> List<UAnnotation>
) : KotlinULocalVariable(psi, uastParent) {
override val annotations: List<UAnnotation> by lz { computeAnnotations(this) }
}
open class KotlinUEnumConstant(
psi: PsiEnumConstant,
givenParent: UElement?
) : AbstractKotlinUVariable(givenParent), UEnumConstant, PsiEnumConstant by psi {
override val initializingClass: UClass? by lz {
(psi.initializingClass as? KtLightClass)?.let { initializingClass ->
KotlinUClass.create(initializingClass, this)
}
}
override val psi = unwrap<UEnumConstant, PsiEnumConstant>(psi)
override fun getContainingFile(): PsiFile {
return super.getContainingFile()
}
override fun getNameIdentifier(): PsiIdentifier {
return super.getNameIdentifier()
}
override val kind: UastCallKind
get() = UastCallKind.CONSTRUCTOR_CALL
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = KotlinEnumConstantClassReference(psi, this)
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val valueArgumentCount: Int
get() = psi.argumentList?.expressions?.size ?: 0
override val valueArguments by lz(fun(): List<UExpression> {
val ktEnumEntry = (psi as? KtLightElement<*, *>)?.kotlinOrigin as? KtEnumEntry ?: return emptyList()
val ktSuperTypeCallEntry = ktEnumEntry.initializerList?.initializers?.firstOrNull() as? KtSuperTypeCallEntry ?: return emptyList()
return ktSuperTypeCallEntry.valueArguments.map {
it.getArgumentExpression()?.let { getLanguagePlugin().convertElement(it, this) } as? UExpression ?: UastEmptyExpression
}
})
override val returnType: PsiType?
get() = psi.type
override fun resolve() = psi.resolveMethod()
override val methodName: String?
get() = null
private class KotlinEnumConstantClassReference(
override val psi: PsiEnumConstant,
private val givenParent: UElement?
) : JavaAbstractUExpression(), USimpleNameReferenceExpression {
override val uastParent: UElement? by lz {
givenParent ?: KotlinUastLanguagePlugin().convertElementWithParent(psi.parent ?: psi.containingFile, null)
}
override fun resolve() = psi.containingClass
override val resolvedName: String?
get() = psi.containingClass?.name
override val identifier: String
get() = psi.containingClass?.name ?: "<error>"
}
}
@@ -1,110 +0,0 @@
package org.jetbrains.uast.kotlin.expressions
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.CommonSupertypes
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.*
import org.jetbrains.uast.kotlin.kinds.KotlinSpecialExpressionKinds
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable
private fun createVariableReferenceExpression(variable: UVariable, containingElement: UElement?) =
object : USimpleNameReferenceExpression {
override val psi: PsiElement? = null
override fun resolve(): PsiElement? = variable
override val uastParent: UElement? = containingElement
override val resolvedName: String? = variable.name
override val annotations: List<UAnnotation> = emptyList()
override val identifier: String = variable.name.orAnonymous()
}
private fun createNullLiteralExpression(containingElement: UElement?) =
object : ULiteralExpression {
override val psi: PsiElement? = null
override val uastParent: UElement? = containingElement
override val value: Any? = null
override val annotations: List<UAnnotation> = emptyList()
}
private fun createNotEqWithNullExpression(variable: UVariable, containingElement: UElement?) =
object : UBinaryExpression {
override val psi: PsiElement? = null
override val uastParent: UElement? = containingElement
override val leftOperand: UExpression by lz { createVariableReferenceExpression(variable, this) }
override val rightOperand: UExpression by lz { createNullLiteralExpression(this) }
override val operator: UastBinaryOperator = UastBinaryOperator.NOT_EQUALS
override val operatorIdentifier: UIdentifier? = UIdentifier(null, this)
override fun resolveOperator(): PsiMethod? = null
override val annotations: List<UAnnotation> = emptyList()
}
private fun createElvisExpressions(
left: KtExpression,
right: KtExpression,
containingElement: UElement?,
psiParent: PsiElement): List<UExpression> {
val declaration = KotlinUDeclarationsExpression(containingElement)
val tempVariable = KotlinULocalVariable(UastKotlinPsiVariable.create(left, declaration, psiParent), declaration)
declaration.declarations = listOf(tempVariable)
val ifExpression = object : UIfExpression {
override val psi: PsiElement? = null
override val uastParent: UElement? = containingElement
override val condition: UExpression by lz { createNotEqWithNullExpression(tempVariable, this) }
override val thenExpression: UExpression? by lz { createVariableReferenceExpression(tempVariable, this) }
override val elseExpression: UExpression? by lz { KotlinConverter.convertExpression(right, this ) }
override val isTernary: Boolean = false
override val annotations: List<UAnnotation> = emptyList()
override val ifIdentifier: UIdentifier = UIdentifier(null, this)
override val elseIdentifier: UIdentifier? = UIdentifier(null, this)
}
return listOf(declaration, ifExpression)
}
fun createElvisExpression(elvisExpression: KtBinaryExpression, givenParent: UElement?): UExpression {
val left = elvisExpression.left ?: return UastEmptyExpression
val right = elvisExpression.right ?: return UastEmptyExpression
return KotlinUElvisExpression(elvisExpression, left, right, givenParent)
}
class KotlinUElvisExpression(
private val elvisExpression: KtBinaryExpression,
private val left: KtExpression,
private val right: KtExpression,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UExpressionList, KotlinEvaluatableUElement {
override val psi: PsiElement? = elvisExpression
override val kind = KotlinSpecialExpressionKinds.ELVIS
override val annotations: List<UAnnotation> = emptyList()
override val expressions: List<UExpression> by lz {
createElvisExpressions(left, right, this, elvisExpression.parent)
}
val lhsDeclaration get() = (expressions[0] as UDeclarationsExpression).declarations.single()
val rhsIfExpression get() = expressions[1] as UIfExpression
override fun asRenderString(): String {
return kind.name + " " +
expressions.joinToString(separator = "\n", prefix = "{\n", postfix = "\n}") {
it.asRenderString().withMargin
}
}
override fun getExpressionType(): PsiType? {
val leftType = left.analyze()[BindingContext.EXPRESSION_TYPE_INFO, left]?.type ?: return null
val rightType = right.analyze()[BindingContext.EXPRESSION_TYPE_INFO, right]?.type ?: return null
return CommonSupertypes
.commonSupertype(listOf(leftType, rightType))
.toPsiType(this, elvisExpression, boxed = false)
}
}
@@ -1,59 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtAnonymousInitializer
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.uast.*
class KotlinUBlockExpression(
override val psi: KtBlockExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UBlockExpression, KotlinUElementWithType {
override val expressions by lz { psi.statements.map { KotlinConverter.convertOrEmpty(it, this) } }
class KotlinLazyUBlockExpression(
override val uastParent: UElement?,
expressionProducer: (expressionParent: UElement) -> List<UExpression>
) : UBlockExpression {
override val psi: PsiElement? = null
override val annotations: List<UAnnotation> = emptyList()
override val expressions by lz { expressionProducer(this) }
}
companion object {
fun create(initializers: List<KtAnonymousInitializer>, uastParent: UElement): UBlockExpression {
val languagePlugin = uastParent.getLanguagePlugin()
return KotlinLazyUBlockExpression(uastParent) { expressionParent ->
initializers.map { languagePlugin.convertOpt<UExpression>(it.body, expressionParent) ?: UastEmptyExpression }
}
}
}
override fun convertParent(): UElement? {
val directParent = super.convertParent()
if (directParent is UnknownKotlinExpression && directParent.psi is KtAnonymousInitializer) {
val containingUClass = directParent.getContainingUClass() ?: return directParent
containingUClass.methods
.find { it is KotlinConstructorUMethod && it.isPrimary || it is KotlinSecondaryConstructorWithInitializersUMethod }?.let {
return it.uastBody
}
}
return directParent
}
}
@@ -1,42 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.uast.UCatchClause
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UParameter
import org.jetbrains.uast.UTypeReferenceExpression
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
class KotlinUCatchClause(
override val psi: KtCatchClause,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UCatchClause {
override val body by lz { KotlinConverter.convertOrEmpty(psi.catchBody, this) }
override val parameters by lz {
val parameter = psi.catchParameter ?: return@lz emptyList<UParameter>()
listOf(KotlinUParameter(UastKotlinPsiParameter.create(parameter, psi, this, 0), this))
}
override val typeReferences by lz {
val parameter = psi.catchParameter ?: return@lz emptyList<UTypeReferenceExpression>()
val typeReference = parameter.typeReference ?: return@lz emptyList<UTypeReferenceExpression>()
listOf(LazyKotlinUTypeReferenceExpression(typeReference, this) { typeReference.toPsiType(this, boxed = true) } )
}
}
@@ -1,54 +0,0 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.uast.kotlin.expressions
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.KotlinAbstractUExpression
import org.jetbrains.uast.kotlin.KotlinConverter
import org.jetbrains.uast.kotlin.KotlinUElementWithType
class KotlinUCollectionLiteralExpression(
val sourcePsi: KtCollectionLiteralExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UCallExpression, KotlinUElementWithType {
override val classReference: UReferenceExpression? get() = null
override val kind: UastCallKind = UastCallKind.NESTED_ARRAY_INITIALIZER
override val methodIdentifier: UIdentifier? by lazy { UIdentifier(sourcePsi.leftBracket, this) }
override val methodName: String? get() = null
override val receiver: UExpression? get() = null
override val receiverType: PsiType? get() = null
override val returnType: PsiType? get() = getExpressionType()
override val typeArgumentCount: Int get() = typeArguments.size
override val typeArguments: List<PsiType> get() = listOfNotNull((returnType as? PsiArrayType)?.componentType)
override val valueArgumentCount: Int
get() = sourcePsi.getInnerExpressions().size
override val valueArguments by lazy {
sourcePsi.getInnerExpressions().map { KotlinConverter.convertOrEmpty(it, this) }
}
override fun asRenderString(): String = "collectionLiteral[" + valueArguments.joinToString { it.asRenderString() } + "]"
override fun resolve(): PsiMethod? = null
override val psi: PsiElement get() = sourcePsi
}
@@ -1,43 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.PsiElement
import org.jetbrains.uast.kotlin.KotlinAbstractUExpression
import org.jetbrains.uast.kotlin.doConvertParent
open class KotlinUDeclarationsExpression(
override val psi: PsiElement?,
givenParent: UElement?,
val psiAnchor: PsiElement? = null
) : KotlinAbstractUExpression(givenParent), UDeclarationsExpression {
override val uastParent: UElement?
get() = if (psiAnchor != null) doConvertParent(this, psiAnchor.parent) else super.uastParent
constructor(uastParent: UElement?) : this(null, uastParent)
override lateinit var declarations: List<UDeclaration>
internal set
}
class KotlinUDestructuringDeclarationExpression(
givenParent: UElement?,
psiAnchor: PsiElement
) : KotlinUDeclarationsExpression(null, givenParent, psiAnchor) {
val tempVarAssignment get() = declarations.first()
}
@@ -1,42 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UForEachExpression
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
import org.jetbrains.uast.psi.UastPsiParameterNotResolved
class KotlinUForEachExpression(
override val psi: KtForExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UForEachExpression {
override val iteratedValue by lz { KotlinConverter.convertOrEmpty(psi.loopRange, this) }
override val body by lz { KotlinConverter.convertOrEmpty(psi.body, this) }
override val variable by lz {
val parameter = psi.loopParameter?.let { UastKotlinPsiParameter.create(it, psi, this, 0) }
?: UastPsiParameterNotResolved(psi, KotlinLanguage.INSTANCE)
KotlinUParameter(parameter, this)
}
override val forIdentifier: UIdentifier
get() = UIdentifier(null, this)
}
@@ -1,52 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.uast.UBlockExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.ULambdaExpression
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
import org.jetbrains.uast.withMargin
class KotlinULambdaExpression(
override val psi: KtLambdaExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), ULambdaExpression, KotlinUElementWithType {
val functionalInterfaceType: PsiType?
get() = getFunctionalInterfaceType()
override val body by lz { KotlinConverter.convertOrEmpty(psi.bodyExpression, this) }
override val valueParameters by lz {
psi.valueParameters.mapIndexed { i, p ->
KotlinUParameter(UastKotlinPsiParameter.create(p, psi, this, i), this)
}
}
override fun asRenderString(): String {
val renderedValueParameters = if (valueParameters.isEmpty())
""
else
valueParameters.joinToString { it.asRenderString() } + " ->\n"
val expressions = (body as? UBlockExpression)?.expressions
?.joinToString("\n") { it.asRenderString().withMargin } ?: body.asRenderString()
return "{ $renderedValueParameters\n$expressions\n}"
}
}
@@ -1,102 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.psi.ValueArgument
import org.jetbrains.uast.*
class KotlinUNamedExpression private constructor(
override val name: String?,
givenParent: UElement?,
expressionProducer: (UElement) -> UExpression
) : KotlinAbstractUElement(givenParent), UNamedExpression {
override val expression: UExpression by lz { expressionProducer(this) }
override val annotations: List<UAnnotation> = emptyList()
override val psi: PsiElement? = null
companion object {
internal fun create(name: String?, valueArgument: ValueArgument, uastParent: UElement?): UNamedExpression {
val expression = valueArgument.getArgumentExpression()
return KotlinUNamedExpression(name, uastParent) { expressionParent ->
expression?.let { expressionParent.getLanguagePlugin().convertOpt<UExpression>(it, expressionParent) }
?: UastEmptyExpression
}
}
internal fun create(
name: String?,
valueArguments: List<ValueArgument>,
uastParent: UElement?
): UNamedExpression {
return KotlinUNamedExpression(name, uastParent) { expressionParent ->
KotlinUVarargExpression(valueArguments, expressionParent)
}
}
}
}
class KotlinUVarargExpression(
private val valueArgs: List<ValueArgument>,
uastParent: UElement?
) : KotlinAbstractUExpression(uastParent), UCallExpression {
override val kind: UastCallKind = UastCallKind.NESTED_ARRAY_INITIALIZER
override val valueArguments: List<UExpression> by lz {
valueArgs.map {
it.getArgumentExpression()?.let { argumentExpression ->
getLanguagePlugin().convert<UExpression>(argumentExpression, this)
} ?: UastEmptyExpression
}
}
override val valueArgumentCount: Int
get() = valueArgs.size
override val psi: PsiElement?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = null
override fun resolve() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
}
@@ -1,95 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import com.intellij.psi.impl.light.LightPsiClassBuilder
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.psi.KtObjectLiteralExpression
import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
import org.jetbrains.uast.*
class KotlinUObjectLiteralExpression(
override val psi: KtObjectLiteralExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UObjectLiteralExpression, KotlinUElementWithType {
override val declaration: UClass by lz {
val lightClass: KtLightClass? = psi.objectDeclaration.toLightClass()
if (lightClass != null) {
getLanguagePlugin().convert<UClass>(lightClass, this)
} else {
logger.error(
"Failed to create light class for object declaration",
Attachment(psi.containingFile.virtualFile?.path ?: "<no path>", psi.containingFile.text)
)
getLanguagePlugin().convert(LightPsiClassBuilder(psi, "<unnamed>"), this)
}
}
override fun getExpressionType() = psi.objectDeclaration.toPsiType()
private val superClassConstructorCall by lz {
psi.objectDeclaration.superTypeListEntries.firstOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry
}
override val classReference: UReferenceExpression? by lz { superClassConstructorCall?.let { ObjectLiteralClassReference(it, this) } }
override val valueArgumentCount: Int
get() = superClassConstructorCall?.valueArguments?.size ?: 0
override val valueArguments by lz {
val psi = superClassConstructorCall ?: return@lz emptyList<UExpression>()
psi.valueArguments.map { KotlinConverter.convertOrEmpty(it.getArgumentExpression(), this) }
}
override val typeArgumentCount: Int
get() = superClassConstructorCall?.typeArguments?.size ?: 0
override val typeArguments by lz {
val psi = superClassConstructorCall ?: return@lz emptyList<PsiType>()
psi.typeArguments.map { it.typeReference.toPsiType(this, boxed = true) }
}
override fun resolve() = superClassConstructorCall?.resolveCallToDeclaration(this) as? PsiMethod
private class ObjectLiteralClassReference(
override val psi: KtSuperTypeCallEntry,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), USimpleNameReferenceExpression {
override fun resolve() = (psi.resolveCallToDeclaration(this) as? PsiMethod)?.containingClass
override val annotations: List<UAnnotation>
get() = emptyList()
override val resolvedName: String?
get() = identifier
override val identifier: String
get() = psi.name ?: "<error>"
}
companion object {
val logger by lz { Logger.getInstance(KotlinUObjectLiteralExpression::class.java) }
}
}
@@ -1,217 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiNamedElement
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.utils.addToStdlib.constant
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.UastVisitor
open class KotlinUSimpleReferenceExpression(
override val psi: KtSimpleNameExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression, KotlinUElementWithType, KotlinEvaluatableUElement {
private val resolvedDeclaration by lz { psi.resolveCallToDeclaration(this) }
override val identifier get() = psi.getReferencedName()
override fun resolve() = resolvedDeclaration
override val resolvedName: String?
get() = (resolvedDeclaration as? PsiNamedElement)?.name
override fun accept(visitor: UastVisitor) {
visitor.visitSimpleNameReferenceExpression(this)
if (psi.parent.destructuringDeclarationInitializer != true) {
visitAccessorCalls(visitor)
}
visitor.afterVisitSimpleNameReferenceExpression(this)
}
private fun visitAccessorCalls(visitor: UastVisitor) {
// Visit Kotlin get-set synthetic Java property calls as function calls
val bindingContext = psi.analyze()
val access = psi.readWriteAccess()
val resolvedCall = psi.getResolvedCall(bindingContext)
val resultingDescriptor = resolvedCall?.resultingDescriptor as? SyntheticJavaPropertyDescriptor
if (resultingDescriptor != null) {
val setterValue = if (access.isWrite) {
findAssignment(psi, psi.parent)?.right ?: run {
visitor.afterVisitSimpleNameReferenceExpression(this)
return
}
} else {
null
}
if (resolvedCall != null) {
if (access.isRead) {
val getDescriptor = resultingDescriptor.getMethod
KotlinAccessorCallExpression(psi, this, resolvedCall, getDescriptor, null).accept(visitor)
}
if (access.isWrite && setterValue != null) {
val setDescriptor = resultingDescriptor.setMethod
if (setDescriptor != null) {
KotlinAccessorCallExpression(psi, this, resolvedCall, setDescriptor, setterValue).accept(visitor)
}
}
}
}
}
private tailrec fun findAssignment(prev: PsiElement?, element: PsiElement?): KtBinaryExpression? = when (element) {
is KtBinaryExpression -> if (element.left == prev && element.operationToken == KtTokens.EQ) element else null
is KtQualifiedExpression -> findAssignment(element, element.parent)
is KtSimpleNameExpression -> findAssignment(element, element.parent)
else -> null
}
class KotlinAccessorCallExpression(
override val psi: KtElement,
override val uastParent: KotlinUSimpleReferenceExpression,
private val resolvedCall: ResolvedCall<*>,
private val accessorDescriptor: DeclarationDescriptor,
val setterValue: KtExpression?
) : UCallExpression {
override val methodName: String?
get() = accessorDescriptor.name.asString()
override val receiver: UExpression?
get() {
val containingElement = uastParent.uastParent
return if (containingElement is UQualifiedReferenceExpression && containingElement.selector == this)
containingElement.receiver
else
null
}
override val annotations: List<UAnnotation>
get() = emptyList()
override val receiverType by lz {
val type = (resolvedCall.dispatchReceiver ?: resolvedCall.extensionReceiver)?.type ?: return@lz null
type.toPsiType(this, psi, boxed = true)
}
override val methodIdentifier: UIdentifier?
get() = UIdentifier(uastParent.psi, this)
override val classReference: UReferenceExpression?
get() = null
override val valueArgumentCount: Int
get() = if (setterValue != null) 1 else 0
override val valueArguments by lz {
if (setterValue != null)
listOf(KotlinConverter.convertOrEmpty(setterValue, this))
else
emptyList()
}
override val typeArgumentCount: Int
get() = resolvedCall.typeArguments.size
override val typeArguments by lz {
resolvedCall.typeArguments.values.map { it.toPsiType(this, psi, true) }
}
override val returnType by lz {
(accessorDescriptor as? CallableDescriptor)?.returnType?.toPsiType(this, psi, boxed = false)
}
override val kind: UastCallKind
get() = UastCallKind.METHOD_CALL
override fun resolve(): PsiMethod? {
val source = accessorDescriptor.toSource()
return resolveSource(psi, accessorDescriptor, source)
}
}
enum class ReferenceAccess(val isRead: Boolean, val isWrite: Boolean) {
READ(true, false), WRITE(false, true), READ_WRITE(true, true)
}
private fun KtExpression.readWriteAccess(): ReferenceAccess {
var expression = getQualifiedExpressionForSelectorOrThis()
loop@ while (true) {
val parent = expression.parent
when (parent) {
is KtParenthesizedExpression, is KtAnnotatedExpression, is KtLabeledExpression -> expression = parent as KtExpression
else -> break@loop
}
}
val assignment = expression.getAssignmentByLHS()
if (assignment != null) {
return when (assignment.operationToken) {
KtTokens.EQ -> ReferenceAccess.WRITE
else -> ReferenceAccess.READ_WRITE
}
}
return if ((expression.parent as? KtUnaryExpression)?.operationToken
in constant { setOf(KtTokens.PLUSPLUS, KtTokens.MINUSMINUS) })
ReferenceAccess.READ_WRITE
else
ReferenceAccess.READ
}
}
class KotlinClassViaConstructorUSimpleReferenceExpression(
override val psi: KtCallElement,
override val identifier: String,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression, KotlinUElementWithType {
override val resolvedName: String?
get() = (psi.getResolvedCall(psi.analyze())?.resultingDescriptor as? ConstructorDescriptor)
?.containingDeclaration?.name?.asString()
override fun resolve(): PsiElement? {
val resolvedCall = psi.getResolvedCall(psi.analyze())
val resultingDescriptor = resolvedCall?.resultingDescriptor as? ConstructorDescriptor ?: return null
val clazz = resultingDescriptor.containingDeclaration
return clazz.toSource()?.getMaybeLightElement(this)
}
}
class KotlinStringUSimpleReferenceExpression(
override val identifier: String,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression {
override val psi: PsiElement?
get() = null
override fun resolve() = null
override val resolvedName: String?
get() = identifier
}
@@ -1,91 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtWhenEntry
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.kinds.KotlinSpecialExpressionKinds
class KotlinUSwitchExpression(
override val psi: KtWhenExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), USwitchExpression, KotlinUElementWithType {
override val expression by lz { KotlinConverter.convertOrNull(psi.subjectExpression, this) }
override val body: UExpressionList by lz {
object : KotlinUExpressionList(psi, KotlinSpecialExpressionKinds.WHEN, this@KotlinUSwitchExpression) {
override fun asRenderString() = expressions.joinToString("\n") { it.asRenderString().withMargin }
}.apply {
expressions = this@KotlinUSwitchExpression.psi.entries.map { KotlinUSwitchEntry(it, this) }
}
}
override fun asRenderString() = buildString {
val expr = expression?.let { "(" + it.asRenderString() + ") " } ?: ""
appendln("switch $expr {")
appendln(body.asRenderString())
appendln("}")
}
override val switchIdentifier: UIdentifier
get() = UIdentifier(null, this)
}
class KotlinUSwitchEntry(
override val psi: KtWhenEntry,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), USwitchClauseExpressionWithBody {
override val caseValues by lz {
psi.conditions.map { KotlinConverter.convertWhenCondition(it, this) ?: UastEmptyExpression }
}
override val body: UExpressionList by lz {
object : KotlinUExpressionList(psi, KotlinSpecialExpressionKinds.WHEN_ENTRY, this@KotlinUSwitchEntry) {
override fun asRenderString() = buildString {
appendln("{")
expressions.forEach { appendln(it.asRenderString().withMargin) }
appendln("}")
}
}.apply {
val exprPsi = this@KotlinUSwitchEntry.psi.expression
val userExpressions = when (exprPsi) {
is KtBlockExpression -> exprPsi.statements.map { KotlinConverter.convertOrEmpty(it, this) }
else -> listOf(KotlinConverter.convertOrEmpty(exprPsi, this))
}
expressions = userExpressions + object : UBreakExpression {
override val psi: PsiElement?
get() = null
override val label: String?
get() = null
override val uastParent: UElement?
get() = this@KotlinUSwitchEntry
override val annotations: List<UAnnotation>
get() = emptyList()
}
}
}
override fun convertParent(): UElement? {
val result = KotlinConverter.unwrapElements(psi.parent)?.let { parentUnwrapped ->
KotlinUastLanguagePlugin().convertElementWithParent(parentUnwrapped, null)
}
return (result as? KotlinUSwitchExpression)?.body ?: result
}
}
@@ -1,60 +0,0 @@
package org.jetbrains.uast.kotlin.expressions
import com.intellij.psi.PsiType
import com.intellij.psi.PsiVariable
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.*
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable
internal class KotlinLocalFunctionUVariable(
val function: KtFunction,
override val psi: PsiVariable,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UVariable, PsiVariable by psi {
override val uastInitializer: UExpression? by lz {
createLocalFunctionLambdaExpression(function, this)
}
override val typeReference: UTypeReferenceExpression? = null
override val uastAnchor: UElement? = null
override val annotations: List<UAnnotation> = emptyList()
}
private class KotlinLocalFunctionULambdaExpression(
override val psi: KtFunction,
givenParent: UElement?
): KotlinAbstractUExpression(givenParent), ULambdaExpression {
val functionalInterfaceType: PsiType?
get() = null
override val body by lz { KotlinConverter.convertOrEmpty(psi.bodyExpression, this) }
override val valueParameters by lz {
psi.valueParameters.mapIndexed { i, p ->
KotlinUParameter(UastKotlinPsiParameter.create(p, psi, this, i), this)
}
}
override fun asRenderString(): String {
val renderedValueParameters = valueParameters.joinToString(prefix = "(", postfix = ")",
transform = KotlinUParameter::asRenderString)
val expressions = (body as? UBlockExpression)?.expressions?.joinToString("\n") {
it.asRenderString().withMargin
} ?: body.asRenderString()
return "fun $renderedValueParameters {\n${expressions.withMargin}\n}"
}
}
fun createLocalFunctionDeclaration(function: KtFunction, parent: UElement?): UDeclarationsExpression {
return KotlinUDeclarationsExpression(null, parent, function).apply {
val functionVariable = UastKotlinPsiVariable.create(function.name.orAnonymous(), function, this)
declarations = listOf(KotlinLocalFunctionUVariable(function, functionVariable, this))
}
}
fun createLocalFunctionLambdaExpression(function: KtFunction, parent: UElement?): ULambdaExpression =
KotlinLocalFunctionULambdaExpression(function, parent)
@@ -1,53 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.kotlin.internal
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.uast.UComment
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.kotlin.JvmDeclarationUElementPlaceholder
interface KotlinUElementWithComments : JvmDeclarationUElementPlaceholder {
override val comments: List<UComment>
get() {
val psi = psi ?: return emptyList()
val childrenComments = psi.children.filterIsInstance<PsiComment>().map { UComment(it, this) }
if (this !is UExpression) return childrenComments
val childrenAndSiblingComments = childrenComments +
psi.nearestCommentSibling(forward = true)?.let { listOf(UComment(it, this)) }.orEmpty() +
psi.nearestCommentSibling(forward = false)?.let { listOf(UComment(it, this)) }.orEmpty()
val parent = psi.parent as? KtValueArgument ?: return childrenAndSiblingComments
return childrenAndSiblingComments +
parent.nearestCommentSibling(forward = true)?.let { listOf(UComment(it, this)) }.orEmpty() +
parent.nearestCommentSibling(forward = false)?.let { listOf(UComment(it, this)) }.orEmpty()
}
private fun PsiElement.nearestCommentSibling(forward: Boolean): PsiComment? {
var sibling = if (forward) nextSibling else prevSibling
while (sibling is PsiWhiteSpace && !sibling.text.contains('\n')) {
sibling = if (forward) sibling.nextSibling else sibling.prevSibling
}
return sibling as? PsiComment
}
}
-161
View File
@@ -1,161 +0,0 @@
UFile (package = )
UClass (name = A)
UField (name = str)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = getStr)
UAnnotationMethod (name = A)
UParameter (name = str)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = A)
UParameter (name = i)
UAnnotation (fqName = null)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (this))
USimpleNameReferenceExpression (identifier = <init>)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = i)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (toString))
USimpleNameReferenceExpression (identifier = toString)
UClass (name = AWithInit)
UField (name = str)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = getStr)
UAnnotationMethod (name = AWithInit)
UParameter (name = str)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
UAnnotationMethod (name = AWithInit)
UParameter (name = i)
UAnnotation (fqName = null)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (this))
USimpleNameReferenceExpression (identifier = <init>)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = i)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (toString))
USimpleNameReferenceExpression (identifier = toString)
UClass (name = AWith2Init)
UField (name = str)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = getStr)
UAnnotationMethod (name = AWith2Init)
UParameter (name = str)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
ULiteralExpression (value = 1)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
ULiteralExpression (value = 2)
UAnnotationMethod (name = AWith2Init)
UParameter (name = i)
UAnnotation (fqName = null)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (this))
USimpleNameReferenceExpression (identifier = <init>)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = i)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (toString))
USimpleNameReferenceExpression (identifier = toString)
UClass (name = AOnlyInit)
UAnnotationMethod (name = AOnlyInit)
UBlockExpression
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
ULiteralExpression (value = 1)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
ULiteralExpression (value = 2)
UClass (name = AWithSecondary)
UField (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = getA)
UAnnotationMethod (name = setA)
UParameter (name = p)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = AWithSecondary)
UParameter (name = i)
UAnnotation (fqName = null)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0))
UIdentifier (Identifier ())
USimpleNameReferenceExpression (identifier = <init>)
UBinaryExpression (operator = =)
USimpleNameReferenceExpression (identifier = a)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = i)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (toString))
USimpleNameReferenceExpression (identifier = toString)
UAnnotationMethod (name = AWithSecondary)
UParameter (name = s)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0))
UIdentifier (Identifier ())
USimpleNameReferenceExpression (identifier = <init>)
UBinaryExpression (operator = =)
USimpleNameReferenceExpression (identifier = a)
USimpleNameReferenceExpression (identifier = s)
UClass (name = AWithSecondaryInit)
UField (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = getA)
UAnnotationMethod (name = setA)
UParameter (name = p)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = AWithSecondaryInit)
UParameter (name = i)
UAnnotation (fqName = null)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0))
UIdentifier (Identifier ())
USimpleNameReferenceExpression (identifier = <init>)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
UBinaryExpression (operator = =)
USimpleNameReferenceExpression (identifier = a)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = i)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (toString))
USimpleNameReferenceExpression (identifier = toString)
UAnnotationMethod (name = AWithSecondaryInit)
UParameter (name = s)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0))
UIdentifier (Identifier ())
USimpleNameReferenceExpression (identifier = <init>)
UBinaryExpression (operator = =)
USimpleNameReferenceExpression (identifier = a)
USimpleNameReferenceExpression (identifier = s)
UDeclarationsExpression
ULocalVariable (name = local)
USimpleNameReferenceExpression (identifier = s)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = local)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (toString))
USimpleNameReferenceExpression (identifier = toString)
@@ -1,81 +0,0 @@
public final class A {
private final var str: java.lang.String
public final fun getStr() : java.lang.String = UastEmptyExpression
public fun A(str: java.lang.String) = UastEmptyExpression
public fun A(i: int) {
<init>(i.toString())
}
}
public final class AWithInit {
private final var str: java.lang.String
public final fun getStr() : java.lang.String = UastEmptyExpression
public fun AWithInit(str: java.lang.String) {
{
println()
}
}
public fun AWithInit(i: int) {
<init>(i.toString())
}
}
public final class AWith2Init {
private final var str: java.lang.String
public final fun getStr() : java.lang.String = UastEmptyExpression
public fun AWith2Init(str: java.lang.String) {
{
println(1)
}
{
println(2)
}
}
public fun AWith2Init(i: int) {
<init>(i.toString())
}
}
public final class AOnlyInit {
public fun AOnlyInit() {
{
println(1)
}
{
println(2)
}
}
}
public final class AWithSecondary {
public var a: java.lang.String
public final fun getA() : java.lang.String = UastEmptyExpression
public final fun setA(p: java.lang.String) : void = UastEmptyExpression
public fun AWithSecondary(i: int) {
<init>()
a = i.toString()
}
public fun AWithSecondary(s: java.lang.String) {
<init>()
a = s
}
}
public final class AWithSecondaryInit {
public var a: java.lang.String
public final fun getA() : java.lang.String = UastEmptyExpression
public final fun setA(p: java.lang.String) : void = UastEmptyExpression
public fun AWithSecondaryInit(i: int) {
<init>()
{
println()
}
a = i.toString()
}
public fun AWithSecondaryInit(s: java.lang.String) {
<init>()
a = s
var local: java.lang.String = s
local.toString()
}
}
@@ -1,10 +0,0 @@
UFile (package = ) [public final class CycleInTypeParametersKt {...]
UClass (name = CycleInTypeParametersKt) [public final class CycleInTypeParametersKt {...}]
UField (name = a) [private static final var a: Device<?> = null as? Device<?>]
UAnnotation (fqName = org.jetbrains.annotations.Nullable) [@org.jetbrains.annotations.Nullable]
UBinaryExpressionWithType [null as? Device<?>] : PsiType:Device<?>
ULiteralExpression (value = null) [null] : PsiType:Void
UTypeReferenceExpression (name = Device<?>) [Device<?>]
UAnnotationMethod (name = getA) [public static final fun getA() : Device<?> = UastEmptyExpression]
UClass (name = Device) [public final class Device {...}]
UAnnotationMethod (name = Device) [public fun Device() = UastEmptyExpression]
@@ -1,10 +0,0 @@
UFile (package = )
UClass (name = DefaultParameterValuesKt)
UAnnotationMethod (name = foo)
UParameter (name = a)
UAnnotation (fqName = null)
ULiteralExpression (value = 1)
UParameter (name = foo)
UAnnotation (fqName = org.jetbrains.annotations.Nullable)
ULiteralExpression (value = null)
UBlockExpression
@@ -1,4 +0,0 @@
public final class DefaultParameterValuesKt {
public static final fun foo(a: int, foo: java.lang.String) : void {
}
}
-65
View File
@@ -1,65 +0,0 @@
UFile (package = ) [public final class MyColor {...]
UClass (name = MyColor) [public final class MyColor {...}]
UField (name = x) [private final var x: int]
UAnnotation (fqName = null) [@null]
UField (name = y) [private final var y: int]
UAnnotation (fqName = null) [@null]
UField (name = z) [private final var z: int]
UAnnotation (fqName = null) [@null]
UAnnotationMethod (name = getX) [public final fun getX() : int = UastEmptyExpression]
UAnnotationMethod (name = getY) [public final fun getY() : int = UastEmptyExpression]
UAnnotationMethod (name = getZ) [public final fun getZ() : int = UastEmptyExpression]
UAnnotationMethod (name = MyColor) [public fun MyColor(x: int, y: int, z: int) = UastEmptyExpression]
UParameter (name = x) [var x: int]
UAnnotation (fqName = null) [@null]
UParameter (name = y) [var y: int]
UAnnotation (fqName = null) [@null]
UParameter (name = z) [var z: int]
UAnnotation (fqName = null) [@null]
UClass (name = Some) [public final class Some {...}]
UField (name = delegate$delegate) [private final var delegate$delegate: kotlin.Lazy]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [lazy({ ...})] = external lazy({
<init>(18, 2, 3)
})(Undetermined)
UIdentifier (Identifier (lazy)) [UIdentifier (Identifier (lazy))]
USimpleNameReferenceExpression (identifier = lazy) [lazy] = external lazy({
<init>(18, 2, 3)
})(Undetermined)
ULambdaExpression [{ ...}] = Undetermined
UBlockExpression [{...}] = external <init>(18, 2, 3)(18, 2, 3)
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 3)) [<init>(18, 2, 3)] = external <init>(18, 2, 3)(18, 2, 3)
UIdentifier (Identifier (MyColor)) [UIdentifier (Identifier (MyColor))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] = external <init>(18, 2, 3)(18, 2, 3)
ULiteralExpression (value = 18) [18] = 18
ULiteralExpression (value = 2) [2] = 2
ULiteralExpression (value = 3) [3] = 3
UField (name = lambda) [private final var lambda: kotlin.Lazy<MyColor> = lazy({ ...})]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [lazy({ ...})] = external lazy({
<init>(1, 2, 3)
})(Undetermined)
UIdentifier (Identifier (lazy)) [UIdentifier (Identifier (lazy))]
USimpleNameReferenceExpression (identifier = lazy) [lazy] = external lazy({
<init>(1, 2, 3)
})(Undetermined)
ULambdaExpression [{ ...}] = Undetermined
UBlockExpression [{...}] = external <init>(1, 2, 3)(1, 2, 3)
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 3)) [<init>(1, 2, 3)] = external <init>(1, 2, 3)(1, 2, 3)
UIdentifier (Identifier (MyColor)) [UIdentifier (Identifier (MyColor))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] = external <init>(1, 2, 3)(1, 2, 3)
ULiteralExpression (value = 1) [1] = 1
ULiteralExpression (value = 2) [2] = 2
ULiteralExpression (value = 3) [3] = 3
UField (name = nonLazy) [private final var nonLazy: MyColor = <init>(1, 2, 3)]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 3)) [<init>(1, 2, 3)] = external <init>(1, 2, 3)(1, 2, 3)
UIdentifier (Identifier (MyColor)) [UIdentifier (Identifier (MyColor))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] = external <init>(1, 2, 3)(1, 2, 3)
ULiteralExpression (value = 1) [1] = 1
ULiteralExpression (value = 2) [2] = 2
ULiteralExpression (value = 3) [3] = 3
UAnnotationMethod (name = getDelegate) [public final fun getDelegate() : MyColor = UastEmptyExpression]
UAnnotationMethod (name = getLambda) [public final fun getLambda() : kotlin.Lazy<MyColor> = UastEmptyExpression]
UAnnotationMethod (name = getNonLazy) [public final fun getNonLazy() : MyColor = UastEmptyExpression]
UAnnotationMethod (name = Some) [public fun Some() = UastEmptyExpression]
@@ -1,21 +0,0 @@
UFile (package = )
UClass (name = DestructuringDeclarationKt)
UAnnotationMethod (name = foo)
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = var268d4034)
UBinaryExpression (operator = <other>)
ULiteralExpression (value = "foo")
ULiteralExpression (value = 1)
ULocalVariable (name = a)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = var268d4034)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (component1))
USimpleNameReferenceExpression (identifier = <anonymous class>)
ULocalVariable (name = b)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = var268d4034)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (component2))
USimpleNameReferenceExpression (identifier = <anonymous class>)
@@ -1,7 +0,0 @@
public final class DestructuringDeclarationKt {
public static final fun foo() : void {
var var268d4034: <ErrorType> = "foo" <other> 1
var a: java.lang.String = var268d4034.<anonymous class>()
var b: int = var268d4034.<anonymous class>()
}
}
-46
View File
@@ -1,46 +0,0 @@
UFile (package = )
UClass (name = ElvisKt)
UAnnotationMethod (name = foo)
UParameter (name = bar)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UReturnExpression
ULiteralExpression (value = null)
UAnnotationMethod (name = bar)
UBlockExpression
UReturnExpression
ULiteralExpression (value = 42)
UAnnotationMethod (name = baz)
UBlockExpression
UReturnExpression
UExpressionList (elvis)
UDeclarationsExpression
ULocalVariable (name = var243c51a0)
UExpressionList (elvis)
UDeclarationsExpression
ULocalVariable (name = varc4aef569)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (foo))
USimpleNameReferenceExpression (identifier = foo)
ULiteralExpression (value = "Lorem ipsum")
UIfExpression
UBinaryExpression (operator = !=)
USimpleNameReferenceExpression (identifier = varc4aef569)
ULiteralExpression (value = null)
USimpleNameReferenceExpression (identifier = varc4aef569)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (foo))
USimpleNameReferenceExpression (identifier = foo)
ULiteralExpression (value = "dolor sit amet")
UIfExpression
UBinaryExpression (operator = !=)
USimpleNameReferenceExpression (identifier = var243c51a0)
ULiteralExpression (value = null)
USimpleNameReferenceExpression (identifier = var243c51a0)
UQualifiedReferenceExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (bar))
USimpleNameReferenceExpression (identifier = bar)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (toString))
USimpleNameReferenceExpression (identifier = toString)
-17
View File
@@ -1,17 +0,0 @@
public final class ElvisKt {
public static final fun foo(bar: java.lang.String) : java.lang.String {
return null
}
public static final fun bar() : int {
return 42
}
public static final fun baz() : java.lang.String {
return elvis {
var var243c51a0: java.lang.String = elvis {
var varc4aef569: java.lang.String = foo("Lorem ipsum")
if (varc4aef569 != null) varc4aef569 else foo("dolor sit amet")
}
if (var243c51a0 != null) var243c51a0 else bar().toString()
}
}
}
@@ -1,18 +0,0 @@
UFile (package = )
UClass (name = Style)
UEnumConstant (name = SHEET)
USimpleNameReferenceExpression (identifier = Style)
ULiteralExpression (value = "foo")
UClass (name = null)
UAnnotationMethod (name = getExitAnimation)
UBlockExpression
UReturnExpression
ULiteralExpression (value = "bar")
UAnnotationMethod (name = SHEET)
UField (name = value)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = getExitAnimation)
UAnnotationMethod (name = getValue)
UAnnotationMethod (name = Style)
UParameter (name = value)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
@@ -1,12 +0,0 @@
public enum Style {
SHEET("foo") {
public fun getExitAnimation() : java.lang.String {
return "bar"
}
fun SHEET() = UastEmptyExpression
}
private final var value: java.lang.String
public abstract fun getExitAnimation() : java.lang.String = UastEmptyExpression
public final fun getValue() : java.lang.String = UastEmptyExpression
protected fun Style(value: java.lang.String) = UastEmptyExpression
}
-27
View File
@@ -1,27 +0,0 @@
UFile (package = )
UClass (name = Foo)
UAnnotationMethod (name = Foo)
UClass (name = Bar)
UField (name = a)
UAnnotation (fqName = null)
UField (name = b)
UAnnotation (fqName = null)
UAnnotationMethod (name = getAPlusB)
UBlockExpression
UReturnExpression
UBinaryExpression (operator = +)
USimpleNameReferenceExpression (identifier = a)
USimpleNameReferenceExpression (identifier = b)
UAnnotationMethod (name = getA)
UAnnotationMethod (name = getB)
UAnnotationMethod (name = Bar)
UParameter (name = a)
UAnnotation (fqName = null)
UParameter (name = b)
UAnnotation (fqName = null)
UClass (name = Baz)
UAnnotationMethod (name = doNothing)
UBlockExpression
UReturnExpression
USimpleNameReferenceExpression (identifier = Unit)
UAnnotationMethod (name = Baz)
@@ -1,19 +0,0 @@
public final class Foo {
public fun Foo() = UastEmptyExpression
public static final class Bar {
private final var a: int
private final var b: int
public final fun getAPlusB() : int {
return a + b
}
public final fun getA() : int = UastEmptyExpression
public final fun getB() : int = UastEmptyExpression
public fun Bar(a: int, b: int) = UastEmptyExpression
public static final class Baz {
public final fun doNothing() : void {
return Unit
}
public fun Baz() = UastEmptyExpression
}
}
}
@@ -1,33 +0,0 @@
UFile (package = )
UClass (name = LocalDeclarationsKt)
UAnnotationMethod (name = foo)
UBlockExpression
UDeclarationsExpression
UClass (name = Local)
UAnnotationMethod (name = LocalDeclarationsKt$foo$Local)
UDeclarationsExpression
UVariable (name = bar)
ULambdaExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0))
UIdentifier (Identifier (Local))
USimpleNameReferenceExpression (identifier = <init>)
UDeclarationsExpression
ULocalVariable (name = baz)
ULambdaExpression
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0))
UIdentifier (Identifier (Local))
USimpleNameReferenceExpression (identifier = <init>)
UDeclarationsExpression
UVariable (name = someLocalFun)
ULambdaExpression
UParameter (name = text)
ULiteralExpression (value = 42)
UReturnExpression
UBinaryExpression (operator = ==)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (bar))
USimpleNameReferenceExpression (identifier = bar)
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0))
UIdentifier (Identifier (Local))
USimpleNameReferenceExpression (identifier = <init>)
@@ -1,17 +0,0 @@
public final class LocalDeclarationsKt {
public static final fun foo() : boolean {
public static final class Local {
public fun LocalDeclarationsKt$foo$Local() = UastEmptyExpression
}
var bar: <ErrorType> = fun () {
<init>()
}
var baz: kotlin.jvm.functions.Function0<? extends kotlin.Unit> = fun () {
<init>()
}
var someLocalFun: kotlin.jvm.functions.Function2<? super java.lang.Integer,? super java.lang.String,? extends java.lang.Integer> = fun (var text: java.lang.String) {
42
}
return bar() == <init>()
}
}
@@ -1,33 +0,0 @@
UFile (package = ) [public final class LocalDeclarationsKt {...]
UClass (name = LocalDeclarationsKt) [public final class LocalDeclarationsKt {...}]
UAnnotationMethod (name = foo) [public static final fun foo() : boolean {...}]
UBlockExpression [{...}] : PsiType:Void
UDeclarationsExpression [public static final class Local {...}]
UClass (name = Local) [public static final class Local {...}]
UAnnotationMethod (name = LocalDeclarationsKt$foo$Local) [public fun LocalDeclarationsKt$foo$Local() = UastEmptyExpression]
UDeclarationsExpression [var bar: <ErrorType> = fun () {...}]
UVariable (name = bar) [var bar: <ErrorType> = fun () {...}]
ULambdaExpression [fun () {...}]
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [<init>()] : PsiType:<ErrorType>
UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] : PsiType:<ErrorType>
UDeclarationsExpression [var baz: kotlin.jvm.functions.Function0<? extends kotlin.Unit> = fun () {...}]
ULocalVariable (name = baz) [var baz: kotlin.jvm.functions.Function0<? extends kotlin.Unit> = fun () {...}]
ULambdaExpression [fun () {...}]
UBlockExpression [{...}] : PsiType:<ErrorType>
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [<init>()] : PsiType:<ErrorType>
UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] : PsiType:<ErrorType>
UDeclarationsExpression [var someLocalFun: kotlin.jvm.functions.Function2<? super java.lang.Integer,? super java.lang.String,? extends java.lang.Integer> = fun (var text: java.lang.String) {...}]
UVariable (name = someLocalFun) [var someLocalFun: kotlin.jvm.functions.Function2<? super java.lang.Integer,? super java.lang.String,? extends java.lang.Integer> = fun (var text: java.lang.String) {...}]
ULambdaExpression [fun (var text: java.lang.String) {...}]
UParameter (name = text) [var text: java.lang.String]
ULiteralExpression (value = 42) [42] : PsiType:int
UReturnExpression [return bar() == <init>()] : PsiType:Void
UBinaryExpression (operator = ==) [bar() == <init>()] : PsiType:boolean
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) [bar()] : PsiType:<ErrorType>
UIdentifier (Identifier (bar)) [UIdentifier (Identifier (bar))]
USimpleNameReferenceExpression (identifier = bar) [bar] : PsiType:<ErrorType>
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [<init>()] : PsiType:<ErrorType>
UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] : PsiType:<ErrorType>
@@ -1,33 +0,0 @@
UFile (package = ) [public final class LocalDeclarationsKt {...]
UClass (name = LocalDeclarationsKt) [public final class LocalDeclarationsKt {...}]
UAnnotationMethod (name = foo) [public static final fun foo() : boolean {...}]
UBlockExpression [{...}] = Nothing
UDeclarationsExpression [public static final class Local {...}] = Undetermined
UClass (name = Local) [public static final class Local {...}]
UAnnotationMethod (name = LocalDeclarationsKt$foo$Local) [public fun LocalDeclarationsKt$foo$Local() = UastEmptyExpression]
UDeclarationsExpression [var bar: <ErrorType> = fun () {...}] = Undetermined
UVariable (name = bar) [var bar: <ErrorType> = fun () {...}]
ULambdaExpression [fun () {...}] = Undetermined
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [<init>()] = external <init>()()
UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] = external <init>()()
UDeclarationsExpression [var baz: kotlin.jvm.functions.Function0<? extends kotlin.Unit> = fun () {...}] = Undetermined
ULocalVariable (name = baz) [var baz: kotlin.jvm.functions.Function0<? extends kotlin.Unit> = fun () {...}]
ULambdaExpression [fun () {...}] = Undetermined
UBlockExpression [{...}] = external <init>()()
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [<init>()] = external <init>()()
UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] = external <init>()()
UDeclarationsExpression [var someLocalFun: kotlin.jvm.functions.Function2<? super java.lang.Integer,? super java.lang.String,? extends java.lang.Integer> = fun (var text: java.lang.String) {...}] = Undetermined
UVariable (name = someLocalFun) [var someLocalFun: kotlin.jvm.functions.Function2<? super java.lang.Integer,? super java.lang.String,? extends java.lang.Integer> = fun (var text: java.lang.String) {...}]
ULambdaExpression [fun (var text: java.lang.String) {...}] = Undetermined
UParameter (name = text) [var text: java.lang.String]
ULiteralExpression (value = 42) [42] = 42
UReturnExpression [return bar() == <init>()] = Nothing
UBinaryExpression (operator = ==) [bar() == <init>()] = Undetermined
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) [bar()] = external bar()()
UIdentifier (Identifier (bar)) [UIdentifier (Identifier (bar))]
USimpleNameReferenceExpression (identifier = bar) [bar] = external bar()()
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [<init>()] = external <init>()()
UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] = external <init>()()
@@ -1,31 +0,0 @@
UFile (package = )
UClass (name = MyAnnotation)
UClass (name = MyAnnotation2)
UClass (name = MyAnnotation3)
UClass (name = MyAnnotation4)
UClass (name = MyAnnotation5)
UClass (name = Test1)
UField (name = bar)
UAnnotation (fqName = null)
UAnnotationMethod (name = getBar)
UAnnotationMethod (name = setBar)
UParameter (name = p)
UAnnotation (fqName = null)
UAnnotationMethod (name = Test1)
UParameter (name = bar)
UAnnotation (fqName = MyAnnotation)
UAnnotation (fqName = null)
UClass (name = Test2)
UField (name = bar)
UAnnotation (fqName = MyAnnotation5)
UAnnotation (fqName = null)
UAnnotationMethod (name = getBar)
UAnnotation (fqName = MyAnnotation)
UAnnotationMethod (name = setBar)
UAnnotation (fqName = MyAnnotation2)
UParameter (name = p)
UAnnotation (fqName = MyAnnotation3)
UAnnotation (fqName = null)
UAnnotationMethod (name = Test2)
UParameter (name = bar)
UAnnotation (fqName = null)
@@ -1,30 +0,0 @@
public abstract annotation MyAnnotation {
}
public abstract annotation MyAnnotation2 {
}
public abstract annotation MyAnnotation3 {
}
public abstract annotation MyAnnotation4 {
}
public abstract annotation MyAnnotation5 {
}
public final class Test1 {
private var bar: int
public final fun getBar() : int = UastEmptyExpression
public final fun setBar(p: int) : void = UastEmptyExpression
public fun Test1(bar: int) = UastEmptyExpression
}
public final class Test2 {
private var bar: int
@MyAnnotation
public final fun getBar() : int = UastEmptyExpression
@MyAnnotation2
public final fun setBar(p: int) : void = UastEmptyExpression
public fun Test2(bar: int) = UastEmptyExpression
}
@@ -1,14 +0,0 @@
UFile (package = )
UClass (name = ParametersWithDefaultValuesKt)
UAnnotationMethod (name = foo)
UParameter (name = a)
UAnnotation (fqName = null)
UParameter (name = b)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UParameter (name = c)
UAnnotation (fqName = null)
ULiteralExpression (value = 0)
UParameter (name = flag)
UAnnotation (fqName = null)
ULiteralExpression (value = false)
UBlockExpression
@@ -1,4 +0,0 @@
public final class ParametersWithDefaultValuesKt {
public static final fun foo(a: int, b: java.lang.String, c: int, flag: boolean) : void {
}
}
@@ -1,11 +0,0 @@
public final class PropertyTest {
public final fun getStringRepresentation() : java.lang.String {
return this.toString()
}
public final fun setStringRepresentation(value: java.lang.String) : void {
setDataFromString(value)
}
public final fun setDataFromString(data: java.lang.String) : void {
}
public fun PropertyTest() = UastEmptyExpression
}
-5
View File
@@ -1,5 +0,0 @@
val sdCardPath by lazy { "/sdcard" }
fun localPropertyTest() {
val sdCardPathLocal by lazy { "/sdcard" }
}
@@ -1,21 +0,0 @@
UFile (package = )
UClass (name = PropertyDelegateKt)
UField (name = sdCardPath$delegate)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (lazy))
USimpleNameReferenceExpression (identifier = lazy)
ULambdaExpression
UBlockExpression
ULiteralExpression (value = "/sdcard")
UAnnotationMethod (name = getSdCardPath)
UAnnotationMethod (name = localPropertyTest)
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = sdCardPathLocal)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (lazy))
USimpleNameReferenceExpression (identifier = lazy)
ULambdaExpression
UBlockExpression
ULiteralExpression (value = "/sdcard")
@@ -1,7 +0,0 @@
public final class PropertyDelegateKt {
private static final var sdCardPath$delegate: kotlin.Lazy
public static final fun getSdCardPath() : java.lang.String = UastEmptyExpression
public static final fun localPropertyTest() : void {
var sdCardPathLocal: java.lang.String
}
}
@@ -1,10 +0,0 @@
public final class TestPropertyInitializer {
private var withSetter: java.lang.String = "/sdcard"
public final fun getWithSetter() : java.lang.String {
return field
}
public final fun setWithSetter(p: java.lang.String) : void {
field = p
}
public fun TestPropertyInitializer() = UastEmptyExpression
}
@@ -1,7 +0,0 @@
public final class PropertyInitializerWithoutSetterKt {
private static var withoutSetter: java.lang.String = "/sdcard"
public static final fun getWithoutSetter() : java.lang.String {
return field
}
public static final fun setWithoutSetter(p: java.lang.String) : void = UastEmptyExpression
}
@@ -1,27 +0,0 @@
UFile (package = )
UClass (name = PropertyWithAnnotationKt)
UField (name = prop1)
UAnnotation (fqName = null)
ULiteralExpression (value = 0)
UField (name = prop3)
UAnnotation (fqName = null)
ULiteralExpression (value = 0)
UAnnotationMethod (name = getProp1)
UAnnotationMethod (name = getProp2)
UAnnotation (fqName = TestAnnotation)
UBlockExpression
UReturnExpression
ULiteralExpression (value = 0)
UAnnotationMethod (name = getProp3)
UBlockExpression
UReturnExpression
ULiteralExpression (value = 0)
UAnnotationMethod (name = setProp3)
UAnnotation (fqName = TestAnnotation)
UParameter (name = value)
UAnnotation (fqName = null)
UBlockExpression
UBinaryExpression (operator = =)
USimpleNameReferenceExpression (identifier = field)
USimpleNameReferenceExpression (identifier = value)
UClass (name = TestAnnotation)
@@ -1,19 +0,0 @@
public final class PropertyWithAnnotationKt {
private static final var prop1: int = 0
private static var prop3: int = 0
public static final fun getProp1() : int = UastEmptyExpression
@TestAnnotation
public static final fun getProp2() : int {
return 0
}
public static final fun getProp3() : int {
return 0
}
@TestAnnotation
public static final fun setProp3(value: int) : void {
field = value
}
}
public abstract annotation TestAnnotation {
}
View File
-8
View File
@@ -1,8 +0,0 @@
public final class Simple {
private final var property: java.lang.String = "Mary"
public final fun method() : void {
println("Hello, world!")
}
public final fun getProperty() : java.lang.String = UastEmptyExpression
public fun Simple() = UastEmptyExpression
}
-13
View File
@@ -1,13 +0,0 @@
UFile (package = ) [public final class Simple {...]
UClass (name = Simple) [public final class Simple {...}]
UField (name = property) [private final var property: java.lang.String = "Mary"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
ULiteralExpression (value = "Mary") ["Mary"] = "Mary"
UAnnotationMethod (name = method) [public final fun method() : void {...}]
UBlockExpression [{...}] = external println("Hello, world!")("Hello, world!")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [println("Hello, world!")] = external println("Hello, world!")("Hello, world!")
UIdentifier (Identifier (println)) [UIdentifier (Identifier (println))]
USimpleNameReferenceExpression (identifier = println) [println] = external println("Hello, world!")("Hello, world!")
ULiteralExpression (value = "Hello, world!") ["Hello, world!"] = "Hello, world!"
UAnnotationMethod (name = getProperty) [public final fun getProperty() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = Simple) [public fun Simple() = UastEmptyExpression]
-51
View File
@@ -1,51 +0,0 @@
UFile (package = )
UClass (name = SimpleScript)
UAnnotationMethod (name = getBarOrNull)
UParameter (name = flag)
UAnnotation (fqName = null)
UBlockExpression
UReturnExpression
UIfExpression
USimpleNameReferenceExpression (identifier = flag)
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (Bar))
USimpleNameReferenceExpression (identifier = <init>)
ULiteralExpression (value = 42)
ULiteralExpression (value = null)
UAnnotationMethod (name = SimpleScript)
UParameter (name = p)
UAnnotation (fqName = null)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
ULiteralExpression (value = "Hello World!")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (getBarOrNull))
USimpleNameReferenceExpression (identifier = getBarOrNull)
ULiteralExpression (value = true)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
ULiteralExpression (value = "Goodbye World!")
UClass (name = Bar)
UField (name = b)
UAnnotation (fqName = null)
ULiteralExpression (value = 0)
UField (name = a)
UAnnotation (fqName = null)
UAnnotationMethod (name = getB)
UAnnotationMethod (name = getAPlusB)
UBlockExpression
UReturnExpression
UBinaryExpression (operator = +)
USimpleNameReferenceExpression (identifier = a)
USimpleNameReferenceExpression (identifier = b)
UAnnotationMethod (name = getA)
UAnnotationMethod (name = Bar)
UParameter (name = a)
UAnnotation (fqName = null)
UClass (name = Baz)
UAnnotationMethod (name = doSomething)
UBlockExpression
UAnnotationMethod (name = Baz)
@@ -1,25 +0,0 @@
public class SimpleScript : kotlin.script.templates.standard.ScriptTemplateWithArgs {
public final fun getBarOrNull(flag: boolean) : SimpleScript.Bar {
return if (flag) <init>(42) else null
}
public fun SimpleScript(p: java.lang.String[]) {
println("Hello World!")
getBarOrNull(true)
println("Goodbye World!")
}
public static final class Bar {
private final var b: int = 0
private final var a: int
public final fun getB() : int = UastEmptyExpression
public final fun getAPlusB() : int {
return a + b
}
public final fun getA() : int = UastEmptyExpression
public fun Bar(a: int) = UastEmptyExpression
public static final class Baz {
public final fun doSomething() : void {
}
public fun Baz() = UastEmptyExpression
}
}
}
@@ -1,10 +0,0 @@
public final class StringTemplateKt {
private static final var foo: java.lang.String = "lorem"
private static final var bar: java.lang.String = "ipsum"
private static final var baz: java.lang.String = "dolor"
private static final var foobarbaz: java.lang.String = foo + " " + bar + " " + baz
public static final fun getFoo() : java.lang.String = UastEmptyExpression
public static final fun getBar() : java.lang.String = UastEmptyExpression
public static final fun getBaz() : java.lang.String = UastEmptyExpression
public static final fun getFoobarbaz() : java.lang.String = UastEmptyExpression
}
@@ -1,23 +0,0 @@
UFile (package = ) [public final class StringTemplateKt {...]
UClass (name = StringTemplateKt) [public final class StringTemplateKt {...}]
UField (name = foo) [private static final var foo: java.lang.String = "lorem"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
ULiteralExpression (value = "lorem") ["lorem"] : PsiType:String
UField (name = bar) [private static final var bar: java.lang.String = "ipsum"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
ULiteralExpression (value = "ipsum") ["ipsum"] : PsiType:String
UField (name = baz) [private static final var baz: java.lang.String = "dolor"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
ULiteralExpression (value = "dolor") ["dolor"] : PsiType:String
UField (name = foobarbaz) [private static final var foobarbaz: java.lang.String = foo + " " + bar + " " + baz]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UPolyadicExpression (operator = +) [foo + " " + bar + " " + baz] : PsiType:String
USimpleNameReferenceExpression (identifier = foo) [foo] : PsiType:String
ULiteralExpression (value = " ") [" "] : PsiType:String
USimpleNameReferenceExpression (identifier = bar) [bar] : PsiType:String
ULiteralExpression (value = " ") [" "] : PsiType:String
USimpleNameReferenceExpression (identifier = baz) [baz] : PsiType:String
UAnnotationMethod (name = getFoo) [public static final fun getFoo() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = getBar) [public static final fun getBar() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = getBaz) [public static final fun getBaz() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = getFoobarbaz) [public static final fun getFoobarbaz() : java.lang.String = UastEmptyExpression]
@@ -1,70 +0,0 @@
UFile (package = )
UClass (name = StringTemplateComplexKt)
UField (name = muchRecur)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
ULiteralExpression (value = "abc")
UField (name = case4)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UPolyadicExpression (operator = +)
ULiteralExpression (value = "a ")
ULiteralExpression (value = "literal")
ULiteralExpression (value = " z")
UField (name = case5)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UPolyadicExpression (operator = +)
ULiteralExpression (value = "a ")
ULiteralExpression (value = "literal")
ULiteralExpression (value = " ")
ULiteralExpression (value = "literal")
ULiteralExpression (value = " z")
UField (name = literalInLiteral)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UPolyadicExpression (operator = +)
ULiteralExpression (value = "a ")
UPolyadicExpression (operator = +)
ULiteralExpression (value = "literal")
USimpleNameReferenceExpression (identifier = case4)
ULiteralExpression (value = " z")
UField (name = literalInLiteral2)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UPolyadicExpression (operator = +)
ULiteralExpression (value = "a ")
UQualifiedReferenceExpression
UPolyadicExpression (operator = +)
ULiteralExpression (value = "literal")
USimpleNameReferenceExpression (identifier = case4)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (repeat))
USimpleNameReferenceExpression (identifier = repeat)
ULiteralExpression (value = 4)
ULiteralExpression (value = " z")
UAnnotationMethod (name = getMuchRecur)
UAnnotationMethod (name = getCase4)
UAnnotationMethod (name = getCase5)
UAnnotationMethod (name = getLiteralInLiteral)
UAnnotationMethod (name = getLiteralInLiteral2)
UAnnotationMethod (name = simpleForTemplate)
UParameter (name = i)
UAnnotation (fqName = null)
ULiteralExpression (value = 0)
UBlockExpression
UReturnExpression
USimpleNameReferenceExpression (identifier = i)
UAnnotationMethod (name = foo)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
USimpleNameReferenceExpression (identifier = baz)
UDeclarationsExpression
ULocalVariable (name = template1)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (simpleForTemplate))
USimpleNameReferenceExpression (identifier = simpleForTemplate)
UDeclarationsExpression
ULocalVariable (name = template2)
UPolyadicExpression (operator = +)
ULiteralExpression (value = ".")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (simpleForTemplate))
USimpleNameReferenceExpression (identifier = simpleForTemplate)
@@ -1,20 +0,0 @@
public final class StringTemplateComplexKt {
private static final var muchRecur: java.lang.String = "abc"
private static final var case4: java.lang.String = "a " + "literal" + " z"
private static final var case5: java.lang.String = "a " + "literal" + " " + "literal" + " z"
private static final var literalInLiteral: java.lang.String = "a " + "literal" + case4 + " z"
private static final var literalInLiteral2: java.lang.String = "a " + "literal" + case4.repeat(4) + " z"
public static final fun getMuchRecur() : java.lang.String = UastEmptyExpression
public static final fun getCase4() : java.lang.String = UastEmptyExpression
public static final fun getCase5() : java.lang.String = UastEmptyExpression
public static final fun getLiteralInLiteral() : java.lang.String = UastEmptyExpression
public static final fun getLiteralInLiteral2() : java.lang.String = UastEmptyExpression
public static final fun simpleForTemplate(i: int) : java.lang.String {
return i
}
public static final fun foo() : void {
println(baz)
var template1: java.lang.String = simpleForTemplate()
var template2: java.lang.String = "." + simpleForTemplate()
}
}
@@ -1,70 +0,0 @@
UFile (package = ) [public final class StringTemplateComplexKt {...]
UClass (name = StringTemplateComplexKt) [public final class StringTemplateComplexKt {...}]
UField (name = muchRecur) [private static final var muchRecur: java.lang.String = "abc"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
ULiteralExpression (value = "abc") ["abc"] : PsiType:String
UField (name = case4) [private static final var case4: java.lang.String = "a " + "literal" + " z"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UPolyadicExpression (operator = +) ["a " + "literal" + " z"] : PsiType:String
ULiteralExpression (value = "a ") ["a "] : PsiType:String
ULiteralExpression (value = "literal") ["literal"] : PsiType:String
ULiteralExpression (value = " z") [" z"] : PsiType:String
UField (name = case5) [private static final var case5: java.lang.String = "a " + "literal" + " " + "literal" + " z"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UPolyadicExpression (operator = +) ["a " + "literal" + " " + "literal" + " z"] : PsiType:String
ULiteralExpression (value = "a ") ["a "] : PsiType:String
ULiteralExpression (value = "literal") ["literal"] : PsiType:String
ULiteralExpression (value = " ") [" "] : PsiType:String
ULiteralExpression (value = "literal") ["literal"] : PsiType:String
ULiteralExpression (value = " z") [" z"] : PsiType:String
UField (name = literalInLiteral) [private static final var literalInLiteral: java.lang.String = "a " + "literal" + case4 + " z"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UPolyadicExpression (operator = +) ["a " + "literal" + case4 + " z"] : PsiType:String
ULiteralExpression (value = "a ") ["a "] : PsiType:String
UPolyadicExpression (operator = +) ["literal" + case4] : PsiType:String
ULiteralExpression (value = "literal") ["literal"] : PsiType:String
USimpleNameReferenceExpression (identifier = case4) [case4] : PsiType:String
ULiteralExpression (value = " z") [" z"] : PsiType:String
UField (name = literalInLiteral2) [private static final var literalInLiteral2: java.lang.String = "a " + "literal" + case4.repeat(4) + " z"]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UPolyadicExpression (operator = +) ["a " + "literal" + case4.repeat(4) + " z"] : PsiType:String
ULiteralExpression (value = "a ") ["a "] : PsiType:String
UQualifiedReferenceExpression ["literal" + case4.repeat(4)] : PsiType:String
UPolyadicExpression (operator = +) ["literal" + case4] : PsiType:String
ULiteralExpression (value = "literal") ["literal"] : PsiType:String
USimpleNameReferenceExpression (identifier = case4) [case4] : PsiType:String
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [repeat(4)] : PsiType:String
UIdentifier (Identifier (repeat)) [UIdentifier (Identifier (repeat))]
USimpleNameReferenceExpression (identifier = repeat) [repeat] : PsiType:String
ULiteralExpression (value = 4) [4] : PsiType:int
ULiteralExpression (value = " z") [" z"] : PsiType:String
UAnnotationMethod (name = getMuchRecur) [public static final fun getMuchRecur() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = getCase4) [public static final fun getCase4() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = getCase5) [public static final fun getCase5() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = getLiteralInLiteral) [public static final fun getLiteralInLiteral() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = getLiteralInLiteral2) [public static final fun getLiteralInLiteral2() : java.lang.String = UastEmptyExpression]
UAnnotationMethod (name = simpleForTemplate) [public static final fun simpleForTemplate(i: int) : java.lang.String {...}]
UParameter (name = i) [var i: int = 0]
UAnnotation (fqName = null) [@null]
ULiteralExpression (value = 0) [0] : PsiType:int
UBlockExpression [{...}]
UReturnExpression [return i]
USimpleNameReferenceExpression (identifier = i) [i] : PsiType:int
UAnnotationMethod (name = foo) [public static final fun foo() : void {...}]
UBlockExpression [{...}] : PsiType:void
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [println(baz)] : PsiType:void
UIdentifier (Identifier (println)) [UIdentifier (Identifier (println))]
USimpleNameReferenceExpression (identifier = println) [println] : PsiType:void
USimpleNameReferenceExpression (identifier = baz) [baz]
UDeclarationsExpression [var template1: java.lang.String = simpleForTemplate()]
ULocalVariable (name = template1) [var template1: java.lang.String = simpleForTemplate()]
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) [simpleForTemplate()] : PsiType:String
UIdentifier (Identifier (simpleForTemplate)) [UIdentifier (Identifier (simpleForTemplate))]
USimpleNameReferenceExpression (identifier = simpleForTemplate) [simpleForTemplate] : PsiType:String
UDeclarationsExpression [var template2: java.lang.String = "." + simpleForTemplate()]
ULocalVariable (name = template2) [var template2: java.lang.String = "." + simpleForTemplate()]
UPolyadicExpression (operator = +) ["." + simpleForTemplate()] : PsiType:String
ULiteralExpression (value = ".") ["."] : PsiType:String
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) [simpleForTemplate()] : PsiType:String
UIdentifier (Identifier (simpleForTemplate)) [UIdentifier (Identifier (simpleForTemplate))]
USimpleNameReferenceExpression (identifier = simpleForTemplate) [simpleForTemplate] : PsiType:String
-109
View File
@@ -1,109 +0,0 @@
UFile (package = )
UClass (name = SuperCallsKt)
UField (name = anon)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UObjectLiteralExpression
ULiteralExpression (value = "textForAnon")
UClass (name = null)
UAnnotationMethod (name = bar)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (cons))
USimpleNameReferenceExpression (identifier = cons)
UObjectLiteralExpression
ULiteralExpression (value = "inner literal")
UClass (name = null)
UAnnotationMethod (name = SuperCallsKt$anon$1$bar$1)
UAnnotationMethod (name = SuperCallsKt$anon$1)
UClass (name = innerObject)
UField (name = INSTANCE)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = innerObject)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (A))
USimpleNameReferenceExpression (identifier = <init>)
ULiteralExpression (value = "inner object")
UClass (name = InnerClass)
UAnnotationMethod (name = InnerClass)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (A))
USimpleNameReferenceExpression (identifier = <init>)
ULiteralExpression (value = "inner class")
UAnnotationMethod (name = getAnon)
UAnnotationMethod (name = cons)
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UClass (name = A)
UField (name = str)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = foo)
UParameter (name = a)
UAnnotation (fqName = null)
UBlockExpression
UAnnotationMethod (name = getStr)
UAnnotationMethod (name = A)
UParameter (name = str)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UAnnotationMethod (name = A)
UParameter (name = i)
UAnnotation (fqName = null)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (this))
USimpleNameReferenceExpression (identifier = <init>)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = i)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (toString))
USimpleNameReferenceExpression (identifier = toString)
UClass (name = B)
UAnnotationMethod (name = B)
UParameter (name = param)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (A))
USimpleNameReferenceExpression (identifier = <init>)
USimpleNameReferenceExpression (identifier = param)
UClass (name = C)
UAnnotationMethod (name = foo)
UParameter (name = a)
UAnnotation (fqName = null)
UBlockExpression
UQualifiedReferenceExpression
USuperExpression (label = null)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (foo))
USimpleNameReferenceExpression (identifier = foo)
USimpleNameReferenceExpression (identifier = a)
UAnnotationMethod (name = C)
UParameter (name = p)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (super))
USimpleNameReferenceExpression (identifier = <init>)
USimpleNameReferenceExpression (identifier = p)
UAnnotationMethod (name = C)
UParameter (name = i)
UAnnotation (fqName = null)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (super))
USimpleNameReferenceExpression (identifier = <init>)
USimpleNameReferenceExpression (identifier = i)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println)
UClass (name = O)
UField (name = INSTANCE)
UAnnotation (fqName = null)
UAnnotationMethod (name = O)
UBlockExpression
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1))
UIdentifier (Identifier (A))
USimpleNameReferenceExpression (identifier = <init>)
ULiteralExpression (value = "text")
-51
View File
@@ -1,51 +0,0 @@
public final class SuperCallsKt {
private static final var anon: A = anonymous object : A("textForAnon") {
fun bar() {
cons(object : A("inner literal"))
}
object innerObject : A("inner object")
inner class InnerClass : A("inner class")
}
public static final fun getAnon() : A = UastEmptyExpression
public static final fun cons(a: A) : void {
}
}
public class A {
private final var str: java.lang.String
public fun foo(a: long) : void {
}
public final fun getStr() : java.lang.String = UastEmptyExpression
public fun A(str: java.lang.String) = UastEmptyExpression
public fun A(i: int) {
<init>(i.toString())
}
}
public final class B : A {
public fun B(param: java.lang.String) {
<init>(param)
}
}
public final class C : A {
public fun foo(a: long) : void {
super.foo(a)
}
public fun C(p: java.lang.String) {
<init>(p)
}
public fun C(i: int) {
<init>(i)
println()
}
}
public final class O : A {
public static final var INSTANCE: O
private fun O() {
<init>("text")
}
}
@@ -1,20 +0,0 @@
public abstract interface Callback {
public abstract fun onError(throwable: java.lang.Throwable) : void = UastEmptyExpression
}
public final class Model {
public final fun crashMe(clazz: java.lang.Class<T>, factory: kotlin.jvm.functions.Function0<? extends T>) : void {
throw <init>()
}
public fun Model() {
{
crashMe(Callback.java, {
anonymous object : Callback {
override fun onError(throwable: Throwable) {
throw UnsupportedOperationException("")
}
}
})
}
}
}
@@ -1,39 +0,0 @@
UFile (package = ) [public abstract interface Callback {...]
UClass (name = Callback) [public abstract interface Callback {...}]
UAnnotationMethod (name = onError) [public abstract fun onError(throwable: java.lang.Throwable) : void = UastEmptyExpression]
UParameter (name = throwable) [var throwable: java.lang.Throwable]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UClass (name = Model) [public final class Model {...}]
UAnnotationMethod (name = crashMe) [public final fun crashMe(clazz: java.lang.Class<T>, factory: kotlin.jvm.functions.Function0<? extends T>) : void {...}]
UParameter (name = clazz) [var clazz: java.lang.Class<T>]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UParameter (name = factory) [var factory: kotlin.jvm.functions.Function0<? extends T>]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UBlockExpression [{...}] : PsiType:Void
UThrowExpression [throw <init>()] : PsiType:Void
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [<init>()] : PsiType:UnsupportedOperationException
UIdentifier (Identifier (UnsupportedOperationException)) [UIdentifier (Identifier (UnsupportedOperationException))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] : PsiType:UnsupportedOperationException
UAnnotationMethod (name = Model) [public fun Model() {...}]
UBlockExpression [{...}]
UBlockExpression [{...}] : PsiType:void
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 2)) [crashMe(Callback.java, { ...})] : PsiType:void
UIdentifier (Identifier (crashMe)) [UIdentifier (Identifier (crashMe))]
USimpleNameReferenceExpression (identifier = crashMe) [crashMe] : PsiType:void
UQualifiedReferenceExpression [Callback.java] : PsiType:Class<Callback>
UClassLiteralExpression [Callback] : PsiType:KClass<Callback>
USimpleNameReferenceExpression (identifier = java) [java] : PsiType:Class<Callback>
ULambdaExpression [{ ...}] : PsiType:<ErrorType>
UBlockExpression [{...}]
UObjectLiteralExpression [anonymous object : Callback {... }] : PsiType:Callback
UClass (name = null) [final class null {...}]
UAnnotationMethod (name = onError) [public fun onError(throwable: java.lang.Throwable) : void {...}]
UParameter (name = throwable) [var throwable: java.lang.Throwable]
UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull]
UBlockExpression [{...}] : PsiType:Void
UThrowExpression [throw <init>("")] : PsiType:Void
UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) [<init>("")] : PsiType:UnsupportedOperationException
UIdentifier (Identifier (UnsupportedOperationException)) [UIdentifier (Identifier (UnsupportedOperationException))]
USimpleNameReferenceExpression (identifier = <init>) [<init>] : PsiType:UnsupportedOperationException
ULiteralExpression (value = "") [""] : PsiType:String
UAnnotationMethod (name = Model$1$1) [fun Model$1$1() = UastEmptyExpression]
@@ -1,42 +0,0 @@
UFile (package = )
UClass (name = WhenAndDestructingKt)
UAnnotationMethod (name = getElementsAdditionalResolve)
UParameter (name = string)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = arr)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 2))
UIdentifier (Identifier (listOf))
USimpleNameReferenceExpression (identifier = listOf)
ULiteralExpression (value = "1")
ULiteralExpression (value = "2")
USwitchExpression
USimpleNameReferenceExpression (identifier = string)
UExpressionList (when)
USwitchClauseExpressionWithBody
ULiteralExpression (value = "aaaa")
UExpressionList (when_entry)
UReturnExpression
ULiteralExpression (value = "bindingContext")
UBreakExpression (label = null)
USwitchClauseExpressionWithBody
UExpressionList (when_entry)
UDeclarationsExpression
ULocalVariable (name = var837f1e82)
USimpleNameReferenceExpression (identifier = arr)
ULocalVariable (name = bindingContext)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = var837f1e82)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (component1))
USimpleNameReferenceExpression (identifier = <anonymous class>)
ULocalVariable (name = statementFilter)
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = var837f1e82)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (component2))
USimpleNameReferenceExpression (identifier = <anonymous class>)
UReturnExpression
USimpleNameReferenceExpression (identifier = bindingContext)
UBreakExpression (label = null)
@@ -1,21 +0,0 @@
public final class WhenAndDestructingKt {
public static final fun getElementsAdditionalResolve(string: java.lang.String) : java.lang.String {
var arr: java.util.List<? extends java.lang.String> = listOf("1", "2")
switch (string) {
"aaaa" -> {
return "bindingContext"
break
}
-> {
var var837f1e82: <ErrorType> = arr
var bindingContext: java.lang.String = var837f1e82.<anonymous class>()
var statementFilter: java.lang.String = var837f1e82.<anonymous class>()
return bindingContext
break
}
}
}
}
-17
View File
@@ -1,17 +0,0 @@
public final class WhenIsKt {
public static final fun foo(bar: java.lang.Object) : java.lang.String {
return switch (bar) {
it is java.lang.String -> {
bar
break
}
it !is java.lang.String -> {
"<error>"
break
}
}
}
}
@@ -1,33 +0,0 @@
UFile (package = )
UClass (name = WhenStringLiteralKt)
UField (name = a)
UAnnotation (fqName = org.jetbrains.annotations.Nullable)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (readLine))
USimpleNameReferenceExpression (identifier = readLine)
UField (name = b)
UAnnotation (fqName = null)
USwitchExpression
USimpleNameReferenceExpression (identifier = a)
UExpressionList (when)
USwitchClauseExpressionWithBody
ULiteralExpression (value = "abc")
UExpressionList (when_entry)
ULiteralExpression (value = 1)
UBreakExpression (label = null)
USwitchClauseExpressionWithBody
ULiteralExpression (value = "def")
ULiteralExpression (value = "ghi")
UExpressionList (when_entry)
ULiteralExpression (value = 2)
UBreakExpression (label = null)
USwitchClauseExpressionWithBody
UExpressionList (when_entry)
ULiteralExpression (value = 3)
UBreakExpression (label = null)
UAnnotationMethod (name = getA)
UAnnotationMethod (name = getB)
UAnnotationMethod (name = <no name provided>)
UBlockExpression
ULiteralExpression (value = "abc1")
ULiteralExpression (value = "def1")
@@ -1,27 +0,0 @@
public final class WhenStringLiteralKt {
private static final var a: java.lang.String = readLine()
private static final var b: int = switch (a) {
"abc" -> {
1
break
}
"def", "ghi" -> {
2
break
}
-> {
3
break
}
}
public static final fun getA() : java.lang.String = UastEmptyExpression
public static final fun getB() : int = UastEmptyExpression
public static final fun <no name provided>() : void {
"abc1"
"def1"
}
}
-14
View File
@@ -1,14 +0,0 @@
UFile (package = ) [public final class Ea101715Kt {...]
UClass (name = Ea101715Kt) [public final class Ea101715Kt {...}]
UAnnotationMethod (name = a) [public static final fun a() : void {...}]
UBlockExpression [{...}] : PsiType:void
UDeclarationsExpression [var a: <ErrorType> = Obj(555)]
ULocalVariable (name = a) [var a: <ErrorType> = Obj(555)]
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [Obj(555)]
UIdentifier (Identifier (Obj)) [UIdentifier (Identifier (Obj))]
USimpleNameReferenceExpression (identifier = Obj) [Obj]
ULiteralExpression (value = 555) [555] : PsiType:int
UClass (name = Obj) [public final class Obj {...}]
UField (name = INSTANCE) [public static final var INSTANCE: Obj]
UAnnotation (fqName = null) [@null]
UAnnotationMethod (name = Obj) [private fun Obj() = UastEmptyExpression]
@@ -1,107 +0,0 @@
package org.jetbrains.uast.test.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementVisitor
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.utils.addToStdlib.assertedCast
import org.jetbrains.uast.UDeclaration
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UFile
import org.jetbrains.uast.kotlin.KOTLIN_CACHED_UELEMENT_KEY
import org.jetbrains.uast.kotlin.KotlinUastLanguagePlugin
import org.jetbrains.uast.test.common.RenderLogTestBase
import org.jetbrains.uast.visitor.UastVisitor
import org.junit.Assert
import java.io.File
import java.util.*
abstract class AbstractKotlinRenderLogTest : AbstractKotlinUastTest(), RenderLogTestBase {
override fun getTestFile(testName: String, ext: String) =
File(File(TEST_KOTLIN_MODEL_DIR, testName).canonicalPath + '.' + ext)
override fun check(testName: String, file: UFile) {
check(testName, file, true)
}
fun check(testName: String, file: UFile, checkParentConsistency: Boolean) {
super.check(testName, file)
if (checkParentConsistency) {
checkParentConsistency(file)
}
file.checkContainingFileForAllElements()
}
private fun checkParentConsistency(file: UFile) {
val parentMap = mutableMapOf<PsiElement, String>()
file.accept(object : UastVisitor {
private val parentStack = Stack<UElement>()
override fun visitElement(node: UElement): Boolean {
val parent = node.uastParent
if (parent == null) {
Assert.assertTrue("Wrong parent of $node", parentStack.empty())
}
else {
Assert.assertEquals("Wrong parent of $node", parentStack.peek(), parent)
}
node.psi?.let {
if (it !in parentMap) {
parentMap[it] = parentStack.reversed().joinToString { it.asLogString() }
}
}
parentStack.push(node)
return false
}
override fun afterVisitElement(node: UElement) {
super.afterVisitElement(node)
parentStack.pop()
}
})
file.psi.clearUastCaches()
file.psi.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
val uElement = KotlinUastLanguagePlugin().convertElementWithParent(element, null)
val expectedParents = parentMap[element]
if (expectedParents != null) {
assertNotNull("Expected to be able to convert PSI element $element", uElement)
val parents = generateSequence(uElement!!.uastParent) { it.uastParent }.joinToString { it.asLogString() }
assertEquals("Inconsistent parents for ${uElement.asRenderString()}(${uElement.asLogString()})(${uElement.javaClass}) (converted from $element[${element.text}])", expectedParents, parents)
}
super.visitElement(element)
}
})
}
private fun UFile.checkContainingFileForAllElements() {
accept(object : UastVisitor {
override fun visitElement(node: UElement): Boolean {
if (node is PsiElement) {
node.containingFile.assertedCast<KtFile> { "containingFile should be KtFile for ${node.asLogString()}" }
}
val anchorPsi = (node as? UDeclaration)?.uastAnchor?.psi
if (anchorPsi != null) {
anchorPsi.containingFile.assertedCast<KtFile> { "uastAnchor.containingFile should be KtFile for ${node.asLogString()}" }
}
return false
}
})
}
}
private fun PsiFile.clearUastCaches() {
accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
super.visitElement(element)
element.putUserData(KOTLIN_CACHED_UELEMENT_KEY, null)
}
})
}
@@ -1,303 +0,0 @@
package org.jetbrains.uast.test.kotlin
import com.intellij.psi.PsiModifier
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.kotlin.asJava.toLightAnnotation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase
import org.jetbrains.kotlin.utils.addToStdlib.assertedCast
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.sure
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.KotlinUastLanguagePlugin
import org.jetbrains.uast.test.env.findElementByText
import org.jetbrains.uast.test.env.findElementByTextFromPsi
import org.jetbrains.uast.visitor.AbstractUastVisitor
import org.junit.Assert
import org.junit.Test
class KotlinUastApiTest : AbstractKotlinUastTest() {
override fun check(testName: String, file: UFile) {
}
@Test fun testAnnotationParameters() {
doTest("AnnotationParameters") { _, file ->
val annotation = file.findElementByText<UAnnotation>("@IntRange(from = 10, to = 0)")
assertEquals(annotation.findAttributeValue("from")?.evaluate(), 10)
val toAttribute = annotation.findAttributeValue("to")!!
assertEquals(toAttribute.evaluate(), 0)
KtUsefulTestCase.assertInstanceOf(annotation.psi.toUElement(), UAnnotation::class.java)
KtUsefulTestCase.assertInstanceOf(
annotation.psi.cast<KtAnnotationEntry>().toLightAnnotation().toUElement(),
UAnnotation::class.java
)
KtUsefulTestCase.assertInstanceOf(toAttribute.uastParent, UNamedExpression::class.java)
KtUsefulTestCase.assertInstanceOf(toAttribute.psi.toUElement()?.uastParent, UNamedExpression::class.java)
}
}
@Test fun testConvertStringTemplate() {
doTest("StringTemplateInClass") { _, file ->
val literalExpression = file.findElementByText<ULiteralExpression>("lorem")
val psi = literalExpression.psi!!
Assert.assertTrue(psi is KtLiteralStringTemplateEntry)
val literalExpressionAgain = psi.toUElement()
Assert.assertTrue(literalExpressionAgain is ULiteralExpression)
}
}
@Test fun testConvertStringTemplateWithExpectedType() {
doTest("StringTemplateWithVar") { _, file ->
val index = file.psi.text.indexOf("foo")
val stringTemplate = file.psi.findElementAt(index)!!.getParentOfType<KtStringTemplateExpression>(false)
val uLiteral = stringTemplate.toUElementOfType<ULiteralExpression>()
assertNull(uLiteral)
}
}
@Test fun testNameContainingFile() {
doTest("NameContainingFile") { _, file ->
val foo = file.findElementByText<UClass>("class Foo")
assertEquals(file.psi, foo.nameIdentifier!!.containingFile)
val bar = file.findElementByText<UMethod>("fun bar() {}")
assertEquals(file.psi, bar.nameIdentifier!!.containingFile)
val xyzzy = file.findElementByText<UVariable>("val xyzzy: Int = 0")
assertEquals(file.psi, xyzzy.nameIdentifier!!.containingFile)
}
}
@Test fun testInterfaceMethodWithBody() {
doTest("DefaultImpls") { _, file ->
val bar = file.findElementByText<UMethod>("fun bar() = \"Hello!\"")
assertFalse(bar.containingFile.text!!, bar.psi.modifierList.hasExplicitModifier(PsiModifier.DEFAULT))
assertTrue(bar.containingFile.text!!, bar.psi.modifierList.hasModifierProperty(PsiModifier.DEFAULT))
}
}
@Test fun testParameterPropertyWithAnnotation() {
doTest("ParameterPropertyWithAnnotation") { _, file ->
val test1 = file.classes.find { it.name == "Test1" }!!
val constructor1 = test1.methods.find { it.name == "Test1" }!!
assertTrue(constructor1.uastParameters.first().annotations.any { it.qualifiedName == "MyAnnotation" })
val getter1 = test1.methods.find { it.name == "getBar" }!!
assertFalse(getter1.annotations.any { it.qualifiedName == "MyAnnotation" })
val setter1 = test1.methods.find { it.name == "setBar" }!!
assertFalse(setter1.annotations.any { it.qualifiedName == "MyAnnotation" })
assertFalse(setter1.uastParameters.first().annotations.any { it.qualifiedName == "MyAnnotation" })
val test2 = file.classes.find { it.name == "Test2" }!!
val constructor2 = test2.methods.find { it.name == "Test2" }!!
assertFalse(constructor2.uastParameters.first().annotations.any { it.qualifiedName?.startsWith("MyAnnotation") ?: false })
val getter2 = test2.methods.find { it.name == "getBar" }!!
getter2.annotations.single { it.qualifiedName == "MyAnnotation" }
val setter2 = test2.methods.find { it.name == "setBar" }!!
setter2.annotations.single { it.qualifiedName == "MyAnnotation2" }
setter2.uastParameters.first().annotations.single { it.qualifiedName == "MyAnnotation3" }
test2.fields.find { it.name == "bar" }!!.annotations.single { it.qualifiedName == "MyAnnotation5" }
}
}
@Test fun testElvisType() {
doTest("ElvisType") { _, file ->
val elvisExpression = file.findElementByText<UExpression>("text ?: return")
assertEquals("String", elvisExpression.getExpressionType()!!.presentableText)
}
}
@Test fun testFindAttributeDefaultValue() {
doTest("AnnotationParameters") { _, file ->
val witDefaultValue = file.findElementByText<UAnnotation>("@WithDefaultValue")
assertEquals(42, witDefaultValue.findAttributeValue("value")!!.evaluate())
assertEquals(42, witDefaultValue.findAttributeValue(null)!!.evaluate())
}
}
@Test fun testIfCondition() {
doTest("IfStatement") { _, file ->
val psiFile = file.psi
val element = psiFile.findElementAt(psiFile.text.indexOf("\"abc\""))!!
val binaryExpression = element.getParentOfType<KtBinaryExpression>(false)!!
val uBinaryExpression = KotlinUastLanguagePlugin().convertElementWithParent(binaryExpression, null)!!
UsefulTestCase.assertInstanceOf(uBinaryExpression.uastParent, UIfExpression::class.java)
}
}
@Test
fun testWhenStringLiteral() {
doTest("WhenStringLiteral") { _, file ->
file.findElementByTextFromPsi<ULiteralExpression>("abc").let { literalExpression ->
val psi = literalExpression.psi!!
Assert.assertTrue(psi is KtLiteralStringTemplateEntry)
UsefulTestCase.assertInstanceOf(literalExpression.uastParent, USwitchClauseExpressionWithBody::class.java)
}
file.findElementByTextFromPsi<ULiteralExpression>("def").let { literalExpression ->
val psi = literalExpression.psi!!
Assert.assertTrue(psi is KtLiteralStringTemplateEntry)
UsefulTestCase.assertInstanceOf(literalExpression.uastParent, USwitchClauseExpressionWithBody::class.java)
}
file.findElementByTextFromPsi<ULiteralExpression>("def1").let { literalExpression ->
val psi = literalExpression.psi!!
Assert.assertTrue(psi is KtLiteralStringTemplateEntry)
UsefulTestCase.assertInstanceOf(literalExpression.uastParent, UBlockExpression::class.java)
}
}
}
@Test
fun testWhenAndDestructing() {
doTest("WhenAndDestructing") { _, file ->
file.findElementByTextFromPsi<UExpression>("val (bindingContext, statementFilter) = arr").let { e ->
val uBlockExpression = e.getParentOfType<UBlockExpression>()
Assert.assertNotNull(uBlockExpression)
val uMethod = uBlockExpression!!.getParentOfType<UMethod>()
Assert.assertNotNull(uMethod)
}
}
}
@Test
fun testBrokenMethodTypeResolve() {
doTest("BrokenMethod") { _, file ->
file.accept(object : AbstractUastVisitor() {
override fun visitCallExpression(node: UCallExpression): Boolean {
node.returnType
return false
}
})
}
}
@Test
fun testTypeAliases() {
doTest("TypeAliases") { _, file ->
val g = (file.psi as KtFile).declarations.single { it.name == "G" } as KtTypeAlias
val originalType = g.getTypeReference()!!.typeElement as KtFunctionType
val originalTypeParameters = originalType.parameterList.toUElement() as UDeclarationsExpression
Assert.assertTrue((originalTypeParameters.declarations.single() as UParameter).type.isValid)
}
}
@Test
fun testResolvedDeserializedMethod() = doTest("Resolve") { _, file ->
val barMethod = file.psi.findElementAt(file.psi.text.indexOf("bar")).sure { "sourceElement" }
.parentsWithSelf.mapNotNull { it.toUElementOfType<UMethod>() }.firstOrNull().sure { "parent UMethod" }
fun UElement.assertResolveCall(callText: String, methodName: String = callText.substringBefore("(")) {
this.findElementByTextFromPsi<UCallExpression>(callText).let {
val resolve = it.resolve().sure { "resolving '$callText'" }
assertEquals(methodName, resolve.name)
}
}
barMethod.assertResolveCall("foo()")
barMethod.assertResolveCall("inlineFoo()")
barMethod.assertResolveCall("forEach { println(it) }", "forEach")
barMethod.assertResolveCall("joinToString()")
barMethod.assertResolveCall("last()")
}
@Test
fun testUtilsStreamLambda() {
doTest("Lambdas") { _, file ->
val lambda = file.findElementByTextFromPsi<ULambdaExpression>("{ it.isEmpty() }")
assertEquals(
"kotlin.jvm.functions.Function1<? super java.lang.String,? extends java.lang.Boolean>",
lambda.getExpressionType()?.canonicalText
)
val uCallExpression = lambda.uastParent.assertedCast<UCallExpression> { "UCallExpression expected" }
assertTrue(uCallExpression.valueArguments.contains(lambda))
}
}
@Test
fun testLambdaParamCall() {
doTest("Lambdas") { _, file ->
val lambdaCall = file.findElementByTextFromPsi<UCallExpression>("selectItemFunction()")
assertEquals(
"UIdentifier (Identifier (selectItemFunction))",
lambdaCall.methodIdentifier?.asLogString()
)
assertEquals(
"selectItemFunction",
lambdaCall.methodIdentifier?.name
)
assertEquals(
"invoke",
lambdaCall.methodName
)
val receiver = lambdaCall.receiver ?: kotlin.test.fail("receiver expected")
assertEquals("UReferenceExpression", receiver.asLogString())
val uParameter = (receiver as UReferenceExpression).resolve().toUElement() ?: kotlin.test.fail("uelement expected")
assertEquals("UParameter (name = selectItemFunction)", uParameter.asLogString())
}
}
@Test
fun testLocalLambdaCall() {
doTest("Lambdas") { _, file ->
val lambdaCall = file.findElementByTextFromPsi<UCallExpression>("baz()")
assertEquals(
"UIdentifier (Identifier (baz))",
lambdaCall.methodIdentifier?.asLogString()
)
assertEquals(
"baz",
lambdaCall.methodIdentifier?.name
)
assertEquals(
"invoke",
lambdaCall.methodName
)
val receiver = lambdaCall.receiver ?: kotlin.test.fail("receiver expected")
assertEquals("UReferenceExpression", receiver.asLogString())
val uParameter = (receiver as UReferenceExpression).resolve().toUElement() ?: kotlin.test.fail("uelement expected")
assertEquals("ULocalVariable (name = baz)", uParameter.asLogString())
}
}
@Test
fun testLocalDeclarationCall() {
doTest("LocalDeclarations") { _, file ->
val localFunction = file.findElementByTextFromPsi<UElement>("bar() == Local()").
findElementByText<UCallExpression>("bar()")
assertEquals(
"UIdentifier (Identifier (bar))",
localFunction.methodIdentifier?.asLogString()
)
assertEquals(
"bar",
localFunction.methodIdentifier?.name
)
assertEquals(
"bar",
localFunction.methodName
)
assertNull(localFunction.resolve())
val receiver = localFunction.receiver ?: kotlin.test.fail("receiver expected")
assertEquals("UReferenceExpression", receiver.asLogString())
val uParameter = (receiver as UReferenceExpression).resolve().toUElement() ?: kotlin.test.fail("uelement expected")
assertEquals("ULambdaExpression", uParameter.asLogString())
}
}
}
@@ -1,65 +0,0 @@
package org.jetbrains.uast.test.kotlin
import org.junit.Test
class SimpleKotlinRenderLogTest : AbstractKotlinRenderLogTest() {
@Test fun testLocalDeclarations() = doTest("LocalDeclarations")
@Test fun testSimple() = doTest("Simple")
@Test fun testWhenIs() = doTest("WhenIs")
@Test fun testDefaultImpls() = doTest("DefaultImpls")
@Test fun testElvis() = doTest("Elvis")
@Test fun testPropertyAccessors() = doTest("PropertyAccessors")
@Test fun testPropertyInitializer() = doTest("PropertyInitializer")
@Test fun testPropertyInitializerWithoutSetter() = doTest("PropertyInitializerWithoutSetter")
@Test fun testAnnotationParameters() = doTest("AnnotationParameters")
@Test fun testEnumValueMembers() = doTest("EnumValueMembers")
@Test fun testStringTemplate() = doTest("StringTemplate")
@Test fun testStringTemplateComplex() = doTest("StringTemplateComplex")
@Test fun testQualifiedConstructorCall() = doTest("QualifiedConstructorCall")
@Test fun testPropertyDelegate() = doTest("PropertyDelegate")
@Test fun testPropertyWithAnnotation() = doTest("PropertyWithAnnotation")
@Test fun testIfStatement() = doTest("IfStatement")
@Test fun testInnerClasses() = doTest("InnerClasses")
@Test fun testSimpleScript() = doTest("SimpleScript") { testName, file -> check(testName, file, false) }
@Test fun testDestructuringDeclaration() = doTest("DestructuringDeclaration")
@Test fun testDefaultParameterValues() = doTest("DefaultParameterValues")
@Test fun testParameterPropertyWithAnnotation() = doTest("ParameterPropertyWithAnnotation")
@Test fun testParametersWithDefaultValues() = doTest("ParametersWithDefaultValues")
@Test fun testUnexpectedContainer() = doTest("UnexpectedContainerException") { testName, file -> check(testName, file, false) }
@Test fun testWhenStringLiteral() = doTest("WhenStringLiteral") { testName, file -> check(testName, file, false) }
@Test
fun testWhenAndDestructing() = doTest("WhenAndDestructing") { testName, file -> check(testName, file, false) }
@Test
fun testSuperCalls() = doTest("SuperCalls")
@Test
fun testConstructors() = doTest("Constructors")
@Test
fun testLambdas() = doTest("Lambdas")
}