Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type attribution fixes #334

Merged
merged 1 commit into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/main/kotlin/org/openrewrite/kotlin/KotlinTypeMapping.kt
Original file line number Diff line number Diff line change
Expand Up @@ -855,7 +855,7 @@ class KotlinTypeMapping(typeCache: JavaTypeCache, firSession: FirSession) : Java
@OptIn(SymbolInternals::class)
fun variableType(
symbol: FirVariableSymbol<out FirVariable>?,
owner: JavaType.FullyQualified?,
owner: JavaType?,
ownerFallBack: FirBasedSymbol<*>?
): JavaType.Variable? {
if (symbol == null) {
Expand All @@ -875,7 +875,15 @@ class KotlinTypeMapping(typeCache: JavaTypeCache, firSession: FirSession) : Java
typeCache.put(signature, variable)
val annotations = listAnnotations(symbol.annotations)
var resolvedOwner: JavaType? = owner
if (owner == null && ownerFallBack != null) {
if (owner == null) {
val lookupTag: ConeClassLikeLookupTag? = symbol.containingClassLookupTag()
if (lookupTag != null && lookupTag.toSymbol(firSession) !is FirAnonymousObjectSymbol) {
// TODO check type attribution for `FirAnonymousObjectSymbol` case
resolvedOwner =
type(lookupTag.toFirRegularClassSymbol(firSession)!!.fir) as JavaType.FullyQualified?
}
}
if (resolvedOwner == null && ownerFallBack != null) {
// There isn't a way to link a Callable back to the owner unless it's a class member, but class members already set the owner.
// The fallback isn't always safe and may result in type erasure.
// We'll need to find the owner in the parser to set this on properties and variables in local scopes.
Expand All @@ -890,7 +898,7 @@ class KotlinTypeMapping(typeCache: JavaTypeCache, firSession: FirSession) : Java
return variable
}

fun variableType(javaField: JavaField, owner: JavaType.FullyQualified?): JavaType.Variable? {
fun variableType(javaField: JavaField, owner: JavaType?): JavaType.Variable? {
val signature = signatureBuilder.variableSignature(javaField)
val existing = typeCache.get<JavaType.Variable>(signature)
if (existing != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,8 @@ class KotlinTypeSignatureBuilder(private val firSession: FirSession) : JavaTypeS
if (owner.contains("<")) {
owner = owner.substring(0, owner.indexOf('<'))
}
} else if (ownerSymbol is FirFunctionSymbol<*>) {
owner = methodDeclarationSignature(ownerSymbol, null)
} else if (ownerSymbol != null) {
owner = classSignature(ownerSymbol.fir)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ class KotlinParserVisitor(
private val generatedFirProperties: MutableMap<TextRange, FirProperty>

// Associate top-level function and property declarations to the file.
private var currentFile: FirFile? = null
private val ownerStack: ArrayDeque<FirDeclaration> = ArrayDeque()
private var aliasImportMap: MutableMap<String, String>

init {
Expand All @@ -134,7 +134,7 @@ class KotlinParserVisitor(
private fun type(obj: Any?, ownerFallBack: FirBasedSymbol<*>? = null) = typeMapping.type(obj, ownerFallBack)

override fun visitFile(file: FirFile, data: ExecutionContext): J {
currentFile = file
ownerStack.push(file)
generatedFirProperties.clear()
var annotations: List<J.Annotation>? = null
val annotationList = PsiTreeUtil.findChildOfType(
Expand Down Expand Up @@ -3281,7 +3281,7 @@ class KotlinParserVisitor(
name,
emptyList(),
if (initializer != null) padLeft(sourceBefore("="), convertToExpression(initializer, data)!!) else null,
typeMapping.variableType(valueParameter.symbol, null, getCurrentFile())
name.fieldType
)
)
val vars: MutableList<JRightPadded<J.VariableDeclarations.NamedVariable>> = ArrayList(1)
Expand Down Expand Up @@ -4551,9 +4551,9 @@ class KotlinParserVisitor(
val msg = StringBuilder(typeName)
msg.append(" is not supported at cursor: ")
msg.append(source, cursor, min(source.length, cursor + 30))
if (currentFile != null) {
if (ownerStack.isNotEmpty()) {
msg.append("in file: ")
msg.append(currentFile!!.name)
msg.append((ownerStack.last as FirFile).name)
}
return msg.toString()
}
Expand Down Expand Up @@ -4593,7 +4593,19 @@ class KotlinParserVisitor(
j as Expression
)
}
return visitElement0(firElement, data)

var newOwner = false
try {
if (firElement is FirClass || firElement is FirSimpleFunction) {
ownerStack.push(firElement as FirDeclaration)
newOwner = true
}
return visitElement0(firElement, data)
} finally {
if (newOwner) {
ownerStack.pop()
}
}
}

private fun visitElement0(firElement: FirElement, data: ExecutionContext): J? {
Expand Down Expand Up @@ -4733,28 +4745,28 @@ class KotlinParserVisitor(
}

private fun createIdentifier(name: String?, firElement: FirElement): J.Identifier {
val type = type(firElement, getCurrentFile())
val type = type(firElement, owner(firElement)?.symbol)
return createIdentifier(
name ?: "",
if (type is JavaType.Variable) type.type else type,
if (type is JavaType.Variable) type else null
)
}

private fun owner(firElement: FirElement): FirDeclaration? {
if (ownerStack.peek() == firElement) {
return ownerStack.elementAt(1)
}
return ownerStack.peek()
}

@OptIn(SymbolInternals::class)
private fun createIdentifier(name: String, namedReference: FirResolvedNamedReference): J.Identifier {
val resolvedSymbol = namedReference.resolvedSymbol
if (resolvedSymbol is FirVariableSymbol<*>) {
var owner: JavaType.FullyQualified? = null
val lookupTag: ConeClassLikeLookupTag? = resolvedSymbol.containingClassLookupTag()
if (lookupTag != null && lookupTag.toSymbol(firSession) !is FirAnonymousObjectSymbol) {
// TODO check type attribution for `FirAnonymousObjectSymbol` case
owner =
type(lookupTag.toFirRegularClassSymbol(firSession)!!.fir) as JavaType.FullyQualified?
}
return createIdentifier(
name, type(namedReference, getCurrentFile()),
typeMapping.variableType(resolvedSymbol, owner, getCurrentFile())
typeMapping.variableType(resolvedSymbol, null, owner(namedReference)!!.symbol)
)
}
return createIdentifier(name, namedReference as FirElement)
Expand Down Expand Up @@ -4956,7 +4968,7 @@ class KotlinParserVisitor(
}

private fun getCurrentFile(): FirBasedSymbol<*>? {
return if (currentFile == null) null else currentFile!!.symbol
return if (ownerStack.isEmpty()) null else ownerStack.last.symbol
}

private fun at(c: Char) = cursor < source.length && source[cursor] == c
Expand Down
13 changes: 11 additions & 2 deletions src/test/java/org/openrewrite/kotlin/KotlinTypeMappingTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,19 @@ void fieldType() {
assertThat(id.getType()).isInstanceOf(JavaType.Class.class);
assertThat(id.getType().toString()).isEqualTo("kotlin.Int");

assertThat(property.getGetter().getMethodType().toString().substring(property.getGetter().getMethodType().toString().indexOf("openRewriteFileKt"))).isEqualTo("openRewriteFileKt{name=accessor,return=kotlin.Int,parameters=[]}");

JavaType.FullyQualified declaringType = property.getGetter().getMethodType().getDeclaringType();
assertThat(declaringType.getFullyQualifiedName()).isEqualTo("org.openrewrite.kotlin.KotlinTypeGoat");
assertThat(property.getGetter().getMethodType().getName()).isEqualTo("accessor");
assertThat(property.getGetter().getMethodType().getReturnType()).isEqualTo(id.getType());
assertThat(property.getGetter().getMethodType()).isEqualTo(property.getGetter().getName().getType());
assertThat(property.getSetter().getMethodType().toString().substring(property.getGetter().getMethodType().toString().indexOf("openRewriteFileKt"))).isEqualTo("openRewriteFileKt{name=accessor,return=kotlin.Unit,parameters=[kotlin.Int]}");
assertThat(property.getGetter().getMethodType().toString().substring(declaringType.toString().length())).isEqualTo("{name=accessor,return=kotlin.Int,parameters=[]}");

declaringType = property.getSetter().getMethodType().getDeclaringType();
assertThat(declaringType.getFullyQualifiedName()).isEqualTo("org.openrewrite.kotlin.KotlinTypeGoat");
assertThat(property.getSetter().getMethodType().getName()).isEqualTo("accessor");
assertThat(property.getSetter().getMethodType()).isEqualTo(property.getSetter().getName().getType());
assertThat(property.getSetter().getMethodType().toString().substring(declaringType.toString().length())).isEqualTo("{name=accessor,return=kotlin.Unit,parameters=[kotlin.Int]}");
}

@Test
Expand Down
Loading