openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
codegen/generator/src/Visitors/ContentInnerCollectionDefinedVisitor.cs
59lines · modecode
| 1 | using Microsoft.TypeSpec.Generator.ClientModel; |
| 2 | using Microsoft.TypeSpec.Generator.Expressions; |
| 3 | using Microsoft.TypeSpec.Generator.Providers; |
| 4 | using Microsoft.TypeSpec.Generator.Snippets; |
| 5 | using Microsoft.TypeSpec.Generator.Statements; |
| 6 | using System.Collections.Generic; |
| 7 | using System.Linq; |
| 8 | using static OpenAILibraryPlugin.Visitors.VisitorHelpers; |
| 9 | |
| 10 | namespace OpenAILibraryPlugin.Visitors; |
| 11 | |
| 12 | /// <summary> |
| 13 | /// This visitor supplements instances of a conditional check of "Optional.IsDefined(Content)" to include a parallel |
| 14 | /// check to "Content.IsInnerCollectionDefined()". |
| 15 | /// </summary> |
| 16 | public class ContentInnerCollectionDefinedVisitor : ScmLibraryVisitor |
| 17 | { |
| 18 | private const string Comment = "Plugin customization: add Content.IsInnerCollectionDefined() check"; |
| 19 | |
| 20 | protected override MethodProvider VisitMethod(MethodProvider method) |
| 21 | { |
| 22 | if (method.Signature.Name != "JsonModelWriteCore" |
| 23 | || method.BodyStatements is not MethodBodyStatements methodBodyStatements) |
| 24 | { |
| 25 | return method; |
| 26 | } |
| 27 | |
| 28 | List<MethodBodyStatement> statements = methodBodyStatements.ToList(); |
| 29 | VisitExplodedMethodBodyStatements( |
| 30 | statements, |
| 31 | statement |
| 32 | => GetUpdatedIfStatement( |
| 33 | statement, |
| 34 | expression => |
| 35 | { |
| 36 | InvokeMethodExpression? invokeMethodExpression |
| 37 | = expression as InvokeMethodExpression |
| 38 | ?? (expression as ScopedApi<bool>)?.Original as InvokeMethodExpression; |
| 39 | if (invokeMethodExpression?.InstanceReference is TypeReferenceExpression instanceTypeReferenceExpression |
| 40 | && instanceTypeReferenceExpression.Type?.Name == "Optional" |
| 41 | && invokeMethodExpression.MethodName == "IsDefined" |
| 42 | && invokeMethodExpression.Arguments.Count == 1 |
| 43 | && invokeMethodExpression.Arguments[0] is MemberExpression argumentMemberExpression |
| 44 | && argumentMemberExpression.MemberName == "Content" |
| 45 | && method.EnclosingType.Name != "InternalEvalRunOutputItemSampleOutput") |
| 46 | if (statement is IfStatement ifStatement) |
| 47 | { |
| 48 | return invokeMethodExpression |
| 49 | .As<bool>() |
| 50 | .And(new MemberExpression(null, "Content").Invoke("IsInnerCollectionDefined")); |
| 51 | } |
| 52 | return expression; |
| 53 | }, |
| 54 | Comment)); |
| 55 | |
| 56 | method.Update(bodyStatements: statements); |
| 57 | return method; |
| 58 | } |
| 59 | } |