2
0

DeepCloner.cs 22 KB

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