openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
codegen/generator/src/Visitors/InvariantFormatAdditionalPropertiesVisitor.cs
60lines · 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 | /// 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> |
| 17 | public 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 | } |