none
(Roslyn) Cannot get SyntaxTree from Compilation object RRS feed

  • Question

  • 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 instruction, 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.




    Tuesday, March 5, 2019 5:17 AM

All replies

  • Hi friend,

    Welcome to MSDN forum.

    And sorry for the delay. When I research for this and search info online. I find the same issue you post in SO. And the issue seems to be solved nowadays.

    We would appreciate it so much if you share your solution here! So that other community members with similar issue could find it easier. 

    And you can mark it as answer, which benefit other members and we can archive this thread for you.

    Thanks for your understanding and great help!

    Best Regards

    Lance


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 22, 2019 10:45 AM
  • I'll jump on this issue as well.  I also found that using CSharpSyntaxTree.ParseText method I was able to build a Walker that would pull out the information that I needed, but when trying to build this into an extension, I cannot find a way to get a snapshot of the SyntaxTree.  I know Visual Studio is doing the code parsing and colorizing, but nothing clear is jumping out that could give me a new copy of the SyntaxTree every time it changes.

    I have build a simple classifier based on the tutorials, but the GetClassificationSpans seems to give me line-by-line SnapshotSpans that are not helping me do some multi-line comment identification based on the Syntax.

    There should be a way to register with the Syntax Parser and get a new copy of the SyntaxTree every time it changes so I can work on that to see if my key comment highlighting need to change.

    Any help?

    Sunday, March 24, 2019 8:39 PM
  • Hi John,

    Maybe you can get some help from TrailRunner-MF's answer. And since the issue you meet have some difference from this case. I suggest you can open a new thread in MSDN forum.

    Thanks for your understanding and cooperation!
    Best Regards

    Lance


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, March 25, 2019 7:13 AM
  • Hi friend,

    Welcome to MSDN forum.

    According to your description, your issue is more related to Roslyn development, and since this is VS Integrate forum(We discuss about usage and development about vs extension like .vsix), I suggest you open a new thread on stackoverflow to get more professional support.

    Thanks for your understanding and Cooperation:)

    Best Regards

    Lance


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, April 8, 2019 7:41 AM