Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fusion] Improve Inlining Rewriter #7838

Merged
merged 9 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Immutable;
using HotChocolate.Fusion.Types;
using HotChocolate.Language;
Expand Down Expand Up @@ -31,14 +33,14 @@ public DocumentNode RewriteDocument(DocumentNode document, string? operationName
return new DocumentNode(ImmutableArray<IDefinitionNode>.Empty.Add(newOperation));
}

private void RewriteFields(SelectionSetNode selectionSet, Context context)
internal void RewriteFields(SelectionSetNode selectionSet, Context context)
{
foreach (var selection in selectionSet.Selections)
{
switch (selection)
{
case FieldNode field:
RewriteField(field, context);
context.AddField(field);
break;

case InlineFragmentNode inlineFragment:
Expand All @@ -50,6 +52,23 @@ private void RewriteFields(SelectionSetNode selectionSet, Context context)
break;
}
}

foreach (var (_, fields) in context.Fields)
{
foreach (var field in fields.GroupBy(t => t, t => t, FieldComparer.Instance))
{
var mergedField = field.Key;

if (mergedField.SelectionSet is not null)
{
mergedField = mergedField.WithSelectionSet(
new SelectionSetNode(
field.SelectMany(t => t.SelectionSet!.Selections).ToList()));
}

RewriteField(mergedField, context);
}
}
}

private void RewriteField(FieldNode fieldNode, Context context)
Expand Down Expand Up @@ -224,10 +243,239 @@ public readonly ref struct Context(

public HashSet<ISelectionNode> Visited { get; } = new(SyntaxComparer.BySyntax);

public OrderedDictionary<string, List<FieldNode>> Fields { get; } = new(StringComparer.Ordinal);

public FragmentDefinitionNode GetFragmentDefinition(string name)
=> fragments[name];

public void AddField(FieldNode field)
{
if (!Fields.TryGetValue(field.Name.Value, out var fields))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be alias or name.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you are right

{
fields = [];
Fields.Add(field.Name.Value, fields);
}

fields.Add(field);
}

public Context Branch(ICompositeNamedType type)
=> new(type, fragments);
}

private sealed class FieldComparer : IEqualityComparer<FieldNode>
{
public bool Equals(FieldNode? x, FieldNode? y)
{
if (ReferenceEquals(x, y))
{
return true;
}

if (x is null)
{
return false;
}

if (y is null)
{
return false;
}

return Equals(x.Alias, y.Alias)
&& x.Name.Equals(y.Name)
&& Equals(x.Directives, y.Directives)
&& Equals(x.Arguments, y.Arguments);
}

private bool Equals(IReadOnlyList<ISyntaxNode> a, IReadOnlyList<ISyntaxNode> b)
{
if (a.Count == 0 && b.Count == 0)
{
return true;
}

return a.SequenceEqual(b, SyntaxComparer.BySyntax);
}

public int GetHashCode(FieldNode obj)
{
var hashCode = new HashCode();

if (obj.Alias is not null)
{
hashCode.Add(obj.Alias.Value);
}

hashCode.Add(obj.Name.Value);

for (var i = 0; i < obj.Directives.Count; i++)
{
hashCode.Add(SyntaxComparer.BySyntax.GetHashCode(obj.Directives[i]));
}

for (var i = 0; i < obj.Arguments.Count; i++)
{
hashCode.Add(SyntaxComparer.BySyntax.GetHashCode(obj.Arguments[i]));
}

return hashCode.ToHashCode();
}

public static FieldComparer Instance { get; } = new();
}
}

#if NET8_0
public class OrderedDictionary<TKey, TValue>
: IDictionary<TKey, TValue>
, IReadOnlyDictionary<TKey, TValue>
where TKey : notnull
{
private readonly List<KeyValuePair<TKey, TValue>> _order;
private readonly Dictionary<TKey, TValue> _map;

public OrderedDictionary(IEqualityComparer<TKey> keyComparer)
{
_order = [];
_map = new Dictionary<TKey, TValue>(keyComparer);
}

public OrderedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> values)
{
if (values is null)
{
throw new ArgumentNullException(nameof(values));
}

_order = [];
_map = new Dictionary<TKey, TValue>();

foreach (var item in values)
{
_map.Add(item.Key, item.Value);
_order.Add(item);
}
}

