| | | 1 | | using System.Buffers; |
| | | 2 | | using System.Collections; |
| | | 3 | | using System.Text; |
| | | 4 | | using NGql.Core; |
| | | 5 | | using NGql.Core.Abstractions; |
| | | 6 | | using NGql.Core.Caching; |
| | | 7 | | using NGql.Core.Extensions; |
| | | 8 | | |
| | | 9 | | namespace NGql.Core.Builders; |
| | | 10 | | |
| | | 11 | | internal sealed class QueryTextBuilder |
| | | 12 | | { |
| | | 13 | | private readonly StringBuilder _stringBuilder; |
| | | 14 | | |
| | | 15 | | // Constructor for creating new instances |
| | 1440 | 16 | | private QueryTextBuilder() => _stringBuilder = new StringBuilder(); |
| | | 17 | | |
| | | 18 | | private const int IndentSize = 4; |
| | | 19 | | private const int MaxBuilderCapacity = 256 * 1024; // UTF-16 characters, not bytes |
| | | 20 | | |
| | | 21 | | // Pre-allocated padding strings for common indentation levels to avoid repeated allocations |
| | 9 | 22 | | private static readonly string[] PaddingCache = new string[20]; |
| | | 23 | | |
| | | 24 | | // Singleton comparer — Dictionary<string,FieldDefinition> is unordered, so we sort at render time. |
| | | 25 | | // Static readonly avoids any per-call allocation; the static lambda is stored as a cached delegate. |
| | | 26 | | // |
| | | 27 | | // Array.Sort with a comparer is an unstable introsort, so the primary key (effective name, |
| | | 28 | | // case-insensitive) alone leaves fields that share an effective key — e.g. a plain `a` and a |
| | | 29 | | // `b` aliased to `a` — in an order chosen arbitrarily by introsort internals, which can differ |
| | | 30 | | // across runtimes and .NET versions and breaks the deterministic render guarantee. The Name and |
| | | 31 | | // Alias tiebreakers (ordinal) turn the comparison into a total order derived purely from each |
| | | 32 | | // field's own data, so equal effective keys resolve to one well-defined order with no extra |
| | | 33 | | // allocation and no insertion-index threading. Primary key semantics are unchanged. |
| | 9 | 34 | | private static readonly Comparison<FieldDefinition> FieldSortComparer = |
| | 9 | 35 | | static (a, b) => |
| | 9 | 36 | | { |
| | 73175304 | 37 | | var effectiveNameComparison = |
| | 73175304 | 38 | | StringComparer.OrdinalIgnoreCase.Compare(a.Alias ?? a.Name, b.Alias ?? b.Name); |
| | 145954624 | 39 | | if (effectiveNameComparison != 0) return effectiveNameComparison; |
| | 9 | 40 | | |
| | 395984 | 41 | | var nameComparison = string.CompareOrdinal(a.Name, b.Name); |
| | 397031 | 42 | | if (nameComparison != 0) return nameComparison; |
| | 9 | 43 | | |
| | 394937 | 44 | | return string.CompareOrdinal(a.Alias, b.Alias); |
| | 9 | 45 | | }; |
| | | 46 | | |
| | | 47 | | // SHARED thread-local builder pool used by both QueryBlock and QueryDefinition |
| | | 48 | | // This consolidates the pooling strategy and prevents duplicate ThreadLocal instances |
| | 9 | 49 | | private static readonly ThreadLocal<Stack<QueryTextBuilder>> SharedBuilderStack = |
| | 636 | 50 | | new(() => new Stack<QueryTextBuilder>()); |
| | | 51 | | |
| | | 52 | | private const int MaxPooledBuilders = 4; |
| | | 53 | | |
| | | 54 | | static QueryTextBuilder() |
| | | 55 | | { |
| | 378 | 56 | | for (int i = 0; i < PaddingCache.Length; i++) |
| | | 57 | | { |
| | 180 | 58 | | PaddingCache[i] = new string(' ', i * IndentSize); |
| | | 59 | | } |
| | 9 | 60 | | } |
| | | 61 | | |
| | | 62 | | /// <summary> |
| | | 63 | | /// Gets a builder instance from the thread-local pool or creates a new one. |
| | | 64 | | /// Caller must return the builder via <see cref="ReturnToPool(QueryTextBuilder)"/>. |
| | | 65 | | /// </summary> |
| | | 66 | | internal static QueryTextBuilder GetFromPool() |
| | | 67 | | { |
| | 28704 | 68 | | var stack = SharedBuilderStack.Value!; |
| | 28704 | 69 | | return stack.Count > 0 ? stack.Pop() : new QueryTextBuilder(); |
| | | 70 | | } |
| | | 71 | | |
| | | 72 | | /// <summary> |
| | | 73 | | /// Returns a builder to the thread-local pool for reuse. |
| | | 74 | | /// Clears the builder and checks capacity to prevent unbounded memory growth. |
| | | 75 | | /// </summary> |
| | | 76 | | internal static void ReturnToPool(QueryTextBuilder builder) |
| | | 77 | | { |
| | | 78 | | // Reject before Clear: clearing a multi-chunk builder can allocate a large |
| | | 79 | | // contiguous buffer that would immediately be discarded. |
| | 28686 | 80 | | if (builder._stringBuilder.Capacity > MaxBuilderCapacity) |
| | | 81 | | { |
| | 21 | 82 | | return; |
| | | 83 | | } |
| | | 84 | | |
| | 28665 | 85 | | var stack = SharedBuilderStack.Value!; |
| | 28665 | 86 | | if (stack.Count < MaxPooledBuilders) |
| | | 87 | | { |
| | 28665 | 88 | | if (stack.Count > 0) |
| | | 89 | | { |
| | 330 | 90 | | var retainedCapacity = builder._stringBuilder.Capacity; |
| | 3270 | 91 | | foreach (var pooled in stack) retainedCapacity += pooled._stringBuilder.Capacity; |
| | 330 | 92 | | if (retainedCapacity > MaxBuilderCapacity) |
| | | 93 | | { |
| | 51 | 94 | | RetainLargestWithinBudget(stack, builder); |
| | 51 | 95 | | return; |
| | | 96 | | } |
| | | 97 | | } |
| | 28614 | 98 | | builder._stringBuilder.Clear(); |
| | 28614 | 99 | | stack.Push(builder); |
| | | 100 | | } |
| | | 101 | | // If pool is full, let GC handle it |
| | 28614 | 102 | | } |
| | | 103 | | |
| | | 104 | | // Over budget: keep the largest builders that fit, because those are the costly ones to regrow. |
| | | 105 | | // Rejecting the incoming builder unconditionally let a small pooled builder block a large one |
| | | 106 | | // on every nested render. The largest ends on top, where the outermost render rents it. |
| | | 107 | | private static void RetainLargestWithinBudget(Stack<QueryTextBuilder> stack, QueryTextBuilder incoming) |
| | | 108 | | { |
| | | 109 | | // Nested renders of large queries land here on every return, so the scratch array is |
| | | 110 | | // reused per thread and cleared afterwards to avoid rooting rejected builders. |
| | 51 | 111 | | var candidates = _retentionScratch ??= new QueryTextBuilder[MaxPooledBuilders]; |
| | 51 | 112 | | var count = stack.Count + 1; |
| | 51 | 113 | | stack.CopyTo(candidates, 0); |
| | 51 | 114 | | candidates[count - 1] = incoming; |
| | 51 | 115 | | candidates.AsSpan(0, count).Sort(LargestCapacityFirst); |
| | | 116 | | |
| | 51 | 117 | | stack.Clear(); |
| | 51 | 118 | | var retainedCapacity = 0; |
| | 51 | 119 | | var kept = 0; |
| | 306 | 120 | | for (var i = 0; i < count; i++) |
| | | 121 | | { |
| | 102 | 122 | | var capacity = candidates[i]._stringBuilder.Capacity; |
| | 102 | 123 | | if (retainedCapacity + capacity > MaxBuilderCapacity) continue; |
| | 51 | 124 | | retainedCapacity += capacity; |
| | 51 | 125 | | candidates[kept++] = candidates[i]; |
| | | 126 | | } |
| | | 127 | | |
| | 204 | 128 | | for (var i = kept - 1; i >= 0; i--) |
| | | 129 | | { |
| | 54 | 130 | | if (ReferenceEquals(candidates[i], incoming)) incoming._stringBuilder.Clear(); |
| | 51 | 131 | | stack.Push(candidates[i]); |
| | | 132 | | } |
| | | 133 | | |
| | 51 | 134 | | Array.Clear(candidates, 0, count); |
| | 51 | 135 | | } |
| | | 136 | | |
| | | 137 | | [ThreadStatic] |
| | | 138 | | private static QueryTextBuilder[]? _retentionScratch; |
| | | 139 | | |
| | 9 | 140 | | private static readonly Comparison<QueryTextBuilder> LargestCapacityFirst = |
| | 60 | 141 | | static (left, right) => right._stringBuilder.Capacity.CompareTo(left._stringBuilder.Capacity); |
| | | 142 | | |
| | | 143 | | /// <summary> |
| | | 144 | | /// Gets padding string for the specified indent level, using cache for common levels. |
| | | 145 | | /// </summary> |
| | | 146 | | /// <param name="indent">Indentation level</param> |
| | | 147 | | /// <returns>Padding string</returns> |
| | | 148 | | private static string GetPadding(int indent) |
| | | 149 | | { |
| | 297426 | 150 | | var paddingLevel = indent / IndentSize; |
| | 297426 | 151 | | return paddingLevel < PaddingCache.Length |
| | 297426 | 152 | | ? PaddingCache[paddingLevel] |
| | 297426 | 153 | | : new string(' ', indent); |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | public string Build(QueryBlock queryBlock, int indent = 0, string? prefix = null) |
| | | 157 | | { |
| | 1212 | 158 | | BuildBlockCore(queryBlock, indent, prefix); |
| | 1212 | 159 | | return _stringBuilder.ToString(); |
| | | 160 | | } |
| | | 161 | | |
| | | 162 | | public string Build(QueryDefinition queryDefinition) |
| | | 163 | | { |
| | 24789 | 164 | | BuildDefinitionCore(queryDefinition); |
| | 24765 | 165 | | return _stringBuilder.ToString(); |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | /// <summary> |
| | | 169 | | /// Renders <paramref name="queryDefinition"/> into the pooled builder and appends the result |
| | | 170 | | /// to the caller-supplied <paramref name="target"/> chunk-by-chunk, with no intermediate |
| | | 171 | | /// string allocation. Shares the exact render machinery used by <see cref="Build(QueryDefinition)"/>. |
| | | 172 | | /// </summary> |
| | | 173 | | internal void BuildInto(QueryDefinition queryDefinition, StringBuilder target) |
| | | 174 | | { |
| | 48 | 175 | | BuildDefinitionCore(queryDefinition); |
| | 48 | 176 | | target.Append(_stringBuilder); |
| | 48 | 177 | | } |
| | | 178 | | |
| | | 179 | | /// <summary> |
| | | 180 | | /// Renders <paramref name="queryDefinition"/> into the pooled builder and writes the result |
| | | 181 | | /// to the caller-supplied <paramref name="writer"/> chunk-by-chunk, with no intermediate |
| | | 182 | | /// string allocation. Shares the exact render machinery used by <see cref="Build(QueryDefinition)"/>. |
| | | 183 | | /// </summary> |
| | | 184 | | internal void BuildInto(QueryDefinition queryDefinition, TextWriter writer) |
| | | 185 | | { |
| | 1221 | 186 | | BuildDefinitionCore(queryDefinition); |
| | 1221 | 187 | | WriteBuilderTo(writer); |
| | 1221 | 188 | | } |
| | | 189 | | |
| | | 190 | | /// <summary> |
| | | 191 | | /// Renders <paramref name="queryBlock"/> into the pooled builder and appends the result to the |
| | | 192 | | /// caller-supplied <paramref name="target"/> chunk-by-chunk, with no intermediate string |
| | | 193 | | /// allocation. Shares the exact render machinery used by <see cref="Build(QueryBlock, int, string?)"/>. |
| | | 194 | | /// </summary> |
| | | 195 | | internal void BuildInto(QueryBlock queryBlock, StringBuilder target, string? prefix = null) |
| | | 196 | | { |
| | 6 | 197 | | BuildBlockCore(queryBlock, 0, prefix); |
| | 6 | 198 | | target.Append(_stringBuilder); |
| | 6 | 199 | | } |
| | | 200 | | |
| | | 201 | | /// <summary> |
| | | 202 | | /// Renders <paramref name="queryBlock"/> into the pooled builder and writes the result to the |
| | | 203 | | /// caller-supplied <paramref name="writer"/> chunk-by-chunk, with no intermediate string |
| | | 204 | | /// allocation. Shares the exact render machinery used by <see cref="Build(QueryBlock, int, string?)"/>. |
| | | 205 | | /// </summary> |
| | | 206 | | internal void BuildInto(QueryBlock queryBlock, TextWriter writer, string? prefix = null) |
| | | 207 | | { |
| | 1206 | 208 | | BuildBlockCore(queryBlock, 0, prefix); |
| | 1206 | 209 | | WriteBuilderTo(writer); |
| | 1206 | 210 | | } |
| | | 211 | | |
| | | 212 | | /// <summary> |
| | | 213 | | /// Renders <paramref name="queryDefinition"/> into the pooled builder and transcodes the result |
| | | 214 | | /// to UTF-8 directly into the caller-supplied <paramref name="bufferWriter"/>, with no |
| | | 215 | | /// intermediate <see cref="string"/> or <c>byte[]</c> allocation. Shares the exact render |
| | | 216 | | /// machinery used by <see cref="Build(QueryDefinition)"/>. |
| | | 217 | | /// </summary> |
| | | 218 | | internal void BuildInto(QueryDefinition queryDefinition, IBufferWriter<byte> bufferWriter) |
| | | 219 | | { |
| | 90 | 220 | | BuildDefinitionCore(queryDefinition); |
| | 90 | 221 | | WriteBuilderToUtf8(bufferWriter); |
| | 90 | 222 | | } |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// Renders <paramref name="queryBlock"/> into the pooled builder and transcodes the result to |
| | | 226 | | /// UTF-8 directly into the caller-supplied <paramref name="bufferWriter"/>, with no intermediate |
| | | 227 | | /// <see cref="string"/> or <c>byte[]</c> allocation. Shares the exact render machinery used by |
| | | 228 | | /// <see cref="Build(QueryBlock, int, string?)"/>. |
| | | 229 | | /// </summary> |
| | | 230 | | internal void BuildInto(QueryBlock queryBlock, IBufferWriter<byte> bufferWriter, string? prefix = null) |
| | | 231 | | { |
| | 12 | 232 | | BuildBlockCore(queryBlock, 0, prefix); |
| | 12 | 233 | | WriteBuilderToUtf8(bufferWriter); |
| | 12 | 234 | | } |
| | | 235 | | |
| | | 236 | | // Streams the pooled builder's backing chunks straight to the writer — TextWriter.Write(span) |
| | | 237 | | // (net8+) copies each chunk with no intermediate .ToString() materialization. |
| | | 238 | | private void WriteBuilderTo(TextWriter writer) |
| | | 239 | | { |
| | 9716 | 240 | | foreach (var chunk in _stringBuilder.GetChunks()) |
| | | 241 | | { |
| | 2431 | 242 | | writer.Write(chunk.Span); |
| | | 243 | | } |
| | 2427 | 244 | | } |
| | | 245 | | |
| | | 246 | | // Transcodes the pooled builder's backing chunks to UTF-8 straight into the buffer writer with |
| | | 247 | | // no intermediate string or byte[]. A single Encoder carries encoder state across chunks: a |
| | | 248 | | // surrogate PAIR (astral codepoint / emoji) can be split across two GetChunks() boundaries, and |
| | | 249 | | // a per-chunk stateless Encoding.GetBytes would mis-encode each half as U+FFFD. Convert with the |
| | | 250 | | // stateful encoder — flushing only on the final chunk — reassembles the pair correctly. |
| | | 251 | | private void WriteBuilderToUtf8(IBufferWriter<byte> bufferWriter) |
| | | 252 | | { |
| | | 253 | | // A StringBuilder always exposes a first chunk, even when it is empty. |
| | 102 | 254 | | var chunks = _stringBuilder.GetChunks(); |
| | 102 | 255 | | chunks.MoveNext(); |
| | | 256 | | |
| | 102 | 257 | | var first = chunks.Current; |
| | 102 | 258 | | if (!chunks.MoveNext()) |
| | | 259 | | { |
| | | 260 | | // A writer that hands back less than the requested size (bounded or slab-capped |
| | | 261 | | // buffers) cannot take the chunk in one call; the encoder loop below fills it in parts. |
| | 93 | 262 | | var destination = bufferWriter.GetSpan(Encoding.UTF8.GetMaxByteCount(first.Length)); |
| | 93 | 263 | | if (Encoding.UTF8.TryGetBytes(first.Span, destination, out var written)) |
| | | 264 | | { |
| | 84 | 265 | | bufferWriter.Advance(written); |
| | 84 | 266 | | return; |
| | | 267 | | } |
| | | 268 | | |
| | 9 | 269 | | EncodeChunk(Encoding.UTF8.GetEncoder(), first.Span, true, bufferWriter); |
| | 9 | 270 | | return; |
| | | 271 | | } |
| | | 272 | | |
| | 9 | 273 | | var encoder = Encoding.UTF8.GetEncoder(); |
| | | 274 | | |
| | | 275 | | // GetChunks exposes no count, so track the last chunk by comparing against the total length |
| | | 276 | | // consumed. Flush must happen exactly once, on the final Convert call, so any trailing |
| | | 277 | | // high-surrogate left dangling by malformed input is emitted rather than silently swallowed. |
| | 9 | 278 | | var remaining = _stringBuilder.Length - first.Length; |
| | 9 | 279 | | EncodeChunk(encoder, first.Span, false, bufferWriter); |
| | | 280 | | do |
| | | 281 | | { |
| | 594 | 282 | | var chars = chunks.Current.Span; |
| | 594 | 283 | | remaining -= chars.Length; |
| | 594 | 284 | | var isLast = remaining == 0; |
| | 594 | 285 | | EncodeChunk(encoder, chars, isLast, bufferWriter); |
| | 594 | 286 | | } while (chunks.MoveNext()); |
| | 9 | 287 | | } |
| | | 288 | | |
| | | 289 | | private static void EncodeChunk(Encoder encoder, ReadOnlySpan<char> chars, bool flush, IBufferWriter<byte> bufferWri |
| | | 290 | | { |
| | | 291 | | while (true) |
| | | 292 | | { |
| | | 293 | | // Size the destination for the whole remaining slice; GetMaxByteCount(0) is still a |
| | | 294 | | // positive minimum so an empty final flush chunk gets a valid span. |
| | 21948 | 295 | | var span = bufferWriter.GetSpan(Encoding.UTF8.GetMaxByteCount(chars.Length)); |
| | 21948 | 296 | | encoder.Convert(chars, span, flush, out var charsUsed, out var bytesUsed, out var completed); |
| | 21948 | 297 | | bufferWriter.Advance(bytesUsed); |
| | 21948 | 298 | | chars = chars[charsUsed..]; |
| | | 299 | | |
| | | 300 | | // completed=false means the destination span filled before the source drained — loop to |
| | | 301 | | // rent more. Otherwise the chunk is done (a pending surrogate is retained in encoder |
| | | 302 | | // state for the next chunk when flush=false). |
| | 21948 | 303 | | if (completed && chars.IsEmpty) |
| | | 304 | | { |
| | | 305 | | break; |
| | | 306 | | } |
| | | 307 | | } |
| | 612 | 308 | | } |
| | | 309 | | |
| | | 310 | | private void BuildBlockCore(QueryBlock queryBlock, int indent, string? prefix) |
| | | 311 | | { |
| | | 312 | | // Clear only at the top-level call; recursive sub-query calls (indent > 0) accumulate. |
| | 4872 | 313 | | if (indent == 0) _stringBuilder.Clear(); |
| | | 314 | | |
| | 2436 | 315 | | BuildBlock(queryBlock, indent, prefix); |
| | 2436 | 316 | | } |
| | | 317 | | |
| | | 318 | | private void BuildDefinitionCore(QueryDefinition queryDefinition) |
| | | 319 | | { |
| | 26148 | 320 | | _stringBuilder.Clear(); |
| | 26148 | 321 | | _stringBuilder.Append(queryDefinition.OperationType switch |
| | 26148 | 322 | | { |
| | 24 | 323 | | OperationType.Subscription => "subscription ", |
| | 60 | 324 | | OperationType.Mutation => "mutation ", |
| | 26064 | 325 | | _ => "query ", |
| | 26148 | 326 | | }); |
| | | 327 | | |
| | 26148 | 328 | | if (!string.IsNullOrEmpty(queryDefinition.Name)) |
| | | 329 | | { |
| | 26148 | 330 | | _stringBuilder.Append(queryDefinition.Name); |
| | | 331 | | } |
| | | 332 | | |
| | 26148 | 333 | | if (queryDefinition._variables?.Count > 0) |
| | | 334 | | { |
| | 195 | 335 | | _stringBuilder.Append('('); |
| | 195 | 336 | | bool first = true; |
| | 930 | 337 | | foreach (var variable in queryDefinition._variables) |
| | | 338 | | { |
| | 270 | 339 | | if (!first) |
| | | 340 | | { |
| | 75 | 341 | | _stringBuilder.Append(", "); |
| | | 342 | | } |
| | | 343 | | |
| | 270 | 344 | | first = false; |
| | 270 | 345 | | variable.Print(_stringBuilder, variable.Name, true); |
| | | 346 | | } |
| | | 347 | | |
| | 195 | 348 | | _stringBuilder.Append(')'); |
| | | 349 | | } |
| | | 350 | | |
| | 26148 | 351 | | _stringBuilder.AppendLine("{"); |
| | | 352 | | |
| | 26148 | 353 | | BuildFieldDefinitions(queryDefinition.FieldsInternal, IndentSize); |
| | | 354 | | |
| | 26124 | 355 | | _stringBuilder.Append("}"); |
| | | 356 | | |
| | 26124 | 357 | | if (queryDefinition._namedFragments is { Count: > 0 }) |
| | | 358 | | { |
| | 123 | 359 | | BuildNamedFragmentDefinitions(queryDefinition._namedFragments); |
| | | 360 | | } |
| | 26124 | 361 | | } |
| | | 362 | | |
| | | 363 | | /// <summary> |
| | | 364 | | /// Appends one query block (and, via <see cref="AddFields"/>, its sub-blocks) to the shared |
| | | 365 | | /// builder without materializing a string. Only the top-level <see cref="Build(QueryBlock, int, string?)"/> |
| | | 366 | | /// call pays for ToString. |
| | | 367 | | /// </summary> |
| | | 368 | | private void BuildBlock(QueryBlock queryBlock, int indent, string? prefix = null) |
| | | 369 | | { |
| | 3051 | 370 | | var pad = GetPadding(indent); |
| | 3051 | 371 | | var prevPad = pad; |
| | | 372 | | |
| | 3051 | 373 | | if (!string.IsNullOrWhiteSpace(queryBlock.Alias) && indent != 0) |
| | | 374 | | { |
| | 108 | 375 | | _stringBuilder.Append(pad); |
| | 108 | 376 | | _stringBuilder.Append(queryBlock.Alias); |
| | 108 | 377 | | _stringBuilder.Append(':'); |
| | 108 | 378 | | pad = ""; |
| | | 379 | | } |
| | | 380 | | |
| | 3051 | 381 | | _stringBuilder.Append(pad); |
| | 3051 | 382 | | if (!string.IsNullOrWhiteSpace(prefix)) |
| | | 383 | | { |
| | 1503 | 384 | | _stringBuilder.Append(prefix).Append(' '); |
| | | 385 | | } |
| | | 386 | | |
| | 3051 | 387 | | _stringBuilder.Append(queryBlock.Name); |
| | | 388 | | |
| | 3051 | 389 | | AddArguments(queryBlock, indent == 0); |
| | 3051 | 390 | | indent += IndentSize; |
| | | 391 | | |
| | 3051 | 392 | | AddFields(queryBlock, prevPad, indent); |
| | 3051 | 393 | | } |
| | | 394 | | |
| | | 395 | | private void BuildFieldDefinitions(FieldChildren children, int indent) |
| | | 396 | | { |
| | | 397 | | // Take ONE snapshot of the concurrent collection. FieldChildren.Count and AsSpan() each do |
| | | 398 | | // an independent volatile read; reading them separately can tear if a concurrent Append lands |
| | | 399 | | // between the two, yielding a span longer than the rented count and silently dropping the tail |
| | | 400 | | // field(s). Rent, copy, render, clear and return all key off this single snapshot's length. |
| | 265038 | 401 | | var span = children.AsSpan(); |
| | 265038 | 402 | | var count = span.Length; |
| | 265038 | 403 | | if (count <= 1) |
| | | 404 | | { |
| | 242365 | 405 | | RenderFields(span, indent); |
| | 242365 | 406 | | return; |
| | | 407 | | } |
| | 22673 | 408 | | var arr = ArrayPool<FieldDefinition>.Shared.Rent(count); |
| | | 409 | | try |
| | | 410 | | { |
| | 22673 | 411 | | span.CopyTo(arr); |
| | 22673 | 412 | | RenderSortedFields(arr, count, indent); |
| | 22673 | 413 | | } |
| | | 414 | | finally |
| | | 415 | | { |
| | 22673 | 416 | | Array.Clear(arr, 0, count); |
| | 22673 | 417 | | ArrayPool<FieldDefinition>.Shared.Return(arr, clearArray: false); |
| | 22673 | 418 | | } |
| | 22673 | 419 | | } |
| | | 420 | | |
| | | 421 | | private void BuildFieldDefinitions(Dictionary<string, FieldDefinition> fields, int indent) |
| | | 422 | | { |
| | 26148 | 423 | | var count = fields.Count; |
| | 26181 | 424 | | if (count == 0) return; |
| | 26115 | 425 | | if (count == 1) |
| | | 426 | | { |
| | 122766 | 427 | | foreach (var field in fields.Values) RenderFields(new ReadOnlySpan<FieldDefinition>(in field), indent); |
| | 24534 | 428 | | return; |
| | | 429 | | } |
| | | 430 | | |
| | | 431 | | // Dictionary<TKey,TValue> is insertion-ordered, not alphabetical. Copy values to a |
| | | 432 | | // pooled buffer so RenderSortedFields can sort once and render with a stable order. |
| | 1557 | 433 | | var arr = ArrayPool<FieldDefinition>.Shared.Rent(count); |
| | | 434 | | try |
| | | 435 | | { |
| | 1557 | 436 | | int i = 0; |
| | 376263 | 437 | | foreach (var f in fields.Values) arr[i++] = f; |
| | 1557 | 438 | | RenderSortedFields(arr, count, indent); |
| | 1557 | 439 | | } |
| | | 440 | | finally |
| | | 441 | | { |
| | 1557 | 442 | | Array.Clear(arr, 0, count); |
| | 1557 | 443 | | ArrayPool<FieldDefinition>.Shared.Return(arr, clearArray: false); |
| | 1557 | 444 | | } |
| | 1557 | 445 | | } |
| | | 446 | | |
| | | 447 | | /// <summary> |
| | | 448 | | /// Sorts <paramref name="arr"/> in place via <see cref="FieldSortComparer"/> and writes the |
| | | 449 | | /// rendered fields into <see cref="_stringBuilder"/>. Shared rendering core for both backing |
| | | 450 | | /// collection types (Dictionary at the root, FieldChildren for nested levels). |
| | | 451 | | /// </summary> |
| | | 452 | | private void RenderSortedFields(FieldDefinition[] arr, int count, int indent) |
| | | 453 | | { |
| | 24230 | 454 | | arr.AsSpan(0, count).Sort(FieldSortComparer); |
| | 24230 | 455 | | RenderFields(arr.AsSpan(0, count), indent); |
| | 24230 | 456 | | } |
| | | 457 | | |
| | | 458 | | private void RenderFields(ReadOnlySpan<FieldDefinition> fields, int indent) |
| | | 459 | | { |
| | 291153 | 460 | | var padding = GetPadding(indent); |
| | | 461 | | |
| | 14168438 | 462 | | foreach (var field in fields) |
| | | 463 | | { |
| | 6793078 | 464 | | _stringBuilder.Append(padding); |
| | | 465 | | |
| | 6793078 | 466 | | if (field.Alias != null) |
| | | 467 | | { |
| | 2193 | 468 | | _stringBuilder.Append(field.Alias); |
| | 2193 | 469 | | _stringBuilder.Append(':'); |
| | | 470 | | } |
| | | 471 | | |
| | 6793078 | 472 | | _stringBuilder.Append(field.Name); |
| | | 473 | | |
| | 6793078 | 474 | | if (field._arguments is { Count: > 0 }) |
| | | 475 | | { |
| | 8058 | 476 | | BuildFieldArguments(field._arguments); |
| | | 477 | | } |
| | | 478 | | |
| | | 479 | | // Directives render after the name+arguments and before the selection set (or the |
| | | 480 | | // bare-leaf newline), space-separated, in insertion order — order is user-visible so |
| | | 481 | | // it is never sorted. |
| | 6793054 | 482 | | if (field._directives is { Count: > 0 }) |
| | | 483 | | { |
| | 159 | 484 | | BuildFieldDirectives(field._directives); |
| | | 485 | | } |
| | | 486 | | |
| | | 487 | | // A field gets a `{ … }` block when it has child fields, inline fragments, or |
| | | 488 | | // named-fragment spreads. Plain leaf fields (none of the above) render as a bare |
| | | 489 | | // name + newline. |
| | 6793054 | 490 | | var hasSelections = field._children is { Count: > 0 } |
| | 6793054 | 491 | | || field._fragments is { Count: > 0 } |
| | 6793054 | 492 | | || field._spreadFragments is { Count: > 0 }; |
| | | 493 | | |
| | 6793054 | 494 | | if (hasSelections) |
| | | 495 | | { |
| | 264933 | 496 | | _stringBuilder.AppendLine("{"); |
| | 264933 | 497 | | BuildSelectionSetBody(field._children, field._fragments, field._spreadFragments, indent + IndentSize); |
| | 264933 | 498 | | _stringBuilder.Append(padding); |
| | 264933 | 499 | | _stringBuilder.AppendLine("}"); |
| | | 500 | | } |
| | | 501 | | else |
| | | 502 | | { |
| | 6528121 | 503 | | _stringBuilder.AppendLine(); |
| | | 504 | | } |
| | | 505 | | } |
| | 291129 | 506 | | } |
| | | 507 | | |
| | | 508 | | /// <summary> |
| | | 509 | | /// Renders one selection-set body — plain fields, then inline fragments, then named-fragment |
| | | 510 | | /// spreads. Single shared implementation for the three nesting contexts (regular fields, |
| | | 511 | | /// inline fragments, named-fragment definitions) so the member order and Count guards live |
| | | 512 | | /// in exactly one place. |
| | | 513 | | /// </summary> |
| | | 514 | | private void BuildSelectionSetBody( |
| | | 515 | | FieldChildren? fields, |
| | | 516 | | Dictionary<string, InlineFragmentDefinition>? fragments, |
| | | 517 | | List<string>? spreadFragments, |
| | | 518 | | int indent) |
| | | 519 | | { |
| | 265227 | 520 | | if (fields is { Count: > 0 }) |
| | | 521 | | { |
| | 265038 | 522 | | BuildFieldDefinitions(fields, indent); |
| | | 523 | | } |
| | 265227 | 524 | | if (fragments is { Count: > 0 }) |
| | | 525 | | { |
| | 126 | 526 | | BuildInlineFragments(fragments, indent); |
| | | 527 | | } |
| | 265227 | 528 | | if (spreadFragments is { Count: > 0 }) |
| | | 529 | | { |
| | 141 | 530 | | BuildSpreadFragments(spreadFragments, indent); |
| | | 531 | | } |
| | 265227 | 532 | | } |
| | | 533 | | |
| | | 534 | | /// <summary> |
| | | 535 | | /// Renders the inline fragments attached to a field. Each fragment is written as |
| | | 536 | | /// <c>... on TypeName { … }</c> with its own selection set rendered recursively. |
| | | 537 | | /// Fragments are sorted alphabetically by type name (case-sensitive — GraphQL type names |
| | | 538 | | /// are case-sensitive) for deterministic output. |
| | | 539 | | /// </summary> |
| | | 540 | | private void BuildInlineFragments(Dictionary<string, InlineFragmentDefinition> fragments, int indent) |
| | | 541 | | { |
| | | 542 | | // Snapshot keys AND values into paired pooled buffers and sort them together — keeps |
| | | 543 | | // the output stable regardless of insertion order without re-looking each fragment up |
| | | 544 | | // by key after the sort. |
| | 126 | 545 | | var count = fragments.Count; |
| | 126 | 546 | | var typeNames = ArrayPool<string>.Shared.Rent(count); |
| | 126 | 547 | | var definitions = ArrayPool<InlineFragmentDefinition>.Shared.Rent(count); |
| | | 548 | | try |
| | | 549 | | { |
| | 126 | 550 | | int i = 0; |
| | 546 | 551 | | foreach (var (key, value) in fragments) |
| | | 552 | | { |
| | 147 | 553 | | typeNames[i] = key; |
| | 147 | 554 | | definitions[i] = value; |
| | 147 | 555 | | i++; |
| | | 556 | | } |
| | 126 | 557 | | Array.Sort(typeNames, definitions, 0, count, StringComparer.Ordinal); |
| | | 558 | | |
| | 126 | 559 | | var padding = GetPadding(indent); |
| | 546 | 560 | | for (int j = 0; j < count; j++) |
| | | 561 | | { |
| | 147 | 562 | | var fragment = definitions[j]; |
| | 147 | 563 | | _stringBuilder.Append(padding); |
| | 147 | 564 | | _stringBuilder.Append("... on "); |
| | 147 | 565 | | _stringBuilder.Append(fragment.TypeName); |
| | | 566 | | |
| | | 567 | | // Directives render after the type condition and before the selection set, exactly |
| | | 568 | | // like on a plain field: `... on Admin @include(if:$a){ … }`. |
| | 147 | 569 | | if (fragment._directives is { Count: > 0 }) |
| | | 570 | | { |
| | 24 | 571 | | BuildFieldDirectives(fragment._directives); |
| | | 572 | | } |
| | | 573 | | |
| | 147 | 574 | | _stringBuilder.AppendLine("{"); |
| | | 575 | | |
| | 147 | 576 | | BuildSelectionSetBody(fragment._fields, fragment._fragments, fragment._spreadFragments, indent + IndentS |
| | | 577 | | |
| | 147 | 578 | | _stringBuilder.Append(padding); |
| | 147 | 579 | | _stringBuilder.AppendLine("}"); |
| | | 580 | | } |
| | 126 | 581 | | } |
| | | 582 | | finally |
| | | 583 | | { |
| | 126 | 584 | | Array.Clear(typeNames, 0, count); |
| | 126 | 585 | | Array.Clear(definitions, 0, count); |
| | 126 | 586 | | ArrayPool<string>.Shared.Return(typeNames, clearArray: false); |
| | 126 | 587 | | ArrayPool<InlineFragmentDefinition>.Shared.Return(definitions, clearArray: false); |
| | 126 | 588 | | } |
| | 126 | 589 | | } |
| | | 590 | | |
| | | 591 | | /// <summary> |
| | | 592 | | /// Renders <c>...Name</c> spreads of named fragments inside a selection set. Order is |
| | | 593 | | /// preserved as recorded by <c>FieldBuilder.SpreadFragment</c> calls — we don't sort |
| | | 594 | | /// because spread order can become user-visible once directives (which differ per spread |
| | | 595 | | /// site) ship in a future release. |
| | | 596 | | /// </summary> |
| | | 597 | | private void BuildSpreadFragments(List<string> spreadFragments, int indent) |
| | | 598 | | { |
| | 141 | 599 | | var padding = GetPadding(indent); |
| | 582 | 600 | | for (int i = 0; i < spreadFragments.Count; i++) |
| | | 601 | | { |
| | 150 | 602 | | _stringBuilder.Append(padding); |
| | 150 | 603 | | _stringBuilder.Append("..."); |
| | 150 | 604 | | _stringBuilder.AppendLine(spreadFragments[i]); |
| | | 605 | | } |
| | 141 | 606 | | } |
| | | 607 | | |
| | | 608 | | /// <summary> |
| | | 609 | | /// Renders the operation's named-fragment definitions as <c>fragment Name on Type{ … }</c> |
| | | 610 | | /// blocks after the operation's closing brace. Fragments are sorted alphabetically by name |
| | | 611 | | /// (case-sensitive) for deterministic output, consistent with how inline fragments and |
| | | 612 | | /// fields are sorted elsewhere. |
| | | 613 | | /// </summary> |
| | | 614 | | private void BuildNamedFragmentDefinitions(Dictionary<string, NamedFragmentDefinition> fragments) |
| | | 615 | | { |
| | 123 | 616 | | var count = fragments.Count; |
| | 123 | 617 | | var names = ArrayPool<string>.Shared.Rent(count); |
| | 123 | 618 | | var definitions = ArrayPool<NamedFragmentDefinition>.Shared.Rent(count); |
| | | 619 | | try |
| | | 620 | | { |
| | 123 | 621 | | int i = 0; |
| | 540 | 622 | | foreach (var (key, value) in fragments) |
| | | 623 | | { |
| | 147 | 624 | | names[i] = key; |
| | 147 | 625 | | definitions[i] = value; |
| | 147 | 626 | | i++; |
| | | 627 | | } |
| | 123 | 628 | | Array.Sort(names, definitions, 0, count, StringComparer.Ordinal); |
| | | 629 | | |
| | 540 | 630 | | for (int j = 0; j < count; j++) |
| | | 631 | | { |
| | 147 | 632 | | var fragment = definitions[j]; |
| | | 633 | | // First fragment: operation ended with `}` (no trailing newline) — emit a |
| | | 634 | | // newline to break onto its own line. Subsequent fragments: previous fragment |
| | | 635 | | // already ended with `}\n`, so go straight to `fragment` with no extra blank line. |
| | 147 | 636 | | if (j == 0) |
| | | 637 | | { |
| | 123 | 638 | | _stringBuilder.AppendLine(); |
| | | 639 | | } |
| | 147 | 640 | | _stringBuilder.Append("fragment "); |
| | 147 | 641 | | _stringBuilder.Append(fragment.Name); |
| | 147 | 642 | | _stringBuilder.Append(" on "); |
| | 147 | 643 | | _stringBuilder.Append(fragment.OnType); |
| | 147 | 644 | | _stringBuilder.AppendLine("{"); |
| | | 645 | | |
| | 147 | 646 | | BuildSelectionSetBody(fragment._fields, fragment._fragments, fragment._spreadFragments, IndentSize); |
| | | 647 | | |
| | 147 | 648 | | _stringBuilder.AppendLine("}"); |
| | | 649 | | } |
| | 123 | 650 | | } |
| | | 651 | | finally |
| | | 652 | | { |
| | 123 | 653 | | Array.Clear(names, 0, count); |
| | 123 | 654 | | Array.Clear(definitions, 0, count); |
| | 123 | 655 | | ArrayPool<string>.Shared.Return(names, clearArray: false); |
| | 123 | 656 | | ArrayPool<NamedFragmentDefinition>.Shared.Return(definitions, clearArray: false); |
| | 123 | 657 | | } |
| | 123 | 658 | | } |
| | | 659 | | |
| | | 660 | | /// <summary> |
| | | 661 | | /// Renders a field's directives in insertion order: <c> @Name</c>, followed by |
| | | 662 | | /// <c>(argName:value, …)</c> when the directive has arguments. Argument values reuse the exact |
| | | 663 | | /// formatter used for field arguments, so <c>if:$x</c> and complex values render identically. |
| | | 664 | | /// The directive LIST order is never sorted — it is user-visible, exactly like fragment-spread |
| | | 665 | | /// order. Individual directive ARGUMENTS, however, are stored in a case-insensitive sorted |
| | | 666 | | /// dictionary (normalized at <see cref="FieldDirective"/> construction, like field arguments), |
| | | 667 | | /// so their key order here is deterministic rather than caller-insertion order. |
| | | 668 | | /// </summary> |
| | | 669 | | private void BuildFieldDirectives(List<FieldDirective> directives) |
| | | 670 | | { |
| | 750 | 671 | | for (int i = 0; i < directives.Count; i++) |
| | | 672 | | { |
| | 192 | 673 | | var directive = directives[i]; |
| | 192 | 674 | | _stringBuilder.Append(" @"); |
| | 192 | 675 | | _stringBuilder.Append(directive.Name); |
| | | 676 | | |
| | 192 | 677 | | var arguments = directive.Arguments; |
| | 192 | 678 | | if (arguments is { Count: > 0 }) |
| | | 679 | | { |
| | 180 | 680 | | _stringBuilder.Append('('); |
| | 180 | 681 | | bool first = true; |
| | 726 | 682 | | foreach (var (key, value) in arguments) |
| | | 683 | | { |
| | 183 | 684 | | if (!first) |
| | | 685 | | { |
| | 3 | 686 | | _stringBuilder.Append(", "); |
| | | 687 | | } |
| | | 688 | | |
| | 183 | 689 | | first = false; |
| | 183 | 690 | | _stringBuilder.Append(key); |
| | 183 | 691 | | _stringBuilder.Append(':'); |
| | 183 | 692 | | WriteObject(_stringBuilder, value); |
| | | 693 | | } |
| | | 694 | | |
| | 180 | 695 | | _stringBuilder.Append(')'); |
| | | 696 | | } |
| | | 697 | | } |
| | 183 | 698 | | } |
| | | 699 | | |
| | | 700 | | private void BuildFieldArguments(IReadOnlyDictionary<string, object?> arguments) |
| | | 701 | | { |
| | 8058 | 702 | | _stringBuilder.Append('('); |
| | | 703 | | |
| | 8058 | 704 | | bool first = true; |
| | 46188 | 705 | | foreach (var (key, value) in arguments) |
| | | 706 | | { |
| | 15048 | 707 | | if (!first) |
| | | 708 | | { |
| | 6990 | 709 | | _stringBuilder.Append(", "); |
| | | 710 | | } |
| | | 711 | | |
| | 15048 | 712 | | first = false; |
| | | 713 | | |
| | 15048 | 714 | | _stringBuilder.Append(key); |
| | 15048 | 715 | | _stringBuilder.Append(':'); |
| | 15048 | 716 | | WriteObject(_stringBuilder, value); |
| | | 717 | | } |
| | | 718 | | |
| | 8034 | 719 | | _stringBuilder.Append(')'); |
| | 8034 | 720 | | } |
| | | 721 | | |
| | | 722 | | internal static void WriteObject(StringBuilder builder, object? value) |
| | | 723 | | { |
| | 25607 | 724 | | if (value is null) |
| | | 725 | | { |
| | 42 | 726 | | builder.Append("null"); |
| | 42 | 727 | | return; |
| | | 728 | | } |
| | | 729 | | |
| | 25565 | 730 | | if (ValueFormatter.TryAppendPrimitive(value, builder)) |
| | 24416 | 731 | | return; |
| | | 732 | | |
| | 1125 | 733 | | var valueType = value.GetType(); |
| | 1149 | 734 | | if (ExtractKeyValuePairProperties(builder, value, valueType)) return; |
| | | 735 | | |
| | | 736 | | switch (value) |
| | | 737 | | { |
| | | 738 | | case IList listValue: |
| | | 739 | | { |
| | 129 | 740 | | Helpers.WriteCollection('[', ']', listValue, builder, WriteObject); |
| | 129 | 741 | | break; |
| | | 742 | | } |
| | | 743 | | |
| | | 744 | | // Arguments are normalized to SortedDictionary<string, object?> (see |
| | | 745 | | // Helpers.SortArgumentValue), so the common case implements the generic interface. |
| | | 746 | | // Enumerating it through the generic enumerator writes each key directly and recurses |
| | | 747 | | // on the value with no boxed KeyValuePair and no reflected PropertyInfo.GetValue — |
| | | 748 | | // exactly the same {k:v, …} output the non-generic IDictionary path below would emit. |
| | | 749 | | case IDictionary<string, object?> typedDict: |
| | | 750 | | { |
| | 921 | 751 | | WriteTypedDictionary(builder, typedDict); |
| | 921 | 752 | | break; |
| | | 753 | | } |
| | | 754 | | |
| | | 755 | | case IDictionary dictValue: |
| | | 756 | | { |
| | 6 | 757 | | Helpers.WriteCollection('{', '}', dictValue, builder, WriteObject); |
| | 6 | 758 | | break; |
| | | 759 | | } |
| | | 760 | | |
| | | 761 | | default: |
| | | 762 | | { |
| | 45 | 763 | | WriteObjectReflection(builder, value, valueType); |
| | | 764 | | break; |
| | | 765 | | } |
| | | 766 | | } |
| | 45 | 767 | | } |
| | | 768 | | |
| | | 769 | | private static void WriteTypedDictionary(StringBuilder builder, IDictionary<string, object?> dictionary) |
| | | 770 | | { |
| | 921 | 771 | | builder.Append('{'); |
| | 921 | 772 | | bool first = true; |
| | 4764 | 773 | | foreach (var kvp in dictionary) |
| | | 774 | | { |
| | 2007 | 775 | | if (!first) builder.Append(", "); |
| | 1461 | 776 | | first = false; |
| | 1461 | 777 | | builder.Append(kvp.Key); |
| | 1461 | 778 | | builder.Append(':'); |
| | 1461 | 779 | | WriteObject(builder, kvp.Value); |
| | | 780 | | } |
| | 921 | 781 | | builder.Append('}'); |
| | 921 | 782 | | } |
| | | 783 | | |
| | | 784 | | private static bool ExtractKeyValuePairProperties(StringBuilder builder, object value, Type valueType) |
| | | 785 | | { |
| | 1125 | 786 | | if (!valueType.IsGenericType || valueType.GetGenericTypeDefinition() != typeof(KeyValuePair<,>)) |
| | | 787 | | { |
| | 1101 | 788 | | return false; |
| | | 789 | | } |
| | | 790 | | |
| | | 791 | | // KeyValuePair<,> is a sealed BCL struct that always exposes Key and Value properties — |
| | | 792 | | // GetProperty cannot return null here, so cache the pair without nullable wrapping. |
| | 24 | 793 | | var (keyProp, valueProp) = TypeMetadataCache.GetKeyValueProperties(valueType); |
| | | 794 | | |
| | 24 | 795 | | builder.Append(keyProp.GetValue(value)); |
| | 24 | 796 | | builder.Append(':'); |
| | 24 | 797 | | WriteObject(builder, valueProp.GetValue(value)); |
| | 24 | 798 | | return true; |
| | | 799 | | } |
| | | 800 | | |
| | | 801 | | private static void WriteObjectReflection(StringBuilder builder, object value, Type valueType) |
| | | 802 | | { |
| | 45 | 803 | | var props = TypeMetadataCache.GetObjectProperties(valueType); |
| | 45 | 804 | | builder.Append('{'); |
| | 45 | 805 | | bool first = true; |
| | 238 | 806 | | foreach (var prop in props) |
| | | 807 | | { |
| | 109 | 808 | | if (!first) builder.Append(", "); |
| | 74 | 809 | | first = false; |
| | 74 | 810 | | builder.Append(prop.Name); |
| | 74 | 811 | | builder.Append(':'); |
| | 74 | 812 | | WriteObject(builder, prop.GetValue(value)); |
| | | 813 | | } |
| | 45 | 814 | | builder.Append('}'); |
| | 45 | 815 | | } |
| | | 816 | | |
| | | 817 | | // Stable sort key for QueryBlock field lists: effective name first, original index as the |
| | | 818 | | // tiebreaker so equal names keep insertion order (matching LINQ OrderBy's stability). |
| | 9 | 819 | | private static readonly Comparison<(string Key, int Index, object Item)> BlockFieldComparer = |
| | 9 | 820 | | static (a, b) => |
| | 9 | 821 | | { |
| | 276 | 822 | | var nameComparison = StringComparer.OrdinalIgnoreCase.Compare(a.Key, b.Key); |
| | 276 | 823 | | return nameComparison != 0 ? nameComparison : a.Index.CompareTo(b.Index); |
| | 9 | 824 | | }; |
| | | 825 | | |
| | | 826 | | private void AddFields(QueryBlock queryBlock, string prevPad, int indent = 0) |
| | | 827 | | { |
| | 3051 | 828 | | if (queryBlock.IsEmpty) |
| | | 829 | | { |
| | 96 | 830 | | return; |
| | | 831 | | } |
| | | 832 | | |
| | 2955 | 833 | | _stringBuilder.AppendLine("{"); |
| | 2955 | 834 | | var padding = GetPadding(indent); |
| | | 835 | | |
| | | 836 | | // Sort fields by their effective name into a pooled buffer. QueryBlock.HandleAddField |
| | | 837 | | // rejects everything except string and QueryBlock at insert time, so a single ternary |
| | | 838 | | // covers every reachable case without a switch default. |
| | 2955 | 839 | | var fields = queryBlock.FieldsList; |
| | 2955 | 840 | | var count = fields.Count; |
| | 2955 | 841 | | var entries = ArrayPool<(string Key, int Index, object Item)>.Shared.Rent(count); |
| | | 842 | | try |
| | | 843 | | { |
| | 10302 | 844 | | for (int i = 0; i < count; i++) |
| | | 845 | | { |
| | 2196 | 846 | | var field = fields[i]; |
| | 2196 | 847 | | var key = field is QueryBlock block ? (block.Alias ?? block.Name) : (string)field; |
| | 2196 | 848 | | entries[i] = (key, i, field); |
| | | 849 | | } |
| | | 850 | | |
| | 2955 | 851 | | entries.AsSpan(0, count).Sort(BlockFieldComparer); |
| | | 852 | | |
| | 10302 | 853 | | for (int i = 0; i < count; i++) |
| | | 854 | | { |
| | 2196 | 855 | | switch (entries[i].Item) |
| | | 856 | | { |
| | | 857 | | case string strValue: |
| | 1581 | 858 | | _stringBuilder.Append(padding); |
| | 1581 | 859 | | _stringBuilder.AppendLine(strValue); |
| | 1581 | 860 | | break; |
| | | 861 | | case QueryBlock subQuery: |
| | 615 | 862 | | BuildBlock(subQuery, indent); |
| | 615 | 863 | | _stringBuilder.AppendLine(); |
| | | 864 | | break; |
| | | 865 | | } |
| | | 866 | | } |
| | 2955 | 867 | | } |
| | | 868 | | finally |
| | | 869 | | { |
| | 2955 | 870 | | Array.Clear(entries, 0, count); |
| | 2955 | 871 | | ArrayPool<(string Key, int Index, object Item)>.Shared.Return(entries, clearArray: false); |
| | 2955 | 872 | | } |
| | | 873 | | |
| | 2955 | 874 | | _stringBuilder.Append(prevPad); |
| | 2955 | 875 | | _stringBuilder.Append('}'); |
| | 2955 | 876 | | } |
| | | 877 | | |
| | | 878 | | private void AddArguments(QueryBlock queryBlock, bool isRootElement) |
| | | 879 | | { |
| | 3051 | 880 | | if (queryBlock.Arguments.Count == 0 && (!isRootElement || queryBlock.Variables.Count == 0)) |
| | | 881 | | { |
| | 381 | 882 | | return; |
| | | 883 | | } |
| | | 884 | | |
| | 2670 | 885 | | _stringBuilder.Append('('); |
| | 2670 | 886 | | if ((!isRootElement || queryBlock.Variables.Count == 0) && queryBlock.TryGetSingleArgument(out var singleKey, ou |
| | | 887 | | { |
| | 708 | 888 | | AppendArgument(singleKey, singleValue, isRootElement); |
| | 708 | 889 | | _stringBuilder.Append(')'); |
| | 708 | 890 | | return; |
| | | 891 | | } |
| | | 892 | | |
| | 1962 | 893 | | if (isRootElement && queryBlock.Arguments.Count == 0 && queryBlock.Variables.Count == 1) |
| | | 894 | | { |
| | 657 | 895 | | var variable = queryBlock.VariablesInternal.Min!; |
| | 657 | 896 | | variable.Print(_stringBuilder, variable.Name, true); |
| | 657 | 897 | | _stringBuilder.Append(')'); |
| | 657 | 898 | | return; |
| | | 899 | | } |
| | | 900 | | |
| | 1305 | 901 | | var explicitCount = queryBlock.Arguments.Count; |
| | 1305 | 902 | | var count = explicitCount + (isRootElement ? queryBlock.Variables.Count : 0); |
| | 1305 | 903 | | var entries = ArrayPool<ArgumentEntry>.Shared.Rent(count); |
| | | 904 | | try |
| | | 905 | | { |
| | 1305 | 906 | | var index = 0; |
| | | 907 | | // An empty SortedDictionary still allocates its traversal stack when enumerated. |
| | 1305 | 908 | | if (explicitCount > 0) |
| | | 909 | | { |
| | 38388 | 910 | | foreach (var (key, value) in queryBlock.ArgumentsInternal) |
| | | 911 | | { |
| | 18201 | 912 | | var renderedKey = isRootElement && value is Variable variable ? variable.Name : key; |
| | 18201 | 913 | | entries[index] = new ArgumentEntry(renderedKey, value, index); |
| | 18201 | 914 | | index++; |
| | | 915 | | } |
| | | 916 | | } |
| | | 917 | | |
| | 1305 | 918 | | if (isRootElement && count > explicitCount) |
| | | 919 | | { |
| | 13776 | 920 | | foreach (var variable in queryBlock.VariablesInternal) |
| | | 921 | | { |
| | 5928 | 922 | | entries[index] = new ArgumentEntry(variable.Name, variable, index); |
| | 5928 | 923 | | index++; |
| | | 924 | | } |
| | | 925 | | } |
| | | 926 | | |
| | 1305 | 927 | | entries.AsSpan(0, count).Sort(ArgumentEntryComparer); |
| | 1305 | 928 | | var i = 0; |
| | 17193 | 929 | | while (i < count) |
| | | 930 | | { |
| | 30471 | 931 | | if (i != 0) _stringBuilder.Append(", "); |
| | 15888 | 932 | | var entry = entries[i++]; |
| | 24129 | 933 | | while (i < count && string.Equals(entry.Key, entries[i].Key, StringComparison.Ordinal)) |
| | | 934 | | { |
| | 8241 | 935 | | var next = entries[i++]; |
| | 13005 | 936 | | if (next.Order < explicitCount || entry.Value is not Variable) entry = next; |
| | | 937 | | } |
| | 15888 | 938 | | AppendArgument(entry.Key, entry.Value, isRootElement); |
| | | 939 | | } |
| | 1305 | 940 | | } |
| | | 941 | | finally |
| | | 942 | | { |
| | 1305 | 943 | | Array.Clear(entries, 0, count); |
| | 1305 | 944 | | ArrayPool<ArgumentEntry>.Shared.Return(entries, clearArray: false); |
| | 1305 | 945 | | } |
| | | 946 | | |
| | 1305 | 947 | | _stringBuilder.Append(')'); |
| | 1305 | 948 | | } |
| | | 949 | | |
| | 293151 | 950 | | private readonly record struct ArgumentEntry(string Key, object Value, int Order); |
| | | 951 | | |
| | 9 | 952 | | private static readonly Comparison<ArgumentEntry> ArgumentEntryComparer = |
| | 9 | 953 | | static (left, right) => |
| | 9 | 954 | | { |
| | 87960 | 955 | | var keyComparison = string.CompareOrdinal(left.Key, right.Key); |
| | 87960 | 956 | | return keyComparison != 0 ? keyComparison : left.Order.CompareTo(right.Order); |
| | 9 | 957 | | }; |
| | | 958 | | |
| | | 959 | | private void AppendArgument(string key, object value, bool isRootElement) |
| | | 960 | | { |
| | 16596 | 961 | | if (value is Variable variable) |
| | | 962 | | { |
| | 8196 | 963 | | variable.Print(_stringBuilder, key, isRootElement); |
| | 8196 | 964 | | return; |
| | | 965 | | } |
| | | 966 | | |
| | 8400 | 967 | | _stringBuilder.Append(key); |
| | 8400 | 968 | | _stringBuilder.Append(':'); |
| | 8400 | 969 | | WriteObject(_stringBuilder, value); |
| | 8400 | 970 | | } |
| | | 971 | | } |