Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/StorableSerializer.cs @ 14927

Last change on this file since 14927 was 14927, checked in by gkronber, 7 years ago

#2520: changed all usages of StorableClass to use StorableType with an auto-generated GUID (did not add StorableType to other type definitions yet)

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