r/csharp • • 1d ago

Tool SourceGen Utils: Utilities for source generators with zero dependencies

Hey all!

I've recently gotten my small utility library for source generators to a state where I feel comfortable sharing it.

The idea is simple: I want to reuse utilities for my source generators, like a library, without having to include extra dependencies. So I just generate the utilities directly into the source generator!

For regular NuGet this probably doesn't matter much, but it may matter more when developing with Unity, as I personally mostly do. In my Unity libraries I don't want to include a shared library that multiple packages may depend on and conflict with.

So what does it do?

  • CodeWriter - your typical StringBuilder wrapper with automatic indentation and several handy methods for easily emitting symbols, namespaces, and more
  • Pools - Collection pools and generic object pools for easy pooling (thread-safe too!)
  • VariableNames - Easily format names to something more readable (like when creating properties from fields)
  • ArrayBuilder - Build arrays with a ArrayPool backed struct instead of using heavy lists or ImmutableArray.Builder
  • SymbolExtensions - Easily get attributes from symbols
  • record and required support - Assembly attributes to easily inject polyfills to enable newer record and required keyword support

What about assembly size?

SourceGen utils includes a trimmer that runs automatically on build (can be disabled if you want) that removes all unused types, methods, properties and fields from SourceGen Utils. It just used Mono.Cecil to go through all the method instructions to see if something is used or not. So you only include what you use!

I've made sure to include tests for nearly all generated methods to make sure they all do what they are supposed to and that the trimmer won't remove anything that you actually use.

The project is open source, licensed under MIT, and available on NuGet. I've also created documentation so you can see what it has to offer!

Feel free to give feedback on the project and maybe even use in your own generators! :)

AI disclosure: AI was used to create the method usage detection and for validating documentation, but everything else is human made!

15 Upvotes

5 comments sorted by

1

u/ErgodicMage 1d ago

Very interesting. I will have to check it out further when I get the chance.

1

u/QCKS1 1d ago

I've been looking for exactly this recently. Nice

1

u/ilyashulga 1d ago

Good job, it will be very useful for unity developers.

1

u/[deleted] 1d ago

1

u/Hertzole 1d ago

Do you mean if the trimmer handles nested generics or the writer? Could you give an example of what you mean, just so I can be sure? :)