简体   繁体   中英

AST walker doesn't seem to work fine

I am using Roslyn and I have created an AST walker in order to detect when certain nodes are traversed.

The source I am trying to parse is the following:

var source = string.Format(@"
    using System;
    using System.Collections;
    using System.Linq;
    using System.Text;

    namespace HelloWorld
      {{
         class {0} : {1}
         {{
            static void Main(string[] args)
            {{
               Console.WriteLine(""Hello, World!"");
            }}
         }}
      }}", "MyClass", "MyBaseClass");

And this is the walker:

namespace MyStuff
{
    using System;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CSharp;
    using Microsoft.CodeAnalysis.CSharp.Syntax;

    public class MyWalker : CSharpSyntaxWalker
    {
        public MyWalker(SyntaxNode node) :
          base(SyntaxWalkerDepth.StructuredTrivia)
        {
            this.Root = node;
        }

        public SyntaxNode Root { get; private set; }

        public void Start()
        {
            this.Visit(this.Root);
        }

        sealed public override void VisitAccessorDeclaration(AccessorDeclarationSyntax node)
        {
            this.DoSomething(node, this.type.IsInstanceOfType(node));
        }

        ...

        sealed public override void VisitYieldStatement(YieldStatementSyntax node)
        {
            this.DoSomething(node, this.type.IsInstanceOfType(node));
        }

        // BREAKPOINT IN THE BODY OF THIS FUNCTION!
        private void DoSomething(SyntaxNode node)
        {
            ...
        }       
    }
}

I am overriding all visit methods, alphabetically from VisitAccessorDeclaration to VisitYieldStatement . I am doing this just to try stuff, not for real applications, I know it is quite nonsense.

Visiting

I run it:

SyntaxNode root = CSharpSyntaxTree.ParseText(source).GetRoot();

And then run the walker:

var astWalker = new MyWalker(this.Root);
astExecutor.Start();
// NEXT OPERATION

What happens? I seta breakpoint on function DoSomething and I expect it to be it a lot of times. Actually it does not happen. It happens only for one node: VisitCompilationUnit . After the control flow passes on on // NEXT OPERATION and that's it.

What am I missing? Thanks

In your overrides, you need to call the base version of the method you are overriding. We allow you to stop the walk. By not calling base so that if you are trying to visit only specific nodes, you can control it.

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