| | | 1 | | using System.Collections; |
| | | 2 | | using System.Diagnostics.CodeAnalysis; |
| | | 3 | | using System.Runtime.CompilerServices; |
| | | 4 | | using System.Text; |
| | | 5 | | using NGql.Core.Abstractions; |
| | | 6 | | |
| | | 7 | | namespace NGql.Core.Extensions; |
| | | 8 | | |
| | | 9 | | [SuppressMessage("Minor Code Smell", "S3267:Loops should be simplified with \"LINQ\" expressions")] |
| | | 10 | | internal static class Helpers |
| | | 11 | | { |
| | | 12 | | internal static void ExtractVariablesFromValue(object? value, SortedSet<Variable> variables) |
| | | 13 | | { |
| | 7458 | 14 | | ExtractVariablesFromValueCore(value, variables, null); |
| | 7458 | 15 | | } |
| | | 16 | | |
| | | 17 | | private static void ExtractVariablesFromValueCore(object? value, SortedSet<Variable> variables, HashSet<object>? vis |
| | | 18 | | { |
| | 22953 | 19 | | if (value == null) |
| | | 20 | | { |
| | 18 | 21 | | return; |
| | | 22 | | } |
| | | 23 | | |
| | 22935 | 24 | | if (value is Variable variable) |
| | | 25 | | { |
| | 216 | 26 | | variables.Add(variable); |
| | 216 | 27 | | return; |
| | | 28 | | } |
| | | 29 | | |
| | 22719 | 30 | | if (value is IDictionary dict) |
| | | 31 | | { |
| | 7980 | 32 | | ExtractVariablesFromDictionary(dict, variables, visited); |
| | 7980 | 33 | | return; |
| | | 34 | | } |
| | | 35 | | |
| | 14739 | 36 | | if (value is IList list) |
| | | 37 | | { |
| | 84 | 38 | | ExtractVariablesFromList(list, variables, visited); |
| | 84 | 39 | | return; |
| | | 40 | | } |
| | | 41 | | |
| | 14655 | 42 | | if (ShouldExtractFromObjectProperties(value)) |
| | | 43 | | { |
| | 111 | 44 | | ExtractVariablesFromObjectProperties(value, variables, visited); |
| | | 45 | | } |
| | 14655 | 46 | | } |
| | | 47 | | |
| | | 48 | | private static void ExtractVariablesFromDictionary(IDictionary dict, SortedSet<Variable> variables, HashSet<object>? |
| | | 49 | | { |
| | 7980 | 50 | | visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance); |
| | 7989 | 51 | | if (!visited.Add(dict)) return; // cycle detected |
| | | 52 | | |
| | 46296 | 53 | | foreach (var val in dict.Values) |
| | | 54 | | { |
| | 15177 | 55 | | ExtractVariablesFromValueCore(val, variables, visited); |
| | | 56 | | } |
| | 7971 | 57 | | } |
| | | 58 | | |
| | | 59 | | private static void ExtractVariablesFromList(IList list, SortedSet<Variable> variables, HashSet<object>? visited) |
| | | 60 | | { |
| | 84 | 61 | | visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance); |
| | 90 | 62 | | if (!visited.Add(list)) return; // cycle detected |
| | | 63 | | |
| | 426 | 64 | | foreach (var item in list) |
| | | 65 | | { |
| | 135 | 66 | | ExtractVariablesFromValueCore(item, variables, visited); |
| | | 67 | | } |
| | 78 | 68 | | } |
| | | 69 | | |
| | | 70 | | private static bool ShouldExtractFromObjectProperties(object obj) |
| | | 71 | | { |
| | 14655 | 72 | | return obj is not string && |
| | 14655 | 73 | | obj is not Variable && |
| | 14655 | 74 | | obj is not QueryBlock && |
| | 14655 | 75 | | obj is not IDictionary && |
| | 14655 | 76 | | obj is not IList && |
| | 14655 | 77 | | !ValueFormatter.IsPrimitiveType(obj); |
| | | 78 | | } |
| | | 79 | | |
| | | 80 | | private static void ExtractVariablesFromObjectProperties(object obj, SortedSet<Variable> variables, HashSet<object>? |
| | | 81 | | { |
| | 111 | 82 | | visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance); |
| | 114 | 83 | | if (!visited.Add(obj)) return; // cycle detected |
| | 108 | 84 | | var properties = obj.GetType().GetProperties(); |
| | 588 | 85 | | foreach (var property in properties) |
| | | 86 | | { |
| | 186 | 87 | | var propertyValue = property.GetValue(obj); |
| | 186 | 88 | | if (propertyValue != null) |
| | | 89 | | { |
| | 183 | 90 | | ExtractVariablesFromValueCore(propertyValue, variables, visited); |
| | | 91 | | } |
| | | 92 | | } |
| | 108 | 93 | | } |
| | | 94 | | |
| | | 95 | | /// <summary> |
| | | 96 | | /// Generic dictionary merging with recursive support for nested dictionaries. |
| | | 97 | | /// </summary> |
| | | 98 | | /// <summary> |
| | | 99 | | /// Merges two dictionaries with support for nullable values and recursive merging of nested dictionaries. |
| | | 100 | | /// This is the primary efficient implementation that avoids extra allocations. |
| | | 101 | | /// </summary> |
| | | 102 | | /// <param name="existing">The existing dictionary</param> |
| | | 103 | | /// <param name="update">The dictionary to merge in</param> |
| | | 104 | | /// <returns>A merged SortedDictionary with nullable values</returns> |
| | | 105 | | internal static SortedDictionary<string, object?> MergeNullableDictionaries( |
| | | 106 | | IDictionary<string, object?> existing, |
| | | 107 | | IDictionary<string, object?> update) |
| | | 108 | | { |
| | 45 | 109 | | var result = new SortedDictionary<string, object?>(StringComparer.OrdinalIgnoreCase); |
| | | 110 | | |
| | | 111 | | // Copy existing entries |
| | 186 | 112 | | foreach (var kvp in existing) |
| | | 113 | | { |
| | 48 | 114 | | result[kvp.Key] = kvp.Value; |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | // Merge update entries with recursive handling for nested dictionaries |
| | 180 | 118 | | foreach (var (key, newValue) in update) |
| | | 119 | | { |
| | 45 | 120 | | if (result.TryGetValue(key, out var existingValue) && |
| | 45 | 121 | | existingValue is IDictionary<string, object?> existingDict && |
| | 45 | 122 | | newValue is IDictionary<string, object?> newDict) |
| | | 123 | | { |
| | | 124 | | // Recursively merge nested dictionaries |
| | 12 | 125 | | result[key] = MergeNullableDictionaries(existingDict, newDict); |
| | | 126 | | } |
| | | 127 | | else |
| | | 128 | | { |
| | | 129 | | // Override with new value for non-dictionary values or new keys |
| | 33 | 130 | | result[key] = newValue; |
| | | 131 | | } |
| | | 132 | | } |
| | | 133 | | |
| | 45 | 134 | | return result; |
| | | 135 | | } |
| | | 136 | | |
| | | 137 | | /// <summary> |
| | | 138 | | /// Merges metadata dictionaries, handling nullable values appropriately with deep/recursive merging for nested dict |
| | | 139 | | /// </summary> |
| | | 140 | | /// <param name="existing">The existing metadata dictionary</param> |
| | | 141 | | /// <param name="update">The metadata dictionary to merge in</param> |
| | | 142 | | /// <returns>A merged Dictionary with nullable values suitable for metadata</returns> |
| | | 143 | | internal static Dictionary<string, object?> MergeMetadata( |
| | | 144 | | Dictionary<string, object?>? existing, |
| | | 145 | | Dictionary<string, object> update) |
| | | 146 | | { |
| | 225 | 147 | | if (existing is null || existing.Count == 0) return ConvertToNullable(update); |
| | 63 | 148 | | if (update.Count == 0) return existing; |
| | | 149 | | |
| | 51 | 150 | | var result = new Dictionary<string, object?>(existing.Count + update.Count, StringComparer.OrdinalIgnoreCase); |
| | 372 | 151 | | foreach (var (key, value) in existing) result[key] = value; |
| | 264 | 152 | | foreach (var (key, newValue) in update) |
| | | 153 | | { |
| | 81 | 154 | | result[key] = MergedMetadataValue(result, key, newValue); |
| | | 155 | | } |
| | | 156 | | |
| | 51 | 157 | | return result; |
| | | 158 | | } |
| | | 159 | | |
| | | 160 | | private static Dictionary<string, object?> ConvertToNullable(Dictionary<string, object> source) |
| | | 161 | | { |
| | 84 | 162 | | var converted = new Dictionary<string, object?>(source.Count, StringComparer.OrdinalIgnoreCase); |
| | 636 | 163 | | foreach (var (key, value) in source) converted[key] = value; |
| | 84 | 164 | | return converted; |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | /// <summary> |
| | | 168 | | /// Merges metadata dictionaries where both existing and update can have nullable values. |
| | | 169 | | /// </summary> |
| | | 170 | | /// <param name="existing">The existing metadata dictionary</param> |
| | | 171 | | /// <param name="update">The metadata dictionary to merge in</param> |
| | | 172 | | /// <returns>A merged Dictionary with nullable values suitable for metadata</returns> |
| | | 173 | | internal static Dictionary<string, object?> MergeNullableMetadata( |
| | | 174 | | Dictionary<string, object?>? existing, |
| | | 175 | | Dictionary<string, object?>? update) |
| | | 176 | | { |
| | 39 | 177 | | if (update is null || update.Count == 0) |
| | 6 | 178 | | return existing ?? new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase); |
| | | 179 | | |
| | 33 | 180 | | if (existing is null || existing.Count == 0) |
| | 6 | 181 | | return new Dictionary<string, object?>(update, StringComparer.OrdinalIgnoreCase); |
| | | 182 | | |
| | 27 | 183 | | var result = new Dictionary<string, object?>(existing.Count + update.Count, StringComparer.OrdinalIgnoreCase); |
| | 153 | 184 | | foreach (var (key, value) in existing) result[key] = value; |
| | 114 | 185 | | foreach (var (key, newValue) in update) |
| | | 186 | | { |
| | 30 | 187 | | result[key] = MergedNullableMetadataValue(result, key, newValue); |
| | | 188 | | } |
| | 27 | 189 | | return result; |
| | | 190 | | } |
| | | 191 | | |
| | | 192 | | private static object? MergedNullableMetadataValue(Dictionary<string, object?> target, string key, object? newValue) |
| | | 193 | | { |
| | 45 | 194 | | if (target.TryGetValue(key, out var existingValue) |
| | 45 | 195 | | && existingValue is Dictionary<string, object?> existingDict |
| | 45 | 196 | | && newValue is Dictionary<string, object?> newDict) |
| | | 197 | | { |
| | 15 | 198 | | return MergeNullableMetadataDictionaries(existingDict, newDict); |
| | | 199 | | } |
| | 30 | 200 | | return newValue; |
| | | 201 | | } |
| | | 202 | | |
| | | 203 | | /// <summary> |
| | | 204 | | /// Deep merges two metadata dictionaries recursively. |
| | | 205 | | /// </summary> |
| | | 206 | | /// <param name="existing">The existing dictionary</param> |
| | | 207 | | /// <param name="update">The dictionary to merge in</param> |
| | | 208 | | /// <returns>A merged dictionary with deep merging of nested dictionaries</returns> |
| | | 209 | | private static Dictionary<string, object?> MergeMetadataDictionaries( |
| | | 210 | | Dictionary<string, object?> existing, |
| | | 211 | | Dictionary<string, object> update) |
| | | 212 | | { |
| | 18 | 213 | | var result = new Dictionary<string, object?>(existing.Count + update.Count, StringComparer.OrdinalIgnoreCase); |
| | 126 | 214 | | foreach (var (key, value) in existing) result[key] = value; |
| | 90 | 215 | | foreach (var (key, newValue) in update) |
| | | 216 | | { |
| | 27 | 217 | | result[key] = MergedMetadataValue(result, key, newValue); |
| | | 218 | | } |
| | 18 | 219 | | return result; |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | private static object? MergedMetadataValue(Dictionary<string, object?> target, string key, object newValue) |
| | | 223 | | { |
| | 108 | 224 | | if (target.TryGetValue(key, out var existingValue) |
| | 108 | 225 | | && existingValue is Dictionary<string, object?> existingNested |
| | 108 | 226 | | && newValue is Dictionary<string, object> newNested) |
| | | 227 | | { |
| | 18 | 228 | | return MergeMetadataDictionaries(existingNested, newNested); |
| | | 229 | | } |
| | 90 | 230 | | return newValue; |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | private static Dictionary<string, object?> MergeNullableMetadataDictionaries( |
| | | 234 | | Dictionary<string, object?> existing, |
| | | 235 | | Dictionary<string, object?> update) |
| | | 236 | | { |
| | 15 | 237 | | var result = new Dictionary<string, object?>(existing.Count + update.Count, StringComparer.OrdinalIgnoreCase); |
| | 75 | 238 | | foreach (var (key, value) in existing) result[key] = value; |
| | 60 | 239 | | foreach (var (key, newValue) in update) |
| | | 240 | | { |
| | 15 | 241 | | result[key] = MergedNullableMetadataValue(result, key, newValue); |
| | | 242 | | } |
| | 15 | 243 | | return result; |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | internal static object? SortArgumentValue(object? value) |
| | | 247 | | { |
| | 15873 | 248 | | if (value is null) return null; |
| | 30690 | 249 | | if (ValueFormatter.IsPrimitiveType(value)) return value; |
| | 960 | 250 | | return SortNonPrimitive(value); |
| | | 251 | | } |
| | | 252 | | |
| | 960 | 253 | | private static object? SortNonPrimitive(object value) => value switch |
| | 960 | 254 | | { |
| | 774 | 255 | | IDictionary<string, object?> dict => SortDictionary(dict), |
| | 60 | 256 | | Array arr => arr.Cast<object>().Select(SortArgumentValue).ToArray(), |
| | 36 | 257 | | IEnumerable<object> list when !value.GetType().IsArray => SortListItems(list), |
| | 108 | 258 | | _ => IsDecomposable(value) ? DecomposeToDictionary(value) : value, |
| | 960 | 259 | | }; |
| | | 260 | | |
| | | 261 | | private static SortedDictionary<string, object?> SortDictionary(IDictionary<string, object?> dict) |
| | 1929 | 262 | | => new(dict.ToDictionary(kvp => kvp.Key, |
| | 1155 | 263 | | elementSelector: kvp => SortArgumentValue(kvp.Value), |
| | 774 | 264 | | comparer: StringComparer.OrdinalIgnoreCase), |
| | 774 | 265 | | comparer: StringComparer.OrdinalIgnoreCase); |
| | | 266 | | |
| | | 267 | | /// <summary>True for arbitrary CLR objects whose properties should be reflected into a |
| | | 268 | | /// sorted dictionary. Excludes types we already format/serialize specially.</summary> |
| | | 269 | | private static bool IsDecomposable(object obj) |
| | 108 | 270 | | => obj is not string and not Variable and not QueryBlock and not IDictionary and not IList; |
| | | 271 | | |
| | | 272 | | private static SortedDictionary<string, object?> DecomposeToDictionary(object obj) |
| | 102 | 273 | | => new(obj.GetType().GetProperties() |
| | 180 | 274 | | .OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase) |
| | 180 | 275 | | .ToDictionary(p => p.Name, |
| | 180 | 276 | | p => SortArgumentValue(p.GetValue(obj)), |
| | 102 | 277 | | comparer: StringComparer.OrdinalIgnoreCase), |
| | 102 | 278 | | comparer: StringComparer.OrdinalIgnoreCase); |
| | | 279 | | |
| | | 280 | | /// <summary> |
| | | 281 | | /// Efficiently sorts list items in a single pass without double allocations. |
| | | 282 | | /// Avoids: .Select().ToList() which creates intermediate IEnumerable + List allocations. |
| | | 283 | | /// </summary> |
| | | 284 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 285 | | private static List<object?> SortListItems(IEnumerable<object> list) |
| | | 286 | | { |
| | 18 | 287 | | var result = new List<object?>(); |
| | 96 | 288 | | foreach (var item in list) |
| | | 289 | | { |
| | 30 | 290 | | result.Add(SortArgumentValue(item)); |
| | | 291 | | } |
| | 18 | 292 | | return result; |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | /// <summary> |
| | | 296 | | /// Compares two argument dictionaries for equality. |
| | | 297 | | /// </summary> |
| | | 298 | | /// <param name="args1">First argument dictionary</param> |
| | | 299 | | /// <param name="args2">Second argument dictionary</param> |
| | | 300 | | /// <returns>True if arguments are equal, false otherwise</returns> |
| | | 301 | | internal static bool AreArgumentsEqual(SortedDictionary<string, object?>? args1, SortedDictionary<string, object?>? |
| | | 302 | | { |
| | 513 | 303 | | var status = CompareArgumentShapes(args1, args2); |
| | 513 | 304 | | return status switch |
| | 513 | 305 | | { |
| | 345 | 306 | | ArgumentShape.Equal => true, |
| | 24 | 307 | | ArgumentShape.Mismatch => false, |
| | 144 | 308 | | _ => ArgumentEntriesMatch(args1!, args2!), |
| | 513 | 309 | | }; |
| | | 310 | | } |
| | | 311 | | |
| | | 312 | | private enum ArgumentShape { Equal, Mismatch, NeedsEntryComparison } |
| | | 313 | | |
| | | 314 | | private static ArgumentShape CompareArgumentShapes(SortedDictionary<string, object?>? a, SortedDictionary<string, ob |
| | | 315 | | { |
| | 855 | 316 | | if (ReferenceEquals(a, b)) return ArgumentShape.Equal; |
| | 189 | 317 | | if (a is null || b is null) return ArgumentShape.Mismatch; |
| | 159 | 318 | | if (a.Count != b.Count) return ArgumentShape.Mismatch; |
| | 150 | 319 | | if (a.Count == 0) return ArgumentShape.Equal; |
| | 144 | 320 | | return ArgumentShape.NeedsEntryComparison; |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | private static bool ArgumentEntriesMatch(SortedDictionary<string, object?> a, SortedDictionary<string, object?> b) |
| | | 324 | | { |
| | 549 | 325 | | foreach (var (key, value1) in a) |
| | | 326 | | { |
| | 171 | 327 | | if (!b.TryGetValue(key, out var value2)) return false; |
| | 222 | 328 | | if (!AreValuesEqual(value1, value2)) return false; |
| | | 329 | | } |
| | 75 | 330 | | return true; |
| | 69 | 331 | | } |
| | | 332 | | |
| | | 333 | | /// <summary> |
| | | 334 | | /// Compares two values for equality, using optimized comparison strategies. |
| | | 335 | | /// </summary> |
| | | 336 | | /// <param name="value1">First value</param> |
| | | 337 | | /// <param name="value2">Second value</param> |
| | | 338 | | /// <returns>True if values are equal, false otherwise</returns> |
| | | 339 | | private static bool AreValuesEqual(object? value1, object? value2) |
| | | 340 | | { |
| | 453 | 341 | | if (ReferenceEquals(value1, value2)) return true; |
| | 264 | 342 | | if (value1 is null || value2 is null) return false; |
| | | 343 | | |
| | 258 | 344 | | var type1 = value1.GetType(); |
| | 279 | 345 | | if (type1 != value2.GetType()) return false; |
| | | 346 | | |
| | 351 | 347 | | if (type1.IsValueType || value1 is string) return value1.Equals(value2); |
| | | 348 | | |
| | 123 | 349 | | return AreReferenceTypedValuesEqual(value1, value2); |
| | | 350 | | } |
| | | 351 | | |
| | | 352 | | private static bool AreReferenceTypedValuesEqual(object value1, object value2) |
| | | 353 | | { |
| | 123 | 354 | | if (value1 is IDictionary<string, object?> dict1 && value2 is IDictionary<string, object?> dict2) |
| | 66 | 355 | | return AreDictionariesEqual(dict1, dict2); |
| | | 356 | | |
| | 57 | 357 | | if (value1 is IList list1 && value2 is IList list2) |
| | 33 | 358 | | return AreListsEqual(list1, list2); |
| | | 359 | | |
| | 24 | 360 | | return AreObjectsStructurallyEqual(value1, value2); |
| | | 361 | | } |
| | | 362 | | |
| | | 363 | | /// <summary> |
| | | 364 | | /// Optimized dictionary equality comparison |
| | | 365 | | /// </summary> |
| | | 366 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 367 | | private static bool AreDictionariesEqual(IDictionary<string, object?> dict1, IDictionary<string, object?> dict2) |
| | | 368 | | { |
| | 69 | 369 | | if (dict1.Count != dict2.Count) return false; |
| | 243 | 370 | | foreach (var kvp in dict1) |
| | | 371 | | { |
| | 75 | 372 | | if (!dict2.TryGetValue(kvp.Key, out var value2)) return false; |
| | 78 | 373 | | if (!AreValuesEqual(kvp.Value, value2)) return false; |
| | | 374 | | } |
| | 42 | 375 | | return true; |
| | 21 | 376 | | } |
| | | 377 | | |
| | | 378 | | /// <summary> |
| | | 379 | | /// Optimized list equality comparison |
| | | 380 | | /// </summary> |
| | | 381 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 382 | | private static bool AreListsEqual(IList list1, IList list2) |
| | | 383 | | { |
| | 33 | 384 | | var count = list1.Count; |
| | 36 | 385 | | if (count != list2.Count) return false; |
| | 192 | 386 | | for (int i = 0; i < count; i++) |
| | | 387 | | { |
| | 84 | 388 | | if (!AreValuesEqual(list1[i], list2[i])) return false; |
| | | 389 | | } |
| | 21 | 390 | | return true; |
| | | 391 | | } |
| | | 392 | | |
| | | 393 | | /// <summary> |
| | | 394 | | /// Structural equality comparison for complex objects using reflection |
| | | 395 | | /// </summary> |
| | | 396 | | private static bool AreObjectsStructurallyEqual(object obj1, object obj2) |
| | | 397 | | { |
| | 24 | 398 | | var type = obj1.GetType(); |
| | 24 | 399 | | var properties = type.GetProperties(); |
| | | 400 | | |
| | 165 | 401 | | foreach (var property in properties) |
| | | 402 | | { |
| | 60 | 403 | | var value1 = property.GetValue(obj1); |
| | 60 | 404 | | var value2 = property.GetValue(obj2); |
| | | 405 | | |
| | 60 | 406 | | if (!AreValuesEqual(value1, value2)) |
| | | 407 | | { |
| | 3 | 408 | | return false; |
| | | 409 | | } |
| | | 410 | | } |
| | | 411 | | |
| | 21 | 412 | | return true; |
| | | 413 | | } |
| | | 414 | | |
| | | 415 | | /// <summary> |
| | | 416 | | /// Parses field type from path if provided in format "Type fieldPath". |
| | | 417 | | /// </summary> |
| | | 418 | | /// <param name="fieldPath">Field path to parse</param> |
| | | 419 | | /// <param name="defaultType">Default type to use if none specified</param> |
| | | 420 | | /// <param name="type">Parsed type output</param> |
| | | 421 | | /// <returns>Field path with type removed and trimmed</returns> |
| | | 422 | | internal static ReadOnlySpan<char> ParseFieldTypeFromPath(ReadOnlySpan<char> fieldPath, ReadOnlySpan<char> defaultTy |
| | | 423 | | { |
| | 4908 | 424 | | var spaceIndex = fieldPath.IndexOf(' '); |
| | 4908 | 425 | | if (spaceIndex <= 0) |
| | | 426 | | { |
| | 4452 | 427 | | type = defaultType; |
| | 4452 | 428 | | return fieldPath.TrimEndDotsAndSpaces(); |
| | | 429 | | } |
| | | 430 | | |
| | 456 | 431 | | var potentialType = fieldPath[..spaceIndex]; |
| | 456 | 432 | | if (LooksLikeTypeAnnotation(potentialType)) |
| | | 433 | | { |
| | 426 | 434 | | type = potentialType; |
| | 426 | 435 | | fieldPath = fieldPath[(spaceIndex + 1)..]; |
| | | 436 | | } |
| | | 437 | | else |
| | | 438 | | { |
| | 30 | 439 | | type = defaultType; |
| | | 440 | | } |
| | 456 | 441 | | return fieldPath.TrimEndDotsAndSpaces(); |
| | | 442 | | } |
| | | 443 | | |
| | | 444 | | // Type annotation must start with a letter or '[', contain no dots, and either include a |
| | | 445 | | // letter/digit OR be the bare "[]" array marker. |
| | | 446 | | private static bool LooksLikeTypeAnnotation(ReadOnlySpan<char> candidate) |
| | 456 | 447 | | => candidate.Length > 0 |
| | 456 | 448 | | && (char.IsLetter(candidate[0]) || candidate[0] == '[') |
| | 456 | 449 | | && candidate.IndexOf('.') < 0 |
| | 456 | 450 | | && (candidate.HasLetterOrDigit() || candidate.SequenceEqual("[]".AsSpan())); |
| | | 451 | | |
| | | 452 | | /// <summary> |
| | | 453 | | /// Creates a new FieldDefinition with sorted arguments for consistent behavior. |
| | | 454 | | /// Arguments are passed by reference to avoid unnecessary copying of potentially large dictionaries. |
| | | 455 | | /// <param name="name">Field name</param> |
| | | 456 | | /// <param name="type">Field type</param> |
| | | 457 | | /// <param name="alias">Optional field alias</param> |
| | | 458 | | /// <param name="arguments">Field arguments (passed by reference for performance)</param> |
| | | 459 | | /// <param name="path">Field path for caching</param> |
| | | 460 | | /// <param name="metadata">Optional field metadata</param> |
| | | 461 | | /// <returns>New FieldDefinition instance</returns> |
| | | 462 | | /// </summary> |
| | | 463 | | internal static FieldDefinition CreateFieldDefinition(ReadOnlySpan<char> name, ReadOnlySpan<char> type, ReadOnlySpan |
| | | 464 | | { |
| | | 465 | | // Use type interning for memory efficiency |
| | 43335 | 466 | | var nameStr = name.ToString(); |
| | 43335 | 467 | | var typeStr = Caching.TypeCache.GetInternedType(type); |
| | 43335 | 468 | | var aliasStr = alias.IsEmpty ? null : alias.ToString(); |
| | 43335 | 469 | | var pathStr = path.ToString(); |
| | | 470 | | |
| | | 471 | | // FAST PATH: Skip dictionary operations when arguments are empty or null |
| | 43335 | 472 | | if (arguments?.Count == 0 || arguments == null) |
| | | 473 | | { |
| | 36249 | 474 | | return new FieldDefinition(nameStr, typeStr, aliasStr, null) |
| | 36249 | 475 | | { |
| | 36249 | 476 | | Path = pathStr, |
| | 36249 | 477 | | _metadata = metadata |
| | 36249 | 478 | | }; |
| | | 479 | | } |
| | | 480 | | |
| | | 481 | | // Create a new sorted dictionary to ensure consistent argument ordering |
| | 7086 | 482 | | var sortedArguments = new SortedDictionary<string, object?>(StringComparer.OrdinalIgnoreCase); |
| | 42432 | 483 | | foreach (var kvp in arguments) |
| | | 484 | | { |
| | 14130 | 485 | | sortedArguments[kvp.Key] = SortArgumentValue(kvp.Value); |
| | | 486 | | } |
| | | 487 | | |
| | 7086 | 488 | | return new FieldDefinition(nameStr, typeStr, aliasStr, sortedArguments) |
| | 7086 | 489 | | { |
| | 7086 | 490 | | Path = pathStr, |
| | 7086 | 491 | | _metadata = metadata |
| | 7086 | 492 | | }; |
| | | 493 | | } |
| | | 494 | | |
| | | 495 | | /// <summary> |
| | | 496 | | /// Finds an existing field in the collection by name, alias, or path. |
| | | 497 | | /// </summary> |
| | | 498 | | /// <param name="fields">Field collection to search</param> |
| | | 499 | | /// <param name="fieldDefinition">Field definition to find</param> |
| | | 500 | | /// <returns>Existing field if found, null otherwise</returns> |
| | | 501 | | internal static FieldDefinition? FindExistingField(Dictionary<string, FieldDefinition> fields, FieldDefinition field |
| | | 502 | | { |
| | 81 | 503 | | FieldDefinition? existingField = null; |
| | 225 | 504 | | foreach (var f in fields.Values) |
| | | 505 | | { |
| | 51 | 506 | | if (f.Name == fieldDefinition.Name && f._alias == fieldDefinition._alias) |
| | | 507 | | { |
| | 39 | 508 | | existingField = f; |
| | 39 | 509 | | break; |
| | | 510 | | } |
| | | 511 | | } |
| | 81 | 512 | | return existingField ?? fields.GetValueOrDefault(fieldDefinition.Path); |
| | | 513 | | } |
| | | 514 | | |
| | | 515 | | internal static FieldDefinition? FindExistingField(FieldChildren children, FieldDefinition fieldDefinition) |
| | | 516 | | { |
| | 594 | 517 | | foreach (var f in children.AsSpan()) |
| | | 518 | | { |
| | 111 | 519 | | if (f.Name == fieldDefinition.Name && f._alias == fieldDefinition._alias) |
| | 30 | 520 | | return f; |
| | | 521 | | } |
| | 171 | 522 | | return children.Find(fieldDefinition.Path.AsSpan()); |
| | | 523 | | } |
| | | 524 | | |
| | | 525 | | /// <summary> |
| | | 526 | | /// Validates that a field name conforms to GraphQL identifier rules: [_A-Za-z][_0-9A-Za-z]* |
| | | 527 | | /// Handles type-annotation prefixes (e.g. "[User!]! user" → validates "user") and |
| | | 528 | | /// alias prefixes (e.g. "alias:name" → validates both "alias" and "name"). |
| | | 529 | | /// For dotted paths, validate each segment individually before calling this method. |
| | | 530 | | /// </summary> |
| | | 531 | | internal static void ValidateFieldName(ReadOnlySpan<char> name) |
| | | 532 | | { |
| | 3918 | 533 | | if (name.IsEmpty) |
| | 3 | 534 | | throw new ArgumentException("Field name cannot be empty."); |
| | | 535 | | |
| | | 536 | | // Strip type annotation prefix: take identifier part after the last space |
| | 3915 | 537 | | var spaceIndex = name.LastIndexOf(' '); |
| | 3915 | 538 | | var identifier = spaceIndex >= 0 ? name[(spaceIndex + 1)..].Trim() : name.Trim(); |
| | | 539 | | |
| | | 540 | | // Handle alias:name syntax |
| | 3915 | 541 | | var colonIndex = identifier.IndexOf(':'); |
| | 3915 | 542 | | if (colonIndex >= 0) |
| | | 543 | | { |
| | 144 | 544 | | var alias = identifier[..colonIndex].Trim(); |
| | 144 | 545 | | var fieldName = identifier[(colonIndex + 1)..].Trim(); |
| | 285 | 546 | | if (!alias.IsEmpty) ValidateIdentifier(alias); |
| | 276 | 547 | | if (!fieldName.IsEmpty) ValidateIdentifier(fieldName); |
| | 129 | 548 | | return; |
| | | 549 | | } |
| | | 550 | | |
| | 3771 | 551 | | ValidateIdentifier(identifier); |
| | 3759 | 552 | | } |
| | | 553 | | |
| | | 554 | | private static void ValidateIdentifier(ReadOnlySpan<char> name) |
| | | 555 | | { |
| | 4050 | 556 | | if (name.IsEmpty) |
| | 3 | 557 | | throw new ArgumentException("Field name cannot be empty."); |
| | | 558 | | |
| | 4047 | 559 | | if (!IsValidGraphQlNameStart(name[0])) |
| | 9 | 560 | | throw new ArgumentException($"Invalid GraphQL field name '{name.ToString()}': must start with a letter or un |
| | | 561 | | |
| | 40812 | 562 | | for (int i = 1; i < name.Length; i++) |
| | | 563 | | { |
| | 16383 | 564 | | if (!IsValidGraphQlNameChar(name[i])) |
| | 15 | 565 | | throw new ArgumentException($"Invalid GraphQL field name '{name.ToString()}': contains invalid character |
| | | 566 | | } |
| | 4023 | 567 | | } |
| | | 568 | | |
| | | 569 | | private static bool IsValidGraphQlNameStart(char c) |
| | 4047 | 570 | | => c == '_' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); |
| | | 571 | | |
| | | 572 | | private static bool IsValidGraphQlNameChar(char c) |
| | 16383 | 573 | | => c == '_' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'); |
| | | 574 | | |
| | | 575 | | /// <summary> |
| | | 576 | | /// Writes a collection with specified prefix/suffix characters and custom item writer |
| | | 577 | | /// </summary> |
| | | 578 | | internal static void WriteCollection(char prefix, char suffix, IEnumerable list, StringBuilder builder, Action<Strin |
| | | 579 | | { |
| | 954 | 580 | | builder.Append(prefix); |
| | | 581 | | |
| | 954 | 582 | | bool first = true; |
| | 5016 | 583 | | foreach (var obj in list) |
| | | 584 | | { |
| | 1554 | 585 | | if (!first) |
| | | 586 | | { |
| | 621 | 587 | | builder.Append(", "); |
| | | 588 | | } |
| | | 589 | | |
| | 1554 | 590 | | first = false; |
| | 1554 | 591 | | itemWriter(builder, obj); |
| | | 592 | | } |
| | | 593 | | |
| | 954 | 594 | | builder.Append(suffix); |
| | 954 | 595 | | } |
| | | 596 | | } |