Repository navigation
Entity Relations #7000
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
Open
Roudenn
wants to merge
64
commits into
space-wizards:master
Choose a base branch
from
Roudenn:entity-relations
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,421
−8
Open
Entity Relations #7000
Changes from 12 commits
Commits
Show all changes
64 commits
Select commit
Hold shift + click to select a range
02d8ef4
Entity Relations
Roudenn d9ec76c
Part 2
Roudenn feb6d23
Clean components on manual relation remove
Roudenn d97e4fc
Update RobustUnitTest.cs
Roudenn b36a612
More API methods to clear relations
Roudenn 12f0760
Fix API methods
Roudenn f9a89fa
New ExperimentalTM generator for relations
Roudenn 46ba8c6
Update EntityRelationsSystem.cs
Roudenn ef033eb
Make shutdown event codegen a bool parameter
Roudenn 2d2cfcb
Update RobustServerSimulation.cs
Roudenn 97117b7
Update EntityDeserializer.cs
Roudenn 66ff141
Docs + analyzer fixes
Roudenn 8b559a6
Review fixes
Roudenn 3bdb07b
Add debug asserts if you make a self-reference
Roudenn d8e913e
Add a basic test for EntityRelations
Roudenn 9565847
Fix test. fix dictionaries and nullable relations
Roudenn 6733d74
EntityRelationGenerator -> EntityRelationAnalyzer
Roudenn b45a476
small doc fix
Roudenn ed70d47
EntityRelationsGeneratorTest
Roudenn 27c1256
Update EntityRelationsGeneratorTest.cs
Roudenn b9c8ebd
SetRelation `dirty` parameter
Roudenn b3f49d6
Fix dictionary EntityRelation networking
Roudenn dea8fb5
Improve API and tests
Roudenn 2f71711
Update EntityRelationsSystemTests.Networking.cs
Roudenn 97186d4
Content API improvements (no I won't make tests)
Roudenn ed15bd6
Fix swapping Relations by setting them 2 in a row
Roudenn 889823f
Improve collection Relations API even more
Roudenn 01f5dcf
refactor: whitespaces, xml-doc indent, explicit braces and use patter…
Fildrance 84708e3
refactor: extract methods
Fildrance 6d1f358
Review changes
Roudenn 49b1028
Fix network not networking
Roudenn 46fa0cc
Simplify HasRelations method API
Roudenn acb9115
Merge remote-tracking branch 'upstream/master' into entity-relations
Roudenn bddcf8d
Merge remote-tracking branch 'upstream/master' into entity-relations
Roudenn 1b378dc
Clear entity relations on `ComponentRemove`
Roudenn 34adfa4
Remove explicit dirtying and fix component adds
Roudenn ac458c7
Move EntityRelation to separate serializer
Roudenn ca4c1ac
Merge remote-tracking branch 'upstream/master' into entity-relations
Roudenn 4ce05cf
Local entity relations
Roudenn cd885ed
Fix local relations + add tests
Roudenn be4f1d8
Merge remote-tracking branch 'upstream/master' into entity-relations
Roudenn 013c198
SetRemoveOnEmpty ensures the component when false
Roudenn f393e83
Fix codegen not working
Roudenn c63bb59
Throw away buggy EntityRelationSerializer
Roudenn 81c5f01
Collection options for relations
Roudenn cac8740
Fix `ClearRelations` API shenanigans
Roudenn 9cedcc3
Update EntitySystem.Proxy.cs
Roudenn dbb2e5e
Fix test
Roudenn 1507492
Fix networking able to make invalid relations
Roudenn dabb4ec
Entity relation public constructor
Roudenn d6f0e05
start refactoring stuff
Roudenn a07d0c3
api
Roudenn 5011852
Move API to EntityRelationsSystem and simplify it
Roudenn 1110c11
Update EntityRelationsSystemTests.cs
Roudenn 7aa2f9e
Remove collection settings
Roudenn b3aa028
Remove EntityRelation wrapper struct
Roudenn 4ad6280
Reconstruct relations on deserialization
Roudenn e3ec9e8
Oops I did it wrong
Roudenn 50b350d
prevent client from doing anything with relations
Roudenn 1fe7468
Fix tests
Roudenn e20134d
Update EntityRelationsSystem.API.cs
Roudenn 1ee7fd0
Merge remote-tracking branch 'upstream/master' into entity-relations
Roudenn d820b45
EntityQuery ensure comps
Roudenn 221a6fb
I am likely doing something wrong...
Roudenn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
334 changes: 334 additions & 0 deletions
334
Robust.Serialization.Generator/EntityRelationsGenerator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,334 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Text; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Robust.Roslyn.Shared; | ||
| using Robust.Roslyn.Shared.Helpers; | ||
|
|
||
| namespace Robust.Serialization.Generator; | ||
|
|
||
| /// <summary> | ||
| /// Automatically generates implementations for handling timer unpausing. | ||
| /// </summary> | ||
| [Generator(LanguageNames.CSharp)] | ||
| public sealed class EntityRelationsGenerator : IIncrementalGenerator | ||
| { | ||
| private const string AutoGenerateComponentPauseAttributeName = "Robust.Shared.Analyzers.AutoGenerateEntityRelationsAttribute"; | ||
| private const string AutoPausedFieldAttributeName = "Robust.Shared.Analyzers.AutoRelationFieldAttribute"; | ||
| private const string AutoNetworkFieldAttributeName = "Robust.Shared.Analyzers.AutoNetworkedFieldAttribute"; | ||
| // ReSharper disable once InconsistentNaming | ||
| private const string IComponentTypeName = "Robust.Shared.GameObjects.IComponent"; | ||
|
|
||
| private static readonly DiagnosticDescriptor NotComponentDiagnostic = new( | ||
| Diagnostics.IdComponentRelationNotComponent, | ||
| "Class must be an IComponent to use AutoGenerateEntityRelations", | ||
| "Class '{0}' must implement IComponent to be used with [AutoGenerateEntityRelations]", | ||
| "Usage", | ||
| DiagnosticSeverity.Error, | ||
| true); | ||
|
|
||
| private static readonly DiagnosticDescriptor NoFieldsDiagnostic = new( | ||
| Diagnostics.IdComponentRelationNoFields, | ||
| "AutoGenerateEntityRelations has no fields", | ||
| "Class '{0}' has [AutoGenerateEntityRelations] but has no fields or properties with [AutoRelationField]", | ||
| "Usage", | ||
| DiagnosticSeverity.Warning, | ||
| true); | ||
|
|
||
| private static readonly DiagnosticDescriptor NoParentAttributeDiagnostic = new( | ||
| Diagnostics.IdComponentRelationNoParentAttribute, | ||
| "AutoRelationField on type of field without AutoGenerateEntityRelations", | ||
| "Field '{0}' has [AutoRelationField] but its containing type does not have [AutoGenerateEntityRelations]", | ||
| "Usage", | ||
| DiagnosticSeverity.Error, | ||
| true); | ||
|
|
||
| private static readonly DiagnosticDescriptor WrongTypeAttributeDiagnostic = new( | ||
| Diagnostics.IdComponentRelationWrongTypeAttribute, | ||
| "AutoRelationField has wrong type", | ||
| "Field '{0}' has [AutoRelationField] but is not of type EntityRelation", | ||
| "Usage", | ||
| DiagnosticSeverity.Error, | ||
| true); | ||
|
|
||
| public void Initialize(IncrementalGeneratorInitializationContext context) | ||
| { | ||
| var componentInfos = context.SyntaxProvider.ForAttributeWithMetadataName( | ||
| AutoGenerateComponentPauseAttributeName, | ||
| (syntaxNode, _) => syntaxNode is TypeDeclarationSyntax, | ||
| (syntaxContext, _) => | ||
| { | ||
| var symbol = (INamedTypeSymbol)syntaxContext.TargetSymbol; | ||
|
|
||
| var typeDeclarationSyntax = (TypeDeclarationSyntax) syntaxContext.TargetNode; | ||
| var partialTypeInfo = PartialTypeInfo.FromSymbol( | ||
| symbol, | ||
| typeDeclarationSyntax); | ||
|
|
||
| if (syntaxContext.Attributes[0].ConstructorArguments.Length > 0) | ||
| AttributeHelper.GetNamedArgumentBool(syntaxContext.Attributes[0], "Dirty", false); | ||
|
|
||
| var dirty = false; | ||
| if (syntaxContext.Attributes[0].ConstructorArguments[0].Value is bool dirtyBool) | ||
| dirty = dirtyBool; | ||
|
|
||
| var shutdownSub = false; | ||
| if (syntaxContext.Attributes[0].ConstructorArguments[1].Value is bool shutdownSubBool) | ||
| shutdownSub = shutdownSubBool; | ||
|
|
||
| var fieldBuilder = ImmutableArray.CreateBuilder<FieldInfo>(); | ||
| foreach (var member in symbol.GetMembers()) | ||
| { | ||
| if (!AttributeHelper.HasAttribute(member, AutoPausedFieldAttributeName, out var _)) | ||
|
Roudenn marked this conversation as resolved.
Resolved
|
||
| continue; | ||
|
|
||
| var type = member switch | ||
| { | ||
| IPropertySymbol property => property.Type, | ||
| IFieldSymbol field => field.Type, | ||
| _ => null | ||
| }; | ||
|
|
||
| if (type is not INamedTypeSymbol namedType) | ||
| continue; | ||
|
|
||
| var invalid = false; | ||
| var nullable = false; | ||
| var dictionaryKey = false; | ||
| var dictionaryValue = false; | ||
| var collection = false; | ||
| if (namedType.Name != "EntityRelation") | ||
| { | ||
| if (namedType is { Name: "Nullable", TypeArguments: [{Name: "EntityRelation"}] }) | ||
| { | ||
| nullable = true; | ||
| } | ||
| else if (namedType is { Name: "Dictionary", TypeArguments: [{Name: "EntityRelation"}, {}]}) | ||
| { | ||
| dictionaryKey = true; | ||
| } | ||
| else if (namedType is { Name: "Dictionary", TypeArguments: [{}, {Name: "EntityRelation"}]}) | ||
| { | ||
| dictionaryValue = true; | ||
| } | ||
| if (namedType.Name == "List" || namedType.Name == "HashSet" && namedType is { TypeArguments: [{ Name: "EntityRelation" }]}) | ||
| { | ||
| collection = true; | ||
| } | ||
| else | ||
| { | ||
| invalid = true; | ||
| } | ||
| } | ||
|
|
||
| // If any pause field has [AutoNetworkedField], automatically mark it to dirty on unpause. | ||
|
Roudenn marked this conversation as resolved.
Resolved
|
||
| if (AttributeHelper.HasAttribute(member, AutoNetworkFieldAttributeName, out var _)) | ||
| dirty = true; | ||
|
|
||
| fieldBuilder.Add(new FieldInfo(member.Name, nullable, invalid, dictionaryKey, dictionaryValue, collection, member.Locations[0])); | ||
| } | ||
|
|
||
| return new ComponentInfo( | ||
| partialTypeInfo, | ||
| EquatableArray<FieldInfo>.FromImmutableArray(fieldBuilder.ToImmutable()), | ||
| dirty, | ||
| shutdownSub, | ||
| !TypeSymbolHelper.ImplementsInterface(symbol, IComponentTypeName), | ||
| typeDeclarationSyntax.Identifier.GetLocation()); | ||
| }); | ||
|
|
||
| context.RegisterImplementationSourceOutput(componentInfos, static (productionContext, info) => | ||
| { | ||
| if (info.NotComponent) | ||
| { | ||
| productionContext.ReportDiagnostic(Diagnostic.Create( | ||
| NotComponentDiagnostic, | ||
| info.Location, | ||
| info.PartialTypeInfo.Name)); | ||
| return; | ||
| } | ||
|
|
||
| // Component always have to be partial anyways due to the serialization generator. | ||
| // So I can't be arsed to define a diagnostic for this. | ||
| if (!info.PartialTypeInfo.IsValid) | ||
| return; | ||
|
|
||
| if (info.Fields.AsImmutableArray().Length == 0) | ||
| { | ||
| productionContext.ReportDiagnostic(Diagnostic.Create( | ||
| NoFieldsDiagnostic, | ||
| info.Location, | ||
| info.PartialTypeInfo.Name)); | ||
| return; | ||
| } | ||
|
|
||
| var relationBuilder = new StringBuilder(); | ||
| var shutdownBuilder = new StringBuilder(); | ||
|
|
||
| var anyValidField = false; | ||
| foreach (var field in info.Fields) | ||
| { | ||
| if (field.Invalid) | ||
| { | ||
| productionContext.ReportDiagnostic(Diagnostic.Create(WrongTypeAttributeDiagnostic, field.Location)); | ||
| continue; | ||
| } | ||
|
|
||
| if (field.Nullable) | ||
| { | ||
| relationBuilder.AppendLine($""" | ||
| if (ent.Comp.{field.Name}.HasValue && ent.Comp.{field.Name}.Value == args.Relation) | ||
| ent.Comp.{field.Name} = null; | ||
| """); | ||
|
|
||
| shutdownBuilder.AppendLine($" entMan.ClearRelation(ent.Owner, ref ent.Comp.{field.Name});"); | ||
| } | ||
| else if (field.DictionaryKey) | ||
| { | ||
| relationBuilder.AppendLine($" ent.Comp.{field.Name}.Remove(args.Relation);"); | ||
|
|
||
| shutdownBuilder.AppendLine($" entMan.ClearRelation(ent.Owner, ent.Comp.{field.Name});"); | ||
| } | ||
| else if (field.DictionaryValue) | ||
| { | ||
| relationBuilder.AppendLine($$""" | ||
|
Roudenn marked this conversation as resolved.
Resolved
|
||
| foreach (var (key, value) in ent.Comp.{{field.Name}}) | ||
| { | ||
| if (ent.Comp.{{field.Name}}[key] == args.Relation) | ||
|
Roudenn marked this conversation as resolved.
Resolved
|
||
| ent.Comp.{{field.Name}}[key] = EntityRelation.Null; | ||
| } | ||
| """); | ||
|
|
||
| shutdownBuilder.AppendLine($" entMan.ClearRelation(ent.Owner, ent.Comp.{field.Name});"); | ||
| } | ||
| else if (field.Collection) | ||
| { | ||
| relationBuilder.AppendLine($" ent.Comp.{field.Name}.Remove(args.Relation);"); | ||
| shutdownBuilder.AppendLine($" entMan.ClearRelation(ent.Owner, ent.Comp.{field.Name});"); | ||
| } | ||
| else | ||
| { | ||
| relationBuilder.AppendLine($""" | ||
| if (ent.Comp.{field.Name} == args.Relation) | ||
| ent.Comp.{field.Name} = EntityRelation.Null; | ||
| """); | ||
|
|
||
| shutdownBuilder.AppendLine($" entMan.ClearRelation(ent.Owner, ref ent.Comp.{field.Name});"); | ||
| } | ||
|
|
||
| anyValidField = true; | ||
| } | ||
|
|
||
| if (!anyValidField) | ||
| return; | ||
|
|
||
| if (info.Dirty) | ||
| relationBuilder.AppendLine(" Dirty(ent);"); | ||
|
|
||
| var shutdownSub = info.ShutdownEvent | ||
| ? $" SubscribeLocalEvent<{info.PartialTypeInfo.Name}, ComponentShutdown>(OnRelationShutdown);" | ||
| : string.Empty; | ||
|
|
||
| var shutdownSubMethod = info.ShutdownEvent | ||
| ? $$""" | ||
| private void OnRelationShutdown(Entity<{{info.PartialTypeInfo.Name}}> ent, ref ComponentShutdown args) | ||
| { | ||
| {{info.PartialTypeInfo.Name}}.ClearComponentRelations(ent, EntityManager); | ||
| } | ||
| """ | ||
| : string.Empty; | ||
|
|
||
| var result = new StringBuilder(); | ||
|
|
||
| result.AppendLine(""" | ||
| // <auto-generated /> | ||
|
|
||
| using Robust.Shared.GameObjects; | ||
|
|
||
| """); | ||
|
|
||
| info.PartialTypeInfo.WriteHeader(result); | ||
|
|
||
| result.AppendLine($$""" | ||
|
|
||
| { | ||
| [RobustAutoGenerated] | ||
| [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] | ||
| public sealed partial class {{info.PartialTypeInfo.Name}}_AutoRelationsSystem : EntitySystem | ||
|
Roudenn marked this conversation as resolved.
Resolved
|
||
| { | ||
| public override void Initialize() | ||
| { | ||
| base.Initialize(); | ||
| {{shutdownSub}} | ||
| SubscribeLocalEvent<{{info.PartialTypeInfo.Name}}, EntityRelationDeleteEvent>(OnRelationDeleted); | ||
| } | ||
|
|
||
| private void OnRelationDeleted(Entity<{{info.PartialTypeInfo.Name}}> ent, ref EntityRelationDeleteEvent args) | ||
| { | ||
| {{relationBuilder}} | ||
| } | ||
|
|
||
| {{shutdownSubMethod}} | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Auto-generated method that clears all relations in a certain entity. | ||
| /// This has to be called on component shutdown to keep all relations correct. | ||
| /// </summary> | ||
| public static void ClearComponentRelations(Entity<{{info.PartialTypeInfo.Name}}> ent, IEntityManager entMan) | ||
| { | ||
| {{shutdownBuilder}} | ||
| } | ||
| } | ||
| """); | ||
|
|
||
| info.PartialTypeInfo.WriteFooter(result); | ||
|
|
||
| productionContext.AddSource(info.PartialTypeInfo.GetGeneratedFileName(), result.ToString()); | ||
| }); | ||
|
|
||
| // Code to report diagnostic for fields that have it but don't have the attribute on the parent. | ||
| var allFields = context.SyntaxProvider.ForAttributeWithMetadataName( | ||
| AutoPausedFieldAttributeName, | ||
| (syntaxNode, _) => syntaxNode is VariableDeclaratorSyntax or PropertyDeclarationSyntax, | ||
| (syntaxContext, _) => | ||
| { | ||
| var errorTarget = syntaxContext.TargetNode is PropertyDeclarationSyntax prop | ||
| ? prop.Identifier.GetLocation() | ||
| : syntaxContext.TargetNode.GetLocation(); | ||
| return new AllFieldInfo( | ||
| syntaxContext.TargetSymbol.Name, | ||
| syntaxContext.TargetSymbol.ContainingType.ToDisplayString(), | ||
| errorTarget); | ||
| }); | ||
|
|
||
| var allComponentsTogether = componentInfos.Collect(); | ||
| var allFieldsTogether = allFields.Collect(); | ||
| var componentFieldJoin = allFieldsTogether.Combine(allComponentsTogether); | ||
|
|
||
| context.RegisterImplementationSourceOutput(componentFieldJoin, (productionContext, info) => | ||
| { | ||
| var componentsByName = new HashSet<string>(info.Right.Select(x => x.PartialTypeInfo.DisplayName)); | ||
| foreach (var field in info.Left) | ||
| { | ||
| if (!componentsByName.Contains(field.ParentDisplayName)) | ||
| { | ||
| productionContext.ReportDiagnostic( | ||
| Diagnostic.Create(NoParentAttributeDiagnostic, field.Location, field.Name)); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| public sealed record ComponentInfo( | ||
| PartialTypeInfo PartialTypeInfo, | ||
| EquatableArray<FieldInfo> Fields, | ||
| bool Dirty, | ||
| bool ShutdownEvent, | ||
| bool NotComponent, | ||
| Location Location); | ||
|
|
||
| public sealed record FieldInfo(string Name, bool Nullable, bool Invalid, bool DictionaryKey, bool DictionaryValue, bool Collection, Location Location); | ||
|
|
||
| public sealed record AllFieldInfo(string Name, string ParentDisplayName, Location Location); | ||
|
Roudenn marked this conversation as resolved.
Resolved
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.