Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 0 additions & 20 deletions Game.Client/ClassMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
Expand All @@ -32,24 +30,6 @@ public class ClassMap : IClassMap
{
public static readonly ClassMap g_ClassMap = new();
public static ClassMap GetClassMap() => g_ClassMap;
static ClassMap() {
// Here is where we start initializing things based on LinkEntityToClassAttribute's
var typePairs = Assembly.GetExecutingAssembly().GetTypesWithAttributeMulti<LinkEntityToClassAttribute>();
foreach (var type in typePairs) {
var attr = type.Value;

DynamicMethod m = new DynamicMethod("LinkEntity_Instantiate" + type.Key.Name + "_ToMap_" + attr.LocalName, typeof(C_BaseEntity), []);
ILGenerator il = m.GetILGenerator();

il.Emit(OpCodes.Newobj, type.Key.GetConstructor([]) ?? throw new Exception("no constructor for auto factory"));
il.Emit(OpCodes.Castclass, typeof(C_BaseEntity));
il.Emit(OpCodes.Ret);

DispatchFunction dispatch = m.CreateDelegate<DispatchFunction>();

GetClassMap().Add(type.Key, attr.LocalName, type.Key.Name, dispatch);
}
}


readonly Dictionary<ulong, ClassEntry> ClassDict = [];
Expand Down
1 change: 1 addition & 0 deletions Game.Client/Game.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
<ProjectReference Include="../Source.CodeAnalysis.Lua/Source.CodeAnalysis.Lua.csproj" PrivateAssets="all" ReferenceOutputAssembly="false" OutputItemType="Analyzer" />
<ProjectReference Include="../Source.CodeAnalysis.NetworkVars/Source.CodeAnalysis.NetworkVars.csproj" PrivateAssets="all" ReferenceOutputAssembly="false" OutputItemType="Analyzer" />
<ProjectReference Include="../Source.CodeAnalysis.BitVec/Source.CodeAnalysis.BitVec.csproj" PrivateAssets="all" ReferenceOutputAssembly="false" OutputItemType="Analyzer" />
<ProjectReference Include="../Source.CodeAnalysis.EntityFactories/Source.CodeAnalysis.EntityFactories.csproj" PrivateAssets="all" ReferenceOutputAssembly="false" OutputItemType="Analyzer" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
Expand Down
2 changes: 2 additions & 0 deletions Game.Server/Game.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\Source.CodeAnalysis.BitVec\Source.CodeAnalysis.BitVec.csproj"
OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\Source.CodeAnalysis.EntityFactories\Source.CodeAnalysis.EntityFactories.csproj"
OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Game.Shared\*.cs" Link="Shared\%(Filename)%(Extension)" />
Expand Down
6 changes: 0 additions & 6 deletions Game.Server/SourceDllMain.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using Game.Shared;

using Microsoft.Extensions.DependencyInjection;

using Source;
using Source.Common;
using Source.Common.Commands;
Expand All @@ -18,10 +16,6 @@ namespace Game.Server;

public static class SourceDllMain
{
public static void Link(IServiceCollection services) {
ClassMap.Init();
}

[Dependency] public static IEngineServer engine { get; private set; } = null!;
[Dependency] public static IFileSystem filesystem { get; private set; } = null!;
[Dependency] public static ServerGlobalVariables gpGlobals { get; private set; } = null!;
Expand Down
17 changes: 0 additions & 17 deletions Game.Server/Util.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,6 @@
namespace Game;


public static class ClassMap
{
static bool Initialized;
public static void Init() {
if (Initialized) return;
Initialized = true;
// Here is where we start initializing things based on LinkEntityToClassAttribute's
var typePairs = Assembly.GetExecutingAssembly().GetTypesWithAttributeMulti<LinkEntityToClassAttribute>();
foreach (var type in typePairs) {
var attr = type.Value;

var factoryType = typeof(CEntityFactory<>).MakeGenericType(type.Key);
Activator.CreateInstance(factoryType, [type.Value.LocalName]);
}
}
}

public interface IEntityFactory
{
IServerNetworkable? Create(ReadOnlySpan<char> className);
Expand Down
204 changes: 204 additions & 0 deletions Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;

namespace Source.CodeAnalysis.EntityFactories
{
[Generator(LanguageNames.CSharp)]
public sealed class EntityFactoryGenerator : IIncrementalGenerator
{
const string LinkAttribute = "Game.Shared.LinkEntityToClassAttribute";
const string ClientClassMap = "Game.Client.ClassMap";
const string ClientBaseEntity = "Game.Client.C_BaseEntity";
const string ServerFactory = "Game.CEntityFactory`1";
const string G = "global::";

static readonly DiagnosticDescriptor Skipped = new DiagnosticDescriptor(
id: "ENTFACT001",

Check warning on line 23 in Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, Release)

Enable analyzer release tracking for the analyzer project containing rule 'ENTFACT001' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 23 in Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, Debug)

Enable analyzer release tracking for the analyzer project containing rule 'ENTFACT001' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 23 in Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest, Release)

Enable analyzer release tracking for the analyzer project containing rule 'ENTFACT001' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 23 in Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest, Debug)

Enable analyzer release tracking for the analyzer project containing rule 'ENTFACT001' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 23 in Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest, Debug)

Enable analyzer release tracking for the analyzer project containing rule 'ENTFACT001' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 23 in Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest, Release)

