Can you tell me if it's possible to force annotati...
# compiler
e
Can you tell me if it's possible to force annotation argument resolution (push the phase to
ANNOTATION_ARGUMENTS
) from the
getTopLevelCallableIds
getter in a
FirDeclarationGenerationExtension
? I need to extract a class literal target from an annotation argument right during the top-level declaration indexing phase. However, when running inside the AA, any attempt to call
resolvedAnnotationsWithArguments
or trigger lazy resolution from within
getTopLevelCallableIds
breaks the compiler contracts, throwing a
FirLazyResolveContractViolationException
. Even worse, it occasionally triggers a silent infinite recursion loop where the IDE endlessly retries the analysis (bruh). Also, what is the idiomatic way to look up annotated class-like symbols at this early stage? Relying on
session.predicateBasedProvider.getSymbolsByPredicate
inside
getTopLevelCallableIds
returns an empty collection during clean CLI/Gradle builds, because the predicate index hasn't been populated yet when top-level IDs are being collected. How should one handle dynamic top-level extension generation based on annotation arguments without falling into these phase/lazy resolve deadlocks?
Here is a collection of stacktraces that I collected today
Copy code
org.jetbrains.kotlin.utils.exceptions.KotlinIllegalArgumentExceptionWithAttachments: Error while resolving org.jetbrains.kotlin.fir.declarations.impl.FirRegularClassImpl
from RAW_FIR to ANNOTATION_ARGUMENTS
current declaration phase CONSTANT_EVALUATION
origin: Source
session: class org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirSourcesSession
module data: class org.jetbrains.kotlin.analysis.low.level.api.fir.projectStructure.LLFirModuleData
KaModule: class org.jetbrains.kotlin.idea.base.fir.projectStructure.modules.source.KaSourceModuleImpl
platform: JVM (25)
	at org.jetbrains.kotlin.analysis.low.level.api.fir.lazy.resolve.LLFirModuleLazyDeclarationResolverKt.handleExceptionFromResolve(LLFirModuleLazyDeclarationResolver.kt:228)
and
Copy code
Caused by: org.jetbrains.kotlin.fir.symbols.FirLazyResolveContractViolationException: `lazyResolveToPhase(ANNOTATION_ARGUMENTS)` cannot be called from a transformer with a phase ANNOTATION_ARGUMENTS.
`lazyResolveToPhase` can be called only from a transformer with a phase which is strictly greater than a requested phase;
 i.e., `lazyResolveToPhase(A)` may be only called from a lazy transformer with a phase B, where A < B. This is a contract of lazy resolve
