Skip to content
This repository has been archived by the owner on Aug 28, 2024. It is now read-only.

Commit

Permalink
refactor: changed the way to create the code.
Browse files Browse the repository at this point in the history
Use the Roslyn way to create the code in the RS.

Issues: #572, #565
  • Loading branch information
ArchiDog1998 committed Apr 3, 2024
1 parent 7dd7ba3 commit 84af732
Show file tree
Hide file tree
Showing 13 changed files with 498 additions and 837 deletions.
2 changes: 1 addition & 1 deletion RotationSolver.Basic/Actions/ActionTargetInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ private readonly IEnumerable<BattleChara> GetCanTargets(bool skipStatusProvideCh
}

var isAuto = !DataCenter.IsManual || IsTargetFriendly;
return objs.Where(b => isAuto || b.Address == Svc.Targets.Target?.Address)
return objs.Where(b => isAuto || b.ObjectId == Svc.Targets.Target?.ObjectId)
.Where(InViewTarget).Where(CanUseTo).Where(action.Setting.CanTarget);
}

Expand Down
1 change: 0 additions & 1 deletion RotationSolver.GameData/Getters/ExcelRowGetter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ internal abstract class ExcelRowGetter<T>(Lumina.GameData gameData) where T : Ex

protected virtual void BeforeCreating() { }


public string GetCode()
{
var items = _gameData.GetExcelSheet<T>();
Expand Down
43 changes: 43 additions & 0 deletions RotationSolver.GameData/OpCodeGetter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Newtonsoft.Json.Linq;
using System.Net;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static RotationSolver.GameData.SyntaxHelper;

namespace RotationSolver.GameData;
internal static class OpCodeGetter
{
public static async Task GetOpCode(DirectoryInfo dirInfo)
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
using var result = await client.GetAsync("https://raw.githubusercontent.com/karashiiro/FFXIVOpcodes/master/opcodes.json");

if (result.StatusCode != HttpStatusCode.OK) return;
var responseStream = await result.Content.ReadAsStringAsync();

var enums = JToken.Parse(responseStream)[0]!["lists"]!.Children()
.SelectMany(i => i.Children()).SelectMany(i => i.Children()).Cast<JObject>()
.Select(i =>
{
var name = (string)((JValue)i["name"]!).Value!;
var value = (ushort)(long)((JValue)i["opcode"]!).Value!;
var description = name!.Space();

var desc = AttributeList(SingletonSeparatedList(DescriptionAttribute(description))).WithXmlComment($"/// <summary> {description} </summary>");

return EnumMember(name, value).AddAttributeLists(desc);
});

var enumDefinition = EnumDeclaration("OpCode")
.AddBaseListTypes(SimpleBaseType(PredefinedType(Token(SyntaxKind.UShortKeyword))))
.AddAttributeLists(GeneratedCodeAttribute(typeof(OpCodeGetter)).WithXmlComment($"/// <summary> The OpCode </summary>"))
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddMembers([EnumMember("None", 0).WithXmlComment($"/// <summary/>")
, ..enums]);

var majorNameSpace = NamespaceDeclaration("RotationSolver.Basic.Data").AddMembers(enumDefinition);

await SaveNode(majorNameSpace, dirInfo, "OpCode");
}
}
30 changes: 5 additions & 25 deletions RotationSolver.GameData/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Lumina;
using Lumina.Data;
using Lumina.Excel.GeneratedSheets;
using Newtonsoft.Json;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Newtonsoft.Json.Linq;
using RotationSolver.GameData;
using RotationSolver.GameData.Getters;
Expand Down Expand Up @@ -92,30 +94,8 @@ namespace RotationSolver.Basic.Rotations.Basic;
.Select(job => new RotationGetter(gameData, job).GetCode());
res.AddResource("Rotation", header + string.Join("\n\n", rotations));

using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
using var result = await client.GetAsync("https://raw.githubusercontent.com/karashiiro/FFXIVOpcodes/master/opcodes.json");

if (result.StatusCode != HttpStatusCode.OK) return;
var responseStream = await result.Content.ReadAsStringAsync();


var strs = JToken.Parse(responseStream)[0]!["lists"]!.Children()
.SelectMany(i => i.Children()).SelectMany(i => i.Children()).Cast<JObject>()
.Select(i =>
{
var name = ((JValue)i["name"]!).Value as string;
var description = name!.Space();

return $$"""
/// <summary>
///{{description}}
/// </summary>
[Description("{{description}}")]
{{name}} = {{((JValue)i["opcode"]!).Value}},
""";
});
res.AddResource("OpCode", string.Join("\n", strs));

