| | | 1 | | // Copyright (c) NexusLabs. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System.Collections.Immutable; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.Linq; |
| | | 7 | | using System.Text; |
| | | 8 | | using System.Threading; |
| | | 9 | | |
| | | 10 | | using Microsoft.CodeAnalysis; |
| | | 11 | | using Microsoft.CodeAnalysis.CSharp; |
| | | 12 | | using Microsoft.CodeAnalysis.CSharp.Syntax; |
| | | 13 | | |
| | | 14 | | namespace NexusLabs.Needlr.AgentFramework.Generators; |
| | | 15 | | |
| | | 16 | | internal static class AgentDiscoveryHelper |
| | | 17 | | { |
| | | 18 | | private const string AgentFunctionAttributeName = "NexusLabs.Needlr.AgentFramework.AgentFunctionAttribute"; |
| | | 19 | | private const string AgentFunctionGroupAttributeName = "NexusLabs.Needlr.AgentFramework.AgentFunctionGroupAttribute" |
| | | 20 | | |
| | | 21 | | public static AgentFunctionTypeInfo? GetAgentFunctionTypeInfo( |
| | | 22 | | GeneratorSyntaxContext context, |
| | | 23 | | CancellationToken cancellationToken) |
| | | 24 | | { |
| | 2675 | 25 | | var classDeclaration = (ClassDeclarationSyntax)context.Node; |
| | 2675 | 26 | | var typeSymbol = context.SemanticModel |
| | 2675 | 27 | | .GetDeclaredSymbol(classDeclaration, cancellationToken) as INamedTypeSymbol; |
| | | 28 | | |
| | 2675 | 29 | | if (typeSymbol is null) |
| | 0 | 30 | | return null; |
| | | 31 | | |
| | 2675 | 32 | | return TryGetTypeInfo(typeSymbol); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | public static AgentFunctionTypeInfo? TryGetTypeInfo(INamedTypeSymbol typeSymbol) |
| | | 36 | | { |
| | 2675 | 37 | | if (typeSymbol.TypeKind != TypeKind.Class) |
| | 0 | 38 | | return null; |
| | | 39 | | |
| | 2675 | 40 | | if (!IsAccessibleFromGeneratedCode(typeSymbol)) |
| | 0 | 41 | | return null; |
| | | 42 | | |
| | 2675 | 43 | | if (!typeSymbol.IsStatic && typeSymbol.IsAbstract) |
| | 0 | 44 | | return null; |
| | | 45 | | |
| | 2675 | 46 | | bool hasAgentFunction = false; |
| | 31003 | 47 | | foreach (var member in typeSymbol.GetMembers()) |
| | | 48 | | { |
| | 12855 | 49 | | if (member is not IMethodSymbol method) |
| | | 50 | | continue; |
| | | 51 | | |
| | 7285 | 52 | | if (method.MethodKind != MethodKind.Ordinary) |
| | | 53 | | continue; |
| | | 54 | | |
| | 615 | 55 | | if (method.DeclaredAccessibility != Accessibility.Public) |
| | | 56 | | continue; |
| | | 57 | | |
| | 1287 | 58 | | foreach (var attribute in method.GetAttributes()) |
| | | 59 | | { |
| | 57 | 60 | | if (attribute.AttributeClass?.ToDisplayString() == AgentFunctionAttributeName) |
| | | 61 | | { |
| | 57 | 62 | | hasAgentFunction = true; |
| | 57 | 63 | | break; |
| | | 64 | | } |
| | | 65 | | } |
| | | 66 | | |
| | 615 | 67 | | if (hasAgentFunction) |
| | | 68 | | break; |
| | | 69 | | } |
| | | 70 | | |
| | 2675 | 71 | | if (!hasAgentFunction) |
| | 2618 | 72 | | return null; |
| | | 73 | | |
| | 57 | 74 | | var methodInfos = ImmutableArray.CreateBuilder<AgentFunctionMethodInfo>(); |
| | 338 | 75 | | foreach (var member in typeSymbol.GetMembers()) |
| | | 76 | | { |
| | 112 | 77 | | if (member is not IMethodSymbol method) |
| | | 78 | | continue; |
| | | 79 | | |
| | 112 | 80 | | if (method.MethodKind != MethodKind.Ordinary) |
| | | 81 | | continue; |
| | | 82 | | |
| | 57 | 83 | | if (method.DeclaredAccessibility != Accessibility.Public) |
| | | 84 | | continue; |
| | | 85 | | |
| | 57 | 86 | | bool isAgentFunction = false; |
| | 171 | 87 | | foreach (var attribute in method.GetAttributes()) |
| | | 88 | | { |
| | 57 | 89 | | if (attribute.AttributeClass?.ToDisplayString() == AgentFunctionAttributeName) |
| | | 90 | | { |
| | 57 | 91 | | isAgentFunction = true; |
| | 57 | 92 | | break; |
| | | 93 | | } |
| | | 94 | | } |
| | | 95 | | |
| | 57 | 96 | | if (!isAgentFunction) |
| | | 97 | | continue; |
| | | 98 | | |
| | 57 | 99 | | var returnType = method.ReturnType; |
| | 57 | 100 | | bool isVoid = returnType.SpecialType == SpecialType.System_Void; |
| | 57 | 101 | | bool isTask = returnType is INamedTypeSymbol nt && |
| | 57 | 102 | | nt.ContainingNamespace?.ToDisplayString() == "System.Threading.Tasks" && |
| | 57 | 103 | | (nt.MetadataName == "Task" || nt.MetadataName == "ValueTask"); |
| | 57 | 104 | | bool isTaskOfT = returnType is INamedTypeSymbol nt2 && |
| | 57 | 105 | | nt2.ContainingNamespace?.ToDisplayString() == "System.Threading.Tasks" && |
| | 57 | 106 | | (nt2.MetadataName == "Task`1" || nt2.MetadataName == "ValueTask`1") && |
| | 57 | 107 | | nt2.TypeArguments.Length == 1; |
| | 57 | 108 | | bool isAsync = isTask || isTaskOfT; |
| | 57 | 109 | | bool isVoidLike = isVoid || isTask; |
| | 57 | 110 | | string? returnValueTypeFQN = isVoidLike ? null : isTaskOfT |
| | 57 | 111 | | ? GetFullyQualifiedName(((INamedTypeSymbol)returnType).TypeArguments[0]) |
| | 57 | 112 | | : GetFullyQualifiedName(returnType); |
| | | 113 | | |
| | 57 | 114 | | string? returnJsonSchemaType = null; |
| | 57 | 115 | | string? returnObjectSchemaJson = null; |
| | 57 | 116 | | if (!isVoidLike) |
| | | 117 | | { |
| | 53 | 118 | | var unwrappedReturnType = isTaskOfT |
| | 53 | 119 | | ? ((INamedTypeSymbol)returnType).TypeArguments[0] |
| | 53 | 120 | | : returnType; |
| | 53 | 121 | | returnJsonSchemaType = GetJsonSchemaType(unwrappedReturnType, out _); |
| | 53 | 122 | | if (returnJsonSchemaType == "object") |
| | | 123 | | { |
| | 1 | 124 | | returnObjectSchemaJson = BuildObjectSchemaJson(unwrappedReturnType); |
| | | 125 | | } |
| | | 126 | | } |
| | | 127 | | |
| | 57 | 128 | | string? methodDesc = GetDescriptionFromAttributes(method.GetAttributes()); |
| | | 129 | | |
| | 57 | 130 | | var parameters = ImmutableArray.CreateBuilder<AgentFunctionParameterInfo>(); |
| | 224 | 131 | | foreach (var param in method.Parameters) |
| | | 132 | | { |
| | 55 | 133 | | bool isCancellationToken = param.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == "glob |
| | 55 | 134 | | bool isNullable = param.NullableAnnotation == NullableAnnotation.Annotated || |
| | 55 | 135 | | (param.Type is INamedTypeSymbol pnt && pnt.ConstructedFrom.SpecialType == SpecialType.System_Nullabl |
| | 55 | 136 | | bool hasDefault = param.HasExplicitDefaultValue; |
| | 55 | 137 | | string? defaultLiteral = hasDefault |
| | 55 | 138 | | ? ConvertToCSharpLiteral(param.ExplicitDefaultValue, param.Type) |
| | 55 | 139 | | : null; |
| | 55 | 140 | | bool isEnum = param.Type.TypeKind == TypeKind.Enum || |
| | 55 | 141 | | (param.Type is INamedTypeSymbol enumNullable && |
| | 55 | 142 | | enumNullable.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T && |
| | 55 | 143 | | enumNullable.TypeArguments.Length == 1 && |
| | 55 | 144 | | enumNullable.TypeArguments[0].TypeKind == TypeKind.Enum); |
| | 55 | 145 | | string? paramDesc = GetDescriptionFromAttributes(param.GetAttributes()); |
| | 55 | 146 | | string jsonSchemaType = GetJsonSchemaType(param.Type, out string? itemJsonSchemaType); |
| | 55 | 147 | | string? jsonSchemaFormat = GetJsonSchemaFormat(param.Type); |
| | 55 | 148 | | string typeFullName = GetFullyQualifiedName(param.Type); |
| | | 149 | | |
| | | 150 | | // Build object schema for complex array items (e.g., FaqEntry[] → properties of FaqEntry) |
| | 55 | 151 | | string? itemObjectSchemaJson = null; |
| | 55 | 152 | | IReadOnlyList<ObjectPropertyInfo>? itemObjectProperties = null; |
| | 55 | 153 | | if (jsonSchemaType == "array" && itemJsonSchemaType == "object") |
| | | 154 | | { |
| | 5 | 155 | | ITypeSymbol? elementType = null; |
| | 5 | 156 | | if (param.Type is IArrayTypeSymbol arrSym) |
| | 5 | 157 | | elementType = arrSym.ElementType; |
| | 0 | 158 | | else if (param.Type is INamedTypeSymbol namedSym && namedSym.IsGenericType && namedSym.TypeArguments |
| | 0 | 159 | | elementType = namedSym.TypeArguments[0]; |
| | | 160 | | |
| | 5 | 161 | | if (elementType != null) |
| | | 162 | | { |
| | 5 | 163 | | itemObjectSchemaJson = BuildObjectSchemaJson(elementType); |
| | 5 | 164 | | itemObjectProperties = BuildObjectPropertyInfos(elementType); |
| | | 165 | | } |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | // Build object schema for top-level complex DTO parameters (e.g., MyDto dto). |
| | | 169 | | // Same machinery as array items but applied to the parameter type itself — |
| | | 170 | | // gives the LLM a proper {"type":"object","properties":{…},"required":[…]} |
| | | 171 | | // schema and lets the wrapper extract per-property via TryGetProperty + helper |
| | | 172 | | // calls instead of the broken as-cast that silently returns default(MyDto). |
| | 55 | 173 | | string? objectSchemaJson = null; |
| | 55 | 174 | | IReadOnlyList<ObjectPropertyInfo>? objectProperties = null; |
| | 55 | 175 | | if (jsonSchemaType == "object") |
| | | 176 | | { |
| | 5 | 177 | | var dtoType = param.Type; |
| | 5 | 178 | | if (dtoType is INamedTypeSymbol dtoNullable && dtoNullable.ConstructedFrom.SpecialType == SpecialTyp |
| | 0 | 179 | | dtoType = dtoNullable.TypeArguments[0]; |
| | 5 | 180 | | objectSchemaJson = BuildObjectSchemaJson(dtoType); |
| | 5 | 181 | | objectProperties = BuildObjectPropertyInfos(dtoType); |
| | | 182 | | } |
| | | 183 | | |
| | 55 | 184 | | parameters.Add(new AgentFunctionParameterInfo( |
| | 55 | 185 | | param.Name, typeFullName, jsonSchemaType, jsonSchemaFormat, itemJsonSchemaType, |
| | 55 | 186 | | itemObjectSchemaJson, itemObjectProperties, |
| | 55 | 187 | | objectSchemaJson, objectProperties, |
| | 55 | 188 | | isCancellationToken, isNullable, hasDefault, defaultLiteral, isEnum, paramDesc)); |
| | | 189 | | } |
| | | 190 | | |
| | 57 | 191 | | methodInfos.Add(new AgentFunctionMethodInfo( |
| | 57 | 192 | | method.Name, isAsync, isVoidLike, returnValueTypeFQN, |
| | 57 | 193 | | returnJsonSchemaType, returnObjectSchemaJson, |
| | 57 | 194 | | parameters.ToImmutable(), methodDesc ?? "")); |
| | | 195 | | } |
| | | 196 | | |
| | 57 | 197 | | return new AgentFunctionTypeInfo( |
| | 57 | 198 | | GetFullyQualifiedName(typeSymbol), |
| | 57 | 199 | | typeSymbol.ContainingAssembly?.Name ?? "Unknown", |
| | 57 | 200 | | typeSymbol.IsStatic, |
| | 57 | 201 | | methodInfos.ToImmutable()); |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | public static ImmutableArray<AgentFunctionGroupEntry> GetAgentFunctionGroupEntries( |
| | | 205 | | GeneratorSyntaxContext context, |
| | | 206 | | CancellationToken cancellationToken) |
| | | 207 | | { |
| | 2675 | 208 | | var classDeclaration = (ClassDeclarationSyntax)context.Node; |
| | 2675 | 209 | | var typeSymbol = context.SemanticModel |
| | 2675 | 210 | | .GetDeclaredSymbol(classDeclaration, cancellationToken) as INamedTypeSymbol; |
| | | 211 | | |
| | 2675 | 212 | | if (typeSymbol is null || !IsAccessibleFromGeneratedCode(typeSymbol)) |
| | 0 | 213 | | return ImmutableArray<AgentFunctionGroupEntry>.Empty; |
| | | 214 | | |
| | 2675 | 215 | | var entries = ImmutableArray.CreateBuilder<AgentFunctionGroupEntry>(); |
| | | 216 | | |
| | 9174 | 217 | | foreach (var attr in typeSymbol.GetAttributes()) |
| | | 218 | | { |
| | 1912 | 219 | | if (attr.AttributeClass?.ToDisplayString() != AgentFunctionGroupAttributeName) |
| | | 220 | | continue; |
| | | 221 | | |
| | 51 | 222 | | if (attr.ConstructorArguments.Length != 1) |
| | | 223 | | continue; |
| | | 224 | | |
| | 51 | 225 | | var groupName = attr.ConstructorArguments[0].Value as string; |
| | 51 | 226 | | if (string.IsNullOrWhiteSpace(groupName)) |
| | | 227 | | continue; |
| | | 228 | | |
| | 51 | 229 | | entries.Add(new AgentFunctionGroupEntry(GetFullyQualifiedName(typeSymbol), groupName!)); |
| | | 230 | | } |
| | | 231 | | |
| | 2675 | 232 | | return entries.ToImmutable(); |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | public static NeedlrAiAgentTypeInfo? GetNeedlrAiAgentTypeInfo( |
| | | 236 | | GeneratorAttributeSyntaxContext context, |
| | | 237 | | CancellationToken cancellationToken) |
| | | 238 | | { |
| | 107 | 239 | | var typeSymbol = context.TargetSymbol as INamedTypeSymbol; |
| | 107 | 240 | | if (typeSymbol is null || !IsAccessibleFromGeneratedCode(typeSymbol)) |
| | 0 | 241 | | return null; |
| | | 242 | | |
| | 107 | 243 | | var classDeclaration = context.TargetNode as ClassDeclarationSyntax; |
| | 225 | 244 | | var isPartial = classDeclaration?.Modifiers.Any(m => m.ValueText == "partial") ?? false; |
| | | 245 | | |
| | 107 | 246 | | var namespaceName = typeSymbol.ContainingNamespace?.IsGlobalNamespace == true |
| | 107 | 247 | | ? null |
| | 107 | 248 | | : typeSymbol.ContainingNamespace?.ToDisplayString(); |
| | | 249 | | |
| | 107 | 250 | | var functionGroupNames = ImmutableArray<string>.Empty; |
| | 107 | 251 | | var explicitFunctionTypeFQNs = ImmutableArray<string>.Empty; |
| | 107 | 252 | | var hasExplicitFunctionTypes = false; |
| | | 253 | | |
| | 107 | 254 | | var agentAttr = context.Attributes.FirstOrDefault(); |
| | 107 | 255 | | if (agentAttr is not null) |
| | | 256 | | { |
| | 117 | 257 | | var groupsArg = agentAttr.NamedArguments.FirstOrDefault(a => a.Key == "FunctionGroups"); |
| | 107 | 258 | | if (groupsArg.Key is not null && groupsArg.Value.Kind == TypedConstantKind.Array) |
| | | 259 | | { |
| | 2 | 260 | | functionGroupNames = groupsArg.Value.Values |
| | 2 | 261 | | .Select(v => v.Value as string) |
| | 2 | 262 | | .Where(s => !string.IsNullOrWhiteSpace(s)) |
| | 2 | 263 | | .Select(s => s!) |
| | 2 | 264 | | .ToImmutableArray(); |
| | | 265 | | } |
| | | 266 | | |
| | 117 | 267 | | var typesArg = agentAttr.NamedArguments.FirstOrDefault(a => a.Key == "FunctionTypes"); |
| | 107 | 268 | | if (typesArg.Key is not null && typesArg.Value.Kind == TypedConstantKind.Array) |
| | | 269 | | { |
| | 2 | 270 | | hasExplicitFunctionTypes = true; |
| | 2 | 271 | | explicitFunctionTypeFQNs = typesArg.Value.Values |
| | 1 | 272 | | .Where(v => v.Kind == TypedConstantKind.Type && v.Value is INamedTypeSymbol) |
| | 1 | 273 | | .Select(v => GetFullyQualifiedName((INamedTypeSymbol)v.Value!)) |
| | 2 | 274 | | .ToImmutableArray(); |
| | | 275 | | } |
| | | 276 | | } |
| | | 277 | | |
| | 107 | 278 | | return new NeedlrAiAgentTypeInfo( |
| | 107 | 279 | | GetFullyQualifiedName(typeSymbol), |
| | 107 | 280 | | typeSymbol.Name, |
| | 107 | 281 | | namespaceName, |
| | 107 | 282 | | isPartial, |
| | 107 | 283 | | functionGroupNames, |
| | 107 | 284 | | explicitFunctionTypeFQNs, |
| | 107 | 285 | | hasExplicitFunctionTypes); |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | public static ImmutableArray<HandoffEntry> GetHandoffEntries( |
| | | 289 | | GeneratorAttributeSyntaxContext context, |
| | | 290 | | CancellationToken cancellationToken) |
| | | 291 | | { |
| | 5 | 292 | | var typeSymbol = context.TargetSymbol as INamedTypeSymbol; |
| | 5 | 293 | | if (typeSymbol is null || !IsAccessibleFromGeneratedCode(typeSymbol)) |
| | 0 | 294 | | return ImmutableArray<HandoffEntry>.Empty; |
| | | 295 | | |
| | 5 | 296 | | var initialTypeName = GetFullyQualifiedName(typeSymbol); |
| | 5 | 297 | | var entries = ImmutableArray.CreateBuilder<HandoffEntry>(); |
| | | 298 | | |
| | 20 | 299 | | foreach (var attr in context.Attributes) |
| | | 300 | | { |
| | 5 | 301 | | if (attr.ConstructorArguments.Length < 1) |
| | | 302 | | continue; |
| | | 303 | | |
| | 5 | 304 | | var typeArg = attr.ConstructorArguments[0]; |
| | 5 | 305 | | if (typeArg.Kind != TypedConstantKind.Type || typeArg.Value is not INamedTypeSymbol targetTypeSymbol) |
| | | 306 | | continue; |
| | | 307 | | |
| | 5 | 308 | | var targetTypeName = GetFullyQualifiedName(targetTypeSymbol); |
| | 5 | 309 | | var reason = attr.ConstructorArguments.Length > 1 ? attr.ConstructorArguments[1].Value as string : null; |
| | | 310 | | |
| | 5 | 311 | | entries.Add(new HandoffEntry(initialTypeName, typeSymbol.Name, targetTypeName, reason)); |
| | | 312 | | } |
| | | 313 | | |
| | 5 | 314 | | return entries.ToImmutable(); |
| | | 315 | | } |
| | | 316 | | |
| | | 317 | | public static ImmutableArray<GroupChatEntry> GetGroupChatEntries( |
| | | 318 | | GeneratorAttributeSyntaxContext context, |
| | | 319 | | CancellationToken cancellationToken) |
| | | 320 | | { |
| | 8 | 321 | | var typeSymbol = context.TargetSymbol as INamedTypeSymbol; |
| | 8 | 322 | | if (typeSymbol is null || !IsAccessibleFromGeneratedCode(typeSymbol)) |
| | 0 | 323 | | return ImmutableArray<GroupChatEntry>.Empty; |
| | | 324 | | |
| | 8 | 325 | | var agentTypeName = GetFullyQualifiedName(typeSymbol); |
| | 8 | 326 | | var entries = ImmutableArray.CreateBuilder<GroupChatEntry>(); |
| | | 327 | | |
| | 32 | 328 | | foreach (var attr in context.Attributes) |
| | | 329 | | { |
| | 8 | 330 | | if (attr.ConstructorArguments.Length < 1) |
| | | 331 | | continue; |
| | | 332 | | |
| | 8 | 333 | | var groupName = attr.ConstructorArguments[0].Value as string; |
| | 8 | 334 | | if (string.IsNullOrWhiteSpace(groupName)) |
| | | 335 | | continue; |
| | | 336 | | |
| | 8 | 337 | | var order = 0; |
| | 16 | 338 | | foreach (var named in attr.NamedArguments) |
| | | 339 | | { |
| | 0 | 340 | | if (named.Key == "Order" && named.Value.Value is int orderValue) |
| | | 341 | | { |
| | 0 | 342 | | order = orderValue; |
| | 0 | 343 | | break; |
| | | 344 | | } |
| | | 345 | | } |
| | | 346 | | |
| | 8 | 347 | | entries.Add(new GroupChatEntry(agentTypeName, groupName!, order)); |
| | | 348 | | } |
| | | 349 | | |
| | 8 | 350 | | return entries.ToImmutable(); |
| | | 351 | | } |
| | | 352 | | |
| | | 353 | | public static ImmutableArray<SequenceEntry> GetSequenceEntries( |
| | | 354 | | GeneratorAttributeSyntaxContext context, |
| | | 355 | | CancellationToken cancellationToken) |
| | | 356 | | { |
| | 24 | 357 | | var typeSymbol = context.TargetSymbol as INamedTypeSymbol; |
| | 24 | 358 | | if (typeSymbol is null || !IsAccessibleFromGeneratedCode(typeSymbol)) |
| | 0 | 359 | | return ImmutableArray<SequenceEntry>.Empty; |
| | | 360 | | |
| | 24 | 361 | | var agentTypeName = GetFullyQualifiedName(typeSymbol); |
| | 24 | 362 | | var entries = ImmutableArray.CreateBuilder<SequenceEntry>(); |
| | | 363 | | |
| | 96 | 364 | | foreach (var attr in context.Attributes) |
| | | 365 | | { |
| | 24 | 366 | | if (attr.ConstructorArguments.Length < 2) |
| | | 367 | | continue; |
| | | 368 | | |
| | 24 | 369 | | var pipelineName = attr.ConstructorArguments[0].Value as string; |
| | 24 | 370 | | if (string.IsNullOrWhiteSpace(pipelineName)) |
| | | 371 | | continue; |
| | | 372 | | |
| | 24 | 373 | | if (attr.ConstructorArguments[1].Value is not int order) |
| | | 374 | | continue; |
| | | 375 | | |
| | 24 | 376 | | entries.Add(new SequenceEntry(agentTypeName, pipelineName!, order)); |
| | | 377 | | } |
| | | 378 | | |
| | 24 | 379 | | return entries.ToImmutable(); |
| | | 380 | | } |
| | | 381 | | |
| | | 382 | | public static ImmutableArray<TerminationConditionEntry> GetTerminationConditionEntries( |
| | | 383 | | GeneratorAttributeSyntaxContext context, |
| | | 384 | | CancellationToken cancellationToken) |
| | | 385 | | { |
| | 8 | 386 | | var typeSymbol = context.TargetSymbol as INamedTypeSymbol; |
| | 8 | 387 | | if (typeSymbol is null || !IsAccessibleFromGeneratedCode(typeSymbol)) |
| | 0 | 388 | | return ImmutableArray<TerminationConditionEntry>.Empty; |
| | | 389 | | |
| | 8 | 390 | | var agentTypeName = GetFullyQualifiedName(typeSymbol); |
| | 8 | 391 | | var entries = ImmutableArray.CreateBuilder<TerminationConditionEntry>(); |
| | | 392 | | |
| | 32 | 393 | | foreach (var attr in context.Attributes) |
| | | 394 | | { |
| | 8 | 395 | | if (attr.ConstructorArguments.Length < 1) |
| | | 396 | | continue; |
| | | 397 | | |
| | 8 | 398 | | var typeArg = attr.ConstructorArguments[0]; |
| | 8 | 399 | | if (typeArg.Kind != TypedConstantKind.Type || typeArg.Value is not INamedTypeSymbol condTypeSymbol) |
| | | 400 | | continue; |
| | | 401 | | |
| | 8 | 402 | | var condTypeFQN = GetFullyQualifiedName(condTypeSymbol); |
| | 8 | 403 | | var ctorArgLiterals = ImmutableArray<string>.Empty; |
| | | 404 | | |
| | 8 | 405 | | if (attr.ConstructorArguments.Length > 1) |
| | | 406 | | { |
| | 8 | 407 | | var paramsArg = attr.ConstructorArguments[1]; |
| | 8 | 408 | | if (paramsArg.Kind == TypedConstantKind.Array) |
| | | 409 | | { |
| | 8 | 410 | | ctorArgLiterals = paramsArg.Values |
| | 8 | 411 | | .Select(SerializeTypedConstant) |
| | 8 | 412 | | .Where(s => s is not null) |
| | 8 | 413 | | .Select(s => s!) |
| | 8 | 414 | | .ToImmutableArray(); |
| | | 415 | | } |
| | | 416 | | } |
| | | 417 | | |
| | 8 | 418 | | entries.Add(new TerminationConditionEntry(agentTypeName, condTypeFQN, ctorArgLiterals)); |
| | | 419 | | } |
| | | 420 | | |
| | 8 | 421 | | return entries.ToImmutable(); |
| | | 422 | | } |
| | | 423 | | |
| | | 424 | | public static string? SerializeTypedConstant(TypedConstant constant) |
| | | 425 | | { |
| | 8 | 426 | | return constant.Kind switch |
| | 8 | 427 | | { |
| | 8 | 428 | | TypedConstantKind.Primitive when constant.Value is string s => |
| | 8 | 429 | | "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"", |
| | 0 | 430 | | TypedConstantKind.Primitive when constant.Value is int i => i.ToString(), |
| | 0 | 431 | | TypedConstantKind.Primitive when constant.Value is long l => l.ToString() + "L", |
| | 0 | 432 | | TypedConstantKind.Primitive when constant.Value is bool b => b ? "true" : "false", |
| | 0 | 433 | | TypedConstantKind.Primitive when constant.Value is null => "null", |
| | 0 | 434 | | TypedConstantKind.Type when constant.Value is ITypeSymbol ts => |
| | 0 | 435 | | $"typeof({GetFullyQualifiedName(ts)})", |
| | 0 | 436 | | _ => null, |
| | 8 | 437 | | }; |
| | | 438 | | } |
| | | 439 | | |
| | | 440 | | public static ImmutableArray<ProgressSinksEntry> GetProgressSinksEntries( |
| | | 441 | | GeneratorAttributeSyntaxContext context, |
| | | 442 | | CancellationToken cancellationToken) |
| | | 443 | | { |
| | 4 | 444 | | var typeSymbol = context.TargetSymbol as INamedTypeSymbol; |
| | 4 | 445 | | if (typeSymbol is null || !IsAccessibleFromGeneratedCode(typeSymbol)) |
| | 0 | 446 | | return ImmutableArray<ProgressSinksEntry>.Empty; |
| | | 447 | | |
| | 4 | 448 | | var agentTypeName = GetFullyQualifiedName(typeSymbol); |
| | | 449 | | |
| | 12 | 450 | | foreach (var attr in context.Attributes) |
| | | 451 | | { |
| | | 452 | | // params Type[] is a single constructor arg of TypedConstantKind.Array |
| | 4 | 453 | | if (attr.ConstructorArguments.Length < 1) |
| | | 454 | | continue; |
| | | 455 | | |
| | 4 | 456 | | var firstArg = attr.ConstructorArguments[0]; |
| | 4 | 457 | | if (firstArg.Kind != TypedConstantKind.Array) |
| | | 458 | | continue; |
| | | 459 | | |
| | 4 | 460 | | var sinkFQNs = ImmutableArray.CreateBuilder<string>(); |
| | 16 | 461 | | foreach (var element in firstArg.Values) |
| | | 462 | | { |
| | 4 | 463 | | if (element.Kind == TypedConstantKind.Type && element.Value is INamedTypeSymbol sinkType) |
| | | 464 | | { |
| | 4 | 465 | | sinkFQNs.Add(GetFullyQualifiedName(sinkType)); |
| | | 466 | | } |
| | | 467 | | } |
| | | 468 | | |
| | 4 | 469 | | if (sinkFQNs.Count > 0) |
| | | 470 | | { |
| | 4 | 471 | | return ImmutableArray.Create( |
| | 4 | 472 | | new ProgressSinksEntry(agentTypeName, typeSymbol.Name, sinkFQNs.ToImmutable())); |
| | | 473 | | } |
| | | 474 | | } |
| | | 475 | | |
| | 0 | 476 | | return ImmutableArray<ProgressSinksEntry>.Empty; |
| | | 477 | | } |
| | | 478 | | |
| | | 479 | | public static string? GetDescriptionFromAttributes(ImmutableArray<AttributeData> attributes) |
| | | 480 | | { |
| | 349 | 481 | | foreach (var attr in attributes) |
| | | 482 | | { |
| | 68 | 483 | | if (attr.AttributeClass?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == |
| | 68 | 484 | | "global::System.ComponentModel.DescriptionAttribute" && |
| | 68 | 485 | | attr.ConstructorArguments.Length == 1 && |
| | 68 | 486 | | attr.ConstructorArguments[0].Value is string desc) |
| | 11 | 487 | | return desc; |
| | | 488 | | } |
| | 101 | 489 | | return null; |
| | | 490 | | } |
| | | 491 | | |
| | | 492 | | public static string GetJsonSchemaType(ITypeSymbol type, out string? itemType) |
| | | 493 | | { |
| | 166 | 494 | | itemType = null; |
| | 166 | 495 | | if (type is INamedTypeSymbol nullable && nullable.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T) |
| | 2 | 496 | | type = nullable.TypeArguments[0]; |
| | | 497 | | |
| | 166 | 498 | | switch (type.SpecialType) |
| | | 499 | | { |
| | 84 | 500 | | case SpecialType.System_String: return "string"; |
| | 11 | 501 | | case SpecialType.System_Boolean: return "boolean"; |
| | | 502 | | case SpecialType.System_Byte: |
| | | 503 | | case SpecialType.System_SByte: |
| | | 504 | | case SpecialType.System_Int16: |
| | | 505 | | case SpecialType.System_UInt16: |
| | | 506 | | case SpecialType.System_Int32: |
| | | 507 | | case SpecialType.System_UInt32: |
| | | 508 | | case SpecialType.System_Int64: |
| | 23 | 509 | | case SpecialType.System_UInt64: return "integer"; |
| | | 510 | | case SpecialType.System_Single: |
| | | 511 | | case SpecialType.System_Double: |
| | 8 | 512 | | case SpecialType.System_Decimal: return "number"; |
| | 6 | 513 | | case SpecialType.System_DateTime: return "string"; |
| | | 514 | | } |
| | | 515 | | |
| | 34 | 516 | | if (type is IArrayTypeSymbol arrayType) |
| | | 517 | | { |
| | 8 | 518 | | itemType = GetJsonSchemaType(arrayType.ElementType, out _); |
| | 8 | 519 | | if (string.IsNullOrEmpty(itemType)) |
| | 0 | 520 | | itemType = "object"; |
| | 8 | 521 | | return "array"; |
| | | 522 | | } |
| | | 523 | | |
| | 26 | 524 | | if (type is INamedTypeSymbol named && named.IsGenericType && named.TypeArguments.Length == 1) |
| | | 525 | | { |
| | 0 | 526 | | var baseName = named.ConstructedFrom.ToDisplayString(); |
| | 0 | 527 | | if (baseName == "System.Collections.Generic.IEnumerable<T>" || |
| | 0 | 528 | | baseName == "System.Collections.Generic.List<T>" || |
| | 0 | 529 | | baseName == "System.Collections.Generic.IReadOnlyList<T>" || |
| | 0 | 530 | | baseName == "System.Collections.Generic.ICollection<T>" || |
| | 0 | 531 | | baseName == "System.Collections.Generic.IList<T>") |
| | | 532 | | { |
| | 0 | 533 | | itemType = GetJsonSchemaType(named.TypeArguments[0], out _); |
| | 0 | 534 | | if (string.IsNullOrEmpty(itemType)) |
| | 0 | 535 | | itemType = "object"; |
| | 0 | 536 | | return "array"; |
| | | 537 | | } |
| | | 538 | | } |
| | | 539 | | |
| | | 540 | | // Stringified value types — no SpecialType assignment in Roslyn for these. |
| | | 541 | | // Identified by their full display name. The matching JSON Schema "format" comes |
| | | 542 | | // from GetJsonSchemaFormat. |
| | 26 | 543 | | var displayName = type.ToDisplayString(); |
| | 26 | 544 | | if (displayName == "System.Guid" || |
| | 26 | 545 | | displayName == "System.DateTimeOffset" || |
| | 26 | 546 | | displayName == "System.TimeSpan") |
| | 12 | 547 | | return "string"; |
| | | 548 | | |
| | | 549 | | // Enum types map to string (LLMs pass enum values as strings) |
| | 14 | 550 | | if (type.TypeKind == TypeKind.Enum) |
| | 2 | 551 | | return "string"; |
| | | 552 | | |
| | | 553 | | // Complex types (classes, records, structs) → "object" |
| | 12 | 554 | | if (type.TypeKind == TypeKind.Class || type.TypeKind == TypeKind.Struct) |
| | 12 | 555 | | return "object"; |
| | | 556 | | |
| | 0 | 557 | | return ""; |
| | | 558 | | } |
| | | 559 | | |
| | | 560 | | /// <summary> |
| | | 561 | | /// Returns the JSON Schema <c>format</c> hint for stringified value types: <c>"uuid"</c> |
| | | 562 | | /// for <see cref="System.Guid"/>, <c>"date-time"</c> for <see cref="System.DateTime"/> and |
| | | 563 | | /// <see cref="System.DateTimeOffset"/>, <c>"duration"</c> for <see cref="System.TimeSpan"/>. |
| | | 564 | | /// Returns <see langword="null"/> for any other type. |
| | | 565 | | /// </summary> |
| | | 566 | | public static string? GetJsonSchemaFormat(ITypeSymbol type) |
| | | 567 | | { |
| | 105 | 568 | | if (type is INamedTypeSymbol nullable && nullable.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T) |
| | 2 | 569 | | type = nullable.TypeArguments[0]; |
| | | 570 | | |
| | 105 | 571 | | if (type.SpecialType == SpecialType.System_DateTime) |
| | 6 | 572 | | return "date-time"; |
| | | 573 | | |
| | 99 | 574 | | var displayName = type.ToDisplayString(); |
| | 99 | 575 | | return displayName switch |
| | 99 | 576 | | { |
| | 6 | 577 | | "System.Guid" => "uuid", |
| | 2 | 578 | | "System.DateTimeOffset" => "date-time", |
| | 4 | 579 | | "System.TimeSpan" => "duration", |
| | 87 | 580 | | _ => null, |
| | 99 | 581 | | }; |
| | | 582 | | } |
| | | 583 | | |
| | | 584 | | /// <summary> |
| | | 585 | | /// Builds a JSON schema string for a complex object type's properties. |
| | | 586 | | /// Returns <see langword="null"/> if the type has no public properties or is not a complex type. |
| | | 587 | | /// </summary> |
| | | 588 | | public static string? BuildObjectSchemaJson(ITypeSymbol type) |
| | | 589 | | { |
| | 11 | 590 | | if (type is INamedTypeSymbol nullable && nullable.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T) |
| | 0 | 591 | | type = nullable.TypeArguments[0]; |
| | | 592 | | |
| | | 593 | | // Get public instance properties (including inherited) |
| | 11 | 594 | | var properties = type.GetMembers() |
| | 11 | 595 | | .OfType<IPropertySymbol>() |
| | 29 | 596 | | .Where(p => p.DeclaredAccessibility == Accessibility.Public && |
| | 29 | 597 | | !p.IsStatic && !p.IsIndexer && |
| | 29 | 598 | | p.GetMethod != null) |
| | 11 | 599 | | .ToList(); |
| | | 600 | | |
| | 11 | 601 | | if (properties.Count == 0) |
| | 0 | 602 | | return null; |
| | | 603 | | |
| | 11 | 604 | | var sb = new StringBuilder(); |
| | 11 | 605 | | sb.Append("{\"type\":\"object\",\"properties\":{"); |
| | | 606 | | |
| | 11 | 607 | | var required = new List<string>(); |
| | 11 | 608 | | var first = true; |
| | 78 | 609 | | foreach (var prop in properties) |
| | | 610 | | { |
| | 45 | 611 | | if (!first) sb.Append(","); |
| | 28 | 612 | | first = false; |
| | | 613 | | |
| | | 614 | | // Use camelCase for JSON property names (standard convention) |
| | 28 | 615 | | var propName = char.ToLowerInvariant(prop.Name[0]) + prop.Name.Substring(1); |
| | 28 | 616 | | var propSchemaType = GetJsonSchemaType(prop.Type, out _); |
| | 28 | 617 | | if (string.IsNullOrEmpty(propSchemaType)) |
| | 0 | 618 | | propSchemaType = "string"; // fallback |
| | 28 | 619 | | var propSchemaFormat = GetJsonSchemaFormat(prop.Type); |
| | | 620 | | |
| | | 621 | | // Check for [Description] attribute on the property |
| | 28 | 622 | | string? propDesc = null; |
| | 64 | 623 | | foreach (var attr in prop.GetAttributes()) |
| | | 624 | | { |
| | 7 | 625 | | if (attr.AttributeClass?.Name == "DescriptionAttribute") |
| | | 626 | | { |
| | 6 | 627 | | propDesc = attr.ConstructorArguments.FirstOrDefault().Value?.ToString(); |
| | 6 | 628 | | break; |
| | | 629 | | } |
| | | 630 | | } |
| | | 631 | | |
| | 28 | 632 | | sb.Append($"\"{propName}\":{{\"type\":\"{propSchemaType}\""); |
| | 28 | 633 | | if (!string.IsNullOrEmpty(propSchemaFormat)) |
| | | 634 | | { |
| | 5 | 635 | | sb.Append($",\"format\":\"{propSchemaFormat}\""); |
| | | 636 | | } |
| | 28 | 637 | | if (!string.IsNullOrEmpty(propDesc)) |
| | | 638 | | { |
| | 6 | 639 | | var escapedDesc = propDesc!.Replace("\\", "\\\\").Replace("\"", "\\\""); |
| | 6 | 640 | | sb.Append($",\"description\":\"{escapedDesc}\""); |
| | | 641 | | } |
| | 28 | 642 | | sb.Append("}"); |
| | | 643 | | |
| | | 644 | | // Non-nullable value types and non-nullable reference types are required |
| | 28 | 645 | | if (!prop.Type.IsValueType && prop.NullableAnnotation != NullableAnnotation.Annotated) |
| | 13 | 646 | | required.Add(propName); |
| | 15 | 647 | | else if (prop.Type.IsValueType && prop.NullableAnnotation != NullableAnnotation.Annotated |
| | 15 | 648 | | && prop.Type is INamedTypeSymbol nt && nt.ConstructedFrom.SpecialType != SpecialType.System_Nullabl |
| | 15 | 649 | | required.Add(propName); |
| | | 650 | | } |
| | | 651 | | |
| | 11 | 652 | | sb.Append("}"); |
| | 11 | 653 | | if (required.Count > 0) |
| | | 654 | | { |
| | 11 | 655 | | sb.Append(",\"required\":["); |
| | 39 | 656 | | sb.Append(string.Join(",", required.Select(r => "\"" + r + "\""))); |
| | 11 | 657 | | sb.Append("]"); |
| | | 658 | | } |
| | 11 | 659 | | sb.Append("}"); |
| | | 660 | | |
| | 11 | 661 | | return sb.ToString(); |
| | | 662 | | } |
| | | 663 | | |
| | | 664 | | /// <summary> |
| | | 665 | | /// Builds a list of <see cref="ObjectPropertyInfo"/> for manual property extraction |
| | | 666 | | /// from JsonElement. Used in generated code for AOT-safe deserialization of |
| | | 667 | | /// complex array element types. |
| | | 668 | | /// </summary> |
| | | 669 | | public static IReadOnlyList<ObjectPropertyInfo>? BuildObjectPropertyInfos(ITypeSymbol type) |
| | | 670 | | { |
| | 10 | 671 | | if (type is INamedTypeSymbol nullable && nullable.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T) |
| | 0 | 672 | | type = nullable.TypeArguments[0]; |
| | | 673 | | |
| | 10 | 674 | | var properties = type.GetMembers() |
| | 10 | 675 | | .OfType<IPropertySymbol>() |
| | 26 | 676 | | .Where(p => p.DeclaredAccessibility == Accessibility.Public && |
| | 26 | 677 | | !p.IsStatic && !p.IsIndexer && |
| | 26 | 678 | | p.GetMethod != null && p.SetMethod != null) |
| | 10 | 679 | | .ToList(); |
| | | 680 | | |
| | 10 | 681 | | if (properties.Count == 0) |
| | 1 | 682 | | return null; |
| | | 683 | | |
| | 9 | 684 | | var result = new List<ObjectPropertyInfo>(); |
| | 62 | 685 | | foreach (var prop in properties) |
| | | 686 | | { |
| | 22 | 687 | | var jsonName = char.ToLowerInvariant(prop.Name[0]) + prop.Name.Substring(1); |
| | 22 | 688 | | var schemaType = GetJsonSchemaType(prop.Type, out _); |
| | 22 | 689 | | if (string.IsNullOrEmpty(schemaType)) |
| | 0 | 690 | | schemaType = "string"; |
| | 22 | 691 | | var schemaFormat = GetJsonSchemaFormat(prop.Type); |
| | 22 | 692 | | var csharpTypeFullName = GetFullyQualifiedName(prop.Type); |
| | 22 | 693 | | var isNullable = prop.NullableAnnotation == NullableAnnotation.Annotated || |
| | 22 | 694 | | (prop.Type is INamedTypeSymbol pnt && pnt.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T); |
| | 22 | 695 | | var initDefaultLiteral = TryGetPropertyInitializerLiteral(prop); |
| | 22 | 696 | | result.Add(new ObjectPropertyInfo( |
| | 22 | 697 | | prop.Name, jsonName, csharpTypeFullName, schemaType, schemaFormat, |
| | 22 | 698 | | isNullable, initDefaultLiteral)); |
| | | 699 | | } |
| | | 700 | | |
| | 9 | 701 | | return result; |
| | | 702 | | } |
| | | 703 | | |
| | | 704 | | public static bool IsAccessibleFromGeneratedCode(INamedTypeSymbol typeSymbol) |
| | | 705 | | { |
| | 5551 | 706 | | if (typeSymbol.DeclaredAccessibility == Accessibility.Private || |
| | 5551 | 707 | | typeSymbol.DeclaredAccessibility == Accessibility.Protected) |
| | 0 | 708 | | return false; |
| | | 709 | | |
| | 5551 | 710 | | var current = typeSymbol.ContainingType; |
| | 5551 | 711 | | while (current != null) |
| | | 712 | | { |
| | 0 | 713 | | if (current.DeclaredAccessibility == Accessibility.Private) |
| | 0 | 714 | | return false; |
| | 0 | 715 | | current = current.ContainingType; |
| | | 716 | | } |
| | | 717 | | |
| | 5551 | 718 | | return true; |
| | | 719 | | } |
| | | 720 | | |
| | | 721 | | public static string GetFullyQualifiedName(ITypeSymbol typeSymbol) => |
| | 499 | 722 | | "global::" + typeSymbol.ToDisplayString( |
| | 499 | 723 | | SymbolDisplayFormat.FullyQualifiedFormat |
| | 499 | 724 | | .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted) |
| | 499 | 725 | | .WithMiscellaneousOptions( |
| | 499 | 726 | | SymbolDisplayFormat.FullyQualifiedFormat.MiscellaneousOptions |
| | 499 | 727 | | & ~SymbolDisplayMiscellaneousOptions.UseSpecialTypes)); |
| | | 728 | | |
| | | 729 | | public static string SanitizeIdentifier(string name) |
| | | 730 | | { |
| | 138 | 731 | | if (string.IsNullOrEmpty(name)) |
| | 0 | 732 | | return "Generated"; |
| | | 733 | | |
| | 138 | 734 | | var sb = new StringBuilder(name.Length); |
| | 3588 | 735 | | foreach (var c in name) |
| | | 736 | | { |
| | 1656 | 737 | | if (char.IsLetterOrDigit(c) || c == '_') |
| | 1656 | 738 | | sb.Append(c); |
| | 0 | 739 | | else if (c == '.' || c == '-' || c == ' ') |
| | 0 | 740 | | sb.Append(c == '.' ? '.' : '_'); |
| | | 741 | | } |
| | | 742 | | |
| | 138 | 743 | | var result = sb.ToString(); |
| | 138 | 744 | | var segments = result.Split('.'); |
| | 552 | 745 | | for (int i = 0; i < segments.Length; i++) |
| | | 746 | | { |
| | 138 | 747 | | if (segments[i].Length > 0 && char.IsDigit(segments[i][0])) |
| | 0 | 748 | | segments[i] = "_" + segments[i]; |
| | | 749 | | } |
| | | 750 | | |
| | 276 | 751 | | return string.Join(".", segments.Where(s => s.Length > 0)); |
| | | 752 | | } |
| | | 753 | | |
| | | 754 | | public static string GetShortName(string fqn) |
| | | 755 | | { |
| | 191 | 756 | | var stripped = fqn.StartsWith("global::", System.StringComparison.Ordinal) ? fqn.Substring(8) : fqn; |
| | 191 | 757 | | var lastDot = stripped.LastIndexOf('.'); |
| | 191 | 758 | | return lastDot >= 0 ? stripped.Substring(lastDot + 1) : stripped; |
| | | 759 | | } |
| | | 760 | | |
| | | 761 | | public static string StripAgentSuffix(string className) |
| | | 762 | | { |
| | | 763 | | const string suffix = "Agent"; |
| | 6 | 764 | | return className.EndsWith(suffix, System.StringComparison.Ordinal) && className.Length > suffix.Length |
| | 6 | 765 | | ? className.Substring(0, className.Length - suffix.Length) |
| | 6 | 766 | | : className; |
| | | 767 | | } |
| | | 768 | | |
| | | 769 | | public static string GroupNameToPascalCase(string groupName) |
| | | 770 | | { |
| | 172 | 771 | | var sb = new StringBuilder(); |
| | 172 | 772 | | var capitalizeNext = true; |
| | 2624 | 773 | | foreach (var c in groupName) |
| | | 774 | | { |
| | 1140 | 775 | | if (c == '-' || c == '_' || c == ' ') |
| | | 776 | | { |
| | 44 | 777 | | capitalizeNext = true; |
| | | 778 | | } |
| | 1096 | 779 | | else if (char.IsLetterOrDigit(c)) |
| | | 780 | | { |
| | 1096 | 781 | | sb.Append(capitalizeNext ? char.ToUpperInvariant(c) : c); |
| | 1096 | 782 | | capitalizeNext = false; |
| | | 783 | | } |
| | | 784 | | } |
| | 172 | 785 | | return sb.ToString(); |
| | | 786 | | } |
| | | 787 | | |
| | | 788 | | /// <summary> |
| | | 789 | | /// Converts a Roslyn-supplied parameter default value (boxed as <see cref="object"/>) into a |
| | | 790 | | /// C# literal expression suitable for direct emission into generated source. |
| | | 791 | | /// </summary> |
| | | 792 | | /// <remarks> |
| | | 793 | | /// <para> |
| | | 794 | | /// Handles the three cases that produce non-trivial output: |
| | | 795 | | /// </para> |
| | | 796 | | /// <list type="bullet"> |
| | | 797 | | /// <item><description> |
| | | 798 | | /// <paramref name="value"/> is <see langword="null"/> for a non-nullable value type |
| | | 799 | | /// (e.g., <c>Guid id = default</c>) — emits <c>default(typeFullName)</c> rather than |
| | | 800 | | /// <c>"null"</c> which would not compile against the variable's declared type. |
| | | 801 | | /// </description></item> |
| | | 802 | | /// <item><description> |
| | | 803 | | /// <paramref name="parameterType"/> is an <see langword="enum"/> — Roslyn surfaces the |
| | | 804 | | /// underlying primitive value (e.g., <c>2</c> for <c>Mode.Append</c>); this method |
| | | 805 | | /// resolves the matching enum field by constant value and emits the typed literal |
| | | 806 | | /// (<c>global::MyApp.Mode.Append</c>). When no field matches (flags combination), emits |
| | | 807 | | /// a typed cast (<c>(global::MyApp.Mode)2</c>) which is still C#-legal. |
| | | 808 | | /// </description></item> |
| | | 809 | | /// <item><description> |
| | | 810 | | /// Primitive types — emits the standard C# literal form (e.g., <c>5L</c> for long, |
| | | 811 | | /// <c>9.99m</c> for decimal, escaped string literals). |
| | | 812 | | /// </description></item> |
| | | 813 | | /// </list> |
| | | 814 | | /// <para> |
| | | 815 | | /// Falls back to <c>default(typeFullName)</c> for any value the helper cannot render |
| | | 816 | | /// unambiguously. |
| | | 817 | | /// </para> |
| | | 818 | | /// </remarks> |
| | | 819 | | public static string ConvertToCSharpLiteral(object? value, ITypeSymbol parameterType) |
| | | 820 | | { |
| | 18 | 821 | | var typeFullName = GetFullyQualifiedName(parameterType); |
| | | 822 | | |
| | 18 | 823 | | var underlyingType = parameterType is INamedTypeSymbol nullableNamed && |
| | 18 | 824 | | nullableNamed.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T && |
| | 18 | 825 | | nullableNamed.TypeArguments.Length == 1 |
| | 18 | 826 | | ? nullableNamed.TypeArguments[0] |
| | 18 | 827 | | : parameterType; |
| | | 828 | | |
| | 18 | 829 | | if (value is null) |
| | | 830 | | { |
| | 6 | 831 | | bool isNullableValueType = parameterType is INamedTypeSymbol nvt && |
| | 6 | 832 | | nvt.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T; |
| | 6 | 833 | | bool isAnnotatedReference = !parameterType.IsValueType && |
| | 6 | 834 | | parameterType.NullableAnnotation == NullableAnnotation.Annotated; |
| | | 835 | | |
| | 6 | 836 | | if (parameterType.IsValueType && !isNullableValueType) |
| | 4 | 837 | | return "default(" + typeFullName + ")"; |
| | | 838 | | |
| | 2 | 839 | | if (!parameterType.IsValueType && !isAnnotatedReference) |
| | 0 | 840 | | return "default(" + typeFullName + ")"; |
| | | 841 | | |
| | 2 | 842 | | return "null"; |
| | | 843 | | } |
| | | 844 | | |
| | 12 | 845 | | if (underlyingType.TypeKind == TypeKind.Enum) |
| | | 846 | | { |
| | 1 | 847 | | var underlyingTypeFullName = GetFullyQualifiedName(underlyingType); |
| | 7 | 848 | | foreach (var member in underlyingType.GetMembers().OfType<IFieldSymbol>()) |
| | | 849 | | { |
| | 3 | 850 | | if (member.HasConstantValue && Equals(member.ConstantValue, value)) |
| | 1 | 851 | | return underlyingTypeFullName + "." + member.Name; |
| | | 852 | | } |
| | | 853 | | |
| | 0 | 854 | | var castValue = ConvertPrimitiveLiteral(value, underlyingTypeFullName); |
| | 0 | 855 | | return "(" + underlyingTypeFullName + ")(" + castValue + ")"; |
| | | 856 | | } |
| | | 857 | | |
| | 11 | 858 | | return ConvertPrimitiveLiteral(value, typeFullName); |
| | 1 | 859 | | } |
| | | 860 | | |
| | | 861 | | private static string ConvertPrimitiveLiteral(object value, string typeFullName) |
| | | 862 | | { |
| | 11 | 863 | | return value switch |
| | 11 | 864 | | { |
| | 3 | 865 | | bool b => b ? "true" : "false", |
| | 2 | 866 | | string s => SymbolDisplay.FormatLiteral(s, quote: true), |
| | 0 | 867 | | char c => SymbolDisplay.FormatLiteral(c, quote: true), |
| | 0 | 868 | | byte n => n.ToString(CultureInfo.InvariantCulture), |
| | 0 | 869 | | sbyte n => n.ToString(CultureInfo.InvariantCulture), |
| | 0 | 870 | | short n => n.ToString(CultureInfo.InvariantCulture), |
| | 0 | 871 | | ushort n => n.ToString(CultureInfo.InvariantCulture), |
| | 3 | 872 | | int n => n.ToString(CultureInfo.InvariantCulture), |
| | 0 | 873 | | uint n => n.ToString(CultureInfo.InvariantCulture) + "U", |
| | 0 | 874 | | long n => n.ToString(CultureInfo.InvariantCulture) + "L", |
| | 0 | 875 | | ulong n => n.ToString(CultureInfo.InvariantCulture) + "UL", |
| | 2 | 876 | | float n when !float.IsNaN(n) && !float.IsInfinity(n) => n.ToString("R", CultureInfo.InvariantCulture) + "f", |
| | 2 | 877 | | double n when !double.IsNaN(n) && !double.IsInfinity(n) => n.ToString("R", CultureInfo.InvariantCulture) + " |
| | 1 | 878 | | decimal n => n.ToString(CultureInfo.InvariantCulture) + "m", |
| | 0 | 879 | | _ => "default(" + typeFullName + ")" |
| | 11 | 880 | | }; |
| | | 881 | | } |
| | | 882 | | |
| | | 883 | | /// <summary> |
| | | 884 | | /// Reads the property's source declaration to extract a simple-literal initializer (e.g., |
| | | 885 | | /// <c>= "default"</c>, <c>= 5</c>, <c>= true</c>, <c>= null</c>) and returns it as a C# |
| | | 886 | | /// literal string suitable for direct emission. Returns <see langword="null"/> when the |
| | | 887 | | /// property has no initializer or the initializer is not a simple literal expression |
| | | 888 | | /// (e.g., a method call, an array creation, an interpolated string). Non-literal |
| | | 889 | | /// initializers are intentionally skipped — they are not safe to splice into generated |
| | | 890 | | /// code without semantic analysis. |
| | | 891 | | /// </summary> |
| | | 892 | | public static string? TryGetPropertyInitializerLiteral(IPropertySymbol prop) |
| | | 893 | | { |
| | 76 | 894 | | foreach (var syntaxRef in prop.DeclaringSyntaxReferences) |
| | | 895 | | { |
| | 22 | 896 | | var node = syntaxRef.GetSyntax(); |
| | 22 | 897 | | if (node is PropertyDeclarationSyntax propDecl && |
| | 22 | 898 | | propDecl.Initializer is { } init && |
| | 22 | 899 | | init.Value is LiteralExpressionSyntax literal) |
| | | 900 | | { |
| | 12 | 901 | | return literal.ToString(); |
| | | 902 | | } |
| | | 903 | | } |
| | 10 | 904 | | return null; |
| | | 905 | | } |
| | | 906 | | } |