public static void ForWhenLocal() { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class C { public C() { var i = 0; i = 1; } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes()); var semanticModel = compilation.GetSemanticModel(syntaxTree); Assert.AreEqual(true, semanticModel.TryGetSymbol(syntaxTree.FindVariableDeclaration("i"), CancellationToken.None, out ILocalSymbol local)); using (var walker = IdentifierNameWalker.For(local, semanticModel, CancellationToken.None)) { CollectionAssert.AreEqual(new[] { "i" }, walker.IdentifierNames.Select(x => x.Identifier.ValueText)); Assert.AreEqual(true, walker.TryFind("i", out var match)); Assert.AreEqual("i", match.Identifier.ValueText); Assert.AreEqual(false, walker.TryFind("missing", out _)); } }
public static void ForWhenParameter() { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class C { public C(int i) { i = 1; } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); Assert.AreEqual(true, semanticModel.TryGetSymbol(syntaxTree.FindParameter("i"), CancellationToken.None, out var parameter)); using var walker = IdentifierNameWalker.For(parameter, semanticModel, CancellationToken.None); CollectionAssert.AreEqual(new[] { "i" }, walker.IdentifierNames.Select(x => x.Identifier.ValueText)); Assert.AreEqual(true, walker.TryFind("i", out var match)); Assert.AreEqual("i", match.Identifier.ValueText); Assert.AreEqual(false, walker.TryFind("missing", out _)); }