Quantcast
Channel: Visual Studio Integrate forum
Viewing all articles
Browse latest Browse all 4410

(Roslyn) Cannot get SyntaxTree from Compilation object

$
0
0

Hi, I'm roslyn beginner. To get accustomed to it, I started with a very simple Console Application, which analyze it self by using roslyn.
I refered to the instruction of a tutorial site (https://riptutorial.com/roslyn/example/16545/introspective-analysis-of-an-analyzer-in-csharp).

In accordance with the instraction, I made a .NET Framework Cosole Application (not .NET Core or .NET standard, and target Framework version is 4.7.2), add the NuGet package Microsoft.CodeAnalysis, and Microsoft.CodeAnalysis.Workspaces.MSBuild, then wrote a simple code as I showed below.

using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using System;
using System.Linq;

namespace SimpleRoslynConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            AnalyzeMe();
        }

        static void AnalyzeMe()
        {
            // Declaring a variable with the current project file path.
            // *** You have to change this path to fit your development environment.
            const string projectPath =
                @"C:\Users\[MyName]\Source\Repos\Experimental\RoslynTrial01\RoslynTrialConsole01\RoslynTrialConsole01.csproj";

            // [Step1]Creating a build workspace.
            var workspace = MSBuildWorkspace.Create();

            // [Step2]Opening this project.
            var project = workspace.OpenProjectAsync(projectPath).Result;

            // [Step3]Getting the compilation.
            var compilation = project.GetCompilationAsync().Result;

            // [Step4]As this is a simple single file program, the first syntax tree will be the current file.
            var syntaxTree = compilation.SyntaxTrees.FirstOrDefault();

            if (syntaxTree != null)
            {
                // [Step5]Getting the root node of the file.
                var rootSyntaxNode = syntaxTree.GetRootAsync().Result;

                // [Step6]Finding all the local variable declarations in this file and picking the first one.
                var firstLocalVariablesDeclaration = rootSyntaxNode.DescendantNodesAndSelf()
                    .OfType<LocalDeclarationStatementSyntax>().First();

                // [Step7]Getting the first declared variable in the declaration syntax.
                var firstVariable = firstLocalVariablesDeclaration.Declaration.Variables.First();

                // [Step8]Getting the text of the initialized value.
                var variableInitializer = firstVariable.Initializer.Value.GetFirstToken().ValueText;

                // [Step9]This will print to screen the value assigned to the projectPath variable.
                Console.WriteLine(variableInitializer);
            }
            else
            {
                Console.WriteLine("Could not get SyntaxTrees from this projects.");
            }

            Console.WriteLine("Hit any key.");
            Console.ReadKey();
        }
    }
}

My problem is that, SyntaxTrees property of Compilation object returns null in [Step4]mark.Naturally, following FirstOrDefault method returns null.

I've tried several other code. I found I could get SyntaxTree from CSharp code text, by using CSharpSyntaxTree.ParseText method. But I couldn't get any from source code, by the sequence of

  1. var workspace = MSBuildWorkspace.Create();
  2. var project = workspace.OpenProjectAsync(projectPath).Result;
  3. var compilation = project.GetCompilationAsync().Result;

What I'd like to know is if I miss something to get Syntax information from source code by using above process.

I'll appreciate someone give me a good advice.




Viewing all articles
Browse latest Browse all 4410

Trending Articles