-
Notifications
You must be signed in to change notification settings - Fork 97
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1498 from riganti/feature/custom-primitive-types
Support for custom primitive types
- Loading branch information
Showing
37 changed files
with
988 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
namespace DotVVM.Framework.ViewModel; | ||
|
||
/// <summary> | ||
/// Marker interface instructing DotVVM to treat the type as a primitive type. | ||
/// The type is required to have a static TryParse(string, [IFormatProvider,] out T) method and expected to implement ToString() method which is compatible with the TryParse method. | ||
/// Primitive types are then serialized as string in client-side view models. | ||
/// </summary> | ||
public interface IDotvvmPrimitiveType { } |
27 changes: 27 additions & 0 deletions
27
src/Framework/Framework/Compilation/Javascript/CustomPrimitiveTypesConversionTranslator.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
using System.Reflection; | ||
using DotVVM.Framework.Compilation.Javascript.Ast; | ||
using DotVVM.Framework.Utils; | ||
|
||
namespace DotVVM.Framework.Compilation.Javascript | ||
{ | ||
public class CustomPrimitiveTypesConversionTranslator : IJavascriptMethodTranslator | ||
{ | ||
public JsExpression? TryTranslateCall(LazyTranslatedExpression? context, LazyTranslatedExpression[] arguments, MethodInfo method) | ||
{ | ||
var type = context?.OriginalExpression.Type ?? method.DeclaringType!; | ||
type = type.UnwrapNullableType(); | ||
if (method.Name is "ToString" or "Parse" && ReflectionUtils.IsCustomPrimitiveType(type)) | ||
{ | ||
if (method.Name == "ToString" && arguments.Length == 0 && context is {}) | ||
{ | ||
return context.JsExpression(); | ||
} | ||
else if (method.Name == "Parse" && arguments.Length == 1 && context is null) | ||
{ | ||
return arguments[0].JsExpression(); | ||
} | ||
} | ||
return null; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
77 changes: 77 additions & 0 deletions
77
src/Framework/Framework/Configuration/CustomPrimitiveTypeRegistration.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
using System; | ||
using System.Globalization; | ||
using System.Linq; | ||
using System.Linq.Expressions; | ||
using System.Reflection; | ||
using DotVVM.Framework.Routing; | ||
using DotVVM.Framework.Utils; | ||
using DotVVM.Framework.ViewModel; | ||
|
||
namespace DotVVM.Framework.Configuration | ||
{ | ||
public sealed class CustomPrimitiveTypeRegistration | ||
{ | ||
public Type Type { get; } | ||
|
||
public Func<string, ParseResult> TryParseMethod { get; } | ||
|
||
public Func<object, string> ToStringMethod { get; } | ||
|
||
internal CustomPrimitiveTypeRegistration(Type type) | ||
{ | ||
if (ReflectionUtils.IsCollection(type) || ReflectionUtils.IsDictionary(type)) | ||
{ | ||
throw new DotvvmConfigurationException($"The type {type} implements {nameof(IDotvvmPrimitiveType)}, but it cannot be used as a custom primitive type. Custom primitive types cannot be collections, dictionaries, and cannot be primitive types already supported by DotVVM."); | ||
} | ||
|
||
Type = type; | ||
|
||
TryParseMethod = ResolveTryParseMethod(type); | ||
ToStringMethod = typeof(IFormattable).IsAssignableFrom(type) | ||
? obj => ((IFormattable)obj).ToString(null, CultureInfo.InvariantCulture) | ||
: obj => obj.ToString()!; | ||
} | ||
|
||
internal static Func<string, ParseResult> ResolveTryParseMethod(Type type) | ||
{ | ||
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, | ||
new[] { typeof(string), typeof(IFormatProvider), type.MakeByRefType() }, null) | ||
?? type.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, | ||
new[] { typeof(string), type.MakeByRefType() }, null) | ||
?? throw new DotvvmConfigurationException($"The type {type} implements {nameof(IDotvvmPrimitiveType)} but it does not contain a public static method TryParse(string, IFormatProvider, out {type}) or TryParse(string, out {type})!"); | ||
|
||
var inputParameter = Expression.Parameter(typeof(string), "arg"); | ||
var resultVariable = Expression.Variable(type, "result"); | ||
|
||
var arguments = new Expression?[] | ||
{ | ||
inputParameter, | ||
tryParseMethod.GetParameters().Length == 3 | ||
? Expression.Constant(CultureInfo.InvariantCulture) | ||
: null, | ||
resultVariable | ||
} | ||
.Where(a => a != null) | ||
.Cast<Expression>() | ||
.ToArray(); | ||
var call = Expression.Call(tryParseMethod, arguments); | ||
|
||
var body = Expression.Block( | ||
new[] { resultVariable }, | ||
Expression.Condition( | ||
Expression.IsTrue(call), | ||
Expression.New(typeof(ParseResult).GetConstructor(new[] { typeof(object) })!, Expression.Convert(resultVariable, typeof(object))), | ||
Expression.Constant(ParseResult.Failed) | ||
) | ||
); | ||
return Expression.Lambda<Func<string, ParseResult>>(body, inputParameter).Compile(); | ||
} | ||
|
||
public record ParseResult(object? Result = null) | ||
{ | ||
public bool Successful { get; init; } = true; | ||
|
||
public static readonly ParseResult Failed = new ParseResult() { Successful = false }; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
src/Framework/Framework/ViewModel/Serialization/CustomPrimitiveTypeJsonConverter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Globalization; | ||
using System.Text; | ||
using DotVVM.Framework.Utils; | ||
using DotVVM.Framework.ViewModel; | ||
using Newtonsoft.Json; | ||
|
||
namespace DotVVM.Framework.ViewModel.Serialization | ||
{ | ||
public class DotvvmCustomPrimitiveTypeConverter : JsonConverter | ||
{ | ||
public override bool CanConvert(Type objectType) | ||
{ | ||
return ReflectionUtils.IsCustomPrimitiveType(objectType); | ||
} | ||
|
||
public override object? ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | ||
{ | ||
if (reader.TokenType is JsonToken.String | ||
or JsonToken.Boolean | ||
or JsonToken.Integer | ||
or JsonToken.Float | ||
or JsonToken.Date) | ||
{ | ||
var registration = ReflectionUtils.TryGetCustomPrimitiveTypeRegistration(objectType)!; | ||
var parseResult = registration.TryParseMethod(Convert.ToString(reader.Value, CultureInfo.InvariantCulture)!); | ||
if (!parseResult.Successful) | ||
{ | ||
throw new JsonSerializationException($"The value '{reader.Value}' cannot be deserialized as {objectType} because its TryParse method wasn't able to parse the value!"); | ||
} | ||
return parseResult.Result; | ||
} | ||
else if (reader.TokenType == JsonToken.Null) | ||
{ | ||
return null; | ||
} | ||
else | ||
{ | ||
throw new JsonSerializationException($"Token {reader.TokenType} cannot be deserialized as {objectType}! Primitive value in JSON was expected."); | ||
} | ||
} | ||
|
||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | ||
{ | ||
if (value == null) | ||
{ | ||
writer.WriteNull(); | ||
} | ||
else | ||
{ | ||
var registration = ReflectionUtils.TryGetCustomPrimitiveTypeRegistration(value.GetType())!; | ||
writer.WriteValue(registration.ToStringMethod(value)); | ||
} | ||
} | ||
|
||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.