[3742] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[16140] | 3 | * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[3742] | 4 | *
|
---|
| 5 | * This file is part of HeuristicLab.
|
---|
| 6 | *
|
---|
| 7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
| 8 | * it under the terms of the GNU General Public License as published by
|
---|
| 9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
| 10 | * (at your option) any later version.
|
---|
| 11 | *
|
---|
| 12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
| 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
| 15 | * GNU General Public License for more details.
|
---|
| 16 | *
|
---|
| 17 | * You should have received a copy of the GNU General Public License
|
---|
| 18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
| 19 | */
|
---|
| 20 | #endregion
|
---|
| 21 |
|
---|
| 22 | using System;
|
---|
[1623] | 23 | using System.Collections.Generic;
|
---|
| 24 | using System.Linq;
|
---|
[1705] | 25 | using System.Reflection;
|
---|
[4068] | 26 | using System.Reflection.Emit;
|
---|
[3025] | 27 | using System.Text;
|
---|
[4068] | 28 | using HeuristicLab.Persistence.Core;
|
---|
| 29 | using HeuristicLab.Persistence.Interfaces;
|
---|
[1623] | 30 |
|
---|
[1823] | 31 | namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
|
---|
[1623] | 32 |
|
---|
[2994] | 33 | /// <summary>
|
---|
| 34 | /// Intended for serialization of all custom classes. Classes should have the
|
---|
[3029] | 35 | /// <c>[StorableClass]</c> attribute set. The default mode is to serialize
|
---|
| 36 | /// members with the <c>[Storable]</c> attribute set. Alternatively the
|
---|
| 37 | /// storable mode can be set to <c>AllFields</c>, <c>AllProperties</c>
|
---|
| 38 | /// or <c>AllFieldsAndAllProperties</c>.
|
---|
[2994] | 39 | /// </summary>
|
---|
[3029] | 40 | [StorableClass]
|
---|
[3036] | 41 | public sealed class StorableSerializer : ICompositeSerializer {
|
---|
[1623] | 42 |
|
---|
[4175] | 43 | public StorableSerializer() {
|
---|
| 44 | accessorListCache = new AccessorListCache();
|
---|
| 45 | accessorCache = new AccessorCache();
|
---|
| 46 | constructorCache = new Dictionary<Type, Constructor>();
|
---|
| 47 | hookCache = new Dictionary<HookDesignator, List<StorableReflection.Hook>>();
|
---|
| 48 | }
|
---|
[10958] | 49 |
|
---|
[4806] | 50 | [StorableConstructor]
|
---|
| 51 | private StorableSerializer(bool deserializing) : this() { }
|
---|
[4175] | 52 |
|
---|
[3025] | 53 | #region ICompositeSerializer implementation
|
---|
| 54 |
|
---|
[3036] | 55 | /// <summary>
|
---|
| 56 | /// Priority 200, one of the first default composite serializers to try.
|
---|
| 57 | /// </summary>
|
---|
| 58 | /// <value></value>
|
---|
[1623] | 59 | public int Priority {
|
---|
| 60 | get { return 200; }
|
---|
| 61 | }
|
---|
| 62 |
|
---|
[3036] | 63 | /// <summary>
|
---|
| 64 | /// Determines for every type whether the composite serializer is applicable.
|
---|
| 65 | /// </summary>
|
---|
| 66 | /// <param name="type">The type.</param>
|
---|
| 67 | /// <returns>
|
---|
| 68 | /// <c>true</c> if this instance can serialize the specified type; otherwise, <c>false</c>.
|
---|
| 69 | /// </returns>
|
---|
[1823] | 70 | public bool CanSerialize(Type type) {
|
---|
[10958] | 71 | var markedStorable = StorableReflection.HasStorableClassAttribute(type);
|
---|
[3553] | 72 | if (GetConstructor(type) == null)
|
---|
[3577] | 73 | if (markedStorable)
|
---|
| 74 | throw new Exception("[Storable] type has no default constructor and no [StorableConstructor]");
|
---|
| 75 | else
|
---|
| 76 | return false;
|
---|
| 77 | if (!StorableReflection.IsEmptyOrStorableType(type, true))
|
---|
| 78 | if (markedStorable)
|
---|
| 79 | throw new Exception("[Storable] type has non emtpy, non [Storable] base classes");
|
---|
| 80 | else
|
---|
| 81 | return false;
|
---|
| 82 | return true;
|
---|
[1623] | 83 | }
|
---|
| 84 |
|
---|
[3036] | 85 | /// <summary>
|
---|
| 86 | /// Give a reason if possibly why the given type cannot be serialized by this
|
---|
| 87 | /// ICompositeSerializer.
|
---|
| 88 | /// </summary>
|
---|
| 89 | /// <param name="type">The type.</param>
|
---|
| 90 | /// <returns>
|
---|
| 91 | /// A string justifying why type cannot be serialized.
|
---|
| 92 | /// </returns>
|
---|
[2993] | 93 | public string JustifyRejection(Type type) {
|
---|
[10958] | 94 | var sb = new StringBuilder();
|
---|
[3553] | 95 | if (GetConstructor(type) == null)
|
---|
[3577] | 96 | sb.Append("class has no default constructor and no [StorableConstructor]");
|
---|
[3029] | 97 | if (!StorableReflection.IsEmptyOrStorableType(type, true))
|
---|
[4068] | 98 | sb.Append("class (or one of its bases) is not empty and not marked [Storable]; ");
|
---|
[3577] | 99 | return sb.ToString();
|
---|
[2993] | 100 | }
|
---|
| 101 |
|
---|
[3036] | 102 | /// <summary>
|
---|
| 103 | /// Creates the meta info.
|
---|
| 104 | /// </summary>
|
---|
| 105 | /// <param name="o">The object.</param>
|
---|
| 106 | /// <returns>A list of storable components.</returns>
|
---|
[1623] | 107 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
[3031] | 108 | InvokeHook(HookType.BeforeSerialization, o);
|
---|
[1623] | 109 | return new Tag[] { };
|
---|
| 110 | }
|
---|
| 111 |
|
---|
[3036] | 112 | /// <summary>
|
---|
| 113 | /// Decompose an object into <see cref="Tag"/>s, the tag name can be null,
|
---|
| 114 | /// the order in which elements are generated is guaranteed to be
|
---|
| 115 | /// the same as they will be supplied to the Populate method.
|
---|
| 116 | /// </summary>
|
---|
| 117 | /// <param name="obj">An object.</param>
|
---|
| 118 | /// <returns>An enumerable of <see cref="Tag"/>s.</returns>
|
---|
[1623] | 119 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
[10958] | 120 | return from accessor in GetStorableAccessors(obj.GetType())
|
---|
| 121 | where accessor.Get != null
|
---|
| 122 | select new Tag(accessor.Name, accessor.Get(obj));
|
---|
[1623] | 123 | }
|
---|
| 124 |
|
---|
[3036] | 125 | /// <summary>
|
---|
| 126 | /// Create an instance of the object using the provided meta information.
|
---|
| 127 | /// </summary>
|
---|
| 128 | /// <param name="type">A type.</param>
|
---|
| 129 | /// <param name="metaInfo">The meta information.</param>
|
---|
| 130 | /// <returns>A fresh instance of the provided type.</returns>
|
---|
[1623] | 131 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
[2990] | 132 | try {
|
---|
[3553] | 133 | return GetConstructor(type)();
|
---|
[5292] | 134 | } catch (TargetInvocationException x) {
|
---|
[2990] | 135 | throw new PersistenceException(
|
---|
| 136 | "Could not instantiate storable object: Encountered exception during constructor call",
|
---|
| 137 | x.InnerException);
|
---|
| 138 | }
|
---|
[1623] | 139 | }
|
---|
| 140 |
|
---|
[3036] | 141 | /// <summary>
|
---|
| 142 | /// Populates the specified instance.
|
---|
| 143 | /// </summary>
|
---|
| 144 | /// <param name="instance">The instance.</param>
|
---|
| 145 | /// <param name="objects">The objects.</param>
|
---|
| 146 | /// <param name="type">The type.</param>
|
---|
[1623] | 147 | public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
|
---|
| 148 | var memberDict = new Dictionary<string, Tag>();
|
---|
[10958] | 149 | var iter = objects.GetEnumerator();
|
---|
[1623] | 150 | while (iter.MoveNext()) {
|
---|
| 151 | memberDict.Add(iter.Current.Name, iter.Current);
|
---|
[3029] | 152 | }
|
---|
[3913] | 153 | foreach (var accessor in GetStorableAccessors(instance.GetType())) {
|
---|
[5324] | 154 | if (accessor.Set != null) {
|
---|
| 155 | if (memberDict.ContainsKey(accessor.Name)) {
|
---|
| 156 | accessor.Set(instance, memberDict[accessor.Name].Value);
|
---|
| 157 | } else if (accessor.DefaultValue != null) {
|
---|
| 158 | accessor.Set(instance, accessor.DefaultValue);
|
---|
| 159 | }
|
---|
[1623] | 160 | }
|
---|
| 161 | }
|
---|
[3031] | 162 | InvokeHook(HookType.AfterDeserialization, instance);
|
---|
[1623] | 163 | }
|
---|
[3025] | 164 |
|
---|
| 165 | #endregion
|
---|
| 166 |
|
---|
[3029] | 167 | #region constants & private data types
|
---|
[3025] | 168 |
|
---|
| 169 | private const BindingFlags ALL_CONSTRUCTORS =
|
---|
| 170 | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
---|
| 171 |
|
---|
[10958] | 172 | private sealed class HookDesignator : Tuple<Type, HookType> {
|
---|
| 173 | public HookDesignator(Type type, HookType hookType) : base(type, hookType) { }
|
---|
[3031] | 174 | }
|
---|
| 175 |
|
---|
[3913] | 176 | private sealed class AccessorListCache : Dictionary<Type, IEnumerable<DataMemberAccessor>> { }
|
---|
| 177 | private sealed class AccessorCache : Dictionary<MemberInfo, DataMemberAccessor> { }
|
---|
[4175] | 178 | private delegate object Constructor();
|
---|
[3025] | 179 |
|
---|
| 180 | #endregion
|
---|
| 181 |
|
---|
| 182 | #region caches
|
---|
| 183 |
|
---|
[10958] | 184 | private readonly AccessorListCache accessorListCache;
|
---|
| 185 | private readonly AccessorCache accessorCache;
|
---|
| 186 | private readonly Dictionary<Type, Constructor> constructorCache;
|
---|
| 187 | private readonly Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache;
|
---|
[3025] | 188 |
|
---|
| 189 | #endregion
|
---|
| 190 |
|
---|
[3029] | 191 | #region attribute access
|
---|
[3025] | 192 |
|
---|
[3913] | 193 | private IEnumerable<DataMemberAccessor> GetStorableAccessors(Type type) {
|
---|
| 194 | lock (accessorListCache) {
|
---|
| 195 | if (accessorListCache.ContainsKey(type))
|
---|
| 196 | return accessorListCache[type];
|
---|
| 197 | var storableMembers = StorableReflection
|
---|
| 198 | .GenerateStorableMembers(type)
|
---|
[10958] | 199 | .Select(GetMemberAccessor)
|
---|
| 200 | .ToList();
|
---|
[3913] | 201 | accessorListCache[type] = storableMembers;
|
---|
| 202 | return storableMembers;
|
---|
[4068] | 203 | }
|
---|
[3913] | 204 | }
|
---|
| 205 |
|
---|
| 206 | private DataMemberAccessor GetMemberAccessor(StorableMemberInfo mi) {
|
---|
| 207 | lock (accessorCache) {
|
---|
| 208 | if (accessorCache.ContainsKey(mi.MemberInfo))
|
---|
| 209 | return new DataMemberAccessor(accessorCache[mi.MemberInfo], mi.DisentangledName, mi.DefaultValue);
|
---|
[10958] | 210 | var dma = new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue);
|
---|
[3913] | 211 | accessorCache[mi.MemberInfo] = dma;
|
---|
| 212 | return dma;
|
---|
[3025] | 213 | }
|
---|
[3553] | 214 | }
|
---|
[3025] | 215 |
|
---|
[3553] | 216 | private Constructor GetConstructor(Type type) {
|
---|
[3025] | 217 | lock (constructorCache) {
|
---|
| 218 | if (constructorCache.ContainsKey(type))
|
---|
| 219 | return constructorCache[type];
|
---|
[10958] | 220 | var c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
|
---|
[3553] | 221 | constructorCache.Add(type, c);
|
---|
| 222 | return c;
|
---|
| 223 | }
|
---|
[4068] | 224 | }
|
---|
[3553] | 225 |
|
---|
| 226 | private Constructor GetDefaultConstructor(Type type) {
|
---|
[10958] | 227 | var ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
|
---|
[3553] | 228 | if (ci == null)
|
---|
[4068] | 229 | return null;
|
---|
[10958] | 230 | var dm = new DynamicMethod("", typeof(object), null, type, true);
|
---|
| 231 | var ilgen = dm.GetILGenerator();
|
---|
[3553] | 232 | ilgen.Emit(OpCodes.Newobj, ci);
|
---|
| 233 | ilgen.Emit(OpCodes.Ret);
|
---|
| 234 | return (Constructor)dm.CreateDelegate(typeof(Constructor));
|
---|
| 235 | }
|
---|
| 236 |
|
---|
| 237 | private Constructor FindStorableConstructor(Type type) {
|
---|
[10958] | 238 | foreach (var ci in type
|
---|
| 239 | .GetConstructors(ALL_CONSTRUCTORS)
|
---|
| 240 | .Where(ci => ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0)) {
|
---|
| 241 | if (ci.GetParameters().Length != 1 ||
|
---|
| 242 | ci.GetParameters()[0].ParameterType != typeof(bool))
|
---|
| 243 | throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
|
---|
| 244 | var dm = new DynamicMethod("", typeof(object), null, type, true);
|
---|
| 245 | var ilgen = dm.GetILGenerator();
|
---|
| 246 | ilgen.Emit(OpCodes.Ldc_I4_1); // load true
|
---|
| 247 | ilgen.Emit(OpCodes.Newobj, ci);
|
---|
| 248 | ilgen.Emit(OpCodes.Ret);
|
---|
| 249 | return (Constructor)dm.CreateDelegate(typeof(Constructor));
|
---|
[3025] | 250 | }
|
---|
[3553] | 251 | return null;
|
---|
[4068] | 252 | }
|
---|
[3025] | 253 |
|
---|
[3031] | 254 | private void InvokeHook(HookType hookType, object obj) {
|
---|
| 255 | if (obj == null)
|
---|
[10958] | 256 | throw new ArgumentNullException("obj");
|
---|
| 257 | foreach (var hook in GetHooks(hookType, obj.GetType())) {
|
---|
[3553] | 258 | hook(obj);
|
---|
[3031] | 259 | }
|
---|
| 260 | }
|
---|
| 261 |
|
---|
[3553] | 262 | private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
|
---|
[3031] | 263 | lock (hookCache) {
|
---|
[3553] | 264 | List<StorableReflection.Hook> hooks;
|
---|
[3031] | 265 | var designator = new HookDesignator(type, hookType);
|
---|
| 266 | hookCache.TryGetValue(designator, out hooks);
|
---|
| 267 | if (hooks != null)
|
---|
| 268 | return hooks;
|
---|
[3553] | 269 | hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
|
---|
[3031] | 270 | hookCache.Add(designator, hooks);
|
---|
| 271 | return hooks;
|
---|
| 272 | }
|
---|
| 273 | }
|
---|
| 274 |
|
---|
[3025] | 275 | #endregion
|
---|
[3031] | 276 |
|
---|
[3553] | 277 |
|
---|
| 278 |
|
---|
[1623] | 279 | }
|
---|
[3553] | 280 |
|
---|
[2980] | 281 | } |
---|