|
| 1 | +// |
| 2 | +// Copyright (c) 2019-2022 Angouri. |
| 3 | +// AngouriMath is licensed under MIT. |
| 4 | +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. |
| 5 | +// Website: https://am.angouri.org. |
| 6 | +// |
| 7 | + |
| 8 | +#if NET8_0_OR_GREATER |
| 9 | + |
| 10 | +using System; |
| 11 | +using System.Text.Json; |
| 12 | +using System.Text.Json.Serialization; |
| 13 | + |
| 14 | +namespace AngouriMath.Core.Serialization |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// Reads and writes an <see cref="Entity"/> as a JSON string holding the expression in |
| 18 | + /// the library's own syntax — what <see cref="Entity.Stringize()"/> prints and |
| 19 | + /// <see cref="MathS.FromString(string)"/> reads. |
| 20 | + /// </summary> |
| 21 | + /// <remarks> |
| 22 | + /// <para> |
| 23 | + /// Every node type carries it already (<c>Core/Serialization/Entity.Serialization.cs</c>), so |
| 24 | + /// an expression is serializable wherever it appears — a property, an array, a dictionary key |
| 25 | + /// — with no configuration. Adding an instance to |
| 26 | + /// <see cref="JsonSerializerOptions.Converters"/> is only needed to place it ahead of another |
| 27 | + /// converter for the same type. |
| 28 | + /// </para> |
| 29 | + /// <para> |
| 30 | + /// There is deliberately no second, structural, format. The printed form is already an exact |
| 31 | + /// serialization and it is the one the library has to keep exact anyway, since it is also the |
| 32 | + /// input format: parsing what <c>Stringize</c> prints gives back the expression printed, and |
| 33 | + /// <c>EveryNodeSurvivesEveryPipelineTest</c> enumerates the node types by reflection and fails |
| 34 | + /// the day a new one stops satisfying that. A structural schema would be a second contract |
| 35 | + /// over the same tree, with its own per-node code to keep in step and its own way of drifting |
| 36 | + /// from the first. What it would buy is speed — reading a 43-node expression costs about |
| 37 | + /// 430 us and 0.8 MB through the parser against 6 us and 25 kB to build the same tree from |
| 38 | + /// constructors — and that is an argument for a faster parser, which every caller who writes |
| 39 | + /// <c>Entity e = "..."</c> would also get, rather than for a second representation that only |
| 40 | + /// serialization uses. |
| 41 | + /// </para> |
| 42 | + /// <para> |
| 43 | + /// What the printed form does not carry, and neither therefore does this: |
| 44 | + /// <see cref="Entity.Codomain"/>, which no node prints, so a node narrowed with |
| 45 | + /// <see cref="Entity.WithCodomain(Domain)"/> comes back with the default |
| 46 | + /// (<a href="https://github.com/asc-community/AngouriMath/issues/1022">#1022</a>); and an |
| 47 | + /// <see cref="Entity.Number.Complex"/> with both parts non-zero, which prints as a sum and |
| 48 | + /// reads back as one — the same number, a different node. Nor is a right nesting of an |
| 49 | + /// <em>associative</em> operator kept, since such an operand is not bracketed at its own |
| 50 | + /// precedence: <c>1 + (2 + 3)</c> comes back as <c>(1 + 2) + 3</c>, the same value written the |
| 51 | + /// other way round. Both are properties of printing rather than of this converter, and fixing |
| 52 | + /// them there fixes them here. |
| 53 | + /// </para> |
| 54 | + /// <a href="https://github.com/asc-community/AngouriMath/issues/323">#323</a> |
| 55 | + /// </remarks> |
| 56 | + /// <example> |
| 57 | + /// <code> |
| 58 | + /// using System.Text.Json; |
| 59 | + /// using AngouriMath; |
| 60 | + /// |
| 61 | + /// public sealed record Problem(string Title, Entity Body); |
| 62 | + /// |
| 63 | + /// var json = JsonSerializer.Serialize(new Problem("quadratic", "x ^ 2 - 3 * x + 2")); |
| 64 | + /// // {"Title":"quadratic","Body":"x ^ 2 - 3 * x + 2"} |
| 65 | + /// var back = JsonSerializer.Deserialize<Problem>(json); |
| 66 | + /// // back.Body == (Entity)"x ^ 2 - 3 * x + 2" |
| 67 | + /// </code> |
| 68 | + /// </example> |
| 69 | + public sealed class EntityJsonConverter : JsonConverter<Entity> |
| 70 | + { |
| 71 | + /// <summary> |
| 72 | + /// Every node type, not just <see cref="Entity"/> itself, so that a member declared as |
| 73 | + /// <see cref="Entity.Variable"/> or <see cref="Entity.Matrix"/> is served too. |
| 74 | + /// </summary> |
| 75 | + public override bool CanConvert(Type typeToConvert) |
| 76 | + => typeof(Entity).IsAssignableFrom(typeToConvert); |
| 77 | + |
| 78 | + /// <inheritdoc/> |
| 79 | + public override Entity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 80 | + => Parse(Text(ref reader), typeToConvert); |
| 81 | + |
| 82 | + /// <inheritdoc/> |
| 83 | + public override void Write(Utf8JsonWriter writer, Entity value, JsonSerializerOptions options) |
| 84 | + => writer.WriteStringValue(value.Stringize()); |
| 85 | + |
| 86 | + /// <inheritdoc/> |
| 87 | + public override Entity ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 88 | + => Parse(Text(ref reader), typeToConvert); |
| 89 | + |
| 90 | + /// <inheritdoc/> |
| 91 | + public override void WriteAsPropertyName(Utf8JsonWriter writer, Entity value, JsonSerializerOptions options) |
| 92 | + => writer.WritePropertyName(value.Stringize()); |
| 93 | + |
| 94 | + private static string Text(ref Utf8JsonReader reader) |
| 95 | + => reader.TokenType is JsonTokenType.String or JsonTokenType.PropertyName |
| 96 | + ? reader.GetString()! |
| 97 | + : throw new JsonException( |
| 98 | + $"An expression is written as a JSON string, and this is {reader.TokenType}."); |
| 99 | + |
| 100 | + /// <summary> |
| 101 | + /// A malformed expression is reported the way <see cref="MathS.FromString(string)"/> |
| 102 | + /// reports it, rather than wrapped: the parser's message names the position and what it |
| 103 | + /// expected, and that is worth more than uniformity with the other converters. |
| 104 | + /// </summary> |
| 105 | + private static Entity Parse(string text, Type typeToConvert) |
| 106 | + { |
| 107 | + var parsed = MathS.FromString(text); |
| 108 | + // A member declared as a specific node type is a claim about what may be read into |
| 109 | + // it. Checking here says which expression and which type; letting it through gives |
| 110 | + // the caller an InvalidCastException from inside the serializer with neither. |
| 111 | + if (!typeToConvert.IsInstanceOfType(parsed)) |
| 112 | + throw new JsonException( |
| 113 | + $"\"{text}\" is {parsed.GetType().Name}, which is not {typeToConvert.Name}."); |
| 114 | + return parsed; |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /// <summary> |
| 119 | + /// Puts <see cref="EntityJsonConverter"/> on <see cref="Entity"/> without the reflective |
| 120 | + /// construction the plain attribute would use. Trimming and NativeAOT are a constraint here |
| 121 | + /// (<a href="https://github.com/asc-community/AngouriMath/issues/746">#746</a>), and |
| 122 | + /// <see cref="JsonConverterAttribute"/> falls back to <c>Activator.CreateInstance</c> only |
| 123 | + /// when <see cref="CreateConverter"/> returns <see langword="null"/>. |
| 124 | + /// </summary> |
| 125 | + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] |
| 126 | + internal sealed class EntityJsonConverterAttribute : JsonConverterAttribute |
| 127 | + { |
| 128 | + public override JsonConverter CreateConverter(Type typeToConvert) => new EntityJsonConverter(); |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +#endif |
0 commit comments