Saving User Data to PsiElement
Answered
Hello. I have got a question.
PsiLanguageInjectionHost has a putUserData(key, value) method. If I use it to put a value, and then inject language with intelliLang, it happens that the value, which I put, disappears.
host.putUserData(Constants.KEY, value);
...
assert host.getUserData(Constants.KEY) == null;
What is the correct way to store the value?
Please sign in to leave a comment.
Hi George,
User data is not persistent and lives as long as an owner object lives. If you reparse the file, elements are recreated, and the information is lost. I suggest recalculating this data after reparse or accessing the data via the cache mechanism:
https://plugins.jetbrains.com/docs/intellij/psi-performance.html#cache-results-of-heavy-computations
so it will be calculated on demand and only when absent.
Hello. Thanks for the answer.
But a question arises.
How can you make sure that certain user data is associated with a certain PsiElement?
I'm sorry, but I don't understand the question. PsiLanguageInjectionHost is for marking PSI elements as language injection hosts, so the data in PsiLanguageInjectionHost is the host PSI element's data. If it doesn't answer the question, please elaborate on your use case and other details.
For clarity, I'll give an example. I want to do the following:
Then in another place do something like:
AnyMark anyMark = host.getUserData("AnyKey");if (anyMark != null) {
doSomething(host, anyMark);
}
Here, each PsiElement has user data, with which I understand what has to be done.
If I use cache, I don’t understand how to get the cached value for a specific PsiElement.
You should not compute the values upfront but only when requested. So by using caching, you can skip putting the data phase and use cache with compute value logic in the second part. It may also improve your plugin performance as it won't calculate the value until it is actually needed.