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

[REG-1463] Generate 'partial' class to attach RGState and RGAction to host behavior #116

Merged
merged 5 commits into from
Dec 11, 2023
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
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
using System.Linq;
using System.Text.RegularExpressions;
#if UNITY_EDITOR
using System;
using Codice.Client.Common.TreeGrouper;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using UnityEditor;
using UnityEngine;
#endif

namespace RegressionGames
{
#if UNITY_EDITOR
public class CodeGeneratorUtils
public static class CodeGeneratorUtils
{
public static readonly string HeaderComment = $"/*\r\n* This file has been automatically generated. Do not modify.\r\n*/\r\n\r\n";

public static readonly string HeaderComment = "/// <auto-generated>" + Environment.NewLine +
"/// This file has been automatically generated. Do not modify." + Environment.NewLine +
"/// </auto-generated>" + Environment.NewLine + Environment.NewLine;

public static string SanitizeActionName(string name)
{
return Regex.Replace(name.Replace(" ", "_"), "[^0-9a-zA-Z_]", "_");
Expand All @@ -22,6 +31,33 @@ public static string GetNamespaceForProject()
{
return Regex.Replace("RG" + PlayerSettings.productName.Replace(" ", "_"), "[^0-9a-zA-Z_]", "_");
}

public static NameSyntax QualifiedNameFor(Type type) => SyntaxFactory.ParseName(type.FullName);

public static AttributeSyntax Attribute(Type attributeType, params ExpressionSyntax[] arguments)
{
return SyntaxFactory.Attribute(
QualifiedNameFor(attributeType),
SyntaxFactory.AttributeArgumentList(
SyntaxFactory.SeparatedList(arguments.Select(SyntaxFactory.AttributeArgument))));
}

public static TypeOfExpressionSyntax TypeOf(Type t) => SyntaxFactory.TypeOfExpression(QualifiedNameFor(t));
public static TypeOfExpressionSyntax TypeOf(string fullTypeName) => SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseName(fullTypeName));
public static ClassDeclarationSyntax PartialClass(string name) => SyntaxFactory.ClassDeclaration(name)
.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PartialKeyword)));

public static MemberDeclarationSyntax CreatePartialAttacherClass(
string ns, string name, params string[] componentTypeNames)
{
var classDeclaration = PartialClass(name)
.AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(
componentTypeNames.Select(componentType =>
Attribute(typeof(RequireComponent), TypeOf(componentType))))));
return string.IsNullOrEmpty(ns)
? classDeclaration
: SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(ns)).AddMembers(classDeclaration);
}
}
#endif
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using RegressionGames.RGBotConfigs;
using UnityEditor;
#endif

Expand All @@ -19,7 +20,7 @@ public static class GenerateRGActionClasses
{
public static void Generate(List<RGActionAttributeInfo> actionInfos)
{
Dictionary<string, Task> fileWriteTasks = new();
Dictionary<string, Task> fileWriteTasks = new();
// Iterate through BotActions
foreach (var botAction in actionInfos)
{
Expand All @@ -41,11 +42,12 @@ public static void Generate(List<RGActionAttributeInfo> actionInfos)
}

var projectNamespace = CodeGeneratorUtils.GetNamespaceForProject();

botAction.GeneratedClassName =
$"{projectNamespace}.RGAction_{CodeGeneratorUtils.SanitizeActionName(botAction.ActionName)}";

// Create a new compilation unit
var actionClassName = $"RGAction_{CodeGeneratorUtils.SanitizeActionName(botAction.ActionName)}";
CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit()
.AddUsings(
usings.Select(v => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(v))).ToArray()
Expand All @@ -56,8 +58,13 @@ public static void Generate(List<RGActionAttributeInfo> actionInfos)
.AddMembers(
// Class declaration
SyntaxFactory
.ClassDeclaration(
$"RGAction_{CodeGeneratorUtils.SanitizeActionName(botAction.ActionName)}")
.ClassDeclaration(actionClassName)
.AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(new[]
{
CodeGeneratorUtils.Attribute(typeof(DisallowMultipleComponent)),
CodeGeneratorUtils.Attribute(typeof(RequireComponent),
CodeGeneratorUtils.TypeOf(typeof(RGEntity)))
})))
.AddModifiers(
SyntaxFactory.Token(SyntaxKind.PublicKeyword)
// Only add one of the "class" keywords here
Expand Down Expand Up @@ -87,10 +94,15 @@ public static void Generate(List<RGActionAttributeInfo> actionInfos)
GenerateActionRequestConstructor(botAction)
)
)
);
)
.AddMembers(CodeGeneratorUtils.CreatePartialAttacherClass(
botAction.Namespace,
botAction.Object,
typeof(RGEntity).FullName,
$"{projectNamespace}.{actionClassName}"));

