# SourceGenerators.Shared **Repository Path**: util-core/SourceGenerators.Shared ## Basic Information - **Project Name**: SourceGenerators.Shared - **Description**: 源生成器共享源码包 - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-11-03 - **Last Updated**: 2026-11-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SourceGenerators.Shared [English](README.en.md) · 简体中文 给 Roslyn 源生成器复用的共享源码包。 源码直接注入源生成器项目,不产生运行时程序集依赖。 ## 功能 - **using 管理**:抽取 using 命名空间,避免类型使用完全限定名,并自动处理命名空间冲突。 - **生成源码文件**:输出文件头、命名空间、`using` 块和模块初始化器骨架,分配唯一 `.g.cs` 文件名。 - **名称与字面量处理**:类型名、默认值和配置文本转为合法的 C# 源码文本。 ## 环境要求 - `netstandard2.0` - C# 10+ - `Microsoft.CodeAnalysis.CSharp` 4.8.0+ ## 安装 在**源生成器项目**引用包: ```xml ``` `PrivateAssets="all"` 防止该包进入生成器发布后的依赖。 ## 开发指南 | 类型 | 说明 | | --- | --- | | `ImportScope` | 决定产物里每个类型名怎么写,并给出 `using` 清单。 | | `GeneratedSource` | 把主体包装成完整的 `.cs` 文件。 | | `CompilationIndex` | 索引编译单元的类型与命名空间,供名称判断。 | | `DefaultValueFormatter` | 把默认值、特性实参、配置文本转成 C# 字面量。 | | `HintNameAllocator` | 分配唯一合法的 `.g.cs` 文件名。 | | `TypeNameText` | 类型名字符串的低层处理。 | ### ImportScope 功能:按本次生成用到的类型构建 `using` 清单,短名优先;命名空间冲突时排除冲突方并生成确定性别名。`ForFile` 检查产物文件命名空间外层链上的同名类型,避免遮蔽造成错误绑定。类型引用必须统一经 `Reference` 输出,别名与遮蔽回退才会生效。 **API** - `new ImportScope( index | compilation, frameworkImports, types | fullNames )` — 建域;第二参数是预置 `using`(由调用方提供、不查冲突),第三参数是本次用到的类型或全限定名。 - `Imports` — 含别名的 `using` 清单,直接交给 `GeneratedSource.Wrap`。 - `ForFile( fileNamespace )` — 派生文件作用域,传入产物实际命名空间(私有织入时必须传用户命名空间);全局命名空间传 `""`,不调用则不做遮蔽检查。 - `Reference( type )` / `Reference( fullName )` — 输出无歧义的类型引用名。 - `ReferenceExternal( fullName )` — 未参与建域的外部类型引用。 别名只覆盖简单类型名;泛型、数组与嵌套类型在被排除命名空间下仍输出 `global::` 全限定名。 **示例** ```csharp // 编译单元中 Lib.A 与 Lib.B 都有 Widget var index = CompilationIndex.From( compilation, cancellationToken ); var a = compilation.GetTypeByMetadataName( "Lib.A.Widget" ); var b = compilation.GetTypeByMetadataName( "Lib.B.Widget" ); var scope = new ImportScope( index, new[] { "System" }, new ITypeSymbol[] { a, b } ); scope.Imports; // [ "System", "Lib.A", "LibBWidget = global::Lib.B.Widget" ] scope.Reference( a ); // "Widget" 保留侧用短名 scope.Reference( b ); // "LibBWidget" 被排除侧用别名 // 把 Imports 交给 GeneratedSource.Wrap 后,产物头部: // using System; // using Lib.A; // using LibBWidget = global::Lib.B.Widget; ``` ### GeneratedSource 功能:把主体包装成带文件头、file-scoped namespace 和 `using` 块的完整源码,并提供类型名输出与模块初始化器骨架。`AppendInitializer` 要求产物包含 `System.Runtime.CompilerServices` 且目标框架支持模块初始化器。 **API** - `Wrap( inner, imports, namespaceName )` — 生成完整文件文本,空命名空间表示全局命名空间。 - `AppendImports( builder, imports )` — 单独写入 `using` 块。 - `AppendInitializer( builder, className, classSummary, registerSummary, lines )` — 写入 `internal static class` 与 `[ModuleInitializer]` 注册方法骨架。 - `Full( type )` / `FullDefinition( type )` / `Short( type )` — 全限定名、泛型定义名、短名。 - `Reference( type | fullName, imports )` — 短名优先引用,但不做冲突检测、别名与遮蔽处理;需要这些规则时用 `ImportScope.Reference`。 **示例** ```csharp var text = GeneratedSource.Wrap( "internal class Sample { }", new[] { "System", "Sample.Domain" }, "Sample.Generated" ); // text: // // // namespace Sample.Generated; // // using System; // using Sample.Domain; // // internal class Sample { } var customer = compilation.GetTypeByMetadataName( "Sample.Domain.Customer" ); GeneratedSource.Reference( customer, new[] { "Sample.Domain" } ); // "Customer" GeneratedSource.Reference( customer, new string[0] ); // "global::Sample.Domain.Customer" ``` ### CompilationIndex 功能:遍历当前编译及引用程序集,建立顶层类型与命名空间索引;同一 `Compilation` 实例的结果按 `ConditionalWeakTable` 缓存,可重复调用。索引只收集顶层类型,嵌套类型经外层类型参与判定。 **API** - `From( compilation, cancellationToken )` — 构建或取得缓存索引。 - `TypeExists( metadataName )` — 元数据名在编译单元中唯一存在时返回 `true`。 - `ContainsNamespace( ns )` / `HasNamespaceMember( ns, metadataName )` / `HasSimpleMember( ns, simpleName )` — 命名空间与顶层成员探测。 - `GetNamespaceMembers( ns )` / `GetConflictingNames( namespaces )` — 成员清单、跨命名空间重名类型。 - `AssemblyName` — 当前编译程序集名。 **示例** ```csharp // 编译单元:Sample.Domain.Customer(含嵌套类型 Inner)、Other.Level var index = CompilationIndex.From( compilation, cancellationToken ); index.TypeExists( "Sample.Domain.Customer" ); // true index.TypeExists( "Sample.Domain.Customer.Inner" ); // false,索引只收顶层类型 index.ContainsNamespace( "Sample.Domain" ); // true index.HasNamespaceMember( "Other", "Level" ); // true // Lib.A 与 Lib.B 各有 Widget、Gadget 时 index.GetConflictingNames( new[] { "Lib.A", "Lib.B" } ); // [ "Gadget", "Widget" ] ``` ### DefaultValueFormatter 功能:把参数默认值、特性实参和配置文本输出为合法的 C# 字面量,覆盖枚举、可空类型、浮点特殊值与字符串转义。无法表达时返回 `Omitted`(空串)或 `null`。 **API** - `Format( parameter )` — 无显式默认值返回 `null`;显式 `null` 按值类型/引用类型输出 `default` 或 `null`。 - `Format( text, type )` — 按目标类型解析配置文本,解析失败返回 `null`。 - `Format( TypedConstant )` — 输出特性实参,支持 `typeof(...)`、数组与 `null`。 - `FormatValue( value, type )` — 底层字面量输出。 - `Quote( text )` — 字符串字面量转义。 - `Omitted` — 表示应省略的常量。 **示例** ```csharp // void Run( int count = 42, string name = null, Sample sample = default ) DefaultValueFormatter.Format( method.Parameters[0] ); // "42" DefaultValueFormatter.Format( method.Parameters[1] ); // "null" DefaultValueFormatter.Format( method.Parameters[2] ); // "default" // 配置文本按目标类型解析 DefaultValueFormatter.Format( "High", nullableLevel ); // "( global::Sample.Level )2" // 特性实参 [Sample( typeof( string ), ... )] DefaultValueFormatter.Format( attribute.ConstructorArguments[0] ); // "typeof( string )" DefaultValueFormatter.Quote( "abc" ); // "\"abc\"" ``` ### HintNameAllocator 功能:为 `AddSource` 分配唯一文件名,短名后接 `.g.cs`,非法字符转为下划线,撞名时在扩展名前追加 `_2`、`_3` 序号。构造时可预留固定文件名。 **API** - `new HintNameAllocator( reservedNames )` — 预留已占用的短名。 - `Allocate( shortName )` — 返回唯一文件名。 **示例** ```csharp var allocator = new HintNameAllocator( new[] { "SharedInitializer" } ); allocator.Allocate( "Order" ); // "Order.g.cs" allocator.Allocate( "Order" ); // "Order_2.g.cs" 撞名追加序号 allocator.Allocate( "Sample.Order" ); // "Sample_Order.g.cs" 非法字符转下划线 allocator.Allocate( "SharedInitializer" ); // "SharedInitializer_2.g.cs" 预留名被跳过 ``` ### TypeNameText 功能:类型名字符串的底层处理,包括 `global::` 前缀、数组后缀、泛型实参拆分与尖括号匹配;仅在需要自行解析全限定名时使用。 **API** - `StripGlobal( text )` / `Qualify( text )` — 去掉或补上 `global::`。 - `ArraySuffix( rank )` / `SplitArraySuffix( text, out suffix )` — 生成或拆分数组后缀。 - `SplitTopLevel( body )` / `FindMatchingAngle( text, openIndex )` — 拆分泛型实参、匹配尖括号。 **示例** ```csharp TypeNameText.StripGlobal( "global::A.B" ); // "A.B" TypeNameText.Qualify( "A.B" ); // "global::A.B" TypeNameText.ArraySuffix( 2 ); // "[,]" TypeNameText.SplitArraySuffix( "List[][]", out var suffix ); // "List",suffix 为 "[][]" TypeNameText.SplitTopLevel( "Dictionary, List" ); // [ "Dictionary", "List" ] ``` ## 作者 何镇汐 ## 许可 MIT