Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/StorableSerializer.cs @ 4695

Last change on this file since 4695 was 4175, checked in by epitzer, 14 years ago

Properly copy serializers when initializing global configuration. (#1136)

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