// Format the generated code
string formattedCode = compilationUnit.NormalizeWhitespace().ToFullString();
string formattedCode = compilationUnit.NormalizeWhitespace(eol: Environment.NewLine).ToFullString();

// Save to 'Assets/RegressionGames/Runtime/GeneratedScripts/RGActions,RGSerialization.cs'
string fileName = $"RGAction_{CodeGeneratorUtils.SanitizeActionName(botAction.ActionName)}.cs";
Expand Down Expand Up @@ -167,7 +179,7 @@ private static MemberDeclarationSyntax GenerateGetActionNameMethod(RGActionAttri

return getActionNameMethod;
}

private static ArgumentSyntax GenerateActionDelegate(RGActionAttributeInfo action)
{
// Generate the GetComponent<Object>().MethodName piece for both cases (0 and non-0 parameters)
Expand Down Expand Up @@ -236,14 +248,14 @@ private static MemberDeclarationSyntax GenerateStartActionMethod(RGActionInfo ac
foreach (var parameter in action.Parameters)
{
string paramName = parameter.Name;

methodInvocationArguments.Add(paramName);
parameterParsingStatements.Add(SyntaxFactory.ParseStatement($"{parameter.Type} {paramName} = default;"));
parameterParsingStatements.Add(SyntaxFactory.IfStatement(IfCondition(parameter), IfBody(parameter), ElseBody(parameter)));
}

string methodInvocationArgumentsString = methodInvocationArguments.Count > 0 ?
", " + string.Join(", ", methodInvocationArguments) :
string methodInvocationArgumentsString = methodInvocationArguments.Count > 0 ?
", " + string.Join(", ", methodInvocationArguments) :
string.Empty;

parameterParsingStatements.Add(SyntaxFactory.ParseStatement($"Invoke(\"{action.ActionName}\"{methodInvocationArgumentsString});"));
Expand All @@ -264,16 +276,16 @@ private static InvocationExpressionSyntax IfCondition(RGParameterInfo param)
{
return SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("input"),
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("input"),
SyntaxFactory.IdentifierName("TryGetValue")
)).WithArgumentList(
SyntaxFactory.ArgumentList(
SyntaxFactory.SeparatedList(new List<ArgumentSyntax>
{
SyntaxFactory.SeparatedList(new List<ArgumentSyntax>
{
SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal(param.Name)
)
),
Expand All @@ -291,13 +303,13 @@ private static InvocationExpressionSyntax IfCondition(RGParameterInfo param)
* {
* string:
* key = keyInput.ToString();
*
*
* primitive:
* KeyType.TryParse(keyInput.ToString(), out key);
*
* nonprimitive:
* key = RGSerialization.Deserialize_KeyType(key.ToString());
*
*
* }
* catch (Exception ex)
* {
Expand All @@ -309,7 +321,7 @@ private static StatementSyntax IfBody(RGParameterInfo param)
{
var paramType = param.Type;
var paramName = param.Name;

string tryParseStatement;
if (paramType.ToLower() == "string" || paramType.ToLower() == "system.string")
{
Expand All @@ -321,7 +333,7 @@ private static StatementSyntax IfBody(RGParameterInfo param)
}
else
{
// Do direct type cast whenever possible, taking into account nullable types
// Do direct type cast whenever possible, taking into account nullable types
tryParseStatement = $"if ({paramName}Input is {paramType.Replace("?", "")}";
if (param.Nullable)
{
Expand Down Expand Up @@ -368,30 +380,30 @@ private static ElseClauseSyntax ElseBody(RGParameterInfo param)
{
return default(ElseClauseSyntax);
}

// Validation check for key existence if param must be non-null
return SyntaxFactory.ElseClause(SyntaxFactory.Block(new StatementSyntax[]
return SyntaxFactory.ElseClause(SyntaxFactory.Block(new StatementSyntax[]
{
SyntaxFactory.ExpressionStatement(
SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("RGDebug"),
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("RGDebug"),
SyntaxFactory.IdentifierName("LogError")
)
).WithArgumentList(
SyntaxFactory.ArgumentList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal($"No parameter '{param.Name}' found")
)
)
)
)
)
), SyntaxFactory.ReturnStatement()
), SyntaxFactory.ReturnStatement()
}
));
}
Expand All @@ -400,7 +412,7 @@ private static MemberDeclarationSyntax GenerateActionRequestConstructor(RGAction
{
var methodParameters = new List<ParameterSyntax>();
var parameterParsingStatements = new List<StatementSyntax>();

foreach (var rgParameterInfo in action.Parameters)
{
methodParameters.Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier(rgParameterInfo.Name))
Expand All @@ -416,7 +428,7 @@ private static MemberDeclarationSyntax GenerateActionRequestConstructor(RGAction
}

inputString += "\r\n};";

parameterParsingStatements.Add(
SyntaxFactory.ParseStatement(inputString)
);
Expand All @@ -435,4 +447,4 @@ private static MemberDeclarationSyntax GenerateActionRequestConstructor(RGAction

}
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
Expand All @@ -11,7 +12,7 @@

namespace RegressionGames.Editor.CodeGenerators
{
#if UNITY_EDITOR
#if UNITY_EDITOR
// Dev Note: Not perfect, but mega time saver for generating this gook: https://roslynquoter.azurewebsites.net/
public static class GenerateRGActionMapClass
{
Expand All @@ -37,22 +38,22 @@ public static void Generate(List<RGActionAttributeInfo> botActions)
usings.Select(v=>SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(v))).ToArray()
)
.AddMembers(GenerateClass(botActions));


// Create a compilation unit and add the namespace declaration
CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit()
.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")))
.AddMembers(namespaceDeclaration);

// Format the generated code
string formattedCode = compilationUnit.NormalizeWhitespace().ToFullString();
string formattedCode = compilationUnit.NormalizeWhitespace(eol: Environment.NewLine).ToFullString();

// Save to 'Assets/RegressionGames/Runtime/GeneratedScripts/RGActionMap.cs'
string fileName = "RGActionMap.cs";
string filePath = Path.Combine(Application.dataPath, "RegressionGames", "Runtime", "GeneratedScripts", fileName);
string fileContents = CodeGeneratorUtils.HeaderComment + formattedCode;
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.WriteAllText(filePath, fileContents);
File.WriteAllText(filePath, fileContents);
RGDebug.Log($"Successfully Generated {filePath}");
}

Expand All @@ -66,27 +67,27 @@ private static ClassDeclarationSyntax GenerateClass(List<RGActionAttributeInfo>
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
.WithBody(SyntaxFactory.Block(filteredActions
.GroupBy(b => b.Object)
.SelectMany(g =>
.SelectMany(g =>
{
var innerIfStatements = g.Select(b =>
var innerIfStatements = g.Select(b =>
SyntaxFactory.ExpressionStatement(
SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("gameObject"),
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("gameObject"),
SyntaxFactory.IdentifierName($"AddComponent<RGAction_{CodeGeneratorUtils.SanitizeActionName(b.ActionName)}>")
)
)
)
).ToArray();
return new StatementSyntax[]

return new StatementSyntax[]
{
SyntaxFactory.IfStatement(
SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ThisExpression(),
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ThisExpression(),
SyntaxFactory.GenericName("TryGetComponent")
.WithTypeArgumentList(
SyntaxFactory.TypeArgumentList(
Expand All @@ -98,8 +99,8 @@ private static ClassDeclarationSyntax GenerateClass(List<RGActionAttributeInfo>
),
SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Argument(
null,
SyntaxFactory.Token(SyntaxKind.OutKeyword),
null,
SyntaxFactory.Token(SyntaxKind.OutKeyword),
SyntaxFactory.DeclarationExpression(
SyntaxFactory.IdentifierName("var"),
SyntaxFactory.DiscardDesignation(SyntaxFactory.Token(SyntaxKind.UnderscoreToken))
Expand Down
Loading
Loading