Escorp.Atom.SourceGeneration 0.6.6

dotnet add package Escorp.Atom.SourceGeneration --version 0.6.6
                    
NuGet\Install-Package Escorp.Atom.SourceGeneration -Version 0.6.6
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Escorp.Atom.SourceGeneration" Version="0.6.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Escorp.Atom.SourceGeneration" Version="0.6.6" />
                    
Directory.Packages.props
<PackageReference Include="Escorp.Atom.SourceGeneration" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Escorp.Atom.SourceGeneration --version 0.6.6
                    
#r "nuget: Escorp.Atom.SourceGeneration, 0.6.6"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Escorp.Atom.SourceGeneration@0.6.6
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Escorp.Atom.SourceGeneration&version=0.6.6
                    
Install as a Cake Addin
#tool nuget:?package=Escorp.Atom.SourceGeneration&version=0.6.6
                    
Install as a Cake Tool

Atom.SourceGeneration

Модуль Atom.SourceGeneration предоставляет инфраструктуру для создания Roslyn-генераторов исходного кода и анализаторов. Включает универсальные строители кода, базовые классы синтаксических провайдеров и готовые генераторы для часто используемых паттернов.

Возможности

  • SourceBuilder — fluent-API для программной генерации C#-кода
  • Analyzers — инфраструктура Roslyn-анализаторов с унифицированной диагностикой
  • Generators — базовые классы синтаксических провайдеров для инкрементальных генераторов
  • Готовые генераторы:
    • Buffers — генерация фасадов для объектов пула (IPooled)
    • Architect/Components — компонентная модель с событиями присоединения/отсоединения
    • Architect/Reactive — реактивные свойства с INotifyPropertyChanged/INotifyPropertyChanging
    • Text/Json — типизированные контексты сериализации для System.Text.Json

Установка

<PackageReference Include="Escorp.Atom.SourceGeneration" Version="*" />

Быстрый старт

Генерация кода с SourceBuilder

var source = SourceBuilder.Create()
    .WithNamespace("MyProject.Generated")
    .WithUsing("System.Text.Json")
    .WithClass(
        ClassEntity.Create("GeneratedService", AccessModifier.Public)
            .AsPartial()
            .WithProperty<string>("Name")
            .WithMethod(MethodMember.Create("Initialize", AccessModifier.Public)
                .WithCode("Console.WriteLine(\"Initialized\");"))
    )
    .Build(release: true);

Создание собственного генератора

public sealed class MyTypeSyntaxProvider : TypeSyntaxProvider
{
    public MyTypeSyntaxProvider(IncrementalGeneratorInitializationContext ctx)
        : base(ctx) => WithAttribute("MyMarker");

    protected override void OnExecute(
        SourceProductionContext context,
        string entityName,
        ImmutableArray<ISyntaxProviderInfo<ITypeSymbol, TypeDeclarationSyntax>> sources)
    {
        var src = SourceBuilder.Create()
            .WithNamespace(sources[0].Symbol?.ContainingNamespace.ToDisplayString())
            .WithClass(ClassEntity.Create(entityName).AsPartial()
                .WithMethod(MethodMember.Create("GeneratedMethod")))
            .Build(release: true);

        if (!string.IsNullOrEmpty(src))
            context.AddSource($"{entityName}.g.cs", SourceText.From(src, Encoding.UTF8));
    }
}

[Generator]
public sealed class MyGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
        => context.UseProvider(new MyTypeSyntaxProvider(context));
}

Использование готовых генераторов

Pooled (буферизация объектов)
[Pooled]
public partial class DataBuffer : IPooled
{
    private byte[] _data = new byte[1024];

    public void Reset() => Array.Clear(_data);
}

// Использование:
var buffer = DataBuffer.Rent();
// ... работа с буфером ...
DataBuffer.Return(buffer);
Reactive (реактивные свойства)
public partial class ViewModel
{
    [Reactively]
    private string _title = string.Empty;

    [Reactively(PropertyName = "FullName", IsVirtual = true)]
    private string _name = string.Empty;
}