Maybe I missed something small or it's an environmental issue and it will be visible from the stacktraces
I'm also not entirely sure about
hasPackage
. If a package already physically exists and I'm going to add a virtual top-level function to it, it is not needed to return true for its match?
I tried to figure it out and even learned a lot of useful information from the compiler sources (some sugar for parsing), but I couldn't find any answers or examples in Kotlin itself.
I'm taking a break for now, so it's not urgent at all. I think I'll first study the source code and examples from other third-party plugins.
d
It's not possible. Annotation arguments resolution depends on top-level callables generation, as a plugin could generate a const val and the user could pass this val to an annotation.
Regarding your second question, the predicate provider is the way. If it doesn't return symbols, it's suspicious. @bnorm could you look at it please?
✔️ 1
e
Can someone please tell me if this is even possible within the
FirDeclarationGenerationExtension
, and what other FIR resolving limitations there might be? My goal is: 1. Find classes annotated with
@A
2. Extract the argument of the
Klass
class literal from the
@A
annotation 3. Extract the names of those properties/functions annotated with
@B
4. Generate virtual top-level properties/functions in the
Klass
class package, using the receiver type of the same
Klass
, while otherwise completely repeating the signature of its origin (including context parameters, suspend, etc.) 5. (I think I already understand the transformation to IR, so here goes.) As Dmitriy already told me, I can't resolve
@A
arguments, so I (as I understand it) must extract the class literal using raw FIR. Also, I already know that declarations annotated with
@B
cannot have an implicit return type.
Like this:
Copy code
package com.example
import compiled.library.SomeClass
@A(SomeClass::class)
class SomeMixin {
    @B fun iwannabeext() {}
    fun idont() {}
}
->
Copy code
package compiled.library
fun SomeClass.iwannabeext() {}
By the way, I also noticed this oddity (I tested this hardcoded, without parsing annotations): IDEA suggests generated top-level callables in autocomplete, but when selecting, it doesn't automatically insert the import. However, if I manually wrote the import, everything worked.
@dmitriy.novozhilov sorry, looking back at my notes, that empty collection was most likely a side-effect of a re-entrant recursive loop I got stuck in during earlier debugging LL sessions. In my latest clean tests,
predicateBasedProvider.getSymbolsByPredicate
actually found all the annotated class symbols properly... Although it's possible that there was some kind of error in K2, I can't reproduce it now.
👍 1
d
Your idea should be possible to implement with a caveat of raw class literal, as you've correctly noticed. You can implement your own dummy resolve for it, which will consider only classes from imports and also make a checker which would compare results of your resolve with results of the compiler resolve and report an error if they are different.
e
Thanks, I'll look into that approach! Btw, I've decided to try implementing my idea again right now. I'll report back on my progress today.
I did it! The raw parser code isn't perfect and not optimized, but at least it works. gist.github.com/diskria/… & gist.github.com/diskria/… Thank you very much again for your explanation and time, @dmitriy.novozhilov
👍 1
The second gist is the log, if anyone's interested. I opened a test project with the plugin attached, and only one class, CreeperMixin, was opened in editor. But the logs show how the list of callableIds from other files is calculated. You can also see how the IDE reacted to my edit of the function name.
I realized that I don't want to support the raw parser and decided that it would be much better if I move the target class type from the annotation arguments to the annotation type arguments (
@A<T>
). 😄 Since type arguments are calculated in the
TYPES
phase, I got out of this
ANNOTATION_ARGUMENTS
phase trap with lazy resolver via
getAnnotationByClassId
. (but I wouldn't have been able to understand that such a decision was possible without going through what happened today.) Besides, without
TYPES
, I would still have trouble parsing the signatures of functions located in closed files. Gist: gist.github.com/diskria/… (If anyone is interested, I cleaned up the code a bit more.)
d
Yeah, this would work too. I completely forgot about this option.
e
Although this is no longer relevant, I'm curious to know. In fact, you can't create a constant on a class literal (diagnostic
TYPE_CANT_BE_USED_FOR_CONST_VAL
). So, as I see it, class literals are "hostages" of the
ANNOTATION_ARGUMENTS
phase. I'm just curious, theoretically, if it's possible to move the resolution of
KClass
arguments (and probably
Enum
too) to the
TYPES
phase..? I think so but. Although perhaps that's not the issue, but rather that partial resolution is impossible, right?
I view annotation arguments as, well, a "special type subsystem that's limited by the JVM specification" / "compile-time primitives". For example, we can't call functions from there because a compile time value is required. Basically, I think of it as a simplified expression that can be evaluated earlier. But I'm probably just missing some important details.
d
Theoretically it's possible, but the implementation and maintenance cost isn't worth the effort.
👍 1
e
Quick update: turns out
getTopLevelCallableIds
can indeed be invoked as early as the
SUPERTYPES
stage, which prevented relying on fully resolved types at that point. Because of this, I had to fall back to a dummy import-based resolution to determine the target class package, but I made it much more robust this time. I also got the virtual top-level extension functions generation fully working via
copyFirFunctionWithResolvePhase
(clearing bodies/contracts, setting up receiver parameters, and attaching fake sources for proper IDE navigation). Next up: handling the generic type parameters projection/lowering, and then I can finally move on to the IR phase. Gist: gist.github.com/diskria/…
d
Hmm, could you send a stacktrace when it's invoked on the supertypes phase?
e
I actually saw this in a comment. I don't have any proof, but I thought it was somehow related to delegation.
image.png
d
This comment is about ...ForClass methods.
e
Oh
Damn, I thought this comment is about everything below, but the formatting got broken by experimental api annotation
Ahhh, ok, thanks again 🙂 then I'll go back.. yes Done!
👌 1