Reference Java elements in my custom language

I am working on a plugin for a JVM language and I would need to use Java elements in this language. In particular I would start with auto-completion.

Should I call:
ReferenceProvidersRegistry#getReferencesFromProviders(PsiElement) from my CompletionContributor?

Which Java elements should I target to get the list of Java types (enum, classes and interfaces), for examples?

Comment actions Permalink

You certainly can call getReferencesFromProviders from completion contributor if you feel you need to. But most contributors don't do this directly, they call file.findReferenceAt(offset) (which ends up in getReferencesFromProviders, too).

I don't understand the second part of the question, what do you mean by "targeting"? To get the list of all classes (including interfaces and enums), you can invoke AllClassesGetter.processJavaClasses. JavaLookupElementBuilder#forClass might be useful to you.

Comment actions Permalink

Thank you Peter! I am using:

AllClassesGetter.processJavaClasses(parameters, result.getPrefixMatcher(), parameters.getInvocationCount() <= 1, new Consumer<PsiClass>() {
    public void consume
(PsiClass psiClass) {

in my CompletionContributor and this works. However it inserts the fully qualified name. Now, I am think that in Java it uses AllClassesGetter.TRY_SHORTENING to insert the import at the top of the file and then using the short name. However I do not understand how it does that. I would like to do something similar in my language, by creating the appropriate import. I was thinking to manipulate directly the text but it would help me any advice on that.

Comment actions Permalink

Normally one doesn't change the text directly, but changes imports via PSI. Java does it that way. The logic is quite complicated there, but eventually it results in PsiElementFactory#createImportStatement call and then PsiImportList#add(importStatement). In Groovy it's GroovyFileBase#addImport. So you probably need to have something similar in your language.


Please sign in to leave a comment.