openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
mailinhphan/clientOptions

Branches

Tags

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

Clone

HTTPS

Download ZIP

codegen/generator/src/Visitors/InvariantFormatAdditionalPropertiesVisitor.cs

60lines · 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/// A visitor that removes all "options.Format != "W"" condition checks from JsonModelWriteCore and emitted type
14/// deserialization methods, which causes unknown properties to always be written to the additional properties
15/// collection.
16/// </summary>
17public class InvariantFormatAdditionalPropertiesVisitor : ScmLibraryVisitor
18{
19 private const string Comment = "Plugin customization: remove options.Format != \"W\" check";
20
21 protected override MethodProvider VisitMethod(MethodProvider method)
22 {
23 if (method.Signature.Name == "JsonModelWriteCore"
24 || method.Signature.Name.StartsWith("Deserialize"))
25 {
26 List<MethodBodyStatement> statements = method.BodyStatements?.ToList() ?? [];
27 VisitExplodedMethodBodyStatements(
28 statements!,
29 statement => GetUpdatedIfStatement(
30 statement, expression =>
31 {
32 if (GetIsOptionsFormatNotEqualToWExpression(expression))
33 {
34 return null;
35 }
36 return expression;
37 },
38 Comment));
39 method.Update(bodyStatements: statements);
40 }
41 return method;
42 }
43
44 private static bool GetIsOptionsFormatNotEqualToWExpression(
45 ValueExpression expression)
46 {
47 BinaryOperatorExpression? binaryOperatorExpression
48 = expression as BinaryOperatorExpression
49 ?? (expression as ScopedApi<bool>)?.Original as BinaryOperatorExpression;
50
51 return binaryOperatorExpression?.Left is MemberExpression leftMemberExpression
52 && leftMemberExpression.Inner?.ToDisplayString() == "options"
53 && leftMemberExpression.MemberName == "Format"
54 && binaryOperatorExpression.Operator == "!="
55 && binaryOperatorExpression.Right is ScopedApi<string> rightStringExpression
56 && rightStringExpression.Original is LiteralExpression rightLiteralExpression
57 && rightLiteralExpression.Literal is string rightStringLiteral
58 && rightStringLiteral == "W";
59 }
60}