I am creating a code extractor/inlining tool that will make it easier for me to share snippets of source code. It will ideally take a method that I provide, walk the method's syntax tree looking for references to methods/types in my other assemblies, and extract them all into a single block of code. This way, if I want to share an extension method I wrote that references other extensions that reference other extensions, I don't have to painstakingly compile it all into something I can copy and paste on the internet.
This article got me started:
https://joshvarty.com/learn-roslyn-now/
And below is what I have so far. I have an extension method called TrimWhiteSpace()
in a GeneralUtilities
class in the MyExtensions
namespace. The below code successfully identifies this extension, but I also want access to the method's body so that I can walk the syntax tree there looking for other extensions. Because I am using the DLL directly, it won't have access to the body, so I need to generate a SemanticModel
using the project instead. Using the project path doesn't appear to work.
public static void SemanticsTest()
{
var tree = CSharpSyntaxTree.ParseText(@"using MyExtensions;
namespace TestNamespace
{
public static class TestClass
{
public static void CallTrimWhiteSpace()
{
var x = "" some string "".TrimWhiteSpace();
}
}
}");
var root = tree.GetRoot();
var assemblyPath = MetadataReference.CreateFromFile(typeof(GeneralUtilities).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { assemblyPath });
var model = compilation.GetSemanticModel(tree);
var expression = root.DescendantNodes().OfType<InvocationExpressionSyntax>().FirstOrDefault();
var symbol = model.GetSymbolInfo(expression);
}