Enable analyzer release tracking for the analyzer project containing rule 'ENTFACT001' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 23 in Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs

View workflow job for this annotation

GitHub Actions / build (macos-15-intel, Release)

Enable analyzer release tracking for the analyzer project containing rule 'ENTFACT001' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 23 in Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs

View workflow job for this annotation

GitHub Actions / build (macos-15-intel, Debug)

Enable analyzer release tracking for the analyzer project containing rule 'ENTFACT001' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)
title: "Linked entity class cannot get a generated factory",
messageFormat: "'{0}' is linked to '{1}' but {2}, so no factory is registered",
category: "EntityFactories",
defaultSeverity: DiagnosticSeverity.Warning,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I would make this an error tbh

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We have so many warnings it would get drowned out and it's a pretty serious problem

isEnabledByDefault: true);

enum Side { None, Client, Server }
enum Ctor { Missing, Public, Internal, Hidden }

sealed class Entry : IEquatable<Entry>
{
public string TypeName = "";
public string Name = "";
public string[] LocalNames = Array.Empty<string>();
public string[] Bases = Array.Empty<string>();
public bool IsGeneric;
public bool IsAbstract;
public bool IsAccessible;
public Ctor Ctor;
public Location? Location;

public bool Equals(Entry? other) =>
other != null && TypeName == other.TypeName && Name == other.Name && IsGeneric == other.IsGeneric && IsAbstract == other.IsAbstract
&& IsAccessible == other.IsAccessible && Ctor == other.Ctor && LocalNames.SequenceEqual(other.LocalNames)
&& Bases.SequenceEqual(other.Bases) && Equals(Location, other.Location);
public override bool Equals(object? obj) => Equals(obj as Entry);
public override int GetHashCode() => TypeName.GetHashCode();
}

public void Initialize(IncrementalGeneratorInitializationContext context) {
IncrementalValuesProvider<Entry> entries = context.SyntaxProvider.ForAttributeWithMetadataName(
LinkAttribute,
static (node, _) => true,
static (ctx, _) => Transform(ctx))
.Where(static e => e != null)
.Select(static (e, _) => e!);

IncrementalValueProvider<(Side, string)> side = context.CompilationProvider.Select(static (compilation, _) => DetectSide(compilation));

context.RegisterSourceOutput(entries.Collect().Combine(side), static (spc, input) => Execute(spc, input.Left, input.Right.Item1, input.Right.Item2));
}

static (Side, string) DetectSide(Compilation compilation) {
if (compilation.GetTypeByMetadataName(ClientClassMap) != null) {
INamedTypeSymbol? baseEntity = compilation.GetTypeByMetadataName(ClientBaseEntity);
return baseEntity == null ? (Side.None, "") : (Side.Client, baseEntity.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
}

INamedTypeSymbol? factory = compilation.GetTypeByMetadataName(ServerFactory);
if (factory != null) {
ITypeSymbol? constraint = factory.TypeParameters[0].ConstraintTypes.FirstOrDefault();
return (Side.Server, constraint?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) ?? "");
}

return (Side.None, "");
}

static Entry? Transform(GeneratorAttributeSyntaxContext ctx) {
if (!(ctx.TargetSymbol is INamedTypeSymbol type) || type.TypeKind != TypeKind.Class)
return null;

string[] names = ctx.Attributes
.Where(a => a.ConstructorArguments.Length == 1 && a.ConstructorArguments[0].Value is string)
.Select(a => (string)a.ConstructorArguments[0].Value!)
.ToArray();
if (names.Length == 0)
return null;

List<string> bases = new List<string>();
for (INamedTypeSymbol? t = type.BaseType; t != null; t = t.BaseType)
bases.Add(t.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));

return new Entry {
TypeName = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
Name = type.Name,
LocalNames = names,
Bases = bases.ToArray(),
IsGeneric = IsGeneric(type),
IsAbstract = type.IsAbstract,
IsAccessible = IsAccessible(type),
Ctor = ParameterlessCtor(type),
Location = ctx.TargetNode.GetLocation(),
};
}

