locked
Visual Studio plugin - object metrics, access to AST RRS feed

  • Question

  • Hi. I`m looking for informationas about analyzing source codes of c# files - actually i`m going to write a plugin which can by analyzing source code

    and compute some metric values. Is there a possibility to use Visual Studio AST generated for the project or file? Is there any class of such a functionality?

    Generally speaking, I want to get an AST from Visual and "walk" it in my way. Thanks for all sugestions.

    Wednesday, October 6, 2010 11:12 AM

Answers

  • Hello,

    You may take a look of the following two dlls:

    Microsoft.VisualStudio.CSharp.Services.Language.dll

    Microsoft.VisualStudio.CSharp.Services.Language.Interop.dll

    Use the following code as an example in your add-in:

      var project = solution.Projects.Item(1);
      var host = new IDECompilerHost();
      var compiler = host.CreateCompiler(project);
      foreach (var file in compiler.SourceFiles)
      {
        if (string.Compare(file.Key.Value, @"d:\temp\test\test.cs",
                  StringComparison.InvariantCultureIgnoreCase) == 0)
        {
          source = file.Value;
          break;
        }
      }
      var tree = source.GetParseTree();
      IDECompilation compilation = (IDECompilation)compiler.GetCompilation();
    
      compilation.CompileTypeOrNamespace(tree.RootNode);
      var node = tree.RootNode as NamespaceDeclarationNode;
    
      foreach (var child in node.NamespaceMemberDeclarations.Root.Children)
      {
        if (child is BinaryExpressionNode)
        {
          var bnode = child as BinaryExpressionNode;
          var left = bnode.Left as ClassDeclarationNode;
          var right = bnode.Right as ClassDeclarationNode;
     
          Trace.WriteLine(left.Identifier.Name.Text);
          Trace.WriteLine(right.Identifier.Name.Text);
        }
        else
        {
          Trace.WriteLine(child.AsName().Name.Text);
        }
      }
    
    Hope it helps.
    Looking for TFS Hot Issues? Follow us at Twitter.

    Hongye Sun [MSFT]
    MSDN Subscriber Support in Forum
    If you have any feedback on our support, please contact msdnmg @ microsoft.com

    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Thursday, October 7, 2010 4:30 PM