Ctrl-B through openAPI : how to find PsiVariable from PsiRefExpression ?


PsiReferenceExpression ref = ..
PsiVariable v = some??????Function (ref) ;

On the code below,
how can obtain the PsiVariable (line 1) associated to a
PsiReferenceExpression (line 2)?

 = i + 1 ;
   ...        
]]>



Alain

7 comments

PsiVariable v = (PsiVariable)ref.resolve();

--
regards,
Alexey Kudravtsev.
JetBrains, Inc
http://www.intellij.com
"Develop with pleasure!"


"Alain Ravet" <alain.ravet.list@wanadoo.be> wrote in message news:bop1hb$qg1$1@is.intellij.net...
>

PsiReferenceExpression ref = ..
PsiVariable v = some??????Function (ref) ;

>

On the code below,
how can obtain the PsiVariable (line 1) associated to a
PsiReferenceExpression (line 2)?

>

    int i = 1;
>    i = i + 1 ;
>    ...
> ]]>

>
>

Alain

>


0

Alexey Kudravtsev (JetBrains) wrote:

PsiVariable v = (PsiVariable)ref.resolve();


Casting in this way will give you ClassCastException at some point in the
future with 98% certainity :)

Friendly,
Dmitry
--
Dmitry Lomov
IntelliJ Labs / JetBrains Inc.
http://www.intellij.com
"Develop with pleasure!"

0

Dmitry Lomov (JetBrains) wrote:

>>PsiVariable v = (PsiVariable)ref.resolve();
>>
>>
>
>Casting in this way will give you ClassCastException at some point in the
>future with 98% certainity :)

>


What do you suggest?

Alain

0

Alain Ravet wrote:

Dmitry Lomov (JetBrains) wrote:

>>>PsiVariable v = (PsiVariable)ref.resolve();
>>>
>>>
>>
>>Casting in this way will give you ClassCastException at some point in the
>>future with 98% certainity :)
>>
>>


What do you suggest?


Sorry if i wasn't clear. You should check that ref.resolve() really returns
PsiVariable, as in:

PsiElement resolved = ref.resolve();
if (resolved instanceof PsiVariable) {
// do stuff
} else {
// do other stuff
}

Friendly,
Dmitry

--
Dmitry Lomov
IntelliJ Labs / JetBrains Inc.
http://www.intellij.com
"Develop with pleasure!"

0

Dmitry ,

>You should check that ref.resolve() really returns PsiVariable, ..

>

Your answer triggers another pair of questions :
- when would resolve() called on a PsiReferenceExpression not return
the associated PsiVariable?
- what exactly does resolve() do?

Alain

0

Alain,

In my experience ref.resolve() returns a PsiElement that corresponds to the object described by the reference. So for example, if you have a PsiMethodCallExpression, then

returns a PsiMethod that corresponds to the method being called.

As long as your reference is to a PsiVariable, .resolve() should always return a PsiVariable. A PsiField is a subclass of PsiVariable, so PsiVariable might be safer in more cases. But anything for which a reference can be constructed (classes, methods, fields, variables) could be resolve()'d to the corresponding PsiElement.

HTH,
-Dave

0

Please sign in to leave a comment.