Skip to content

Commit

Permalink
more refactor on expression style (#3687)
Browse files Browse the repository at this point in the history
More refactor on snippet style for things like equal, greaterthan, etc.

Instead of

GreaterThan(expr1, expr2)

you can do

expr1.GreaterThan(expr2)
  • Loading branch information
m-nash authored Jun 28, 2024
1 parent 08dc5fd commit 1bb4032
Show file tree
Hide file tree
Showing 64 changed files with 295 additions and 309 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ private MethodProvider BuildGetObjectMethodProvider()
Declare("dictionary", New.Dictionary(typeof(string), typeof(object)), out var dictionary),
new ForeachStatement("jsonProperty", element.EnumerateObject(), out var jsonProperty)
{
dictionary.Add(jsonProperty.Property(nameof(JsonProperty.Name)), new JsonElementSnippet(jsonProperty.Property(nameof(JsonProperty.Value))).Untyped.Invoke("GetObject"))
dictionary.Add(jsonProperty.Property(nameof(JsonProperty.Name)), new JsonElementSnippet(jsonProperty.Property(nameof(JsonProperty.Value))).Invoke("GetObject"))
},
Return(dictionary)
}),
Expand All @@ -181,7 +181,7 @@ private MethodProvider BuildGetObjectMethodProvider()
Declare("list", New.List(typeof(object)), out var list),
new ForeachStatement("item", element.EnumerateArray(), out var item)
{
list.Add(new JsonElementSnippet(item).Untyped.Invoke("GetObject"))
list.Add(item.Invoke("GetObject"))
},
Return(list.ToArray())
}),
Expand Down Expand Up @@ -228,7 +228,7 @@ private MethodProvider BuildGetDateTimeOffsetMethodProvider()
var element = new JsonElementSnippet(ScmKnownParameters.JsonElement);
var format = new StringSnippet(_formatParameter);
var body = new SwitchExpression(format,
SwitchCaseExpression.When(Literal("U"), Equal(element.ValueKind, JsonValueKindSnippet.Number), DateTimeOffsetSnippet.FromUnixTimeSeconds(element.GetInt64())),
SwitchCaseExpression.When(Literal("U"), element.ValueKind.Equal(JsonValueKindSnippet.Number), DateTimeOffsetSnippet.FromUnixTimeSeconds(element.GetInt64())),
// relying on the param check of the inner call to throw ArgumentNullException if GetString() returns null
SwitchCaseExpression.Default(ParseDateTimeOffset(element.GetString(), format))
);
Expand Down Expand Up @@ -265,7 +265,7 @@ private MethodProvider BuildGetCharMethodProvider()
new MethodBodyStatement[]
{
Declare("text", element.GetString(), out var text),
new IfStatement(Equal(text, Null).Or(NotEqual(text.Length, Literal(1))))
new IfStatement(text.Equal(Null).Or(text.Length.NotEqual(Literal(1))))
{
Throw(New.NotSupportedException(new FormattableStringExpression("Cannot convert \\\"{0}\\\" to a char", [text])))
},
Expand Down Expand Up @@ -307,7 +307,7 @@ private MethodProvider BuildGetRequiredStringMethodProvider()
var body = new MethodBodyStatement[]
{
Declare("value", element.GetString(), out var value),
new IfStatement(Equal(value, Null))
new IfStatement(value.Equal(Null))
{
Throw(New.InvalidOperationException(new FormattableStringExpression("The requested operation requires an element of type 'String', but the target element has type '{0}'.", [element.ValueKind])))
},
Expand Down Expand Up @@ -335,7 +335,7 @@ private MethodProvider BuildWriteBase64StringValueMethodProvider()
var format = new StringSnippet(_formatParameter);
var body = new MethodBodyStatement[]
{
new IfStatement(Equal(value, Null))
new IfStatement(value.Equal(Null))
{
writer.WriteNullValue(),
Return()
Expand Down Expand Up @@ -373,7 +373,7 @@ private MethodProvider BuildWriteNumberValueMethodProvider()
var format = new StringSnippet(_formatParameter);
var body = new MethodBodyStatement[]
{
new IfStatement(NotEqual(format, Literal("U")))
new IfStatement(format.NotEqual(Literal("U")))
{
Throw(New.ArgumentOutOfRangeException(format, "Only 'U' format is supported when writing a DateTimeOffset as a Number.")),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public MrwSerializationTypeProvider(TypeProvider provider, InputModelType inputM
_shouldOverrideMethods = _model.Inherits != null && _model.Inherits is { IsFrameworkType: false, Implementation: TypeProvider };
_utf8JsonWriterSnippet = new Utf8JsonWriterSnippet(_utf8JsonWriterParameter);
_mrwOptionsParameterSnippet = new ModelReaderWriterOptionsSnippet(_serializationOptionsParameter);
_isNotEqualToWireConditionSnippet = NotEqual(_mrwOptionsParameterSnippet.Format, ModelReaderWriterOptionsSnippet.WireFormat);
_isNotEqualToWireConditionSnippet = _mrwOptionsParameterSnippet.Format.NotEqual(ModelReaderWriterOptionsSnippet.WireFormat);

Name = provider.Name;
Namespace = provider.Namespace;
Expand Down Expand Up @@ -433,7 +433,7 @@ private MethodBodyStatement CreateValidateJsonFormat(CSharpType modelInterface,
MethodBodyStatement[] statements =
[
GetConcreteFormat(_mrwOptionsParameterSnippet, modelInterface, out VariableExpression format),
new IfStatement(NotEqual(format, ModelReaderWriterOptionsSnippet.JsonFormat))
new IfStatement(format.NotEqual(ModelReaderWriterOptionsSnippet.JsonFormat))
{
ThrowValidationFailException(format, modelInterface.Arguments[0], action)
},
Expand All @@ -447,7 +447,7 @@ private MethodBodyStatement GetConcreteFormat(ModelReaderWriterOptionsSnippet op
var cast = This.CastTo(iModelTInterface);
var invokeGetFormatFromOptions = cast.Invoke(nameof(IPersistableModel<object>.GetFormatFromOptions), options);
var condition = new TernaryConditionalExpression(
Equal(options.Format, ModelReaderWriterOptionsSnippet.WireFormat),
options.Format.Equal(ModelReaderWriterOptionsSnippet.WireFormat),
invokeGetFormatFromOptions,
options.Format);
var reference = new VariableExpression(typeof(string), "format");
Expand Down Expand Up @@ -552,12 +552,12 @@ private IfElseStatement CheckPropertyIsInitialized(

if (propertyType.IsCollection && !propertyType.IsReadOnlyMemory && isPropRequired)
{
propertyIsInitialized = And(NotEqual(propertyMemberExpression, Null),
OptionalSnippet.IsCollectionDefined(new StringSnippet(propertyMemberExpression)));
propertyIsInitialized = propertyMemberExpression.NotEqual(Null)
.And(OptionalSnippet.IsCollectionDefined(new StringSnippet(propertyMemberExpression)));
}
else
{
propertyIsInitialized = NotEqual(propertyMemberExpression, Null);
propertyIsInitialized = propertyMemberExpression.NotEqual(Null);
}

return new IfElseStatement(
Expand Down Expand Up @@ -601,7 +601,7 @@ private MethodBodyStatement CreateDictionarySerializationStatement(
{
_utf8JsonWriterSnippet.WritePropertyName(keyValuePair.Key),
TypeRequiresNullCheckInSerialization(keyValuePair.ValueType) ?
new IfStatement(Equal(keyValuePair.Value, Null)) { _utf8JsonWriterSnippet.WriteNullValue(), Continue }: EmptyStatement,
new IfStatement(keyValuePair.Value.Equal(Null)) { _utf8JsonWriterSnippet.WriteNullValue(), Continue }: EmptyStatement,
CreateSerializationStatement(keyValuePair.ValueType, keyValuePair.Value, serializationFormat)
},
_utf8JsonWriterSnippet.WriteEndObject()
Expand All @@ -618,7 +618,7 @@ private MethodBodyStatement CreateListSerializationStatement(
new ForeachStatement("item", array, out VariableExpression item)
{
TypeRequiresNullCheckInSerialization(item.Type) ?
new IfStatement(Equal(item, Null)) { _utf8JsonWriterSnippet.WriteNullValue(), Continue } : EmptyStatement,
new IfStatement(item.Equal(Null)) { _utf8JsonWriterSnippet.WriteNullValue(), Continue } : EmptyStatement,
CreateSerializationStatement(item.Type, item, serializationFormat)
},
_utf8JsonWriterSnippet.WriteEndArray()
Expand Down Expand Up @@ -750,7 +750,7 @@ private IfStatement CreateConditionalSerializationStatement(
var isDefinedCondition = propertyType.IsCollection && !propertyType.IsReadOnlyMemory
? OptionalSnippet.IsCollectionDefined(new StringSnippet(propertyMemberExpression))
: OptionalSnippet.IsDefined(new StringSnippet(propertyMemberExpression));
var condition = isReadOnly ? And(_isNotEqualToWireConditionSnippet, isDefinedCondition) : isDefinedCondition;
var condition = isReadOnly ? _isNotEqualToWireConditionSnippet.And(isDefinedCondition) : isDefinedCondition;

return new IfStatement(condition) { writePropertySerializationStatement };
}
Expand All @@ -774,7 +774,7 @@ private MethodBodyStatement CreateWriteAdditionalRawDataStatement()
CreateSerializationStatement(_rawDataField.Type.Arguments[1], item.Value, SerializationFormat.Default),
};

return new IfStatement(And(_isNotEqualToWireConditionSnippet, NotEqual(rawDataDictionaryExp, Null)))
return new IfStatement(_isNotEqualToWireConditionSnippet.And(rawDataDictionaryExp.NotEqual(Null)))
{
forEachStatement,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,16 +174,16 @@ private MethodProvider BuildToBase64UrlStringMethodProvider()
Declare("numBase64Chars", new IntSnippet(new InvokeStaticMethodExpression(typeof(Convert), nameof(Convert.ToBase64CharArray), [value, Int(0), valueLength, output, Int(0)])), out var numBase64Chars),
EmptyLineStatement,
Declare("i", Int(0), out var i),
new ForStatement(null, LessThan(i, numBase64Chars), new UnaryOperatorExpression("++", i, true))
new ForStatement(null, i.LessThan(numBase64Chars), new UnaryOperatorExpression("++", i, true))
{
Declare("ch", new CharSnippet(output[i]), out var ch),
new IfElseStatement(new IfStatement(Equal(ch, Literal('+')))
new IfElseStatement(new IfStatement(ch.Equal(Literal('+')))
{
output[i].Assign(Literal('-')).Terminate()
}, new IfElseStatement(new IfStatement(Equal(ch, Literal('/')))
}, new IfElseStatement(new IfStatement(ch.Equal(Literal('/')))
{
output[i].Assign(Literal('_')).Terminate()
}, new IfStatement(Equal(ch, Literal('=')))
}, new IfStatement(ch.Equal(Literal('=')))
{
Break
}))
Expand Down Expand Up @@ -223,19 +223,19 @@ private MethodProvider BuildFromBase64UrlString()
{
Declare(outputVar, New.Array(typeof(char), new BinaryOperatorExpression("+", value.Length, paddingCharsToAdd))),
Declare("i", Int(0), out var i),
new ForStatement(null, LessThan(i, value.Length), new UnaryOperatorExpression("++", i, true))
new ForStatement(null, i.LessThan(value.Length), new UnaryOperatorExpression("++", i, true))
{
Declare("ch", value[i], out var ch),
new IfElseStatement(new IfStatement(Equal(ch, Literal('-')))
new IfElseStatement(new IfStatement(ch.Equal(Literal('-')))
{
output[i].Assign(Literal('+')).Terminate()
}, new IfElseStatement(new IfStatement(Equal(ch, Literal('_')))
}, new IfElseStatement(new IfStatement(ch.Equal(Literal('_')))
{
output[i].Assign(Literal('/')).Terminate()
}, output[i].Assign(ch).Terminate()))
},
EmptyLineStatement,
new ForStatement(null, LessThan(i, outputLength), new UnaryOperatorExpression("++", i, true))
new ForStatement(null, i.LessThan(outputLength), new UnaryOperatorExpression("++", i, true))
{
output[i].Assign(Literal('=')).Terminate()
},
Expand Down Expand Up @@ -314,10 +314,10 @@ private MethodProvider BuildConvertToStringMethodProvider()
new SwitchCaseExpression(new DeclarationExpression(typeof(bool), "b", out var b), TypeFormattersSnippet.ToString(b)),
new SwitchCaseExpression(GetTypePattern(new CSharpType[] {typeof(int),typeof(float), typeof(double), typeof(long), typeof(decimal)}), value.CastTo(typeof(IFormattable)).Invoke(nameof(IFormattable.ToString), _defaultNumberFormatField, _invariantCultureExpression)),
// TODO -- figure out how to write this line
SwitchCaseExpression.When(new DeclarationExpression(typeof(byte[]), "b", out var bytes), NotEqual(format, Null), TypeFormattersSnippet.ToString(bytes, format)),
SwitchCaseExpression.When(new DeclarationExpression(typeof(byte[]), "b", out var bytes), format.NotEqual(Null), TypeFormattersSnippet.ToString(bytes, format)),
new SwitchCaseExpression(new DeclarationExpression(typeof(IEnumerable<string>), "s", out var enumerable), StringSnippet.Join(Literal(","), enumerable)),
SwitchCaseExpression.When(new DeclarationExpression(typeof(DateTimeOffset), "dateTime", out var dateTime), NotEqual(format, Null), TypeFormattersSnippet.ToString(dateTime, format)),
SwitchCaseExpression.When(new DeclarationExpression(typeof(TimeSpan), "timeSpan", out var timeSpan), NotEqual(format, Null), TypeFormattersSnippet.ToString(timeSpan, format)),
SwitchCaseExpression.When(new DeclarationExpression(typeof(DateTimeOffset), "dateTime", out var dateTime), format.NotEqual(Null), TypeFormattersSnippet.ToString(dateTime, format)),
SwitchCaseExpression.When(new DeclarationExpression(typeof(TimeSpan), "timeSpan", out var timeSpan), format.NotEqual(Null), TypeFormattersSnippet.ToString(timeSpan, format)),
new SwitchCaseExpression(new DeclarationExpression(typeof(TimeSpan), "timeSpan", out var timeSpanNoFormat), new InvokeStaticMethodExpression(typeof(XmlConvert), nameof(XmlConvert.ToString), [timeSpanNoFormat])),
new SwitchCaseExpression(new DeclarationExpression(typeof(Guid), "guid", out var guid), guid.Invoke("ToString")),
new SwitchCaseExpression(new DeclarationExpression(typeof(BinaryData), "binaryData", out var binaryData), ConvertToString(new BinaryDataSnippet(binaryData).ToArray(), format)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace Microsoft.Generator.CSharp.ClientModel.Snippets
{
internal sealed record BinaryContentSnippet(ValueExpression Untyped) : TypedSnippet<BinaryContent>(Untyped)
internal sealed record BinaryContentSnippet(ValueExpression Expression) : TypedSnippet<BinaryContent>(Expression)
{
public static BinaryContentSnippet Create(ValueExpression serializable)
=> new(InvokeStatic(nameof(BinaryContent.Create), serializable));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

namespace Microsoft.Generator.CSharp.ClientModel.Snippets
{
internal sealed record ClientResultSnippet(ValueExpression Untyped) : TypedSnippet<ClientResult>(Untyped)
internal sealed record ClientResultSnippet(ValueExpression Expression) : TypedSnippet<ClientResult>(Expression)
{
public ValueExpression Value => Property(nameof(ClientResult<object>.Value));
public BinaryDataSnippet Content => throw new InvalidOperationException("Result does not have a Content property");
Expand All @@ -29,6 +29,6 @@ public ClientResultSnippet FromValue(ValueExpression value)
public ClientResultSnippet FromValue(CSharpType explicitValueType, ValueExpression value)
=> new(new InvokeStaticMethodExpression(typeof(ClientResult), nameof(ClientResult.FromValue), new[] { value, this }, new[] { explicitValueType }));

public PipelineResponseSnippet GetRawResponse() => new(Untyped.Invoke(nameof(ClientResult<object>.GetRawResponse)));
public PipelineResponseSnippet GetRawResponse() => new(Expression.Invoke(nameof(ClientResult<object>.GetRawResponse)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace Microsoft.Generator.CSharp.ClientModel.Snippets
{
internal sealed record JsonDocumentSnippet(ValueExpression Untyped) : TypedSnippet<JsonDocument>(Untyped)
internal sealed record JsonDocumentSnippet(ValueExpression Expression) : TypedSnippet<JsonDocument>(Expression)
{
public JsonElementSnippet RootElement => new(Property(nameof(JsonDocument.RootElement)));

Expand Down
Loading

0 comments on commit 1bb4032

Please sign in to comment.