DeepCloner.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. #nullable enable
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Reflection;
  6. using System.Text.Json;
  7. using System.Text.Json.Serialization.Metadata;
  8. namespace Terminal.Gui;
  9. /// <summary>
  10. /// Provides deep cloning functionality for Terminal.Gui configuration objects.
  11. /// Creates a deep copy of an object by recursively cloning public properties,
  12. /// handling collections, arrays, dictionaries, and circular references.
  13. /// </summary>
  14. /// <remarks>
  15. /// This class does not use <see cref="ICloneable"/> because it does not guarantee deep cloning,
  16. /// may not handle circular references, and is not widely implemented in modern .NET types.
  17. /// Instead, it uses reflection to ensure consistent deep cloning behavior across all types.
  18. /// <para>
  19. /// Limitations:
  20. /// - Types without a parameterless constructor (and not handled as simple types, arrays, dictionaries, or
  21. /// collections) may be instantiated using uninitialized objects, which could lead to runtime errors if not
  22. /// properly handled.
  23. /// - Immutable collections (e.g., <see cref="System.Collections.Immutable.ImmutableDictionary{TKey,TValue}"/>) are
  24. /// not supported and will throw a <see cref="NotSupportedException"/>.
  25. /// - Only public, writable properties are cloned; private fields, read-only properties, and non-public members are
  26. /// ignored.
  27. /// </para>
  28. /// </remarks>
  29. public static class DeepCloner
  30. {
  31. /// <summary>
  32. /// Creates a deep copy of the specified object.
  33. /// </summary>
  34. /// <typeparam name="T">The type of the object to clone.</typeparam>
  35. /// <param name="source">The object to clone.</param>
  36. /// <returns>A deep copy of the source object, or default if source is null.</returns>
  37. [RequiresUnreferencedCode ("Deep cloning may use reflection which might be incompatible with AOT compilation if types aren't registered in SourceGenerationContext")]
  38. [RequiresDynamicCode ("Deep cloning may use reflection that requires runtime code generation if source generation fails")]
  39. public static T? DeepClone<T> (T? source)
  40. {
  41. if (source is null)
  42. {
  43. return default (T?);
  44. }
  45. // For AOT environments, use source generation exclusively
  46. if (IsAotEnvironment ())
  47. {
  48. if (TryUseSourceGeneratedCloner<T> (source, out T? result))
  49. {
  50. return result;
  51. }
  52. // If in AOT but source generation failed, throw an exception
  53. // instead of silently falling back to reflection
  54. throw new InvalidOperationException (
  55. $"Type {typeof (T).FullName} is not properly registered in SourceGenerationContext " +
  56. $"for AOT-compatible cloning.");
  57. }
  58. // Use reflection-based approach, which should have better performance in non-AOT environments
  59. ConcurrentDictionary<object, object> visited = new (ReferenceEqualityComparer.Instance);
  60. return (T?)DeepCloneInternal (source, visited);
  61. }
  62. [RequiresUnreferencedCode ("Calls Terminal.Gui.DeepCloner.CreateInstance(Type)")]
  63. [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "<Pending>")]
  64. private static object? DeepCloneInternal (object? source, ConcurrentDictionary<object, object> visited)
  65. {
  66. if (source is null)
  67. {
  68. return null;
  69. }
  70. // Handle already visited objects to avoid circular references
  71. if (visited.TryGetValue (source, out object? existingClone))
  72. {
  73. return existingClone;
  74. }
  75. Type type = source.GetType ();
  76. // Handle immutable or simple types
  77. if (IsSimpleType (type))
  78. {
  79. return source;
  80. }
  81. // Handle strings explicitly
  82. if (type == typeof (string))
  83. {
  84. return source;
  85. }
  86. // Handle arrays
  87. if (type.IsArray)
  88. {
  89. return CloneArray (source, visited);
  90. }
  91. // Handle dictionaries
  92. if (source is IDictionary)
  93. {
  94. return CloneDictionary (source, visited);
  95. }
  96. // Handle collections
  97. if (typeof (ICollection).IsAssignableFrom (type))
  98. {
  99. return CloneCollection (source, visited);
  100. }
  101. // Create new instance
  102. object clone = CreateInstance (type);
  103. // Add to visited before cloning properties
  104. visited.TryAdd (source, clone);
  105. // Clone writable public and internal properties
  106. foreach (PropertyInfo prop in type.GetProperties (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
  107. .Where (p => !p.IsSpecialName) // exclude private backing fields or compiler-generated props
  108. .Where (p => p is { CanRead: true, CanWrite: true } && p.GetIndexParameters ().Length == 0))
  109. {
  110. object? value = prop.GetValue (source);
  111. object? clonedValue = DeepCloneInternal (value, visited);
  112. prop.SetValue (clone, clonedValue);
  113. }
  114. return clone;
  115. }
  116. private static bool IsSimpleType ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type)
  117. {
  118. if (type.IsPrimitive
  119. || type.IsEnum
  120. || type == typeof (decimal)
  121. || type == typeof (DateTime)
  122. || type == typeof (DateTimeOffset)
  123. || type == typeof (TimeSpan)
  124. || type == typeof (Guid)
  125. || type == typeof (Rune)
  126. || type == typeof (string))
  127. {
  128. return true;
  129. }
  130. // Treat structs with no writable public properties as simple types (immutable structs)
  131. if (type.IsValueType)
  132. {
  133. IEnumerable<PropertyInfo> writableProperties = type.GetProperties (BindingFlags.Instance | BindingFlags.Public)
  134. .Where (p => p is { CanRead: true, CanWrite: true } && p.GetIndexParameters ().Length == 0);
  135. return !writableProperties.Any ();
  136. }
  137. // Treat PropertyInfo (e.g., RuntimePropertyInfo) as a simple type since it's metadata and shouldn't be cloned
  138. if (typeof (PropertyInfo).IsAssignableFrom (type))
  139. {
  140. return true;
  141. }
  142. return false;
  143. }
  144. [RequiresUnreferencedCode ("Calls System.Text.Json.JsonSerializer.Deserialize(String, Type, JsonSerializerOptions)")]
  145. [RequiresDynamicCode ("Calls System.Text.Json.JsonSerializer.Deserialize(String, Type, JsonSerializerOptions)")]
  146. private static object CreateInstance ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type type)
  147. {
  148. try
  149. {
  150. // Try parameterless constructor
  151. if (type.GetConstructor (Type.EmptyTypes) != null)
  152. {
  153. return Activator.CreateInstance (type)!;
  154. }
  155. // Record support
  156. if (type.GetMethod ("<Clone>$") != null)
  157. {
  158. return Activator.CreateInstance (type)!;
  159. }
  160. // In AOT, try using the JsonSerializer if available
  161. if (IsAotEnvironment () && CanSerializeWithJson (type))
  162. {
  163. return JsonSerializer.Deserialize (JsonSerializer.Serialize (new object (), type), type, ConfigurationManager.SerializerContext.Options)!;
  164. }
  165. throw new InvalidOperationException ($"Cannot create instance of type {type.FullName}. No parameterless constructor or clone method found.");
  166. }
  167. catch (MissingMethodException)
  168. {
  169. throw new InvalidOperationException ($"Cannot create instance of type {type.FullName} in AOT context. Consider adding this type to your SourceGenerationContext.");
  170. }
  171. }
  172. [RequiresDynamicCode ("Calls System.Array.CreateInstance(Type, Int32)")]
  173. [RequiresUnreferencedCode ("Calls Terminal.Gui.DeepCloner.DeepCloneInternal(Object, ConcurrentDictionary<Object, Object>)")]
  174. private static object CloneArray (object source, ConcurrentDictionary<object, object> visited)
  175. {
  176. var array = (Array)source;
  177. Type elementType = array.GetType ().GetElementType ()!;
  178. var newArray = Array.CreateInstance (elementType, array.Length);
  179. visited.TryAdd (source, newArray);
  180. for (var i = 0; i < array.Length; i++)
  181. {
  182. object? value = array.GetValue (i);
  183. object? clonedValue = DeepCloneInternal (value, visited);
  184. newArray.SetValue (clonedValue, i);
  185. }
  186. return newArray;
  187. }
  188. [RequiresDynamicCode ("Calls System.Type.MakeGenericType(params Type[])")]
  189. [RequiresUnreferencedCode ("Calls Terminal.Gui.DeepCloner.DeepCloneInternal(Object, ConcurrentDictionary<Object, Object>)")]
  190. private static object CloneCollection (object source, ConcurrentDictionary<object, object> visited)
  191. {
  192. Type type = source.GetType ();
  193. Type elementType = type.GetGenericArguments ().FirstOrDefault () ?? typeof (object);
  194. // Check for immutable collections and throw if found
  195. if (type.IsGenericType)
  196. {
  197. Type genericTypeDef = type.GetGenericTypeDefinition ();
  198. if (genericTypeDef.FullName != null && genericTypeDef.FullName.StartsWith ("System.Collections.Immutable"))
  199. {
  200. throw new NotSupportedException ($"Cloning of immutable collections like {type.Name} is not supported.");
  201. }
  202. }
  203. Type listType = typeof (List<>).MakeGenericType (elementType);
  204. var tempList = (IList)Activator.CreateInstance (listType)!;
  205. // Add to visited before cloning contents to prevent circular reference issues
  206. visited.TryAdd (source, tempList);
  207. foreach (object? item in (IEnumerable)source)
  208. {
  209. object? clonedItem = DeepCloneInternal (item, visited);
  210. tempList.Add (clonedItem);
  211. }
  212. // Try to create the original collection type if possible
  213. if (type != listType && type.GetConstructor ([listType]) != null)
  214. {
  215. object result = Activator.CreateInstance (type, tempList)!;
  216. visited [source] = result;
  217. return result;
  218. }
  219. return tempList;
  220. }
  221. #region Dictionary Support
  222. [RequiresDynamicCode ("Calls System.Type.MakeGenericType(params Type[])")]
  223. [RequiresUnreferencedCode ("Calls Terminal.Gui.DeepCloner.DeepCloneInternal(Object, ConcurrentDictionary<Object, Object>)")]
  224. private static object CloneDictionary (object source, ConcurrentDictionary<object, object> visited)
  225. {
  226. var sourceDict = (IDictionary)source;
  227. Type type = source.GetType ();
  228. // Check for frozen or immutable dictionaries and throw if found
  229. if (type.IsGenericType)
  230. {
  231. CheckForUnsupportedDictionaryTypes (type);
  232. }
  233. // Determine dictionary type and comparer
  234. Type [] genericArgs = type.GetGenericArguments ();
  235. Type dictType = genericArgs.Length == 2
  236. ? typeof (Dictionary<,>).MakeGenericType (genericArgs)
  237. : typeof (Dictionary<object, object>);
  238. object? comparer = type.GetProperty ("Comparer")?.GetValue (source);
  239. // Create a temporary dictionary to hold cloned key-value pairs
  240. IDictionary tempDict = CreateDictionaryInstance (dictType, comparer);
  241. visited.TryAdd (source, tempDict);
  242. object? lastKey = null;
  243. try
  244. {
  245. // Clone all key-value pairs
  246. foreach (object? key in sourceDict.Keys)
  247. {
  248. lastKey = key;
  249. object? clonedKey = DeepCloneInternal (key, visited);
  250. object? clonedValue = DeepCloneInternal (sourceDict [key], visited);
  251. if (tempDict.Contains (clonedKey!))
  252. {
  253. tempDict [clonedKey!] = clonedValue;
  254. }
  255. else
  256. {
  257. tempDict.Add (clonedKey!, clonedValue);
  258. }
  259. }
  260. }
  261. catch (InvalidOperationException ex)
  262. {
  263. // Handle cases where the dictionary is modified during enumeration
  264. throw new InvalidOperationException ($"Error cloning dictionary ({source}) (last key was \"{lastKey}\"). Ensure the source dictionary is not modified during cloning.", ex);
  265. }
  266. // If the original dictionary type has a parameterless constructor, create a new instance
  267. if (type.GetConstructor (Type.EmptyTypes) != null)
  268. {
  269. return CreateFinalDictionary (type, comparer, tempDict, source, visited);
  270. }
  271. return tempDict;
  272. }
  273. private static IDictionary CreateDictionaryInstance ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors)] Type dictType, object? comparer)
  274. {
  275. try
  276. {
  277. // Try to create the dictionary with the comparer
  278. return comparer != null
  279. ? (IDictionary)Activator.CreateInstance (dictType, comparer)!
  280. : (IDictionary)Activator.CreateInstance (dictType)!;
  281. }
  282. catch (MissingMethodException)
  283. {
  284. // Fallback to parameterless constructor if comparer constructor is not available
  285. return (IDictionary)Activator.CreateInstance (dictType)!;
  286. }
  287. }
  288. private static void CheckForUnsupportedDictionaryTypes (Type type)
  289. {
  290. Type? currentType = type;
  291. while (currentType != null && currentType != typeof (object))
  292. {
  293. if (currentType.IsGenericType)
  294. {
  295. string? genericTypeName = currentType.GetGenericTypeDefinition ().FullName;
  296. if (genericTypeName != null &&
  297. (genericTypeName.StartsWith ("System.Collections.Frozen") ||
  298. genericTypeName.StartsWith ("System.Collections.Immutable")))
  299. {
  300. throw new NotSupportedException ($"Cloning of frozen or immutable dictionaries like {type.Name} is not supported.");
  301. }
  302. }
  303. currentType = currentType.BaseType;
  304. }
  305. }
  306. [RequiresUnreferencedCode ("Calls Terminal.Gui.DeepCloner.DeepCloneInternal(Object, ConcurrentDictionary<Object, Object>)")]
  307. private static object CreateFinalDictionary (
  308. [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type,
  309. object? comparer,
  310. IDictionary tempDict,
  311. object source,
  312. ConcurrentDictionary<object, object> visited)
  313. {
  314. IDictionary newDict;
  315. try
  316. {
  317. // Try to create the dictionary with the comparer
  318. newDict = comparer != null
  319. ? (IDictionary)Activator.CreateInstance (type, comparer)!
  320. : (IDictionary)Activator.CreateInstance (type)!;
  321. }
  322. catch (MissingMethodException)
  323. {
  324. // Fallback to parameterless constructor if comparer constructor is not available
  325. newDict = (IDictionary)Activator.CreateInstance (type)!;
  326. }
  327. newDict.Clear ();
  328. visited [source] = newDict;
  329. // Copy cloned key-value pairs to the new dictionary
  330. foreach (object? key in tempDict.Keys)
  331. {
  332. if (newDict.Contains (key))
  333. {
  334. newDict [key] = tempDict [key];
  335. }
  336. else
  337. {
  338. newDict.Add (key, tempDict [key]);
  339. }
  340. }
  341. // Clone additional properties of the derived dictionary type
  342. foreach (PropertyInfo prop in type.GetProperties (BindingFlags.Instance | BindingFlags.Public)
  343. .Where (p => p.CanRead && p.CanWrite && p.GetIndexParameters ().Length == 0))
  344. {
  345. object? value = prop.GetValue (source);
  346. object? clonedValue = DeepCloneInternal (value, visited);
  347. prop.SetValue (newDict, clonedValue);
  348. }
  349. return newDict;
  350. }
  351. #endregion Dictionary Support
  352. #region AOT Support
  353. /// <summary>
  354. /// Determines if a type can be serialized using System.Text.Json based on the types
  355. /// registered in the SourceGenerationContext.
  356. /// </summary>
  357. /// <param name="type">The type to check</param>
  358. /// <returns>True if the type can be serialized using System.Text.Json; otherwise, false.</returns>
  359. private static bool CanSerializeWithJson (Type type)
  360. {
  361. // Check if the type or any of its base types is registered in SourceGenerationContext
  362. return ConfigurationManager.SerializerContext.GetType ()
  363. .GetProperties (BindingFlags.Public | BindingFlags.Static)
  364. .Any (p => p.PropertyType.IsGenericType &&
  365. p.PropertyType.GetGenericTypeDefinition () == typeof (JsonTypeInfo<>) &&
  366. (p.PropertyType.GetGenericArguments () [0] == type ||
  367. p.PropertyType.GetGenericArguments () [0].IsAssignableFrom (type)));
  368. }
  369. private static bool IsAotEnvironment () =>
  370. // Check if running in an AOT environment
  371. Type.GetType ("System.Runtime.CompilerServices.RuntimeFeature")?.GetProperty ("IsDynamicCodeSupported")?.GetValue (null) is bool isDynamicCodeSupported && !isDynamicCodeSupported;
  372. /// <summary>
  373. /// Attempts to clone an object using source-generated serialization from System.Text.Json.
  374. /// This provides an AOT-compatible alternative to reflection-based deep cloning.
  375. /// </summary>
  376. /// <typeparam name="T">The type of the object to clone</typeparam>
  377. /// <param name="source">The source object to clone</param>
  378. /// <param name="result">The cloned result, if successful</param>
  379. /// <returns>True if cloning succeeded using source generation; otherwise, false</returns>
  380. private static bool TryUseSourceGeneratedCloner<T> (T source, [NotNullWhen (true)] out T? result)
  381. {
  382. result = default;
  383. try
  384. {
  385. // Check if the type has a JsonTypeInfo in our SourceGenerationContext
  386. JsonTypeInfo<T>? jsonTypeInfo = GetJsonTypeInfo<T> ();
  387. if (jsonTypeInfo != null)
  388. {
  389. // Use JSON serialization for deep cloning
  390. string json = JsonSerializer.Serialize (source, jsonTypeInfo);
  391. result = JsonSerializer.Deserialize<T> (json, jsonTypeInfo);
  392. return result != null;
  393. }
  394. return false;
  395. }
  396. catch
  397. {
  398. // If any exception occurs during serialization/deserialization,
  399. // return false to fall back to reflection-based approach
  400. return false;
  401. }
  402. }
  403. /// <summary>
  404. /// Gets JsonTypeInfo for a type from the SourceGenerationContext, if available.
  405. /// </summary>
  406. /// <typeparam name="T">The type to get JsonTypeInfo for</typeparam>
  407. /// <returns>JsonTypeInfo if found; otherwise, null</returns>
  408. private static JsonTypeInfo<T>? GetJsonTypeInfo<T> ()
  409. {
  410. // Try to find a matching JsonTypeInfo property in the SourceGenerationContext
  411. var contextType = ConfigurationManager.SerializerContext.GetType ();
  412. // First try for an exact type match
  413. var exactProperty = contextType.GetProperty (typeof (T).Name);
  414. if (exactProperty != null &&
  415. exactProperty.PropertyType.IsGenericType &&
  416. exactProperty.PropertyType.GetGenericTypeDefinition () == typeof (JsonTypeInfo<>) &&
  417. exactProperty.PropertyType.GetGenericArguments () [0] == typeof (T))
  418. {
  419. return (JsonTypeInfo<T>?)exactProperty.GetValue (null);
  420. }
  421. // Then look for any compatible JsonTypeInfo
  422. foreach (var prop in contextType.GetProperties (BindingFlags.Public | BindingFlags.Static))
  423. {
  424. if (prop.PropertyType.IsGenericType &&
  425. prop.PropertyType.GetGenericTypeDefinition () == typeof (JsonTypeInfo<>) &&
  426. prop.PropertyType.GetGenericArguments () [0].IsAssignableFrom (typeof (T)))
  427. {
  428. // This is a bit tricky - we've found a compatible type but need to cast it
  429. // Warning: This might not work for all types and is a bit of a hack
  430. return (JsonTypeInfo<T>?)prop.GetValue (null);
  431. }
  432. }
  433. return null;
  434. }
  435. #endregion AOT Support
  436. }