1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2015 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Linq;
|
---|
25 | using System.Reflection;
|
---|
26 | using System.Reflection.Emit;
|
---|
27 | using System.Text;
|
---|
28 | using HeuristicLab.Persistence.Core;
|
---|
29 | using HeuristicLab.Persistence.Interfaces;
|
---|
30 |
|
---|
31 | namespace 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 | [StorableConstructor]
|
---|
51 | private StorableSerializer(bool deserializing) : this() { }
|
---|
52 |
|
---|
53 | #region ICompositeSerializer implementation
|
---|
54 |
|
---|
55 | /// <summary>
|
---|
56 | /// Priority 200, one of the first default composite serializers to try.
|
---|
57 | /// </summary>
|
---|
58 | /// <value></value>
|
---|
59 | public int Priority {
|
---|
60 | get { return 200; }
|
---|
61 | }
|
---|
62 |
|
---|
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>
|
---|
70 | public bool CanSerialize(Type type) {
|
---|
71 | var markedStorable = StorableReflection.HasStorableClassAttribute(type);
|
---|
72 | if (GetConstructor(type) == null)
|
---|
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;
|
---|
83 | }
|
---|
84 |
|
---|
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>
|
---|
93 | public string JustifyRejection(Type type) {
|
---|
94 | var sb = new StringBuilder();
|
---|
95 | if (GetConstructor(type) == null)
|
---|
96 | sb.Append("class has no default constructor and no [StorableConstructor]");
|
---|
97 | if (!StorableReflection.IsEmptyOrStorableType(type, true))
|
---|
98 | sb.Append("class (or one of its bases) is not empty and not marked [Storable]; ");
|
---|
99 | return sb.ToString();
|
---|
100 | }
|
---|
101 |
|
---|
102 | /// <summary>
|
---|
103 | /// Creates the meta info.
|
---|
104 | /// </summary>
|
---|
105 | /// <param name="o">The object.</param>
|
---|
106 | /// <returns>A list of storable components.</returns>
|
---|
107 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
108 | InvokeHook(HookType.BeforeSerialization, o);
|
---|
109 | return new Tag[] { };
|
---|
110 | }
|
---|
111 |
|
---|
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>
|
---|
119 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
120 | return from accessor in GetStorableAccessors(obj.GetType())
|
---|
121 | where accessor.Get != null
|
---|
122 | select new Tag(accessor.Name, accessor.Get(obj));
|
---|
123 | }
|
---|
124 |
|
---|
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>
|
---|
131 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
132 | try {
|
---|
133 | return GetConstructor(type)();
|
---|
134 | } catch (TargetInvocationException x) {
|
---|
135 | throw new PersistenceException(
|
---|
136 | "Could not instantiate storable object: Encountered exception during constructor call",
|
---|
137 | x.InnerException);
|
---|
138 | }
|
---|
139 | }
|
---|
140 |
|
---|
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>
|
---|
147 | public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
|
---|
148 | var memberDict = new Dictionary<string, Tag>();
|
---|
149 | var iter = objects.GetEnumerator();
|
---|
150 | while (iter.MoveNext()) {
|
---|
151 | memberDict.Add(iter.Current.Name, iter.Current);
|
---|
152 | }
|
---|
153 | foreach (var accessor in GetStorableAccessors(instance.GetType())) {
|
---|
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 | }
|
---|
160 | }
|
---|
161 | }
|
---|
162 | InvokeHook(HookType.AfterDeserialization, instance);
|
---|
163 | }
|
---|
164 |
|
---|
165 | #endregion
|
---|
166 |
|
---|
167 | #region constants & private data types
|
---|
168 |
|
---|
169 | private const BindingFlags ALL_CONSTRUCTORS =
|
---|
170 | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
---|
171 |
|
---|
172 | private sealed class HookDesignator : Tuple<Type, HookType> {
|
---|
173 | public HookDesignator(Type type, HookType hookType) : base(type, hookType) { }
|
---|
174 | }
|
---|
175 |
|
---|
176 | private sealed class AccessorListCache : Dictionary<Type, IEnumerable<DataMemberAccessor>> { }
|
---|
177 | private sealed class AccessorCache : Dictionary<MemberInfo, DataMemberAccessor> { }
|
---|
178 | private delegate object Constructor();
|
---|
179 |
|
---|
180 | #endregion
|
---|
181 |
|
---|
182 | #region caches
|
---|
183 |
|
---|
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;
|
---|
188 |
|
---|
189 | #endregion
|
---|
190 |
|
---|
191 | #region attribute access
|
---|
192 |
|
---|
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)
|
---|
199 | .Select(GetMemberAccessor)
|
---|
200 | .ToList();
|
---|
201 | accessorListCache[type] = storableMembers;
|
---|
202 | return storableMembers;
|
---|
203 | }
|
---|
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);
|
---|
210 | var dma = new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue);
|
---|
211 | accessorCache[mi.MemberInfo] = dma;
|
---|
212 | return dma;
|
---|
213 | }
|
---|
214 | }
|
---|
215 |
|
---|
216 | private Constructor GetConstructor(Type type) {
|
---|
217 | lock (constructorCache) {
|
---|
218 | if (constructorCache.ContainsKey(type))
|
---|
219 | return constructorCache[type];
|
---|
220 | var c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
|
---|
221 | constructorCache.Add(type, c);
|
---|
222 | return c;
|
---|
223 | }
|
---|
224 | }
|
---|
225 |
|
---|
226 | private Constructor GetDefaultConstructor(Type type) {
|
---|
227 | var ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
|
---|
228 | if (ci == null)
|
---|
229 | return null;
|
---|
230 | var dm = new DynamicMethod("", typeof(object), null, type, true);
|
---|
231 | var ilgen = dm.GetILGenerator();
|
---|
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) {
|
---|
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));
|
---|
250 | }
|
---|
251 | return null;
|
---|
252 | }
|
---|
253 |
|
---|
254 | private void InvokeHook(HookType hookType, object obj) {
|
---|
255 | if (obj == null)
|
---|
256 | throw new ArgumentNullException("obj");
|
---|
257 | foreach (var hook in GetHooks(hookType, obj.GetType())) {
|
---|
258 | hook(obj);
|
---|
259 | }
|
---|
260 | }
|
---|
261 |
|
---|
262 | private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
|
---|
263 | lock (hookCache) {
|
---|
264 | List<StorableReflection.Hook> hooks;
|
---|
265 | var designator = new HookDesignator(type, hookType);
|
---|
266 | hookCache.TryGetValue(designator, out hooks);
|
---|
267 | if (hooks != null)
|
---|
268 | return hooks;
|
---|
269 | hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
|
---|
270 | hookCache.Add(designator, hooks);
|
---|
271 | return hooks;
|
---|
272 | }
|
---|
273 | }
|
---|
274 |
|
---|
275 | #endregion
|
---|
276 |
|
---|
277 |
|
---|
278 |
|
---|
279 | }
|
---|
280 |
|
---|
281 | } |
---|