// Генерируются свойства Title и FullName с событиями PropertyChanging/PropertyChanged
Component (компонентная модель)
[Component]
public partial class HealthComponent
{
    public int CurrentHealth { get; set; }
}

[ComponentOwner]
public partial class Entity
{
    // Генерируются методы Use<T>(), UnUse<T>(), Has<T>(), TryGet<T>()
}
JsonContext (типизированная сериализация)
[JsonContext(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
public partial class UserDto
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Использование:
var json = user.Serialize();
var restored = UserDto.Deserialize(json);

Архитектура

Atom.SourceGeneration/
├── Analyzers/           # Базовые классы анализаторов
├── Generators/          # Синтаксические провайдеры
├── SourceBuilder/       # Строители кода
│   └── Entities/        # Классы, интерфейсы, методы, свойства и т.д.
├── Architect/           # Генераторы архитектурных паттернов
│   ├── Components/      # Компонентная модель
│   └── Reactive/        # Реактивные свойства
├── Buffers/             # Генератор пулов объектов
└── Text/                # Текстовые генераторы
    └── Json/            # JSON-контексты

Ключевые типы

SourceBuilder

Тип Описание
SourceBuilder Главный строитель исходного кода
ClassEntity Строитель класса
InterfaceEntity Строитель интерфейса
EnumEntity Строитель перечисления
FieldMember Строитель поля
PropertyMember Строитель свойства
MethodMember Строитель метода
EventMember Строитель события
GenericEntity Строитель параметра типа

Синтаксические провайдеры

Тип Описание
TypeSyntaxProvider Провайдер для типов (class, struct, interface)
FieldSyntaxProvider Провайдер для полей
MethodSyntaxProvider Провайдер для методов

Анализаторы

Тип Описание
SourceAnalyzer<T> Базовый анализатор с автоматической регистрацией
AttributeAnalyzerSyntaxProvider Провайдер анализа атрибутов

Диагностика

ID Severity Описание
A0001 Hidden Обнаружен маркерный атрибут
A1000 Error Необработанное исключение в генераторе

Пулы объектов

Все строители используют ObjectPool<T> для минимизации аллокаций. Вызывайте Build(release: true) для автоматического возврата объектов в пул:

// Правильно - объекты возвращаются в пул
var source = SourceBuilder.Create()
    .WithClass(ClassEntity.Create("Test"))
    .Build(release: true);

// Если release: false, вызовите Release() вручную
var builder = SourceBuilder.Create();
var source = builder.Build();
// ... использование source ...
builder.Release();

Тестирование генераторов

[Test]
public async Task GeneratorTestAsync()
{
    var test = new CSharpSourceGeneratorTest<MyGenerator, DefaultVerifier>
    {
        TestState =
        {
            ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
            Sources = { sourceCode },
            GeneratedSources = { (typeof(MyGenerator), "Output.g.cs", expectedOutput) },
            AdditionalReferences =
            {
                MetadataReference.CreateFromFile(typeof(MyAttribute).Assembly.Location),
            },
        }
    };

    await test.RunAsync();
}

Ссылки

  • Analyzers — инфраструктура анализаторов
  • Generators — синтаксические провайдеры
  • SourceBuilder — строители кода
  • Buffers — генератор пулов
  • Architect — архитектурные генераторы
  • Text — текстовые генераторы
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.6.6 259 4/3/2026
0.6.5 126 3/11/2026
0.6.4 126 3/11/2026
0.6.3 122 3/11/2026
0.6.2 131 2/1/2026
0.6.1 121 2/1/2026
0.6.0 126 2/1/2026
0.5.9 124 2/1/2026
0.5.8 214 12/5/2025
0.5.7 137 11/30/2025
0.5.6 263 11/14/2025
0.5.5 245 11/14/2025
0.5.4 253 11/14/2025
0.5.3 256 11/14/2025
0.5.2 303 11/13/2025
0.5.1 190 10/12/2025
0.5.0 195 9/5/2025
0.4.10 199 9/5/2025
0.4.9 195 9/5/2025
0.4.8 243 4/7/2025
Loading failed