简体   繁体   中英

How can i find the value of a variable through roslyn

I am making a Diagnostic Analyzer using Roslyn. I want to get the value of a variable in the code which is being analyzed. Such as getting the value of the variable num in this code:

int[] a = { 1, 2, 3 };
int[] num = a;
Person person1 = new Person("bob", num);

I have tried compiling the code on the fly by creating a new Compilation Unit,

SyntaxTree compilationUnitTree = SyntaxTree.ParseText(
            @"using System;
             namespace HelloWorld
            {
                class Program
                {
                    static void Main(string[] args)
                    {
                        int[] a = { 1, 2, 3 };
                        int[] num = a;
                    }
                }
            }");
 var compilation = CSharpCompilation.Create("MyCompilation", syntaxTrees: new[] { compilationUnitTree });
 var semanticModel = compilation.GetSemanticModel(compilationUnitTree);

But I was unable to get its value. I have also tried using DataFlowAnalysis of SemanticModel, I am able to successfully check properties such as if the value is constant or not etc. but when I check for value of num it gives a and not what I expected({1,2,3}).

Is there any way I can get the value of a variable using Roslyn?

You can't in a generic way.

First it can be reduced to the Halting Problem you can't know if a program finishes so you can't know if num will ever receive a value, the code to fill it might throw for example or enter an infinite loop.

Secondly it might not be something that could be known before runtime : It might be initialized from a method that return a random value each time, call a webservice or give the weather of the day...

The problem can be solved in some cases (Like the one you describe) but while roslyn contains some Static Analysis algorithms (Like DataFlowAnalysis) I don't think that it contains this one.

If you do it yourself beware of reference aliasing:

int[] a = { 1, 2, 3 };
int[] b = a;
b[2] = 8;
b = a;
int[] num = a;

What is num ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM