openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
achandmsft-patch-2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

codegen/generator/src/Visitors/ContentInnerCollectionDefinedVisitor.cs

59lines · modecode

1using Microsoft.TypeSpec.Generator.ClientModel;
2using Microsoft.TypeSpec.Generator.Expressions;
3using Microsoft.TypeSpec.Generator.Providers;
4using Microsoft.TypeSpec.Generator.Snippets;
5using Microsoft.TypeSpec.Generator.Statements;
6using System.Collections.Generic;
7using System.Linq;
8using static OpenAILibraryPlugin.Visitors.VisitorHelpers;
9
10namespace 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>
16public 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}