-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathLuaCatsGenerator.cs
More file actions
294 lines (249 loc) · 8.78 KB
/
LuaCatsGenerator.cs
File metadata and controls
294 lines (249 loc) · 8.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#nullable enable
#pragma warning disable MA0136 // Raw String contains an implicit end of line character, line endings will be normalized
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using BizHawk.Common;
using BizHawk.Common.ReflectionExtensions;
using NLua;
namespace BizHawk.Client.Common;
/// <summary>
/// Generates API definitions in the LuaCATS format.
/// </summary>
/// <remarks>
/// See https://luals.github.io/wiki/annotations
/// </remarks>
internal static class LuaCatsGenerator
{
private static readonly Dictionary<Type, string> TypeConversions = new()
{
[typeof(object)] = "any",
[typeof(byte)] = "integer",
[typeof(sbyte)] = "integer",
[typeof(int)] = "integer",
[typeof(uint)] = "integer",
[typeof(short)] = "integer",
[typeof(ushort)] = "integer",
[typeof(long)] = "integer",
[typeof(ulong)] = "integer",
[typeof(float)] = "number",
[typeof(double)] = "number",
[typeof(decimal)] = "number",
[typeof(string)] = "string",
[typeof(bool)] = "boolean",
[typeof(byte[])] = "string",
[typeof(Memory<byte>)] = "string",
[typeof(ReadOnlyMemory<byte>)] = "string",
[typeof(LuaFunction)] = "function",
[typeof(LuaTable)] = "table",
[typeof(System.Drawing.Color)] = "dotnetcolor",
};
private const string Classes = """
---@class dotnetcolor : userdata
---A color in one of the following formats:
--- - Number in the format `0xAARRGGBB`
--- - String in the format `"#RRGGBB"` or `"#AARRGGBB"`
--- - A CSS3/X11 color name e.g. `"blue"`, `"palegoldenrod"`
--- - Color created with `forms.createcolor`
---@alias color dotnetcolor | integer | string
---@alias surface
---| "emucore" # Draw on the emulated screen. Resolution depends on emulated system and game. Drawing is scaled with the rest of the display.
---| "client" # Draw on the BizHawk window. Resolution depends on the window size. Drawing is not scaled.
""";
private const string Preamble = """
-- https://tasvideos.org/Bizhawk
error("This is a definition file for Lua Language Server and not a usable script")
---@meta _
""";
private static string? GetHardcodedType(ParameterInfo parameter)
{
// Technically any string parameter can be passed a number in BizHawk's Lua API, but let's just focus on the ones where it's commonly used
// like `gui.text` and `forms.settext` instead of polluting the entire API surface
if (parameter.Name is "message" or "caption" && parameter.ParameterType == typeof(string))
{
return "string|number";
}
if (parameter.Member.DeclaringType.Name == "GuiLuaLibrary" && parameter.Name == "surfaceName" && parameter.ParameterType == typeof(string))
{
return "surface";
}
return null;
}
public static void Generate(LuaDocumentation docs, string path)
{
var sb0 = new StringBuilder();
sb0.AppendLine($"-- Lua functions available in EmuHawk {VersionInfo.MainVersion}");
sb0.AppendLine(Preamble);
sb0.AppendLine();
sb0.AppendLine(Classes);
sb0.AppendLine();
File.WriteAllText(Path.Combine(path, "classes.d.lua"), sb0.ToString().ReplaceLineEndings());
foreach (var libraryGroup in docs.GroupBy(func => func.Library).OrderBy(group => group.Key))
{
string library = libraryGroup.Key;
string libraryDescription = libraryGroup.First().LibraryDescription;
var libraryType = libraryGroup.First().Method.DeclaringType;
var filePath = Path.Combine(path, library + ".d.lua");
var sb = new StringBuilder();
sb.AppendLine($"-- Lua functions available in EmuHawk {VersionInfo.MainVersion}");
sb.AppendLine(Preamble);
sb.AppendLine();
if (!string.IsNullOrEmpty(libraryDescription))
{
sb.AppendLine(FormatMarkdown(libraryDescription));
}
sb.AppendLine($"---@class {SafeLibraryTypeName(library)}");
if (!typeof(LuaLibraryBase).IsAssignableFrom(libraryType)) sb.Append("local "); // don't make LuaCanvas global
sb.AppendLine($"{library} = {{}}");
sb.AppendLine();
foreach (var func in libraryGroup.OrderBy(func => func.Name))
{
if (!string.IsNullOrEmpty(func.Description))
{
sb.AppendLine(FormatMarkdown(func.Description));
}
if (func.Example != null)
{
sb.AppendLine("---");
sb.AppendLine("---Example:");
sb.AppendLine("---");
sb.AppendLine(FormatMarkdown(func.Example, "---\t"));
}
if (func.IsDeprecated)
{
sb.AppendLine("---@deprecated");
}
foreach (var parameter in func.Method.GetParameters())
{
if (IsParams(parameter))
{
sb.Append("---@vararg");
}
else
{
sb.Append($"---@param {parameter.Name}");
if (parameter.HasDefaultValue || (parameter.IsNRTOrNullableT() ?? true))
{
sb.Append('?');
}
}
sb.Append(' ');
sb.Append(GetLuaType(parameter));
if (IsZeroIndexed(parameter))
{
sb.Append(" Zero-indexed array.");
}
if (parameter.HasDefaultValue && parameter.DefaultValue is not null and not "")
{
sb.Append($" Defaults to `{FormatValue(parameter.DefaultValue)}`");
}
sb.AppendLine();
}
if (func.Method.ReturnType != typeof(void))
{
sb.Append("---@return ");
var luaType = GetLuaType(func.Method.ReturnParameter);
var nilable = func.Method.ReturnParameter.IsNRTOrNullableT() ?? true;
var wrapType = nilable && luaType.IndexOfAny([ ':', '|' ]) != -1; // ? is ambiguous on complex types like `string|int` or `fun(): string`
if (wrapType) sb.Append('(');
sb.Append(luaType);
if (wrapType) sb.Append(')');
if (nilable) sb.Append('?');
if (IsZeroIndexed(func.Method.ReturnParameter))
{
sb.Append(" # Zero-indexed array.");
}
sb.AppendLine();
}
sb.Append($"function {library}.{func.Name}(");
foreach (var parameter in func.Method.GetParameters())
{
if (parameter.Position > 0)
{
sb.Append(", ");
}
sb.Append(IsParams(parameter) ? "..." : parameter.Name);
}
sb.AppendLine(") end");
sb.AppendLine();
}
File.WriteAllText(filePath, sb.ToString().ReplaceLineEndings());
}
}
private static string FormatMarkdown(string value, string prefix = "---")
{
// prefix every line
value = Regex.Replace(value, "^", prefix, RegexOptions.Multiline);
// replace {{wiki markup}} with `markdown`
value = Regex.Replace(value, "{{(.+?)}}", "`$1`");
// replace wiki image markup with markdown
value = Regex.Replace(value, @"\[(?<url>.+?)\|alt=(?<alt>.+?)\]", "");
return value;
}
private static string FormatValue(object value) => value switch
{
string str => $"\"{str}\"",
true => "true",
false => "false",
null => "nil",
_ => value.ToString(),
};
/// <summary>
/// Avoid name collisions with existing Lua types.
/// Only for the <c>@class</c> annotation, not the name of the global.
/// <see href="https://luals.github.io/wiki/annotations/#documenting-types" />
/// </summary>
private static string SafeLibraryTypeName(string name) => name switch
{
"userdata" => $"biz{name}",
_ => name,
};
private static string GetLuaType(ParameterInfo parameter)
{
if (GetOverrideType(parameter) is string overrideType)
{
return overrideType;
}
if (GetHardcodedType(parameter) is string hardcodedType)
{
return hardcodedType;
}
if (parameter.GetCustomAttribute<LuaColorParamAttribute>() is not null)
{
return "color"; // see Preamble
}
if (parameter.ParameterType.IsArray && IsParams(parameter))
{
// no [] array modifier for varargs
return GetLuaType(parameter.ParameterType.GetElementType());
}
return GetLuaType(parameter.ParameterType);
}
private static string GetLuaType(Type type)
{
// try this twice, before and after extracting the array/nullable type
if (TypeConversions.TryGetValue(type, out string luaType))
{
return luaType;
}
if (type.IsArray)
{
return GetLuaType(type.GetElementType()) + "[]";
}
if (Nullable.GetUnderlyingType(type) is Type underlyingType)
{
type = underlyingType;
}
if (TypeConversions.TryGetValue(type, out luaType))
{
return luaType;
}
throw new NotSupportedException($"Unknown type {type.FullName} used in API. Generator must be updated to handle this.");
}
private static bool IsParams(ParameterInfo parameter) => parameter.GetCustomAttribute<ParamArrayAttribute>() is not null;
private static bool IsZeroIndexed(ParameterInfo parameter) => parameter.GetCustomAttribute<LuaZeroIndexedAttribute>() is not null;
private static string? GetOverrideType(ParameterInfo parameter) => parameter.GetCustomAttribute<LuaCatsTypeAttribute>()?.Type;
}