Can I detect (using roslyn) that x
reference in the lambda body is closure over outer variable x
, not some variable local to lambda itself?
var x = "foo";
var a = string[0];
a.Any(i => i == x);
Yup. You can use the DataFlowAnalysis
API.
var tree = CSharpSyntaxTree.ParseText(
@"
class C{
void M(){
var x = ""foo"";
var a = new string[0];
var testing = a.Any(i => i == x);
}
}
");
var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Last();
var dataFlowAnalysis = model.AnalyzeDataFlow(lambda);
var capturedVariables = dataFlowAnalysis.Captured;
foreach(var variable in capturedVariables)
{
//Do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With