res.Generate();

await OpCodeGetter.GetOpCode(dirInfo);

Console.WriteLine("Finished!");
1 change: 1 addition & 0 deletions RotationSolver.GameData/RotationSolver.GameData.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

<ItemGroup>
<PackageReference Include="Lumina.Excel" Version="6.5.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="ResXResourceReader.NetStandard" Version="1.2.0" />
</ItemGroup>
Expand Down
51 changes: 51 additions & 0 deletions RotationSolver.GameData/SyntaxHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Security.Cryptography;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;

namespace RotationSolver.GameData;

public static class SyntaxHelper
{
public static AttributeListSyntax GeneratedCodeAttribute(Type generator)
{
return AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode"))
.AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(generator.FullName ?? generator.Name))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(generator.Assembly.GetName().Version?.ToString() ?? "1.0.0"))))));
}

public static EnumMemberDeclarationSyntax EnumMember(string name, ushort value)
{
return EnumMemberDeclaration(name)
.WithEqualsValue(EqualsValueClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(value))));
}

public static AttributeSyntax DescriptionAttribute(string description)
{
var attributeArgument = AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(description)));
return Attribute(IdentifierName("global::System.ComponentModel.Description"), AttributeArgumentList(SingletonSeparatedList(attributeArgument)));
}

public static TSyntax WithXmlComment<TSyntax>(this TSyntax node, string comment)
where TSyntax : SyntaxNode
{
return node.WithLeadingTrivia(TriviaList([.. comment.Split('\n').Select(Comment)]));
}

public static BaseNamespaceDeclarationSyntax NamespaceDeclaration(string name)
{
return FileScopedNamespaceDeclaration(ParseName(name))
.WithLeadingTrivia(TriviaList(
Comment("// <auto-generated/>"),
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true)),
Trivia(NullableDirectiveTrivia(Token(SyntaxKind.EnableKeyword), true))));
}

public static async Task SaveNode(SyntaxNode node, DirectoryInfo dirInfo, string name)
{
await using var streamWriter = new StreamWriter(dirInfo.FullName + $"\\RotationSolver.SourceGenerators\\Resources\\{name}.txt", false);
node.NormalizeWhitespace().WriteTo(streamWriter);
}
}
48 changes: 24 additions & 24 deletions RotationSolver.GameData/Util.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,30 +92,30 @@ public static string ToCode(this Lumina.Excel.GeneratedSheets.Action item,
}

return $$"""
private readonly Lazy<IBaseAction> _{{actionName}}Creator = new(() =>
{
IBaseAction action = new BaseAction((ActionID){{item.RowId}}, {{isDuty.ToString().ToLower()}});
CustomRotation.LoadActionSetting(ref action);
var setting = action.Setting;
Modify{{actionName}}(ref setting);
action.Setting = setting;
return action;
});
/// <summary>
/// Modify {{actionDescName}}
/// </summary>
static partial void Modify{{actionName}}(ref ActionSetting setting);
/// <summary>
/// {{actionDescName}}
/// {{desc}}
/// </summary>
{{(isDuty ? $"[ID({item.RowId})]" : string.Empty)}}
{{(item.ActionCategory.Row is 9 or 15 ? "private" : "public")}} IBaseAction {{actionName}} => _{{actionName}}Creator.Value;
""";
private readonly Lazy<IBaseAction> _{{actionName}}Creator = new(() =>
{
IBaseAction action = new BaseAction((ActionID){{item.RowId}}, {{isDuty.ToString().ToLower()}});
CustomRotation.LoadActionSetting(ref action);
var setting = action.Setting;
Modify{{actionName}}(ref setting);
action.Setting = setting;
return action;
});
/// <summary>
/// Modify {{actionDescName}}
/// </summary>
static partial void Modify{{actionName}}(ref ActionSetting setting);
/// <summary>
/// {{actionDescName}}
/// {{desc}}
/// </summary>
{{(isDuty ? $"[ID({item.RowId})]" : string.Empty)}}
{{(item.ActionCategory.Row is 9 or 15 ? "private" : "public")}} IBaseAction {{actionName}} => _{{actionName}}Creator.Value;
""";
}

public static string GetDescName(this Lumina.Excel.GeneratedSheets.Action action)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 84af732

Please sign in to comment.