I am using the CSharpSyntaxTree and I have been able to extract the using statements, method and class definitions.The structure of my script is:
<using statements>
<executable code statements (may or may not be in a try-catch block)>
<method definitions>
<class definitions>
But now I am having an issue extracting all independent executable statements.
The line var statementSyntaxes = root.DescendantNodes().OfType<StatementSyntax>().ToList();
gives me all statements in the script but I am not interested in statements in the methods and class definitions. Please, how do I filter them out and retrieve only the statements that stand alone?
Here is my code:
var sourceCode = source.ToString();
SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode);
var root = (CompilationUnitSyntax)tree.GetRoot();
var members = root.Members;
// get all using statements
var usingCollector = new UsingCollector();
usingCollector.Visit(root);
var usingNames = String.Join("\n", usingCollector.Usings.Select(u => u.ToString()));
// get all methods
var methodDeclarationSyntaxes = root.DescendantNodes().OfType<MethodDeclarationSyntax>();
var usefulMethods = methodDeclarationSyntaxes.Where(m => m.Body != null);
var methodsScript = String.Join("\n", usefulMethods.Select(m => m.ToString()));
// get all classes
var classDeclarations = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Select(c => c).ToList();
var classesScript = String.Join("\n", classDeclarations.Select(cc => cc.ToString()));
string customScript = $"{usingNames} \n{methodsScript} \n{classesScript}";
// get all executable statements
var statementSyntaxes = root.DescendantNodes().OfType<StatementSyntax>().ToList();
I am making an edit to the post: So let's say I have a class with one method in it and I want to traverse through each of the executable statements in the method keeping in mind that some or all of these statements might be wrapped in a try-catch block. How do I achieve this, please?