private static MethodBuilder BuildEqualsMethod( string typeName, IReadOnlyList <PropertyDescriptor> properties) { const string other = nameof(other); ConditionBuilder equalCondition = ConditionBuilder .New() .SetReturn() .SetDetermineStatement(); if (properties.Count == 0) { equalCondition.And("true"); } else { foreach (PropertyDescriptor property in properties) { equalCondition.And(ConditionBuilder .New() .Set(BuildPropertyComparison(property.Type, property.Name))); } } return(MethodBuilder .New() .SetName(nameof(IEquatable <object> .Equals)) .SetPublic() .SetInheritance(Inheritance.Virtual) .SetReturnType(TypeNames.Boolean) .AddParameter(other, x => x.SetType(typeName.MakeNullable())) .AddCode(CodeBlockBuilder .New() .AddCode(IfBuilder .New() .SetCondition(MethodCallBuilder .Inline() .SetMethodName(nameof(ReferenceEquals)) .AddArgument("null") .AddArgument(other)) .AddCode("return false;")) .AddEmptyLine() .AddCode(IfBuilder .New() .SetCondition(MethodCallBuilder .Inline() .SetMethodName(nameof(ReferenceEquals)) .AddArgument("this") .AddArgument(other)) .AddCode("return true;")) .AddEmptyLine() .AddCode(IfBuilder .New() .SetCondition($"{other}.GetType() != GetType()") .AddCode("return false;")) .AddEmptyLine() .AddCode(equalCondition))); }
private CodeBlockBuilder CreateConstructorBody( IReadOnlyList <ValueSerializerDescriptor> serializers, string indent) { var body = new StringBuilder(); body.AppendLine("if (serializerResolver is null)"); body.AppendLine("{"); body.AppendLine( $"{indent}throw new {Types.ArgumentNullException}" + "(nameof(serializerResolver));"); body.AppendLine("}"); body.AppendLine(); for (int i = 0; i < serializers.Count; i++) { if (i > 0) { body.AppendLine(); } body.Append( $"{serializers[i].FieldName} = serializerResolver." + $"Get(\"{serializers[i].Name}\");"); } return(CodeBlockBuilder.FromStringBuilder(body)); }
private static ICode RegisterWebSocketConnection(string clientName) => MethodCallBuilder .New() .SetMethodName(TypeNames.AddSingleton) .AddArgument(_services) .AddArgument(LambdaBuilder .New() .AddArgument(_sp) .SetBlock(true) .SetCode(CodeBlockBuilder .New() .AddCode(AssignmentBuilder .New() .SetLefthandSide($"var {_sessionPool}") .SetRighthandSide(MethodCallBuilder .Inline() .SetMethodName(TypeNames.GetRequiredService) .AddGeneric(TypeNames.ISessionPool) .AddArgument(_parentServices))) .AddCode(MethodCallBuilder .New() .SetReturn() .SetNew() .SetMethodName(TypeNames.WebSocketConnection) .AddArgument(LambdaBuilder .New() .SetCode(MethodCallBuilder .Inline() .SetMethodName( _sessionPool, nameof(ISessionPool.CreateAsync)) .AddArgument(clientName.AsStringToken()) .AddArgument("default"))))));
private CodeBlockBuilder CreateDeserializerMethodBody( EnumValueSerializerDescriptor descriptor, string indent) { var code = new StringBuilder(); code.AppendLine("if (serialized is null)"); code.AppendLine("{"); code.AppendLine($"{indent}return null;"); code.AppendLine("}"); code.AppendLine(); code.AppendLine($"var stringValue = (string)serialized"); code.AppendLine(); code.AppendLine("switch(serialized)"); code.AppendLine("{"); foreach (EnumElementDescriptor element in descriptor.Elements) { code.AppendLine( $"{indent}case \"{element.SerializedName}\":"); code.AppendLine( $"{indent}{indent}return {descriptor.EnumTypeName}.{element.Name};"); } code.AppendLine($"{indent}default:"); code.AppendLine($"{indent}{indent}throw new {Types.NotSupportedException}();"); code.AppendLine("}"); return(CodeBlockBuilder.FromStringBuilder(code)); }
private CodeBlockBuilder CreateSerializeBody( InputModelSerializerDescriptor descriptor, string indent) { var body = new StringBuilder(); AppendInitializationCheck(body, indent); body.AppendLine("if (value is null)"); body.AppendLine("{"); body.AppendLine($"{indent}return null;"); body.AppendLine("}"); body.AppendLine(); body.AppendLine($"var input = ({descriptor.InputTypeName})value;"); body.Append(NullableRefTypes ? "var map = new global::System.Collections.Generic.Dictionary<string, object?>();" : "var map = new global::System.Collections.Generic.Dictionary<string, object>();"); foreach (InputFieldSerializerDescriptor field in descriptor.FieldSerializers) { body.AppendLine(); body.AppendLine(); AppendSerializeField(field, body, indent); } body.AppendLine(); body.AppendLine(); body.AppendLine("return map;"); return(CodeBlockBuilder.FromStringBuilder(body)); }
public static ArrayBuilder AddArray(this CodeBlockBuilder method) { var arrayBuilder = ArrayBuilder.New(); method.AddCode(arrayBuilder); return(arrayBuilder); }
private CodeBlockBuilder CreateSerializerMethodBody( EnumValueSerializerDescriptor descriptor, string indent) { var code = new StringBuilder(); code.AppendLine("if (value is null)"); code.AppendLine("{"); code.AppendLine($"{indent}return null;"); code.AppendLine("}"); code.AppendLine(); code.AppendLine($"var enumValue = ({descriptor.EnumTypeName})value"); code.AppendLine(); code.AppendLine("switch(enumValue)"); code.AppendLine("{"); foreach (EnumElementDescriptor element in descriptor.Elements) { code.AppendLine($"{indent}case {descriptor.EnumTypeName}.{element.Name}:"); code.AppendLine($"{indent}{indent}return \"{element.SerializedName}\";"); } code.AppendLine($"{indent}default:"); code.AppendLine($"{indent}{indent}throw new NotSupportedException();"); code.AppendLine("}"); return(CodeBlockBuilder.FromStringBuilder(code)); }
private static ICode RegisterHttpConnection(string clientName) => MethodCallBuilder .New() .SetMethodName(TypeNames.AddSingleton) .AddArgument(_services) .AddArgument(LambdaBuilder .New() .AddArgument(_sp) .SetBlock(true) .SetCode(CodeBlockBuilder .New() .AddCode(AssignmentBuilder .New() .SetLefthandSide($"var {_clientFactory}") .SetRighthandSide(MethodCallBuilder .Inline() .SetMethodName(TypeNames.GetRequiredService) .AddGeneric(TypeNames.IHttpClientFactory) .AddArgument(_parentServices))) .AddCode(MethodCallBuilder .New() .SetReturn() .SetNew() .SetMethodName(TypeNames.HttpConnection) .AddArgument(LambdaBuilder .New() .SetCode(MethodCallBuilder .Inline() .SetMethodName( _clientFactory, nameof(IHttpClientFactory.CreateClient)) .AddArgument(clientName.AsStringToken()))))));
public static CodeBlockBuilder AddBody(this MethodBuilder method) { var code = CodeBlockBuilder.New(); method.AddCode(code); return(code); }
public static MethodCallBuilder AddMethodCall(this CodeBlockBuilder builder) { var methodCallBuilder = MethodCallBuilder.New(); builder.AddCode(methodCallBuilder); return(methodCallBuilder); }
private void AddArrayHandler( ClassBuilder classBuilder, ConstructorBuilder constructorBuilder, MethodBuilder methodBuilder, ListTypeDescriptor listTypeDescriptor, HashSet <string> processed, bool isNonNullable) { methodBuilder.AddParameter( ParameterBuilder.New() .SetType(listTypeDescriptor.ToEntityIdBuilder()) .SetName(ListParamName)); var listVarName = listTypeDescriptor.Name.WithLowerFirstChar() + "s"; if (!isNonNullable) { methodBuilder.AddCode(EnsureProperNullability(ListParamName, isNonNullable)); } methodBuilder.AddCode( AssignmentBuilder.New() .SetLefthandSide($"var {listVarName}") .SetRighthandSide( CodeBlockBuilder.New() .AddCode("new ") .AddCode(TypeNames.List) .AddCode("<") .AddCode( listTypeDescriptor.InnerType.ToBuilder() .SkipTrailingSpace()) .AddCode(">") .AddCode("()"))); methodBuilder.AddEmptyLine(); var loopbuilder = ForEachBuilder.New() .SetLoopHeader( CodeBlockBuilder.New() .AddCode(listTypeDescriptor.InnerType.ToEntityIdBuilder()) .AddCode($"child in {ListParamName}")) .AddCode( MethodCallBuilder.New() .SetPrefix($"{listVarName}.") .SetMethodName("Add") .AddArgument( BuildMapMethodCall( listTypeDescriptor.InnerType, "child"))); methodBuilder.AddCode(loopbuilder); methodBuilder.AddEmptyLine(); methodBuilder.AddCode($"return {listVarName};"); AddMapMethod( listVarName, listTypeDescriptor.InnerType, classBuilder, constructorBuilder, processed); }
private static ICode GenerateEntityHandlerIfClause( ObjectTypeDescriptor objectTypeDescriptor, bool isNonNullable) { var dataMapperName = GetFieldName( CreateEntityMapperName( objectTypeDescriptor.RuntimeType.Name, objectTypeDescriptor.Name)); MethodCallBuilder constructorCall = MethodCallBuilder .New() .SetReturn() .SetWrapArguments() .SetMethodName(dataMapperName, nameof(IEntityMapper <object, object> .Map)); MethodCallBuilder argument = MethodCallBuilder .Inline() .SetMethodName(StoreFieldName, nameof(IEntityStore.GetEntity)) .AddGeneric(CreateEntityTypeName(objectTypeDescriptor.Name)) .AddArgument(isNonNullable ? _entityId : $"{_entityId}.Value"); constructorCall.AddArgument( NullCheckBuilder .New() .SetDetermineStatement(false) .SetCondition(argument) .SetCode(ExceptionBuilder.Inline(TypeNames.GraphQLClientException))); IfBuilder ifCorrectType = IfBuilder .New() .AddCode(constructorCall) .SetCondition( MethodCallBuilder .Inline() .SetMethodName( isNonNullable ? new[] { _entityId, nameof(EntityId.Name), nameof(string.Equals) } : new[] { _entityId, nameof(Nullable <EntityId> .Value), nameof(EntityId.Name), nameof(string.Equals) }) .AddArgument(objectTypeDescriptor.Name.AsStringToken()) .AddArgument(TypeNames.OrdinalStringComparison)); return(CodeBlockBuilder .New() .AddEmptyLine() .AddCode(ifCorrectType)); }
public static CodeBlockBuilder ArgumentException( this CodeBlockBuilder builder, string argumentName, string condition) { return(builder.AddIf(x => x.SetCondition(condition) .AddCode($"throw new {TypeNames.ArgumentException}(nameof({argumentName}));"))); }
public static CodeBlockBuilder AddIf( this CodeBlockBuilder builder, Action <IfBuilder> configure) { var ifBuilder = IfBuilder.New(); configure(ifBuilder); return(builder.AddCode(ifBuilder)); }
private static CodeBlockBuilder CreateDeserializeBody(string indent) { var body = new StringBuilder(); body.AppendLine("throw new NotSupportedException("); body.Append($"{indent}\"Deserializing input values is not supported.\");"); return(CodeBlockBuilder.FromStringBuilder(body)); }
public static CodeBlockBuilder AddMethodCall( this CodeBlockBuilder builder, Action <MethodCallBuilder> configure) { var methodCallBuilder = new MethodCallBuilder(); configure(methodCallBuilder); return(builder.AddCode(methodCallBuilder)); }
private void AddInterfaceDataTypeDeserializerToMethod( MethodBuilder methodBuilder, InterfaceTypeDescriptor interfaceTypeDescriptor) { methodBuilder.AddCode( AssignmentBuilder .New() .SetLefthandSide($"var {_typename}") .SetRighthandSide(MethodCallBuilder .Inline() .SetMethodName( _obj, nameof(Nullable <EntityId> .Value), nameof(JsonElement.GetProperty)) .AddArgument(__typename.AsStringToken()) .Chain(x => x.SetMethodName(nameof(JsonElement.GetString))))); // If the type is an interface foreach (ObjectTypeDescriptor concreteType in interfaceTypeDescriptor.ImplementedBy) { MethodCallBuilder returnStatement = MethodCallBuilder .New() .SetReturn() .SetNew() .SetMethodName( $"{concreteType.RuntimeType.Namespace}.State." + CreateDataTypeName(concreteType.Name)) .AddArgument("typename"); foreach (PropertyDescriptor property in concreteType.Properties) { returnStatement.AddArgument( CodeBlockBuilder .New() .AddCode($"{GetParameterName(property.Name)}: ") .AddCode(BuildUpdateMethodCall(property))); } IfBuilder ifStatement = IfBuilder .New() .SetCondition( $"typename?.Equals(\"{concreteType.Name}\", " + $"{TypeNames.OrdinalStringComparison}) ?? false") .AddCode(returnStatement); methodBuilder .AddEmptyLine() .AddCode(ifStatement); } methodBuilder .AddEmptyLine() .AddCode(ExceptionBuilder.New(TypeNames.NotSupportedException)); }
public static CodeBlockBuilder If( this CodeBlockBuilder builder, bool condition, Action <CodeBlockBuilder> configure) { if (condition) { configure(builder); } return(builder); }
public static AssignmentBuilder AddAssigment( this CodeBlockBuilder builder, string assignedTo) { AssignmentBuilder assignmentBuilder = AssignmentBuilder .New() .SetLefthandSide(assignedTo); builder.AddCode(assignmentBuilder); return(assignmentBuilder); }
private CodeBlockBuilder CreateConstructorBody( OutputModelDescriptor descriptor) { var body = new StringBuilder(); foreach (OutputFieldDescriptor field in descriptor.Fields) { body.AppendLine($"{field.Name} = {field.ParameterName};"); } return(CodeBlockBuilder.FromStringBuilder(body)); }
public static CodeBlockBuilder ForEach <T>( this CodeBlockBuilder codeBlockBuilder, IEnumerable <T> enumerable, Action <CodeBlockBuilder, T> configure) { foreach (T element in enumerable) { configure(codeBlockBuilder, element); } return(codeBlockBuilder); }
private static ICode GenerateEntityHandlerIfClause( ObjectTypeDescriptor objectTypeDescriptor, bool isNonNullable) { var dataMapperName = GetFieldName( CreateEntityMapperName( objectTypeDescriptor.RuntimeType.Name, objectTypeDescriptor.Name)); var ifCorrectType = IfBuilder.New(); if (isNonNullable) { ifCorrectType.SetCondition( $"{EntityIdParamName}.Name.Equals(\"" + $"{objectTypeDescriptor.Name}\", " + $"{TypeNames.OrdinalStringComparison})"); } else { ifCorrectType.SetCondition( $"{EntityIdParamName}.Value.Name.Equals(\"" + $"{objectTypeDescriptor.Name}\", " + $"{TypeNames.OrdinalStringComparison})"); } MethodCallBuilder constructorCall = MethodCallBuilder.New() .SetPrefix($"return {dataMapperName}.") .SetWrapArguments() .SetMethodName(nameof(IEntityMapper <object, object> .Map)); MethodCallBuilder argument = MethodCallBuilder.New() .SetMethodName($"{StoreFieldName}.{nameof(IEntityStore.GetEntity)}") .SetDetermineStatement(false) .AddGeneric(CreateEntityTypeName(objectTypeDescriptor.Name)) .AddArgument(isNonNullable ? EntityIdParamName : $"{EntityIdParamName}.Value"); constructorCall.AddArgument( NullCheckBuilder.New() .SetDetermineStatement(false) .SetCondition(argument) .SetCode(ExceptionBuilder .New(TypeNames.GraphQLClientException) .SetDetermineStatement(false))); ifCorrectType.AddCode(constructorCall); return(CodeBlockBuilder.New() .AddEmptyLine() .AddCode(ifCorrectType)); }
protected override void Generate( CodeWriter writer, InputObjectTypeDescriptor namedTypeDescriptor, out string fileName) { const string serializerResolver = nameof(serializerResolver); const string runtimeValue = nameof(runtimeValue); const string value = nameof(value); fileName = CreateInputValueFormatter(namedTypeDescriptor); NameString typeName = namedTypeDescriptor.Name; ClassBuilder classBuilder = ClassBuilder .New() .SetName(fileName) .AddImplements(TypeNames.IInputValueFormatter); var neededSerializers = namedTypeDescriptor .Properties .GroupBy(x => x.Type.Name) .ToDictionary(x => x, x => x.First()); // Initialize Method CodeBlockBuilder initialize = classBuilder .AddMethod("Initialize") .SetPublic() .AddParameter(serializerResolver, x => x.SetType(TypeNames.ISerializerResolver)) .AddBody(); foreach (var property in neededSerializers.Values) { if (property.Type.GetName().Value is { } name) { var propertyName = GetFieldName(name) + "Formatter"; initialize .AddAssigment(propertyName) .AddMethodCall() .SetMethodName( serializerResolver, nameof(ISerializerResolver.GetInputValueFormatter)) .AddArgument(name.AsStringToken()); classBuilder .AddField(propertyName) .SetAccessModifier(AccessModifier.Private) .SetType(TypeNames.IInputValueFormatter) .SetValue("default!"); }
private CodeBlockBuilder CreateEnumParsingSwitch( string paramName, EnumDescriptor descriptor) { StringBuilder sourceText = new StringBuilder() .AppendLine($"return {paramName} switch") .AppendLine("{") .AppendLineForEach( descriptor.Values, x => $" \"{x.GraphQLName}\" => {descriptor.Name}.{x.Name},") .AppendLine($" _ => throw new {TypeNames.GraphQLClientException}()") .AppendLine("};"); return(CodeBlockBuilder.From(sourceText)); }
public async Task CreateCodeBlock_With_CodeLineBuilder() { // arrange var sb = new StringBuilder(); var writer = new CodeWriter(sb); // act await CodeBlockBuilder.New() .AddCode("abc;") .AddCode(CodeLineBuilder.New().SetLine("def;")) .BuildAsync(writer); // assert sb.ToString().MatchSnapshot(); }
public static AssignmentBuilder AddAssigment( this CodeBlockBuilder builder, string?assignedTo = null) { AssignmentBuilder assignmentBuilder = AssignmentBuilder .New(); if (assignedTo is not null) { assignmentBuilder.SetLefthandSide(assignedTo); } builder.AddCode(assignmentBuilder); return(assignmentBuilder); }
private static ICode GenerateMethodBody(DependencyInjectionDescriptor descriptor) => CodeBlockBuilder .New() .AddMethodCall(x => x.SetMethodName(TypeNames.AddSingleton) .AddArgument(_services) .AddArgument(LambdaBuilder .New() .SetBlock(true) .AddArgument(_sp) .SetCode( CodeBlockBuilder .New() .AddCode( AssignmentBuilder .New() .SetLefthandSide($"var {_serviceCollection}") .SetRighthandSide( MethodCallBuilder .Inline() .SetNew() .SetMethodName(TypeNames.ServiceCollection))) .AddEmptyLine() .AddMethodCall(x => x.SetMethodName("ConfigureClient") .AddArgument(_serviceCollection) .AddArgument(_sp) .AddArgument(_strategy)) .AddEmptyLine() .AddCode(MethodCallBuilder .New() .SetReturn() .SetNew() .SetMethodName("ClientServiceProvider") .SetWrapArguments() .AddArgument(MethodCallBuilder .Inline() .SetMethodName(TypeNames.BuildServiceProvider) .AddArgument(_serviceCollection)))))) .AddEmptyLine() .ForEach( descriptor.Operations, (builder, operation) => builder.AddCode(ForwardSingletonToClientServiceProvider(operation.Name))) .AddEmptyLine() .AddCode(ForwardSingletonToClientServiceProvider(descriptor.Name)) .AddEmptyLine() .AddLine($"return {_services};");
private static CodeBlockBuilder CreateGetVariableValuesBody( IReadOnlyList <OperationArgumentDescriptor> arguments, string indent) { if (arguments.Count == 0) { return(CodeBlockBuilder.New() .AddCode( "return global::System.Array.Empty<" + "global::StrawberryShake.VariableValue>();")); } var body = new StringBuilder(); body.AppendLine("var variables = new List<VariableValue>();"); body.AppendLine(); foreach (OperationArgumentDescriptor argument in arguments) { if (argument.IsOptional) { body.AppendLine("if (Episode.HasValue)"); body.AppendLine("{"); body.AppendLine( $"{indent}variables.Add(new VariableValue(" + $"\"{argument.GraphQLName}\", " + $"\"{argument.GraphQLType}\", " + $"{argument.Name}.Value));"); body.AppendLine("}"); } else { body.AppendLine( $"variables.Add(new VariableValue(" + $"\"{argument.GraphQLName}\", " + $"\"{argument.GraphQLType}\", " + $"{argument.Name}));"); } body.AppendLine(); } body.Append("return variables;"); return(CodeBlockBuilder.FromStringBuilder(body)); }
private static CodeBlockBuilder CreateToStringBody( string originalDocument) { var body = new StringBuilder(); body.Append("return @\""); #pragma warning disable CA1307 body.Append(originalDocument .Replace("\"", "\"\"") .Replace("\r\n", "\n") .Replace("\n\r", "\n") .Replace("\r", "\n") .Replace("\n", "\n")); #pragma warning restore CA1307 body.Append("\";"); return(CodeBlockBuilder.FromStringBuilder(body)); }
private void AddArrayHandler( ClassBuilder classBuilder, MethodBuilder methodBuilder, ListTypeDescriptor listTypeDescriptor, HashSet <string> processed) { var listVarName = GetParameterName(listTypeDescriptor.Name) + "s"; methodBuilder .AddCode( AssignmentBuilder .New() .SetLefthandSide($"var {listVarName}") .SetRighthandSide( CodeBlockBuilder .New() .AddCode("new ") .AddCode(TypeNames.List) .AddCode("<") .AddCode( listTypeDescriptor.InnerType .ToEntityIdBuilder() .SkipTrailingSpace()) .AddCode(">") .AddCode("()"))) .AddEmptyLine() .AddCode( ForEachBuilder .New() .SetLoopHeader( $"{TypeNames.JsonElement} {_child} in {_obj}.Value.EnumerateArray()") .AddCode( MethodCallBuilder .New() .SetMethodName(listVarName, nameof(List <object> .Add)) .AddArgument( BuildUpdateMethodCall( listTypeDescriptor.InnerType, CodeInlineBuilder.From(_child))))) .AddEmptyLine() .AddCode($"return {listVarName};"); AddDeserializeMethod(listTypeDescriptor.InnerType, classBuilder, processed); }