static bool IsGeneric(INamedTypeSymbol type) {
for (INamedTypeSymbol? t = type; t != null; t = t.ContainingType)
if (t.IsGenericType)
return true;
return false;
}

static bool IsAccessible(INamedTypeSymbol type) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

These things are copied from PanelRegistrationGenerator; is there any way we could make a shared helper file for it

for (INamedTypeSymbol? t = type; t != null; t = t.ContainingType) {
Accessibility a = t.DeclaredAccessibility;
if (a != Accessibility.Public && a != Accessibility.Internal && a != Accessibility.ProtectedOrInternal)
return false;
}
return true;
}

static Ctor ParameterlessCtor(INamedTypeSymbol type) {
IMethodSymbol? ctor = type.InstanceConstructors.FirstOrDefault(c => c.Parameters.Length == 0);
if (ctor == null)
return Ctor.Missing;
switch (ctor.DeclaredAccessibility) {
case Accessibility.Public: return Ctor.Public;
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal: return Ctor.Internal;
default: return Ctor.Hidden;
}
}

static string? Problem(Entry e, Side side, string baseEntity) {
if (e.IsGeneric) return "is generic";
if (e.IsAbstract) return "is abstract";
if (!e.IsAccessible) return "is not accessible from generated code";
if (baseEntity.Length != 0 && e.TypeName != baseEntity && !e.Bases.Contains(baseEntity)) return "does not derive from " + baseEntity;
if (side == Side.Server && e.Ctor != Ctor.Public) return "has no public parameterless constructor";
if (e.Ctor == Ctor.Missing) return "has no parameterless constructor";
return null;
}

static void Execute(SourceProductionContext spc, ImmutableArray<Entry> entries, Side side, string baseEntity) {
if (side == Side.None)
return;

StringBuilder accessors = new StringBuilder();
StringBuilder body = new StringBuilder();
int accessorId = 0;

foreach (Entry e in entries) {
string? problem = Problem(e, side, baseEntity);
if (problem != null) {
spc.ReportDiagnostic(Diagnostic.Create(Skipped, e.Location, e.TypeName, e.LocalNames[0], problem));
continue;
}

if (side == Side.Server) {
foreach (string name in e.LocalNames)
body.AppendLine($"\t\tnew {G}Game.CEntityFactory<{e.TypeName}>({Literal(name)});");
continue;
}

string factory;
if (e.Ctor == Ctor.Hidden) {
string accessor = "__Create" + accessorId++;
accessors.AppendLine("\t[global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]");
accessors.AppendLine($"\tstatic extern {e.TypeName} {accessor}();");
accessors.AppendLine();
factory = $"static () => {accessor}()";
}
else
factory = $"static () => new {e.TypeName}()";

foreach (string name in e.LocalNames)
body.AppendLine($"\t\t{G}Game.Client.ClassMap.GetClassMap().Add(typeof({e.TypeName}), {Literal(name)}, {Literal(e.Name)}, {factory});");
}

StringBuilder sb = new StringBuilder();
sb.AppendLine("// <auto-generated/>");
sb.AppendLine("#nullable enable");
sb.AppendLine("#pragma warning disable CA2255");
sb.AppendLine();
sb.AppendLine("namespace Source.Generated;");
sb.AppendLine();
sb.AppendLine("internal static class EntityFactoryRegistration");
sb.AppendLine("{");
sb.Append(accessors);
sb.AppendLine("\t[global::System.Runtime.CompilerServices.ModuleInitializer]");
sb.AppendLine("\tinternal static void Register() {");
sb.Append(body);
sb.AppendLine("\t}");
sb.AppendLine("}");

spc.AddSource("EntityFactoryRegistration.g.cs", SourceText.From(sb.ToString(), Encoding.UTF8));
}

static string Literal(string value) => SymbolDisplay.FormatLiteral(value, true);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<IsPackable>false</IsPackable>
<IsRoslynComponent>true</IsRoslynComponent>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<IncludeBuildOutput>false</IncludeBuildOutput>
<Configurations>Debug;Release;Debug (Dedicated);Release (Dedicated)</Configurations>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
</ItemGroup>

</Project>
3 changes: 3 additions & 0 deletions Source.NET.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
<Project Path="Source.CodeAnalysis.VGUI/Source.CodeAnalysis.VGUI.csproj">
<Platform Project="x64" />
</Project>
<Project Path="Source.CodeAnalysis.EntityFactories/Source.CodeAnalysis.EntityFactories.csproj">
<Platform Project="x64" />
</Project>
<Project Path="Source.CodeAnalysis.NetworkVars/Source.CodeAnalysis.NetworkVars.csproj">
<Platform Project="x64" />
</Project>
Expand Down
Loading