The method call will be a descendant of the loop declaration if it is inside it. You can access the Ancestors
property of any SyntaxNode
. Start going up among the ancestors of the MethodInvocation
node you detected until you hit a loop or a member declaration.
If you hit a loop (ForStatementSyntax
or WhileStatementSyntax
) then you are good.
If you hit a MemberDeclarationSyntax
node that means you have reached the start of whatever block in which your method1
is being called and should probably throw an error.
At this point, your immediate problem is mostly solved, and you have to decide how many corner cases you want to cover. What if it is called from a lambda expression? What if a method that calls method1
is called from a loop? Or from a recursive method?
You can detect all these cases but you have to decide if it is worth the effort.