2
0

DeepCloner.cs 21 KB

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