https://github.com/dcronqvist/inspectree
🔎 A .NET library for inspecting entire syntax trees of methods in C#
https://github.com/dcronqvist/inspectree
csharp roslyn source-generator
Last synced: over 1 year ago
JSON representation
🔎 A .NET library for inspecting entire syntax trees of methods in C#
- Host: GitHub
- URL: https://github.com/dcronqvist/inspectree
- Owner: dcronqvist
- License: mit
- Created: 2024-09-07T20:50:46.000Z (almost 2 years ago)
- Default Branch: master
- Last Pushed: 2024-10-02T18:23:36.000Z (almost 2 years ago)
- Last Synced: 2025-03-28T12:56:56.278Z (over 1 year ago)
- Topics: csharp, roslyn, source-generator
- Language: C#
- Homepage:
- Size: 47.9 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 🔎 InspecTree
InspecTree is a library for inspecting entire syntax trees of lambda functions in C#. [`Expression`](https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1) is commonly used for this purpose, but it is limited to single expressions unless you manually construct a [`BlockExpression`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.blockexpression). InspecTree allows you to inspect entire syntax trees of lambda functions, including entire statement bodies.
## Quick example
This library was initially created with the intention of transpiling C# code to GLSL. Here's a small example of how to access the syntax tree of a lambda function to transpile it to GLSL.
```csharp
// Partial required due to source generator
// creating an overload in the same class
public partial class Program
{
public static void Main(string[] args)
{
var glslCode = TranspileToGLSL(() =>
{
var x = 2 + 5f;
var color = new Vector4(1.0f);
if (x > 4)
{
color = new Vector4(0.2f, 0.3f, x, 1.0f);
}
return color;
});
}
// Overload of this method is generated by source generator that
// accepts a Func, and therefore accepts a lambda function
public static string TranspileToGLSL(InspecTree> shader)
{
var transpiler = new GLSLTranspiler();
return transpiler.Transpile(shader.SyntaxTree);
}
}
```
If you want a more complete example of where this is done, check out the [InspecTree.Example](src/InspecTree.Example/Program.cs) project.
## How it works
InspecTree uses two source generators to make it possible to access both the syntax tree and semantic model of a lambda.
- For each method that accepts an `InspecTree` parameter, it generates an overload that accepts a `Func` parameter instead. This allows you to pass a lambda function to your method since there is no way to implicitly convert a lambda to a user-defined type.
- For each invocation to one of the generated overloads, it generates an interceptor method that will be invoked instead. This interceptor method will create an `InspecTree>` object from the `Func` parameter and store the lambda function's syntax tree and semantic model.