private OrderedDictionary(OrderedDictionary<TKey, TValue> source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}

_order = [..source._order,];
_map = new Dictionary<TKey, TValue>(source._map);
}

public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
=> _map.TryGetValue(key, out value);

public TValue this[TKey key]
{
get
{
return _map[key];
}
set
{
if (_map.ContainsKey(key))
{
_map[key] = value;
_order[IndexOfKey(key)] =
new KeyValuePair<TKey, TValue>(key, value);
}
else
{
Add(key, value);
}
}
}

public ICollection<TKey> Keys => _map.Keys;

IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys =>
Keys;

public ICollection<TValue> Values => _map.Values;

IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values =>
Values;

public int Count => _order.Count;

public bool IsReadOnly => false;

public void Add(TKey key, TValue value)
{
Add(new KeyValuePair<TKey, TValue>(key, value));
}

public void Add(KeyValuePair<TKey, TValue> item)
{
_map.Add(item.Key, item.Value);
_order.Add(item);
}

public void Clear()
{
_map.Clear();
_order.Clear();
}

public bool Contains(KeyValuePair<TKey, TValue> item)
=> _order.Contains(item);

public bool ContainsKey(TKey key)
=> _map.ContainsKey(key);

public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
=> _order.CopyTo(array, arrayIndex);

public bool Remove(TKey key)
{
if (_map.ContainsKey(key))
{
_map.Remove(key);
_order.RemoveAt(IndexOfKey(key));
return true;
}
return false;
}

public bool Remove(KeyValuePair<TKey, TValue> item)
{
var index = _order.IndexOf(item);

if (index != -1)
{
_order.RemoveAt(index);
_map.Remove(item.Key);
return true;
}

return false;
}

private int IndexOfKey(TKey key)
{
for (var i = 0; i < _order.Count; i++)
{
if (key.Equals(_order[i].Key))
{
return i;
}
}
return -1;
}

public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
=> _order.GetEnumerator();

IEnumerator IEnumerable.GetEnumerator()
=> _order.GetEnumerator();

public OrderedDictionary<TKey, TValue> Clone() => new(this);
}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using HotChocolate.Fusion.Types;
using HotChocolate.Language;

namespace HotChocolate.Fusion.Planning;

public class MergeSelectionSetRewriter(CompositeSchema schema)
{
private readonly InlineFragmentOperationRewriter _rewriter = new(schema);

public SelectionSetNode RewriteSelectionSets(
IReadOnlyList<SelectionSetNode> selectionSets,
ICompositeNamedType type)
{
var context = new InlineFragmentOperationRewriter.Context(
type,
new Dictionary<string, FragmentDefinitionNode>());

var merged = new SelectionSetNode(
null,
selectionSets.SelectMany(t => t.Selections).ToList());

_rewriter.RewriteFields(merged, context);

return new SelectionSetNode(
null,
context.Selections.ToImmutable());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public abstract class SelectionPlanNode : PlanNode
{
private List<CompositeDirective>? _directives;
private List<SelectionPlanNode>? _selections;
private List<SelectionSetNode>? _requirements;
private bool? _isConditional;
private string? _skipVariable;
private string? _includeVariable;
Expand Down Expand Up @@ -69,6 +70,12 @@ public IReadOnlyList<CompositeDirective> Directives
public IReadOnlyList<SelectionPlanNode> Selections
=> _selections ?? (IReadOnlyList<SelectionPlanNode>)Array.Empty<SelectionPlanNode>();

/// <summary>
/// Gets the requirements that are needed to execute this selection.
/// </summary>
public IReadOnlyList<SelectionSetNode> RequirementNodes
=> _requirements ?? (IReadOnlyList<SelectionSetNode>)Array.Empty<SelectionSetNode>();

/// <summary>
/// Defines if the selection is conditional.
/// </summary>
Expand Down Expand Up @@ -150,6 +157,12 @@ public void AddDirective(CompositeDirective directive)
public bool RemoveDirective(CompositeDirective directive)
=> _directives?.Remove(directive) == true;

public void AddRequirementNode(SelectionSetNode selectionSet)
{
ArgumentNullException.ThrowIfNull(selectionSet);
(_requirements ??= []).Add(selectionSet);
}

private void InitializeConditions()
{
if (_isConditional.HasValue)
Expand Down
Loading
Loading