diff --git a/.csharpierrc.json b/.csharpierrc.json
new file mode 100644
index 00000000..9e26dfee
--- /dev/null
+++ b/.csharpierrc.json
@@ -0,0 +1 @@
+{}
\ No newline at end of file
diff --git a/.editorconfig b/.editorconfig
deleted file mode 100644
index cac2710b..00000000
--- a/.editorconfig
+++ /dev/null
@@ -1,236 +0,0 @@
-# Remove the line below if you want to inherit .editorconfig settings from higher directories
-root = true
-
-# C# files
-[*.cs]
-
-#### Core EditorConfig Options ####
-
-# Indentation and spacing
-indent_size = 4
-indent_style = space
-tab_width = 4
-
-# New line preferences
-end_of_line = crlf
-insert_final_newline = false
-
-#### .NET Coding Conventions ####
-
-# Organize usings
-dotnet_separate_import_directive_groups = false
-dotnet_sort_system_directives_first = false
-file_header_template = unset
-
-# this. and Me. preferences
-dotnet_style_qualification_for_event = false
-dotnet_style_qualification_for_field = false
-dotnet_style_qualification_for_method = false
-dotnet_style_qualification_for_property = false
-
-# Language keywords vs BCL types preferences
-dotnet_style_predefined_type_for_locals_parameters_members = true
-dotnet_style_predefined_type_for_member_access = true
-
-# Parentheses preferences
-dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity
-dotnet_style_parentheses_in_other_binary_operators = always_for_clarity
-dotnet_style_parentheses_in_other_operators = never_if_unnecessary
-dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
-
-# Modifier preferences
-dotnet_style_require_accessibility_modifiers = omit_if_default
-
-# Expression-level preferences
-dotnet_style_coalesce_expression = true
-dotnet_style_collection_initializer = true
-dotnet_style_explicit_tuple_names = true
-dotnet_style_namespace_match_folder = true
-dotnet_style_null_propagation = true
-dotnet_style_object_initializer = true
-dotnet_style_operator_placement_when_wrapping = beginning_of_line
-dotnet_style_prefer_auto_properties = true
-dotnet_style_prefer_collection_expression = when_types_loosely_match
-dotnet_style_prefer_compound_assignment = true
-dotnet_style_prefer_conditional_expression_over_assignment = true
-dotnet_style_prefer_conditional_expression_over_return = true
-dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
-dotnet_style_prefer_inferred_anonymous_type_member_names = true
-dotnet_style_prefer_inferred_tuple_names = true
-dotnet_style_prefer_is_null_check_over_reference_equality_method = true
-dotnet_style_prefer_simplified_boolean_expressions = true
-dotnet_style_prefer_simplified_interpolation = true
-
-# Field preferences
-dotnet_style_readonly_field = true
-
-# Parameter preferences
-dotnet_code_quality_unused_parameters = all:silent
-
-# Suppression preferences
-dotnet_remove_unnecessary_suppression_exclusions = none
-
-# New line preferences
-dotnet_style_allow_multiple_blank_lines_experimental = true
-dotnet_style_allow_statement_immediately_after_block_experimental = true
-
-#### C# Coding Conventions ####
-
-# var preferences
-csharp_style_var_elsewhere = true
-csharp_style_var_for_built_in_types = true
-csharp_style_var_when_type_is_apparent = true
-
-# Expression-bodied members
-csharp_style_expression_bodied_accessors = true
-csharp_style_expression_bodied_constructors = false
-csharp_style_expression_bodied_indexers = true
-csharp_style_expression_bodied_lambdas = true
-csharp_style_expression_bodied_local_functions = false
-csharp_style_expression_bodied_methods = false
-csharp_style_expression_bodied_operators = false
-csharp_style_expression_bodied_properties = true
-
-# Pattern matching preferences
-csharp_style_pattern_matching_over_as_with_null_check = true
-csharp_style_pattern_matching_over_is_with_cast_check = true
-csharp_style_prefer_extended_property_pattern = true
-csharp_style_prefer_not_pattern = true
-csharp_style_prefer_pattern_matching = true
-csharp_style_prefer_switch_expression = true
-
-# Null-checking preferences
-csharp_style_conditional_delegate_call = true
-
-# Modifier preferences
-csharp_prefer_static_local_function = true
-csharp_preferred_modifier_order = public, private, protected, internal, file, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, required, volatile, async
-csharp_style_prefer_readonly_struct = true
-csharp_style_prefer_readonly_struct_member = true
-
-# Code-block preferences
-csharp_prefer_braces = true
-csharp_prefer_simple_using_statement = true
-csharp_style_namespace_declarations = file_scoped
-csharp_style_prefer_method_group_conversion = true
-csharp_style_prefer_primary_constructors = true
-csharp_style_prefer_top_level_statements = true
-
-# Expression-level preferences
-csharp_prefer_simple_default_expression = true
-csharp_style_deconstructed_variable_declaration = true
-csharp_style_implicit_object_creation_when_type_is_apparent = true
-csharp_style_inlined_variable_declaration = true
-csharp_style_prefer_index_operator = true
-csharp_style_prefer_local_over_anonymous_function = true
-csharp_style_prefer_null_check_over_type_check = true
-csharp_style_prefer_range_operator = true
-csharp_style_prefer_tuple_swap = true
-csharp_style_prefer_utf8_string_literals = true
-csharp_style_throw_expression = true
-csharp_style_unused_value_assignment_preference = discard_variable
-csharp_style_unused_value_expression_statement_preference = discard_variable
-
-# 'using' directive preferences
-csharp_using_directive_placement = outside_namespace
-
-# New line preferences
-csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true
-csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true
-csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true
-csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true
-csharp_style_allow_embedded_statements_on_same_line_experimental = true
-
-#### C# Formatting Rules ####
-
-# New line preferences
-csharp_new_line_before_catch = true
-csharp_new_line_before_else = true
-csharp_new_line_before_finally = true
-csharp_new_line_before_members_in_anonymous_types = true
-csharp_new_line_before_members_in_object_initializers = true
-csharp_new_line_before_open_brace = all
-csharp_new_line_between_query_expression_clauses = true
-
-# Indentation preferences
-csharp_indent_block_contents = true
-csharp_indent_braces = false
-csharp_indent_case_contents = true
-csharp_indent_case_contents_when_block = true
-csharp_indent_labels = one_less_than_current
-csharp_indent_switch_labels = true
-csharp_outdent_statement_labels = true
-
-# Space preferences
-csharp_space_after_cast = false
-csharp_space_after_colon_in_inheritance_clause = true
-csharp_space_after_comma = true
-csharp_space_after_dot = false
-csharp_space_after_keywords_in_control_flow_statements = true
-csharp_space_after_semicolon_in_for_statement = true
-csharp_space_around_binary_operators = before_and_after
-csharp_space_around_declaration_statements = false
-csharp_space_before_colon_in_inheritance_clause = true
-csharp_space_before_comma = false
-csharp_space_before_dot = false
-csharp_space_before_open_square_brackets = false
-csharp_space_before_semicolon_in_for_statement = false
-csharp_space_between_empty_square_brackets = false
-csharp_space_between_method_call_empty_parameter_list_parentheses = false
-csharp_space_between_method_call_name_and_opening_parenthesis = false
-csharp_space_between_method_call_parameter_list_parentheses = false
-csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
-csharp_space_between_method_declaration_name_and_open_parenthesis = false
-csharp_space_between_method_declaration_parameter_list_parentheses = false
-csharp_space_between_parentheses = false
-csharp_space_between_square_brackets = false
-
-# Wrapping preferences
-csharp_preserve_single_line_blocks = true
-csharp_preserve_single_line_statements = true
-max_line_length = 240
-
-#### Naming styles ####
-
-# Naming rules
-
-dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
-dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
-dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
-
-dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
-dotnet_naming_rule.types_should_be_pascal_case.symbols = types
-dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
-
-dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
-dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
-dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
-
-# Symbol specifications
-
-dotnet_naming_symbols.interface.applicable_kinds = interface
-dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
-dotnet_naming_symbols.interface.required_modifiers =
-
-dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
-dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
-dotnet_naming_symbols.types.required_modifiers =
-
-dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
-dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
-dotnet_naming_symbols.non_field_members.required_modifiers =
-
-# Naming styles
-
-dotnet_naming_style.pascal_case.required_prefix =
-dotnet_naming_style.pascal_case.required_suffix =
-dotnet_naming_style.pascal_case.word_separator =
-dotnet_naming_style.pascal_case.capitalization = pascal_case
-
-dotnet_naming_style.begins_with_i.required_prefix = I
-dotnet_naming_style.begins_with_i.required_suffix =
-dotnet_naming_style.begins_with_i.word_separator =
-dotnet_naming_style.begins_with_i.capitalization = pascal_case
-
-
-dotnet_diagnostic.IDE0055.severity = warning
\ No newline at end of file
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
new file mode 100644
index 00000000..7247acda
--- /dev/null
+++ b/.vscode/extensions.json
@@ -0,0 +1,3 @@
+{
+ "recommendations": ["csharpier.csharpier-vscode"]
+}
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 61c885ce..2fb087fb 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -5,5 +5,8 @@
"Vector3"
],
"Lua.runtime.version": "Lua 5.2",
- "dotnet.backgroundAnalysis.analyzerDiagnosticsScope": "fullSolution"
-}
\ No newline at end of file
+ "dotnet.backgroundAnalysis.analyzerDiagnosticsScope": "fullSolution",
+ "[csharp]": {
+ "editor.defaultFormatter": "csharpier.csharpier-vscode"
+ }
+}
diff --git a/Directory.Build.props b/Directory.Build.props
index f3e6ab7c..85428da8 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,16 +1,14 @@
-
-
-
- 0.5.3
- nuskey;Akeit0
- © Yusuke Nakada
- https://github.com/nuskey8/Lua-CSharp
- $(PackageProjectUrl)
- git
- MIT
- README.md
- Icon.png
-
-
-
\ No newline at end of file
+
+
+ 0.5.3
+ nuskey;Akeit0
+ © Yusuke Nakada
+ https://github.com/nuskey8/Lua-CSharp
+ $(PackageProjectUrl)
+ git
+ MIT
+ README.md
+ Icon.png
+
+
diff --git a/Lua.slnx b/Lua.slnx
index 2c0187b0..de8c0f4e 100644
--- a/Lua.slnx
+++ b/Lua.slnx
@@ -1,17 +1,17 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/sandbox/Benchmark/AddBenchmark.cs b/sandbox/Benchmark/AddBenchmark.cs
index 99af7b39..a3df673c 100644
--- a/sandbox/Benchmark/AddBenchmark.cs
+++ b/sandbox/Benchmark/AddBenchmark.cs
@@ -22,14 +22,20 @@ public void Setup()
core.Setup("add.lua");
core.LuaCSharpState.OpenStandardLibraries();
- core.LuaCSharpState.Environment["add"] = new LuaFunction("add", (context, ct) =>
- {
- var a = context.GetArgument(0);
- var b = context.GetArgument(1);
- return new(context.Return(a + b));
- });
+ core.LuaCSharpState.Environment["add"] = new LuaFunction(
+ "add",
+ (context, ct) =>
+ {
+ var a = context.GetArgument(0);
+ var b = context.GetArgument(1);
+ return new(context.Return(a + b));
+ }
+ );
core.MoonSharpState.Globals["add"] = (Func)Add;
- core.NLuaState.RegisterFunction("add", typeof(AddBenchmark).GetMethod(nameof(Add), BindingFlags.Static | BindingFlags.Public));
+ core.NLuaState.RegisterFunction(
+ "add",
+ typeof(AddBenchmark).GetMethod(nameof(Add), BindingFlags.Static | BindingFlags.Public)
+ );
}
[IterationCleanup]
@@ -77,4 +83,4 @@ public async Task Benchmark_LuaCSharp_File()
await core.LuaCSharpState.DoFileAsync(core.FilePath, buffer);
return buffer[0];
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/Benchmark/Benchmark.csproj b/sandbox/Benchmark/Benchmark.csproj
index 9c85d71b..699bc3a0 100644
--- a/sandbox/Benchmark/Benchmark.csproj
+++ b/sandbox/Benchmark/Benchmark.csproj
@@ -1,20 +1,18 @@
+
+ Exe
+ net8.0
+ enable
+ enable
+
-
- Exe
- net8.0
- enable
- enable
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
diff --git a/sandbox/Benchmark/BenchmarkCore.cs b/sandbox/Benchmark/BenchmarkCore.cs
index 4f7d7ee4..714ee752 100644
--- a/sandbox/Benchmark/BenchmarkCore.cs
+++ b/sandbox/Benchmark/BenchmarkCore.cs
@@ -35,4 +35,4 @@ public void Dispose()
{
nLuaState.Dispose();
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/Benchmark/CoroutineBenchmark.cs b/sandbox/Benchmark/CoroutineBenchmark.cs
index 9e24d45a..cbd66be6 100644
--- a/sandbox/Benchmark/CoroutineBenchmark.cs
+++ b/sandbox/Benchmark/CoroutineBenchmark.cs
@@ -54,4 +54,4 @@ public async Task Benchmark_LuaCSharp_File()
await core.LuaCSharpState.DoFileAsync(core.FilePath, buffer);
return buffer[0];
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/Benchmark/FileHelper.cs b/sandbox/Benchmark/FileHelper.cs
index a0b103e3..aa998f1d 100644
--- a/sandbox/Benchmark/FileHelper.cs
+++ b/sandbox/Benchmark/FileHelper.cs
@@ -2,8 +2,11 @@
public static class FileHelper
{
- public static string GetAbsolutePath(string relativePath, [CallerFilePath] string callerFilePath = "")
+ public static string GetAbsolutePath(
+ string relativePath,
+ [CallerFilePath] string callerFilePath = ""
+ )
{
return Path.Combine(Path.GetDirectoryName(callerFilePath)!, relativePath);
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/Benchmark/HookedBenchmark.cs b/sandbox/Benchmark/HookedBenchmark.cs
index 141d3f08..4aa705d5 100644
--- a/sandbox/Benchmark/HookedBenchmark.cs
+++ b/sandbox/Benchmark/HookedBenchmark.cs
@@ -24,7 +24,6 @@ public void Cleanup()
GC.Collect();
}
-
[Benchmark(Description = "NLua (DoString)", Baseline = true)]
public object[] Benchmark_NLua_String()
{
@@ -37,4 +36,4 @@ public async Task Benchmark_LuaCSharp_String()
await core.LuaCSharpState.DoStringAsync(core.SourceText, buffer);
return buffer[0];
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/Benchmark/InterpreterSteps.cs b/sandbox/Benchmark/InterpreterSteps.cs
index fc32ee9f..c62f2625 100644
--- a/sandbox/Benchmark/InterpreterSteps.cs
+++ b/sandbox/Benchmark/InterpreterSteps.cs
@@ -36,7 +36,6 @@ public void CreateState()
LuaState.Create();
}
-
[Benchmark]
public LuaClosure Compile()
{
@@ -48,4 +47,4 @@ public async ValueTask RunAsync()
{
await state.CallAsync(closure, []);
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/Benchmark/NBodyBenchmark.cs b/sandbox/Benchmark/NBodyBenchmark.cs
index 930079aa..1a5b0d07 100644
--- a/sandbox/Benchmark/NBodyBenchmark.cs
+++ b/sandbox/Benchmark/NBodyBenchmark.cs
@@ -62,4 +62,4 @@ public async Task Benchmark_LuaCSharp_File()
await core.LuaCSharpState.DoFileAsync(core.FilePath, buffer);
return buffer[0];
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/Benchmark/Program.cs b/sandbox/Benchmark/Program.cs
index 012c3237..4dd463e2 100644
--- a/sandbox/Benchmark/Program.cs
+++ b/sandbox/Benchmark/Program.cs
@@ -1,19 +1,16 @@
-using BenchmarkDotNet.Configs;
-using BenchmarkDotNet.Diagnosers;
-using BenchmarkDotNet.Jobs;
-using BenchmarkDotNet.Running;
-using System.Reflection;
-
-BenchmarkSwitcher.FromAssembly(Assembly.GetEntryAssembly()!).Run(args);
-
-class BenchmarkConfig : ManualConfig
-{
- public BenchmarkConfig()
- {
- AddDiagnoser(MemoryDiagnoser.Default);
- AddJob(Job.ShortRun
- .WithWarmupCount(10)
- .WithIterationCount(10)
- );
- }
-}
\ No newline at end of file
+using System.Reflection;
+using BenchmarkDotNet.Configs;
+using BenchmarkDotNet.Diagnosers;
+using BenchmarkDotNet.Jobs;
+using BenchmarkDotNet.Running;
+
+BenchmarkSwitcher.FromAssembly(Assembly.GetEntryAssembly()!).Run(args);
+
+class BenchmarkConfig : ManualConfig
+{
+ public BenchmarkConfig()
+ {
+ AddDiagnoser(MemoryDiagnoser.Default);
+ AddJob(Job.ShortRun.WithWarmupCount(10).WithIterationCount(10));
+ }
+}
diff --git a/sandbox/ConsoleApp1/ConsoleApp1.csproj b/sandbox/ConsoleApp1/ConsoleApp1.csproj
index be4ca052..5d2bbe6a 100644
--- a/sandbox/ConsoleApp1/ConsoleApp1.csproj
+++ b/sandbox/ConsoleApp1/ConsoleApp1.csproj
@@ -1,22 +1,20 @@
+
+
+
+ Analyzer
+ false
+
+
+
-
-
-
- Analyzer
- false
-
-
-
-
-
- Exe
- net9.0
- 13
- enable
- enable
- false
- Generated
-
-
+
+ Exe
+ net9.0
+ 13
+ enable
+ enable
+ false
+ Generated
+
diff --git a/sandbox/ConsoleApp1/LVec3.cs b/sandbox/ConsoleApp1/LVec3.cs
index 9a97f843..c1952bb3 100644
--- a/sandbox/ConsoleApp1/LVec3.cs
+++ b/sandbox/ConsoleApp1/LVec3.cs
@@ -9,40 +9,22 @@ public partial class LVec3
[LuaMember("x")]
public float X
{
- get
- {
- return value.X;
- }
- set
- {
- this.value = this.value with { X = value };
- }
+ get { return value.X; }
+ set { this.value = this.value with { X = value }; }
}
[LuaMember("y")]
public float Y
{
- get
- {
- return value.Y;
- }
- set
- {
- this.value = this.value with { Y = value };
- }
+ get { return value.Y; }
+ set { this.value = this.value with { Y = value }; }
}
[LuaMember("z")]
public float Z
{
- get
- {
- return value.Z;
- }
- set
- {
- this.value = this.value with { Z = value };
- }
+ get { return value.Z; }
+ set { this.value = this.value with { Z = value }; }
}
[LuaMember("create")]
@@ -55,4 +37,4 @@ public override string ToString()
{
return value.ToString();
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/ConsoleApp1/Program.cs b/sandbox/ConsoleApp1/Program.cs
index f547886b..5f959f42 100644
--- a/sandbox/ConsoleApp1/Program.cs
+++ b/sandbox/ConsoleApp1/Program.cs
@@ -1,18 +1,20 @@
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
-using Lua.Runtime;
using Lua;
+using Lua.Runtime;
using Lua.Standard;
var state = LuaState.Create();
state.OpenStandardLibraries();
-state.Environment["escape"] = new LuaFunction("escape",
+state.Environment["escape"] = new LuaFunction(
+ "escape",
(c, _) =>
{
var arg = c.HasArgument(0) ? c.GetArgument(0) : "";
return new(c.Return(Regex.Escape(arg)));
- });
+ }
+);
var source = "";
try
{
@@ -37,7 +39,9 @@
state.Pop(count);
if (i % 100 == 0)
{
- Console.WriteLine($"Iteration {i} completed. Time elapsed: {timer.ElapsedMilliseconds} ms");
+ Console.WriteLine(
+ $"Iteration {i} completed. Time elapsed: {timer.ElapsedMilliseconds} ms"
+ );
Thread.Sleep(100);
}
}
@@ -107,7 +111,9 @@ static void DebugChunk(Prototype chunk, int id)
index = 0;
foreach (var upValue in chunk.UpValues.ToArray())
{
- Console.WriteLine($"[{index}]\t{upValue.Name}\t{(upValue.IsLocal ? 1 : 0)}\t{upValue.Index}");
+ Console.WriteLine(
+ $"[{index}]\t{upValue.Name}\t{(upValue.IsLocal ? 1 : 0)}\t{upValue.Index}"
+ );
index++;
}
@@ -121,7 +127,8 @@ static void DebugChunk(Prototype chunk, int id)
}
}
-public class LuaRustLikeException(string message, Exception? innerException) : Exception(message, innerException);
+public class LuaRustLikeException(string message, Exception? innerException)
+ : Exception(message, innerException);
class RustLikeExceptionHook //: ILuaCompileHook
{
@@ -147,14 +154,25 @@ public static string OnCatch(ReadOnlySpan source, LuaCompileException exce
var builder = new StringBuilder();
builder.AppendLine();
builder.AppendLine("[error]: " + exception.MessageWithNearToken);
- builder.AppendLine("-->" + exception.ChunkName + ":" + exception.Position.Line + ":" + exception.Position.Column);
+ builder.AppendLine(
+ "-->"
+ + exception.ChunkName
+ + ":"
+ + exception.Position.Line
+ + ":"
+ + exception.Position.Column
+ );
var line = source.Slice(lineOffset, length).ToString();
var lineNumString = exception.Position.Line.ToString();
builder.AppendLine(new string(' ', lineNumString.Length) + " |");
builder.AppendLine(lineNumString + " | " + line);
- builder.AppendLine(new string(' ', lineNumString.Length) + " | " +
- new string(' ', exception.Position.Column - 1) +
- "^ " + exception.MainMessage);
+ builder.AppendLine(
+ new string(' ', lineNumString.Length)
+ + " | "
+ + new string(' ', exception.Position.Column - 1)
+ + "^ "
+ + exception.MainMessage
+ );
return builder.ToString();
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/ConsoleApp2/ConsoleApp2.csproj b/sandbox/ConsoleApp2/ConsoleApp2.csproj
index 47978586..c01c6009 100644
--- a/sandbox/ConsoleApp2/ConsoleApp2.csproj
+++ b/sandbox/ConsoleApp2/ConsoleApp2.csproj
@@ -1,15 +1,13 @@
+
+ Exe
+ net9.0
+ 13
+ enable
+ enable
+
-
- Exe
- net9.0
- 13
- enable
- enable
-
-
-
-
-
-
+
+
+
diff --git a/sandbox/ConsoleApp2/Program.cs b/sandbox/ConsoleApp2/Program.cs
index 46878825..ca871dff 100644
--- a/sandbox/ConsoleApp2/Program.cs
+++ b/sandbox/ConsoleApp2/Program.cs
@@ -1,11 +1,14 @@
-using Lua.Runtime;
-using Lua;
+using Lua;
+using Lua.Runtime;
using Lua.Standard;
var state = LuaState.Create();
state.OpenStandardLibraries();
{
- var closure = state.Load("return function (a,b,...) print('a : '..a..' b :'..'args : ',...) end", "@simple");
+ var closure = state.Load(
+ "return function (a,b,...) print('a : '..a..' b :'..'args : ',...) end",
+ "@simple"
+ );
using var access = state.CreateThread();
{
var count = await access.RunAsync(closure, 0);
@@ -39,7 +42,9 @@
print('In Lua:', coroutine.yield('from lua', i,v))
end
end
- """, "coroutine");
+ """,
+ "coroutine"
+ );
var f = results[0].Read();
using var coroutine = state.CreateCoroutine(f);
{
@@ -66,4 +71,4 @@
stack.Clear();
}
}
-}
\ No newline at end of file
+}
diff --git a/sandbox/JitTest/JitTest.csproj b/sandbox/JitTest/JitTest.csproj
index a6272705..303789eb 100644
--- a/sandbox/JitTest/JitTest.csproj
+++ b/sandbox/JitTest/JitTest.csproj
@@ -1,21 +1,19 @@
+
+ Exe
+ net9.0
+ 13
+ enable
+ enable
+ true
+
-
- Exe
- net9.0
- 13
- enable
- enable
- true
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
diff --git a/sandbox/JitTest/Program.cs b/sandbox/JitTest/Program.cs
index 574ea406..2c37e43c 100644
--- a/sandbox/JitTest/Program.cs
+++ b/sandbox/JitTest/Program.cs
@@ -38,10 +38,14 @@
}
}
-var method = typeof(LuaVirtualMachine).GetMethod("MoveNext", BindingFlags.Static | BindingFlags.NonPublic)!;
+var method = typeof(LuaVirtualMachine).GetMethod(
+ "MoveNext",
+ BindingFlags.Static | BindingFlags.NonPublic
+)!;
using var disassembler = JitDisassembler.Create();
var nextJitText = disassembler.Disassemble(method, new() { PrintInstructionAddresses = true });
File.WriteAllText(newJIitPath, nextJitText);
+
// Console.WriteLine("New:" + nextJitText.Split("\n")[^1]);
static string GetThisDirectoryName([CallerFilePath] string callerFilePath = "")
@@ -52,4 +56,4 @@ static string GetThisDirectoryName([CallerFilePath] string callerFilePath = "")
static string GetAbsolutePath(string relativePath, [CallerFilePath] string callerFilePath = "")
{
return Path.Join(Path.GetDirectoryName(callerFilePath)!, relativePath);
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Annotations/Attributes.cs b/src/Lua.Annotations/Attributes.cs
index f5e3bba4..46d68939 100644
--- a/src/Lua.Annotations/Attributes.cs
+++ b/src/Lua.Annotations/Attributes.cs
@@ -1,42 +1,36 @@
-namespace Lua;
-
-[AttributeUsage(AttributeTargets.Class)]
-public sealed class LuaObjectAttribute : Attribute
-{
- public LuaObjectAttribute()
- {
- }
-
- public LuaObjectAttribute(string name)
- {
- Name = name;
- }
-
- public string? Name { get; }
-}
-
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
-public sealed class LuaMemberAttribute : Attribute
-{
- public LuaMemberAttribute()
- {
- }
-
- public LuaMemberAttribute(string name)
- {
- Name = name;
- }
-
- public string? Name { get; }
-}
-
-[AttributeUsage(AttributeTargets.Method)]
-public sealed class LuaMetamethodAttribute(LuaObjectMetamethod metamethod) : Attribute
-{
- public LuaObjectMetamethod Metamethod { get; } = metamethod;
-}
-
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
-public sealed class LuaIgnoreMemberAttribute : Attribute
-{
-}
\ No newline at end of file
+namespace Lua;
+
+[AttributeUsage(AttributeTargets.Class)]
+public sealed class LuaObjectAttribute : Attribute
+{
+ public LuaObjectAttribute() { }
+
+ public LuaObjectAttribute(string name)
+ {
+ Name = name;
+ }
+
+ public string? Name { get; }
+}
+
+[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
+public sealed class LuaMemberAttribute : Attribute
+{
+ public LuaMemberAttribute() { }
+
+ public LuaMemberAttribute(string name)
+ {
+ Name = name;
+ }
+
+ public string? Name { get; }
+}
+
+[AttributeUsage(AttributeTargets.Method)]
+public sealed class LuaMetamethodAttribute(LuaObjectMetamethod metamethod) : Attribute
+{
+ public LuaObjectMetamethod Metamethod { get; } = metamethod;
+}
+
+[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
+public sealed class LuaIgnoreMemberAttribute : Attribute { }
diff --git a/src/Lua.Annotations/Lua.Annotations.csproj b/src/Lua.Annotations/Lua.Annotations.csproj
index 4de71fe2..e62efe45 100644
--- a/src/Lua.Annotations/Lua.Annotations.csproj
+++ b/src/Lua.Annotations/Lua.Annotations.csproj
@@ -1,5 +1,4 @@
-
net10.0; net8.0; net6.0; netstandard2.1
13
@@ -19,5 +18,4 @@
-
-
\ No newline at end of file
+
diff --git a/src/Lua.Annotations/LuaObjectMetamethod.cs b/src/Lua.Annotations/LuaObjectMetamethod.cs
index c68facb1..c05a8349 100644
--- a/src/Lua.Annotations/LuaObjectMetamethod.cs
+++ b/src/Lua.Annotations/LuaObjectMetamethod.cs
@@ -19,5 +19,5 @@ public enum LuaObjectMetamethod
IPairs,
ToString,
Index,
- NewIndex
-}
\ No newline at end of file
+ NewIndex,
+}
diff --git a/src/Lua.SourceGenerator/Comparer.cs b/src/Lua.SourceGenerator/Comparer.cs
index 34214ac5..89ddc48e 100644
--- a/src/Lua.SourceGenerator/Comparer.cs
+++ b/src/Lua.SourceGenerator/Comparer.cs
@@ -6,7 +6,10 @@ sealed class Comparer : IEqualityComparer<(GeneratorAttributeSyntaxContext, Comp
{
public static readonly Comparer Instance = new();
- public bool Equals((GeneratorAttributeSyntaxContext, Compilation) x, (GeneratorAttributeSyntaxContext, Compilation) y)
+ public bool Equals(
+ (GeneratorAttributeSyntaxContext, Compilation) x,
+ (GeneratorAttributeSyntaxContext, Compilation) y
+ )
{
return x.Item1.TargetNode.Equals(y.Item1.TargetNode);
}
@@ -15,4 +18,4 @@ public int GetHashCode((GeneratorAttributeSyntaxContext, Compilation) obj)
{
return obj.Item1.TargetNode.GetHashCode();
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/DiagnosticDescriptors.cs b/src/Lua.SourceGenerator/DiagnosticDescriptors.cs
index 1ed2a83d..0b05c66e 100644
--- a/src/Lua.SourceGenerator/DiagnosticDescriptors.cs
+++ b/src/Lua.SourceGenerator/DiagnosticDescriptors.cs
@@ -12,7 +12,8 @@ public static class DiagnosticDescriptors
category: Category,
messageFormat: "LuaObject type '{0}' must be partial",
defaultSeverity: DiagnosticSeverity.Error,
- isEnabledByDefault: true);
+ isEnabledByDefault: true
+ );
public static readonly DiagnosticDescriptor NestedNotAllowed = new(
id: "LUACS002",
@@ -20,7 +21,8 @@ public static class DiagnosticDescriptors
messageFormat: "LuaObject type '{0}' must be not nested",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
- isEnabledByDefault: true);
+ isEnabledByDefault: true
+ );
public static readonly DiagnosticDescriptor AbstractNotAllowed = new(
id: "LUACS003",
@@ -28,7 +30,8 @@ public static class DiagnosticDescriptors
messageFormat: "LuaObject object '{0}' must be not abstract",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
- isEnabledByDefault: true);
+ isEnabledByDefault: true
+ );
public static readonly DiagnosticDescriptor InvalidPropertyType = new(
id: "LUACS004",
@@ -36,7 +39,8 @@ public static class DiagnosticDescriptors
messageFormat: "The type of '{0}' must be LuaValue or a type that can be converted to LuaValue.",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
- isEnabledByDefault: true);
+ isEnabledByDefault: true
+ );
public static readonly DiagnosticDescriptor InvalidReturnType = new(
id: "LUACS005",
@@ -44,7 +48,8 @@ public static class DiagnosticDescriptors
messageFormat: "The return type '{0}' must be LuaValue or types that can be converted to LuaValue.",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
- isEnabledByDefault: true);
+ isEnabledByDefault: true
+ );
public static readonly DiagnosticDescriptor InvalidParameterType = new(
id: "LUACS006",
@@ -52,7 +57,8 @@ public static class DiagnosticDescriptors
messageFormat: "The parameter '{0}' must be LuaValue or types that can be converted to LuaValue.",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
- isEnabledByDefault: true);
+ isEnabledByDefault: true
+ );
public static readonly DiagnosticDescriptor DuplicateMetamethod = new(
id: "LUACS007",
@@ -60,5 +66,6 @@ public static class DiagnosticDescriptors
messageFormat: "Type '{0}' already contains a '{1}' metamethod.,",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
- isEnabledByDefault: true);
-}
\ No newline at end of file
+ isEnabledByDefault: true
+ );
+}
diff --git a/src/Lua.SourceGenerator/Lua.SourceGenerator.csproj b/src/Lua.SourceGenerator/Lua.SourceGenerator.csproj
index c377a3c8..a9d6b158 100644
--- a/src/Lua.SourceGenerator/Lua.SourceGenerator.csproj
+++ b/src/Lua.SourceGenerator/Lua.SourceGenerator.csproj
@@ -1,28 +1,30 @@
+
+ netstandard2.0
+ 13
+ enable
+ enable
+ true
+ cs
+ true
+ false
+ true
+ false
+ true
-
- netstandard2.0
- 13
- enable
- enable
- true
- cs
- true
- false
- true
- false
- true
+
+ LuaCSharp.SourceGenerator
+ lua;interpreter
+ SourceGenerator for Lua-CSharp
+
-
- LuaCSharp.SourceGenerator
- lua;interpreter
- SourceGenerator for Lua-CSharp
-
-
-
-
-
-
-
-
\ No newline at end of file
+
+
+
+
+
diff --git a/src/Lua.SourceGenerator/LuaObjectGenerator.Emit.cs b/src/Lua.SourceGenerator/LuaObjectGenerator.Emit.cs
index 6b23a167..02f39a1f 100644
--- a/src/Lua.SourceGenerator/LuaObjectGenerator.Emit.cs
+++ b/src/Lua.SourceGenerator/LuaObjectGenerator.Emit.cs
@@ -6,7 +6,11 @@ namespace Lua.SourceGenerator;
partial class LuaObjectGenerator
{
- static string GetLuaValuePrefix(ITypeSymbol typeSymbol, SymbolReferences references, Compilation compilation)
+ static string GetLuaValuePrefix(
+ ITypeSymbol typeSymbol,
+ SymbolReferences references,
+ Compilation compilation
+ )
{
if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.Object))
{
@@ -18,13 +22,25 @@ static string GetLuaValuePrefix(ITypeSymbol typeSymbol, SymbolReferences referen
: "(";
}
- static string GetLuaValueExpression(string expression, ITypeSymbol typeSymbol, SymbolReferences references, Compilation compilation)
+ static string GetLuaValueExpression(
+ string expression,
+ ITypeSymbol typeSymbol,
+ SymbolReferences references,
+ Compilation compilation
+ )
{
return $"{GetLuaValuePrefix(typeSymbol, references, compilation)}{expression})";
}
- static bool TryEmit(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation, in SourceProductionContext context, Dictionary metaDict,
- TempCollections tempCollections)
+ static bool TryEmit(
+ TypeMetadata typeMetadata,
+ CodeBuilder builder,
+ SymbolReferences references,
+ Compilation compilation,
+ in SourceProductionContext context,
+ Dictionary metaDict,
+ TempCollections tempCollections
+ )
{
try
{
@@ -33,20 +49,26 @@ static bool TryEmit(TypeMetadata typeMetadata, CodeBuilder builder, SymbolRefere
// must be partial
if (!typeMetadata.IsPartial())
{
- context.ReportDiagnostic(Diagnostic.Create(
- DiagnosticDescriptors.MustBePartial,
- typeMetadata.Syntax.Identifier.GetLocation(),
- typeMetadata.Symbol.Name));
+ context.ReportDiagnostic(
+ Diagnostic.Create(
+ DiagnosticDescriptors.MustBePartial,
+ typeMetadata.Syntax.Identifier.GetLocation(),
+ typeMetadata.Symbol.Name
+ )
+ );
error = true;
}
// nested is not allowed
if (typeMetadata.IsNested())
{
- context.ReportDiagnostic(Diagnostic.Create(
- DiagnosticDescriptors.NestedNotAllowed,
- typeMetadata.Syntax.Identifier.GetLocation(),
- typeMetadata.Symbol.Name));
+ context.ReportDiagnostic(
+ Diagnostic.Create(
+ DiagnosticDescriptors.NestedNotAllowed,
+ typeMetadata.Syntax.Identifier.GetLocation(),
+ typeMetadata.Symbol.Name
+ )
+ );
error = true;
}
@@ -63,12 +85,22 @@ static bool TryEmit(TypeMetadata typeMetadata, CodeBuilder builder, SymbolRefere
builder.AppendLine("// ");
builder.AppendLine("#nullable enable");
builder.AppendLine("#pragma warning disable CS0162 // Unreachable code");
- builder.AppendLine("#pragma warning disable CS0219 // Variable assigned but never used");
- builder.AppendLine("#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.");
- builder.AppendLine("#pragma warning disable CS8601 // Possible null reference assignment");
+ builder.AppendLine(
+ "#pragma warning disable CS0219 // Variable assigned but never used"
+ );
+ builder.AppendLine(
+ "#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type."
+ );
+ builder.AppendLine(
+ "#pragma warning disable CS8601 // Possible null reference assignment"
+ );
builder.AppendLine("#pragma warning disable CS8602 // Possible null return");
- builder.AppendLine("#pragma warning disable CS8604 // Possible null reference argument for parameter");
- builder.AppendLine("#pragma warning disable CS8631 // The type cannot be used as type parameter in the generic type or method");
+ builder.AppendLine(
+ "#pragma warning disable CS8604 // Possible null reference argument for parameter"
+ );
+ builder.AppendLine(
+ "#pragma warning disable CS8631 // The type cannot be used as type parameter in the generic type or method"
+ );
builder.AppendLine();
var ns = typeMetadata.Symbol.ContainingNamespace;
@@ -78,31 +110,63 @@ static bool TryEmit(TypeMetadata typeMetadata, CodeBuilder builder, SymbolRefere
builder.BeginBlock();
}
- var typeDeclarationKeyword = (typeMetadata.Symbol.IsRecord, typeMetadata.Symbol.IsValueType) switch
+ var typeDeclarationKeyword = (
+ typeMetadata.Symbol.IsRecord,
+ typeMetadata.Symbol.IsValueType
+ ) switch
{
(true, true) => "record struct",
(true, false) => "record",
(false, true) => "struct",
- (false, false) => "class"
+ (false, false) => "class",
};
- using var _ = builder.BeginBlockScope($"partial {typeDeclarationKeyword} {typeMetadata.TypeName} : global::Lua.ILuaUserData");
+ using var _ = builder.BeginBlockScope(
+ $"partial {typeDeclarationKeyword} {typeMetadata.TypeName} : global::Lua.ILuaUserData"
+ );
var metamethodSet = tempCollections.Metamethods;
- if (!TryEmitMethods(typeMetadata, builder, references, compilation, metamethodSet, context))
+ if (
+ !TryEmitMethods(
+ typeMetadata,
+ builder,
+ references,
+ compilation,
+ metamethodSet,
+ context
+ )
+ )
{
return false;
}
- if (!TryEmitIndexMetamethod(typeMetadata, builder, references, compilation, context, tempCollections))
+ if (
+ !TryEmitIndexMetamethod(
+ typeMetadata,
+ builder,
+ references,
+ compilation,
+ context,
+ tempCollections
+ )
+ )
{
return false;
}
metamethodSet.Add(LuaObjectMetamethod.Index);
- if (!TryEmitNewIndexMetamethod(typeMetadata, builder, references, compilation, context, tempCollections))
+ if (
+ !TryEmitNewIndexMetamethod(
+ typeMetadata,
+ builder,
+ references,
+ compilation,
+ context,
+ tempCollections
+ )
+ )
{
return false;
}
@@ -115,7 +179,9 @@ static bool TryEmit(TypeMetadata typeMetadata, CodeBuilder builder, SymbolRefere
}
// implicit operator
- builder.AppendLine($"public static implicit operator global::Lua.LuaValue({typeMetadata.FullTypeName} value)");
+ builder.AppendLine(
+ $"public static implicit operator global::Lua.LuaValue({typeMetadata.FullTypeName} value)"
+ );
using (builder.BeginBlockScope())
{
builder.AppendLine("return global::Lua.LuaValue.FromUserData(value);");
@@ -127,12 +193,22 @@ static bool TryEmit(TypeMetadata typeMetadata, CodeBuilder builder, SymbolRefere
}
builder.AppendLine("#pragma warning restore CS0162 // Unreachable code");
- builder.AppendLine("#pragma warning restore CS0219 // Variable assigned but never used");
- builder.AppendLine("#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.");
- builder.AppendLine("#pragma warning restore CS8601 // Possible null reference assignment");
+ builder.AppendLine(
+ "#pragma warning restore CS0219 // Variable assigned but never used"
+ );
+ builder.AppendLine(
+ "#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type."
+ );
+ builder.AppendLine(
+ "#pragma warning restore CS8601 // Possible null reference assignment"
+ );
builder.AppendLine("#pragma warning restore CS8602 // Possible null return");
- builder.AppendLine("#pragma warning restore CS8604 // Possible null reference argument for parameter");
- builder.AppendLine("#pragma warning restore CS8631 // The type cannot be used as type parameter in the generic type or method");
+ builder.AppendLine(
+ "#pragma warning restore CS8604 // Possible null reference argument for parameter"
+ );
+ builder.AppendLine(
+ "#pragma warning restore CS8631 // The type cannot be used as type parameter in the generic type or method"
+ );
return true;
}
catch (Exception)
@@ -141,7 +217,13 @@ static bool TryEmit(TypeMetadata typeMetadata, CodeBuilder builder, SymbolRefere
}
}
- static bool ValidateMembers(TypeMetadata typeMetadata, Compilation compilation, SymbolReferences references, in SourceProductionContext context, Dictionary metaDict)
+ static bool ValidateMembers(
+ TypeMetadata typeMetadata,
+ Compilation compilation,
+ SymbolReferences references,
+ in SourceProductionContext context,
+ Dictionary metaDict
+ )
{
var isValid = true;
@@ -168,12 +250,21 @@ static bool ValidateMembers(TypeMetadata typeMetadata, Compilation compilation,
}
var conversion = compilation.ClassifyConversion(property.Type, references.LuaValue);
- if (!conversion.Exists && (property.Type is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
+ if (
+ !conversion.Exists
+ && (
+ property.Type is not INamedTypeSymbol namedTypeSymbol
+ || !metaDict.ContainsKey(namedTypeSymbol)
+ )
+ )
{
- context.ReportDiagnostic(Diagnostic.Create(
- DiagnosticDescriptors.InvalidPropertyType,
- property.Symbol.Locations.FirstOrDefault(),
- property.Type.Name));
+ context.ReportDiagnostic(
+ Diagnostic.Create(
+ DiagnosticDescriptors.InvalidPropertyType,
+ property.Symbol.Locations.FirstOrDefault(),
+ property.Type.Name
+ )
+ );
isValid = false;
}
@@ -217,23 +308,38 @@ static bool ValidateMembers(TypeMetadata typeMetadata, Compilation compilation,
}
var conversion = compilation.ClassifyConversion(typeSymbol, references.LuaValue);
- if (!conversion.Exists && (typeSymbol is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
+ if (
+ !conversion.Exists
+ && (
+ typeSymbol is not INamedTypeSymbol namedTypeSymbol
+ || !metaDict.ContainsKey(namedTypeSymbol)
+ )
+ )
{
- context.ReportDiagnostic(Diagnostic.Create(
- DiagnosticDescriptors.InvalidReturnType,
- typeSymbol.Locations.FirstOrDefault(),
- typeSymbol.Name));
+ context.ReportDiagnostic(
+ Diagnostic.Create(
+ DiagnosticDescriptors.InvalidReturnType,
+ typeSymbol.Locations.FirstOrDefault(),
+ typeSymbol.Name
+ )
+ );
isValid = false;
}
}
- PARAMETERS:
+ PARAMETERS:
for (var index = 0; index < method.Symbol.Parameters.Length; index++)
{
var parameterSymbol = method.Symbol.Parameters[index];
var typeSymbol = parameterSymbol.Type;
- if (index == method.Symbol.Parameters.Length - 1 && SymbolEqualityComparer.Default.Equals(typeSymbol, references.CancellationToken))
+ if (
+ index == method.Symbol.Parameters.Length - 1
+ && SymbolEqualityComparer.Default.Equals(
+ typeSymbol,
+ references.CancellationToken
+ )
+ )
{
continue;
}
@@ -264,12 +370,21 @@ static bool ValidateMembers(TypeMetadata typeMetadata, Compilation compilation,
}
var conversion = compilation.ClassifyConversion(typeSymbol, references.LuaValue);
- if (!conversion.Exists && (typeSymbol is not INamedTypeSymbol namedTypeSymbol || !metaDict.ContainsKey(namedTypeSymbol)))
+ if (
+ !conversion.Exists
+ && (
+ typeSymbol is not INamedTypeSymbol namedTypeSymbol
+ || !metaDict.ContainsKey(namedTypeSymbol)
+ )
+ )
{
- context.ReportDiagnostic(Diagnostic.Create(
- DiagnosticDescriptors.InvalidParameterType,
- typeSymbol.Locations.FirstOrDefault(),
- typeSymbol.Name));
+ context.ReportDiagnostic(
+ Diagnostic.Create(
+ DiagnosticDescriptors.InvalidParameterType,
+ typeSymbol.Locations.FirstOrDefault(),
+ typeSymbol.Name
+ )
+ );
isValid = false;
}
@@ -281,12 +396,19 @@ static bool ValidateMembers(TypeMetadata typeMetadata, Compilation compilation,
static MethodMetadata? GetMetamethod(TypeMetadata typeMetadata, LuaObjectMetamethod metamethod)
{
- return typeMetadata.Methods.FirstOrDefault(x => x.HasMetamethodAttribute && x.Metamethod == metamethod);
+ return typeMetadata.Methods.FirstOrDefault(x =>
+ x.HasMetamethodAttribute && x.Metamethod == metamethod
+ );
}
- static ITypeSymbol? GetContextArgumentType(MethodMetadata methodMetadata, int contextArgumentIndex)
+ static ITypeSymbol? GetContextArgumentType(
+ MethodMetadata methodMetadata,
+ int contextArgumentIndex
+ )
{
- var parameterIndex = methodMetadata.IsStatic ? contextArgumentIndex : contextArgumentIndex - 1;
+ var parameterIndex = methodMetadata.IsStatic
+ ? contextArgumentIndex
+ : contextArgumentIndex - 1;
if (parameterIndex < 0 || parameterIndex >= methodMetadata.Symbol.Parameters.Length)
{
return null;
@@ -297,31 +419,57 @@ static bool ValidateMembers(TypeMetadata typeMetadata, Compilation compilation,
static bool IsPreloadableArgumentType(ITypeSymbol? typeSymbol, SymbolReferences references)
{
- return typeSymbol != null && !SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue);
+ return typeSymbol != null
+ && !SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue);
}
- static void EmitLuaValueCompatibilityCheck(CodeBuilder builder, string luaValueExpression, ITypeSymbol? typeSymbol, SymbolReferences references)
+ static void EmitLuaValueCompatibilityCheck(
+ CodeBuilder builder,
+ string luaValueExpression,
+ ITypeSymbol? typeSymbol,
+ SymbolReferences references
+ )
{
- if (typeSymbol == null || SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue))
+ if (
+ typeSymbol == null
+ || SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue)
+ )
{
builder.Append("true", false);
return;
}
- builder.Append($"{luaValueExpression}.TryRead<{typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>(out _)", false);
+ builder.Append(
+ $"{luaValueExpression}.TryRead<{typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>(out _)",
+ false
+ );
}
- static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation, in SourceProductionContext context, TempCollections tempCollections)
+ static bool TryEmitIndexMetamethod(
+ TypeMetadata typeMetadata,
+ CodeBuilder builder,
+ SymbolReferences references,
+ Compilation compilation,
+ in SourceProductionContext context,
+ TempCollections tempCollections
+ )
{
var customMetamethod = GetMetamethod(typeMetadata, LuaObjectMetamethod.Index);
- var customKeyType = customMetamethod == null ? null : GetContextArgumentType(customMetamethod, 1);
- var customHandlesStringKey = customMetamethod != null && SymbolEqualityComparer.Default.Equals(customKeyType, references.String);
+ var customKeyType =
+ customMetamethod == null ? null : GetContextArgumentType(customMetamethod, 1);
+ var customHandlesStringKey =
+ customMetamethod != null
+ && SymbolEqualityComparer.Default.Equals(customKeyType, references.String);
- builder.AppendLine(@"static readonly global::Lua.LuaFunction __metamethod_index = new global::Lua.LuaFunction(""index"", (context, ct) =>");
+ builder.AppendLine(
+ @"static readonly global::Lua.LuaFunction __metamethod_index = new global::Lua.LuaFunction(""index"", (context, ct) =>"
+ );
using (builder.BeginBlockScope())
{
- builder.AppendLine($"var userData = context.GetArgument<{typeMetadata.FullTypeName}>(0);");
+ builder.AppendLine(
+ $"var userData = context.GetArgument<{typeMetadata.FullTypeName}>(0);"
+ );
builder.AppendLine("var key = context.GetArgument(1);");
builder.AppendLine("if (key.TryRead(out var stringKey))");
using (builder.BeginBlockScope())
@@ -334,22 +482,32 @@ static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builde
continue;
}
-
- var conversionPrefix = GetLuaValuePrefix(propertyMetadata.Type, references, compilation);
+ var conversionPrefix = GetLuaValuePrefix(
+ propertyMetadata.Type,
+ references,
+ compilation
+ );
if (propertyMetadata.IsStatic)
{
- builder.AppendLine(@$"if (stringKey == ""{propertyMetadata.LuaMemberName}"") return new global::System.Threading.Tasks.ValueTask(context.Return({conversionPrefix}{typeMetadata.FullTypeName}.{propertyMetadata.Symbol.Name})));");
+ builder.AppendLine(
+ @$"if (stringKey == ""{propertyMetadata.LuaMemberName}"") return new global::System.Threading.Tasks.ValueTask(context.Return({conversionPrefix}{typeMetadata.FullTypeName}.{propertyMetadata.Symbol.Name})));"
+ );
}
else
{
- builder.AppendLine(@$"if (stringKey == ""{propertyMetadata.LuaMemberName}"") return new global::System.Threading.Tasks.ValueTask(context.Return({conversionPrefix}userData.{propertyMetadata.Symbol.Name})));");
+ builder.AppendLine(
+ @$"if (stringKey == ""{propertyMetadata.LuaMemberName}"") return new global::System.Threading.Tasks.ValueTask(context.Return({conversionPrefix}userData.{propertyMetadata.Symbol.Name})));"
+ );
}
}
- foreach (var methodMetadata in typeMetadata.Methods
- .Where(x => x.HasMemberAttribute))
+ foreach (
+ var methodMetadata in typeMetadata.Methods.Where(x => x.HasMemberAttribute)
+ )
{
- builder.AppendLine(@$"if (stringKey == ""{methodMetadata.LuaMemberName}"") return new global::System.Threading.Tasks.ValueTask(context.Return(new global::Lua.LuaValue(__function_{methodMetadata.LuaMemberName})));");
+ builder.AppendLine(
+ @$"if (stringKey == ""{methodMetadata.LuaMemberName}"") return new global::System.Threading.Tasks.ValueTask(context.Return(new global::Lua.LuaValue(__function_{methodMetadata.LuaMemberName})));"
+ );
}
if (tempCollections.InvalidMemberNames.Count > 0)
@@ -370,7 +528,9 @@ static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builde
builder.AppendLine(")", false);
using (builder.BeginIndentScope())
{
- builder.AppendLine(@"throw new global::Lua.LuaRuntimeException(context.State, $""'{stringKey}' cannot be read."");");
+ builder.AppendLine(
+ @"throw new global::Lua.LuaRuntimeException(context.State, $""'{stringKey}' cannot be read."");"
+ );
}
tempCollections.InvalidMemberNames.Clear();
@@ -378,13 +538,23 @@ static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builde
if (customMetamethod == null)
{
- builder.AppendLine("return new global::System.Threading.Tasks.ValueTask(context.Return(global::Lua.LuaValue.Nil));");
+ builder.AppendLine(
+ "return new global::System.Threading.Tasks.ValueTask(context.Return(global::Lua.LuaValue.Nil));"
+ );
}
else if (customHandlesStringKey)
{
using (builder.BeginBlockScope())
{
- EmitMethodFunctionBody(typeMetadata, customMetamethod, builder, references, compilation, new Dictionary { [1] = "stringKey" }, "userData");
+ EmitMethodFunctionBody(
+ typeMetadata,
+ customMetamethod,
+ builder,
+ references,
+ compilation,
+ new Dictionary { [1] = "stringKey" },
+ "userData"
+ );
}
}
}
@@ -394,11 +564,22 @@ static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builde
if (IsPreloadableArgumentType(customKeyType, references))
{
builder.Append(@"if (key.TryRead<");
- builder.Append(customKeyType!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), false);
+ builder.Append(
+ customKeyType!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
+ false
+ );
builder.AppendLine(@">(out var arg1))", false);
using (builder.BeginBlockScope())
{
- EmitMethodFunctionBody(typeMetadata, customMetamethod, builder, references, compilation, new Dictionary { [1] = "arg1" }, "userData");
+ EmitMethodFunctionBody(
+ typeMetadata,
+ customMetamethod,
+ builder,
+ references,
+ compilation,
+ new Dictionary { [1] = "arg1" },
+ "userData"
+ );
}
}
else
@@ -408,12 +589,21 @@ static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builde
builder.AppendLine(")", false);
using (builder.BeginBlockScope())
{
- EmitMethodFunctionBody(typeMetadata, customMetamethod, builder, references, compilation, existingUserDataVariable: "userData");
+ EmitMethodFunctionBody(
+ typeMetadata,
+ customMetamethod,
+ builder,
+ references,
+ compilation,
+ existingUserDataVariable: "userData"
+ );
}
}
}
- builder.AppendLine("return new global::System.Threading.Tasks.ValueTask(context.Return(global::Lua.LuaValue.Nil));");
+ builder.AppendLine(
+ "return new global::System.Threading.Tasks.ValueTask(context.Return(global::Lua.LuaValue.Nil));"
+ );
}
builder.AppendLine(");");
@@ -421,17 +611,31 @@ static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builde
return true;
}
- static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation, in SourceProductionContext context, TempCollections tempCollections)
+ static bool TryEmitNewIndexMetamethod(
+ TypeMetadata typeMetadata,
+ CodeBuilder builder,
+ SymbolReferences references,
+ Compilation compilation,
+ in SourceProductionContext context,
+ TempCollections tempCollections
+ )
{
var customMetamethod = GetMetamethod(typeMetadata, LuaObjectMetamethod.NewIndex);
- var customKeyType = customMetamethod == null ? null : GetContextArgumentType(customMetamethod, 1);
- var customHandlesStringKey = customMetamethod != null && SymbolEqualityComparer.Default.Equals(customKeyType, references.String);
+ var customKeyType =
+ customMetamethod == null ? null : GetContextArgumentType(customMetamethod, 1);
+ var customHandlesStringKey =
+ customMetamethod != null
+ && SymbolEqualityComparer.Default.Equals(customKeyType, references.String);
- builder.AppendLine(@"static readonly global::Lua.LuaFunction __metamethod_newindex = new global::Lua.LuaFunction(""newindex"", (context, ct) =>");
+ builder.AppendLine(
+ @"static readonly global::Lua.LuaFunction __metamethod_newindex = new global::Lua.LuaFunction(""newindex"", (context, ct) =>"
+ );
using (builder.BeginBlockScope())
{
- builder.AppendLine($"var userData = context.GetArgument<{typeMetadata.FullTypeName}>(0);");
+ builder.AppendLine(
+ $"var userData = context.GetArgument<{typeMetadata.FullTypeName}>(0);"
+ );
builder.AppendLine("var key = context.GetArgument(1);");
builder.AppendLine("if (key.TryRead(out var stringKey))");
using (builder.BeginBlockScope())
@@ -449,35 +653,58 @@ static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder bui
{
if (propertyMetadata.IsStatic)
{
- if (SymbolEqualityComparer.Default.Equals(propertyMetadata.Type, references.LuaValue))
+ if (
+ SymbolEqualityComparer.Default.Equals(
+ propertyMetadata.Type,
+ references.LuaValue
+ )
+ )
{
- builder.AppendLine($"{typeMetadata.FullTypeName}.{propertyMetadata.Symbol.Name} = context.GetArgument(2);");
+ builder.AppendLine(
+ $"{typeMetadata.FullTypeName}.{propertyMetadata.Symbol.Name} = context.GetArgument(2);"
+ );
}
else
{
- builder.AppendLine($"{typeMetadata.FullTypeName}.{propertyMetadata.Symbol.Name} = context.GetArgument<{propertyMetadata.TypeFullName}>(2);");
+ builder.AppendLine(
+ $"{typeMetadata.FullTypeName}.{propertyMetadata.Symbol.Name} = context.GetArgument<{propertyMetadata.TypeFullName}>(2);"
+ );
}
- builder.AppendLine("return new global::System.Threading.Tasks.ValueTask(context.Return());");
+ builder.AppendLine(
+ "return new global::System.Threading.Tasks.ValueTask(context.Return());"
+ );
}
else
{
- if (SymbolEqualityComparer.Default.Equals(propertyMetadata.Type, references.LuaValue))
+ if (
+ SymbolEqualityComparer.Default.Equals(
+ propertyMetadata.Type,
+ references.LuaValue
+ )
+ )
{
- builder.AppendLine($"userData.{propertyMetadata.Symbol.Name} = context.GetArgument(2);");
+ builder.AppendLine(
+ $"userData.{propertyMetadata.Symbol.Name} = context.GetArgument(2);"
+ );
}
else
{
- builder.AppendLine($"userData.{propertyMetadata.Symbol.Name} = context.GetArgument<{propertyMetadata.TypeFullName}>(2);");
+ builder.AppendLine(
+ $"userData.{propertyMetadata.Symbol.Name} = context.GetArgument<{propertyMetadata.TypeFullName}>(2);"
+ );
}
- builder.AppendLine("return new global::System.Threading.Tasks.ValueTask(context.Return());");
+ builder.AppendLine(
+ "return new global::System.Threading.Tasks.ValueTask(context.Return());"
+ );
}
}
}
- foreach (var methodMetadata in typeMetadata.Methods
- .Where(x => x.HasMemberAttribute))
+ foreach (
+ var methodMetadata in typeMetadata.Methods.Where(x => x.HasMemberAttribute)
+ )
{
tempCollections.InvalidMemberNames.Add(methodMetadata.LuaMemberName);
}
@@ -500,7 +727,9 @@ static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder bui
builder.AppendLine(")");
using (builder.BeginBlockScope())
{
- builder.AppendLine(@"throw new global::Lua.LuaRuntimeException(context.State, $""'{stringKey}' cannot overwrite."");");
+ builder.AppendLine(
+ @"throw new global::Lua.LuaRuntimeException(context.State, $""'{stringKey}' cannot overwrite."");"
+ );
}
tempCollections.InvalidMemberNames.Clear();
@@ -508,13 +737,23 @@ static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder bui
if (customMetamethod == null)
{
- builder.AppendLine(@"throw new global::Lua.LuaRuntimeException(context.State, $""'{stringKey}' not found."");");
+ builder.AppendLine(
+ @"throw new global::Lua.LuaRuntimeException(context.State, $""'{stringKey}' not found."");"
+ );
}
else if (customHandlesStringKey)
{
using (builder.BeginBlockScope())
{
- EmitMethodFunctionBody(typeMetadata, customMetamethod, builder, references, compilation, new Dictionary { [1] = "stringKey" }, "userData");
+ EmitMethodFunctionBody(
+ typeMetadata,
+ customMetamethod,
+ builder,
+ references,
+ compilation,
+ new Dictionary { [1] = "stringKey" },
+ "userData"
+ );
}
}
}
@@ -524,11 +763,22 @@ static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder bui
if (IsPreloadableArgumentType(customKeyType, references))
{
builder.Append(@"if (key.TryRead<");
- builder.Append(customKeyType!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), false);
+ builder.Append(
+ customKeyType!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
+ false
+ );
builder.AppendLine(@">(out var arg1))", false);
using (builder.BeginBlockScope())
{
- EmitMethodFunctionBody(typeMetadata, customMetamethod, builder, references, compilation, new Dictionary { [1] = "arg1" }, "userData");
+ EmitMethodFunctionBody(
+ typeMetadata,
+ customMetamethod,
+ builder,
+ references,
+ compilation,
+ new Dictionary { [1] = "arg1" },
+ "userData"
+ );
}
}
else
@@ -538,12 +788,21 @@ static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder bui
builder.AppendLine(")", false);
using (builder.BeginBlockScope())
{
- EmitMethodFunctionBody(typeMetadata, customMetamethod, builder, references, compilation, existingUserDataVariable: "userData");
+ EmitMethodFunctionBody(
+ typeMetadata,
+ customMetamethod,
+ builder,
+ references,
+ compilation,
+ existingUserDataVariable: "userData"
+ );
}
}
}
- builder.AppendLine(@"throw new global::Lua.LuaRuntimeException(context.State, $""'{key}' not found."");");
+ builder.AppendLine(
+ @"throw new global::Lua.LuaRuntimeException(context.State, $""'{key}' not found."");"
+ );
}
builder.AppendLine(");");
@@ -551,7 +810,14 @@ static bool TryEmitNewIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder bui
return true;
}
- static bool TryEmitMethods(TypeMetadata typeMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation, HashSet metamethodSet, in SourceProductionContext context)
+ static bool TryEmitMethods(
+ TypeMetadata typeMetadata,
+ CodeBuilder builder,
+ SymbolReferences references,
+ Compilation compilation,
+ HashSet metamethodSet,
+ in SourceProductionContext context
+ )
{
builder.AppendLine();
@@ -562,7 +828,15 @@ static bool TryEmitMethods(TypeMetadata typeMetadata, CodeBuilder builder, Symbo
if (methodMetadata.HasMemberAttribute)
{
functionName = $"__function_{methodMetadata.LuaMemberName}";
- EmitMethodFunction(functionName, methodMetadata.LuaMemberName, typeMetadata, methodMetadata, builder, references, compilation);
+ EmitMethodFunction(
+ functionName,
+ methodMetadata.LuaMemberName,
+ typeMetadata,
+ methodMetadata,
+ builder,
+ references,
+ compilation
+ );
}
if (methodMetadata.HasMetamethodAttribute)
@@ -570,26 +844,46 @@ static bool TryEmitMethods(TypeMetadata typeMetadata, CodeBuilder builder, Symbo
var metaMethodName = methodMetadata.Metamethod.ToString().ToLower();
if (!metamethodSet.Add(methodMetadata.Metamethod))
{
- context.ReportDiagnostic(Diagnostic.Create(
- DiagnosticDescriptors.DuplicateMetamethod,
- methodMetadata.Symbol.Locations.FirstOrDefault(),
- typeMetadata.TypeName,
- metaMethodName
- ));
+ context.ReportDiagnostic(
+ Diagnostic.Create(
+ DiagnosticDescriptors.DuplicateMetamethod,
+ methodMetadata.Symbol.Locations.FirstOrDefault(),
+ typeMetadata.TypeName,
+ metaMethodName
+ )
+ );
continue;
}
if (functionName == null)
{
- if (methodMetadata.Metamethod is not LuaObjectMetamethod.Index and not LuaObjectMetamethod.NewIndex)
+ if (
+ methodMetadata.Metamethod
+ is not LuaObjectMetamethod.Index
+ and not LuaObjectMetamethod.NewIndex
+ )
{
- EmitMethodFunction($"__metamethod_{metaMethodName}", metaMethodName, typeMetadata, methodMetadata, builder, references, compilation);
+ EmitMethodFunction(
+ $"__metamethod_{metaMethodName}",
+ metaMethodName,
+ typeMetadata,
+ methodMetadata,
+ builder,
+ references,
+ compilation
+ );
}
}
- else if (methodMetadata.Metamethod is not LuaObjectMetamethod.Index and not LuaObjectMetamethod.NewIndex)
+ else if (
+ methodMetadata.Metamethod
+ is not LuaObjectMetamethod.Index
+ and not LuaObjectMetamethod.NewIndex
+ )
{
- builder.AppendLine($"static global::Lua.LuaFunction __metamethod_{metaMethodName} => {functionName};");
+ builder.AppendLine(
+ $"static global::Lua.LuaFunction __metamethod_{metaMethodName} => {functionName};"
+ );
}
}
}
@@ -597,9 +891,19 @@ static bool TryEmitMethods(TypeMetadata typeMetadata, CodeBuilder builder, Symbo
return true;
}
- static void EmitMethodFunction(string functionName, string chunkName, TypeMetadata typeMetadata, MethodMetadata methodMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation)
+ static void EmitMethodFunction(
+ string functionName,
+ string chunkName,
+ TypeMetadata typeMetadata,
+ MethodMetadata methodMetadata,
+ CodeBuilder builder,
+ SymbolReferences references,
+ Compilation compilation
+ )
{
- builder.AppendLine($@"static readonly global::Lua.LuaFunction {functionName} = new global::Lua.LuaFunction(""{chunkName}"", {(methodMetadata.IsAsync ? "async" : "")} (context, ct) =>");
+ builder.AppendLine(
+ $@"static readonly global::Lua.LuaFunction {functionName} = new global::Lua.LuaFunction(""{chunkName}"", {(methodMetadata.IsAsync ? "async" : "")} (context, ct) =>"
+ );
using (builder.BeginBlockScope())
{
@@ -610,8 +914,15 @@ static void EmitMethodFunction(string functionName, string chunkName, TypeMetada
builder.AppendLine();
}
- static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata methodMetadata, CodeBuilder builder, SymbolReferences references, Compilation compilation, IReadOnlyDictionary? preloadedArguments = null,
- string? existingUserDataVariable = null)
+ static void EmitMethodFunctionBody(
+ TypeMetadata typeMetadata,
+ MethodMetadata methodMetadata,
+ CodeBuilder builder,
+ SymbolReferences references,
+ Compilation compilation,
+ IReadOnlyDictionary? preloadedArguments = null,
+ string? existingUserDataVariable = null
+ )
{
var index = 0;
var luaArgumentIndex = 0;
@@ -623,7 +934,9 @@ static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata met
{
if (existingUserDataVariable == null)
{
- builder.AppendLine($"var {userDataVariable} = context.GetArgument<{typeMetadata.FullTypeName}>(0);");
+ builder.AppendLine(
+ $"var {userDataVariable} = context.GetArgument<{typeMetadata.FullTypeName}>(0);"
+ );
}
index++;
@@ -636,11 +949,22 @@ static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata met
{
var parameter = methodMetadata.Symbol.Parameters[i];
var parameterType = parameter.Type;
- var parameterTypeName = parameterType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
+ var parameterTypeName = parameterType.ToDisplayString(
+ SymbolDisplayFormat.FullyQualifiedFormat
+ );
var variableName = $"arg{index}";
- var isParameterLuaValue = SymbolEqualityComparer.Default.Equals(parameterType, references.LuaValue);
-
- if (i == methodMetadata.Symbol.Parameters.Length - 1 && SymbolEqualityComparer.Default.Equals(parameterType, references.CancellationToken))
+ var isParameterLuaValue = SymbolEqualityComparer.Default.Equals(
+ parameterType,
+ references.LuaValue
+ );
+
+ if (
+ i == methodMetadata.Symbol.Parameters.Length - 1
+ && SymbolEqualityComparer.Default.Equals(
+ parameterType,
+ references.CancellationToken
+ )
+ )
{
hasCancellationToken = true;
break;
@@ -650,17 +974,29 @@ static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata met
{
builder.AppendLine($"{parameterTypeName} {variableName};");
callArguments.Add($"out {variableName}");
- extraReturnValues.Add(GetLuaValueExpression(variableName, parameterType, references, compilation));
+ extraReturnValues.Add(
+ GetLuaValueExpression(variableName, parameterType, references, compilation)
+ );
index++;
continue;
}
- if (preloadedArguments != null && preloadedArguments.TryGetValue(luaArgumentIndex, out var preloadedArgumentName))
+ if (
+ preloadedArguments != null
+ && preloadedArguments.TryGetValue(luaArgumentIndex, out var preloadedArgumentName)
+ )
{
if (parameter.RefKind == RefKind.Ref)
{
callArguments.Add($"ref {preloadedArgumentName}");
- extraReturnValues.Add(GetLuaValueExpression(preloadedArgumentName, parameterType, references, compilation));
+ extraReturnValues.Add(
+ GetLuaValueExpression(
+ preloadedArgumentName,
+ parameterType,
+ references,
+ compilation
+ )
+ );
}
else
{
@@ -678,30 +1014,39 @@ static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata met
if (isParameterLuaValue)
{
- builder.AppendLine($"var {variableName} = context.HasArgument({luaArgumentIndex}) ? context.GetArgument({luaArgumentIndex}) : {syntax.Default!.Value.ToFullString()};");
+ builder.AppendLine(
+ $"var {variableName} = context.HasArgument({luaArgumentIndex}) ? context.GetArgument({luaArgumentIndex}) : {syntax.Default!.Value.ToFullString()};"
+ );
}
else
{
builder.AppendLine(
- $"var {variableName} = context.HasArgument({luaArgumentIndex}) ? context.GetArgument<{parameterTypeName}>({luaArgumentIndex}) : {syntax.Default!.Value.ToFullString()};");
+ $"var {variableName} = context.HasArgument({luaArgumentIndex}) ? context.GetArgument<{parameterTypeName}>({luaArgumentIndex}) : {syntax.Default!.Value.ToFullString()};"
+ );
}
}
else
{
if (isParameterLuaValue)
{
- builder.AppendLine($"var {variableName} = context.GetArgument({luaArgumentIndex});");
+ builder.AppendLine(
+ $"var {variableName} = context.GetArgument({luaArgumentIndex});"
+ );
}
else
{
- builder.AppendLine($"var {variableName} = context.GetArgument<{parameterTypeName}>({luaArgumentIndex});");
+ builder.AppendLine(
+ $"var {variableName} = context.GetArgument<{parameterTypeName}>({luaArgumentIndex});"
+ );
}
}
if (parameter.RefKind == RefKind.Ref)
{
callArguments.Add($"ref {variableName}");
- extraReturnValues.Add(GetLuaValueExpression(variableName, parameterType, references, compilation));
+ extraReturnValues.Add(
+ GetLuaValueExpression(variableName, parameterType, references, compilation)
+ );
}
else
{
@@ -724,7 +1069,10 @@ static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata met
if (methodMetadata.IsStatic)
{
- builder.Append($"{typeMetadata.FullTypeName}.{methodMetadata.Symbol.Name}(", !(methodMetadata.HasReturnValue || methodMetadata.IsAsync));
+ builder.Append(
+ $"{typeMetadata.FullTypeName}.{methodMetadata.Symbol.Name}(",
+ !(methodMetadata.HasReturnValue || methodMetadata.IsAsync)
+ );
builder.Append(string.Join(",", callArguments), false);
if (hasCancellationToken)
@@ -736,7 +1084,10 @@ static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata met
}
else
{
- builder.Append($"{userDataVariable}.{methodMetadata.Symbol.Name}(", !(methodMetadata.HasReturnValue || methodMetadata.IsAsync));
+ builder.Append(
+ $"{userDataVariable}.{methodMetadata.Symbol.Name}(",
+ !(methodMetadata.HasReturnValue || methodMetadata.IsAsync)
+ );
builder.Append(string.Join(",", callArguments), false);
if (hasCancellationToken)
@@ -760,7 +1111,9 @@ static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata met
}
}
- returnValueExpressions.Add(GetLuaValueExpression("result", returnType, references, compilation));
+ returnValueExpressions.Add(
+ GetLuaValueExpression("result", returnType, references, compilation)
+ );
}
returnValueExpressions.AddRange(extraReturnValues);
@@ -768,39 +1121,57 @@ static void EmitMethodFunctionBody(TypeMetadata typeMetadata, MethodMetadata met
switch (returnValueExpressions.Count)
{
case 0:
- builder.AppendLine(methodMetadata.IsAsync ? "return context.Return();" : "return new global::System.Threading.Tasks.ValueTask(context.Return());");
+ builder.AppendLine(
+ methodMetadata.IsAsync
+ ? "return context.Return();"
+ : "return new global::System.Threading.Tasks.ValueTask(context.Return());"
+ );
break;
case 1:
- builder.AppendLine(methodMetadata.IsAsync
- ? $"return context.Return({returnValueExpressions[0]});"
- : $"return new global::System.Threading.Tasks.ValueTask(context.Return({returnValueExpressions[0]}));");
+ builder.AppendLine(
+ methodMetadata.IsAsync
+ ? $"return context.Return({returnValueExpressions[0]});"
+ : $"return new global::System.Threading.Tasks.ValueTask(context.Return({returnValueExpressions[0]}));"
+ );
break;
case 2:
- builder.AppendLine(methodMetadata.IsAsync
- ? $"return context.Return({returnValueExpressions[0]}, {returnValueExpressions[1]});"
- : $"return new global::System.Threading.Tasks.ValueTask(context.Return({returnValueExpressions[0]}, {returnValueExpressions[1]}));");
+ builder.AppendLine(
+ methodMetadata.IsAsync
+ ? $"return context.Return({returnValueExpressions[0]}, {returnValueExpressions[1]});"
+ : $"return new global::System.Threading.Tasks.ValueTask(context.Return({returnValueExpressions[0]}, {returnValueExpressions[1]}));"
+ );
break;
case 3:
- builder.AppendLine(methodMetadata.IsAsync
- ? $"return context.Return({returnValueExpressions[0]}, {returnValueExpressions[1]}, {returnValueExpressions[2]});"
- : $"return new global::System.Threading.Tasks.ValueTask(context.Return({returnValueExpressions[0]}, {returnValueExpressions[1]}, {returnValueExpressions[2]}));");
+ builder.AppendLine(
+ methodMetadata.IsAsync
+ ? $"return context.Return({returnValueExpressions[0]}, {returnValueExpressions[1]}, {returnValueExpressions[2]});"
+ : $"return new global::System.Threading.Tasks.ValueTask(context.Return({returnValueExpressions[0]}, {returnValueExpressions[1]}, {returnValueExpressions[2]}));"
+ );
break;
default:
- builder.AppendLine($"var __returnValues = context.GetReturnBuffer({returnValueExpressions.Count});");
+ builder.AppendLine(
+ $"var __returnValues = context.GetReturnBuffer({returnValueExpressions.Count});"
+ );
for (var i = 0; i < returnValueExpressions.Count; i++)
{
builder.AppendLine($"__returnValues[{i}] = {returnValueExpressions[i]};");
}
- builder.AppendLine(methodMetadata.IsAsync
- ? $"return {returnValueExpressions.Count};"
- : $"return new global::System.Threading.Tasks.ValueTask({returnValueExpressions.Count});");
+ builder.AppendLine(
+ methodMetadata.IsAsync
+ ? $"return {returnValueExpressions.Count};"
+ : $"return new global::System.Threading.Tasks.ValueTask({returnValueExpressions.Count});"
+ );
break;
}
}
- static bool TryEmitMetatable(CodeBuilder builder, IEnumerable metamethods, in SourceProductionContext context)
+ static bool TryEmitMetatable(
+ CodeBuilder builder,
+ IEnumerable metamethods,
+ in SourceProductionContext context
+ )
{
builder.AppendLine("global::Lua.LuaTable? global::Lua.ILuaUserData.Metatable");
using (builder.BeginBlockScope())
@@ -821,7 +1192,9 @@ static bool TryEmitMetatable(CodeBuilder builder, IEnumerable
{
- return node is ClassDeclarationSyntax
- or RecordDeclarationSyntax;
+ return node is ClassDeclarationSyntax or RecordDeclarationSyntax;
},
- static (context, cancellation) => { return context; })
+ static (context, cancellation) =>
+ {
+ return context;
+ }
+ )
.Combine(context.CompilationProvider)
.WithComparer(Comparer.Instance);
@@ -26,16 +29,23 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
{
var (compilation, list) = t;
var references = SymbolReferences.Create(compilation);
- if (references == null) return;
+ if (references == null)
+ return;
var builder = new CodeBuilder();
- var metaDict = new Dictionary(SymbolEqualityComparer.Default);
+ var metaDict = new Dictionary(
+ SymbolEqualityComparer.Default
+ );
foreach (var (x, _) in list)
{
var symbol = (INamedTypeSymbol)x.TargetSymbol;
- var typeMeta = new TypeMetadata((TypeDeclarationSyntax)x.TargetNode, symbol, references);
+ var typeMeta = new TypeMetadata(
+ (TypeDeclarationSyntax)x.TargetNode,
+ symbol,
+ references
+ );
metaDict.Add(symbol, typeMeta);
}
@@ -43,19 +53,33 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
foreach (var pair in metaDict)
{
var typeMeta = pair.Value;
- if (TryEmit(typeMeta, builder, references, compilation, in sourceProductionContext, metaDict, tempCollections))
+ if (
+ TryEmit(
+ typeMeta,
+ builder,
+ references,
+ compilation,
+ in sourceProductionContext,
+ metaDict,
+ tempCollections
+ )
+ )
{
- var fullType = typeMeta.FullTypeName
- .Replace("global::", "")
+ var fullType = typeMeta
+ .FullTypeName.Replace("global::", "")
.Replace("<", "_")
.Replace(">", "_");
- sourceProductionContext.AddSource($"{fullType}.LuaObject.g.cs", builder.ToString());
+ sourceProductionContext.AddSource(
+ $"{fullType}.LuaObject.g.cs",
+ builder.ToString()
+ );
}
tempCollections.Clear();
builder.Clear();
}
- });
+ }
+ );
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/LuaObjectMetamethod.cs b/src/Lua.SourceGenerator/LuaObjectMetamethod.cs
index 98fa5571..7923c3a6 100644
--- a/src/Lua.SourceGenerator/LuaObjectMetamethod.cs
+++ b/src/Lua.SourceGenerator/LuaObjectMetamethod.cs
@@ -22,4 +22,4 @@ enum LuaObjectMetamethod
ToString,
Index,
NewIndex,
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/MethodMetadata.cs b/src/Lua.SourceGenerator/MethodMetadata.cs
index 68626275..10329d97 100644
--- a/src/Lua.SourceGenerator/MethodMetadata.cs
+++ b/src/Lua.SourceGenerator/MethodMetadata.cs
@@ -19,13 +19,22 @@ public MethodMetadata(IMethodSymbol symbol, SymbolReferences references)
IsStatic = symbol.IsStatic;
var returnType = symbol.ReturnType;
- var fullName = (returnType.ContainingNamespace.IsGlobalNamespace ? "" : returnType.ContainingNamespace + ".") + returnType.Name;
- IsAsync = fullName is "System.Threading.Tasks.Task"
- or "System.Threading.Tasks.ValueTask"
- or "Cysharp.Threading.Tasks.UniTask"
- or "UnityEngine.Awaitable";
+ var fullName =
+ (
+ returnType.ContainingNamespace.IsGlobalNamespace
+ ? ""
+ : returnType.ContainingNamespace + "."
+ ) + returnType.Name;
+ IsAsync =
+ fullName
+ is "System.Threading.Tasks.Task"
+ or "System.Threading.Tasks.ValueTask"
+ or "Cysharp.Threading.Tasks.UniTask"
+ or "UnityEngine.Awaitable";
- HasReturnValue = !symbol.ReturnsVoid && !(IsAsync && returnType is INamedTypeSymbol n && !n.IsGenericType);
+ HasReturnValue =
+ !symbol.ReturnsVoid
+ && !(IsAsync && returnType is INamedTypeSymbol n && !n.IsGenericType);
LuaMemberName = symbol.Name;
@@ -49,7 +58,11 @@ public MethodMetadata(IMethodSymbol symbol, SymbolReferences references)
if (metamethodAttribute != null)
{
- Metamethod = (LuaObjectMetamethod)Enum.Parse(typeof(LuaObjectMetamethod), metamethodAttribute.ConstructorArguments[0].Value!.ToString());
+ Metamethod = (LuaObjectMetamethod)
+ Enum.Parse(
+ typeof(LuaObjectMetamethod),
+ metamethodAttribute.ConstructorArguments[0].Value!.ToString()
+ );
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/PropertyMetadata.cs b/src/Lua.SourceGenerator/PropertyMetadata.cs
index f0eeefcf..0b152bfd 100644
--- a/src/Lua.SourceGenerator/PropertyMetadata.cs
+++ b/src/Lua.SourceGenerator/PropertyMetadata.cs
@@ -28,7 +28,8 @@ public PropertyMetadata(ISymbol symbol, SymbolReferences references)
{
Type = property.Type;
TypeFullName = property.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
- IsReadOnly = property.IsReadOnly || property.SetMethod == null || property.SetMethod.IsInitOnly;
+ IsReadOnly =
+ property.IsReadOnly || property.SetMethod == null || property.SetMethod.IsInitOnly;
IsWriteOnly = property.IsWriteOnly;
}
else
@@ -52,4 +53,4 @@ public PropertyMetadata(ISymbol symbol, SymbolReferences references)
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/SymbolReferences.cs b/src/Lua.SourceGenerator/SymbolReferences.cs
index ea15a068..946f58bf 100644
--- a/src/Lua.SourceGenerator/SymbolReferences.cs
+++ b/src/Lua.SourceGenerator/SymbolReferences.cs
@@ -16,8 +16,12 @@ public sealed class SymbolReferences
{
LuaObjectAttribute = luaObjectAttribute,
LuaMemberAttribute = compilation.GetTypeByMetadataName("Lua.LuaMemberAttribute")!,
- LuaIgnoreMemberAttribute = compilation.GetTypeByMetadataName("Lua.LuaIgnoreMemberAttribute")!,
- LuaMetamethodAttribute = compilation.GetTypeByMetadataName("Lua.LuaMetamethodAttribute")!,
+ LuaIgnoreMemberAttribute = compilation.GetTypeByMetadataName(
+ "Lua.LuaIgnoreMemberAttribute"
+ )!,
+ LuaMetamethodAttribute = compilation.GetTypeByMetadataName(
+ "Lua.LuaMetamethodAttribute"
+ )!,
LuaValue = compilation.GetTypeByMetadataName("Lua.LuaValue")!,
Object = compilation.GetTypeByMetadataName("System.Object")!,
Boolean = compilation.GetTypeByMetadataName("System.Boolean")!,
@@ -27,7 +31,9 @@ public sealed class SymbolReferences
LuaThread = compilation.GetTypeByMetadataName("Lua.LuaThread")!,
LuaTable = compilation.GetTypeByMetadataName("Lua.LuaTable")!,
LuaUserData = compilation.GetTypeByMetadataName("Lua.ILuaUserData")!,
- CancellationToken = compilation.GetTypeByMetadataName("System.Threading.CancellationToken")!
+ CancellationToken = compilation.GetTypeByMetadataName(
+ "System.Threading.CancellationToken"
+ )!,
};
}
@@ -45,4 +51,4 @@ public sealed class SymbolReferences
public INamedTypeSymbol LuaTable { get; private set; } = null!;
public INamedTypeSymbol LuaUserData { get; private set; } = null!;
public INamedTypeSymbol CancellationToken { get; private set; } = null!;
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/TempCollections.cs b/src/Lua.SourceGenerator/TempCollections.cs
index d0c65e96..4e0453ad 100644
--- a/src/Lua.SourceGenerator/TempCollections.cs
+++ b/src/Lua.SourceGenerator/TempCollections.cs
@@ -4,9 +4,10 @@ class TempCollections
{
public readonly HashSet Metamethods = new();
public readonly List InvalidMemberNames = new();
+
public void Clear()
{
Metamethods.Clear();
InvalidMemberNames.Clear();
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/TypeMetadata.cs b/src/Lua.SourceGenerator/TypeMetadata.cs
index 82dd5829..6ed9cc67 100644
--- a/src/Lua.SourceGenerator/TypeMetadata.cs
+++ b/src/Lua.SourceGenerator/TypeMetadata.cs
@@ -13,7 +13,11 @@ class TypeMetadata
public PropertyMetadata[] Properties { get; }
public MethodMetadata[] Methods { get; }
- public TypeMetadata(TypeDeclarationSyntax syntax, INamedTypeSymbol symbol, SymbolReferences references)
+ public TypeMetadata(
+ TypeDeclarationSyntax syntax,
+ INamedTypeSymbol symbol,
+ SymbolReferences references
+ )
{
Syntax = syntax;
Symbol = symbol;
@@ -21,7 +25,8 @@ public TypeMetadata(TypeDeclarationSyntax syntax, INamedTypeSymbol symbol, Symbo
TypeName = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
FullTypeName = symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
- Properties = Symbol.GetAllMembers(false)
+ Properties = Symbol
+ .GetAllMembers(false)
.Where(x => x is (IFieldSymbol or IPropertySymbol) and { IsImplicitlyDeclared: false })
.Where(x =>
{
@@ -48,7 +53,8 @@ public TypeMetadata(TypeDeclarationSyntax syntax, INamedTypeSymbol symbol, Symbo
.Select(x => new PropertyMetadata(x, references))
.ToArray();
- Methods = Symbol.GetAllMembers(false)
+ Methods = Symbol
+ .GetAllMembers(false)
.Where(x => x is IMethodSymbol and { IsImplicitlyDeclared: false })
.Select(x => (IMethodSymbol)x)
.Where(x =>
@@ -58,7 +64,8 @@ public TypeMetadata(TypeDeclarationSyntax syntax, INamedTypeSymbol symbol, Symbo
return false;
}
- return x.ContainsAttribute(references.LuaMemberAttribute) || x.ContainsAttribute(references.LuaMetamethodAttribute);
+ return x.ContainsAttribute(references.LuaMemberAttribute)
+ || x.ContainsAttribute(references.LuaMetamethodAttribute);
})
.Select(x => new MethodMetadata(x, references))
.ToArray();
@@ -73,4 +80,4 @@ public bool IsNested()
{
return Syntax.Parent is TypeDeclarationSyntax;
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/Utilities/CodeBuilder.cs b/src/Lua.SourceGenerator/Utilities/CodeBuilder.cs
index 4bd3eacd..17ba6925 100644
--- a/src/Lua.SourceGenerator/Utilities/CodeBuilder.cs
+++ b/src/Lua.SourceGenerator/Utilities/CodeBuilder.cs
@@ -139,4 +139,4 @@ public void Clear()
{
buffer.Clear();
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/Utilities/RoslynAnalyzerExtensions.cs b/src/Lua.SourceGenerator/Utilities/RoslynAnalyzerExtensions.cs
index 6b0d8e24..f187eba4 100644
--- a/src/Lua.SourceGenerator/Utilities/RoslynAnalyzerExtensions.cs
+++ b/src/Lua.SourceGenerator/Utilities/RoslynAnalyzerExtensions.cs
@@ -4,15 +4,21 @@ namespace Lua.SourceGenerator;
static class RoslynAnalyzerExtensions
{
- public static AttributeData? FindAttribute(this IEnumerable attributeDataList, string typeName)
+ public static AttributeData? FindAttribute(
+ this IEnumerable attributeDataList,
+ string typeName
+ )
{
- return attributeDataList
- .FirstOrDefault(x => x.AttributeClass?.ToDisplayString() == typeName);
+ return attributeDataList.FirstOrDefault(x =>
+ x.AttributeClass?.ToDisplayString() == typeName
+ );
}
- public static AttributeData? FindAttributeShortName(this IEnumerable attributeDataList, string typeName)
+ public static AttributeData? FindAttributeShortName(
+ this IEnumerable attributeDataList,
+ string typeName
+ )
{
- return attributeDataList
- .FirstOrDefault(x => x.AttributeClass?.Name == typeName);
+ return attributeDataList.FirstOrDefault(x => x.AttributeClass?.Name == typeName);
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.SourceGenerator/Utilities/SymbolExtensions.cs b/src/Lua.SourceGenerator/Utilities/SymbolExtensions.cs
index 5c3de88c..555220d7 100644
--- a/src/Lua.SourceGenerator/Utilities/SymbolExtensions.cs
+++ b/src/Lua.SourceGenerator/Utilities/SymbolExtensions.cs
@@ -6,15 +6,24 @@ static class SymbolExtensions
{
public static bool ContainsAttribute(this ISymbol symbol, INamedTypeSymbol attribtue)
{
- return symbol.GetAttributes().Any(x => SymbolEqualityComparer.Default.Equals(x.AttributeClass, attribtue));
+ return symbol
+ .GetAttributes()
+ .Any(x => SymbolEqualityComparer.Default.Equals(x.AttributeClass, attribtue));
}
public static AttributeData? GetAttribute(this ISymbol symbol, INamedTypeSymbol attribtue)
{
- return symbol.GetAttributes().FirstOrDefault(x => SymbolEqualityComparer.Default.Equals(x.AttributeClass, attribtue));
+ return symbol
+ .GetAttributes()
+ .FirstOrDefault(x =>
+ SymbolEqualityComparer.Default.Equals(x.AttributeClass, attribtue)
+ );
}
- public static IEnumerable GetAllMembers(this INamedTypeSymbol symbol, bool withoutOverride = true)
+ public static IEnumerable GetAllMembers(
+ this INamedTypeSymbol symbol,
+ bool withoutOverride = true
+ )
{
// Iterate Parent -> Derived
if (symbol.BaseType != null)
@@ -37,4 +46,4 @@ public static IEnumerable GetAllMembers(this INamedTypeSymbol symbol, b
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaAssetEditor.cs b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaAssetEditor.cs
index 5a2bffb5..37fae54d 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaAssetEditor.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaAssetEditor.cs
@@ -9,7 +9,8 @@ public sealed class LuaAssetEditor : UnityEditor.Editor
public override void OnInspectorGUI()
{
- if (textProperty == null) textProperty = serializedObject.FindProperty("text");
+ if (textProperty == null)
+ textProperty = serializedObject.FindProperty("text");
using (new EditorGUI.IndentLevelScope(-1))
{
@@ -17,4 +18,4 @@ public override void OnInspectorGUI()
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaImporter.cs b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaImporter.cs
index 490b9a13..6ec59b57 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaImporter.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuaImporter.cs
@@ -16,4 +16,4 @@ public override void OnImportAsset(AssetImportContext ctx)
ctx.SetMainObject(asset);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs
index 72b2f48c..5b81fddc 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacAssetEditor.cs
@@ -1,8 +1,8 @@
-using Lua.CodeAnalysis.Compilation;
-using Lua.Runtime;
-using System;
+using System;
using System.Text;
using System.Text.RegularExpressions;
+using Lua.CodeAnalysis.Compilation;
+using Lua.Runtime;
using UnityEditor;
namespace Lua.Unity.Editor
@@ -17,7 +17,8 @@ public sealed class LuacAssetEditor : UnityEditor.Editor
public override void OnInspectorGUI()
{
- if (asset == null) asset = (LuacAsset)serializedObject.targetObject;
+ if (asset == null)
+ asset = (LuacAsset)serializedObject.targetObject;
if (bytes == null || !asset.bytes.AsSpan().SequenceEqual(bytes))
{
var prototype = Prototype.FromBytecode(asset.bytes.AsSpan(), asset.name);
@@ -49,7 +50,8 @@ void AppendLine(string line)
if (nestCount == 0)
AppendLine($"Chunk :{chunk.ChunkName}");
- else AppendLine("[" + nestCount + "," + id + "]");
+ else
+ AppendLine("[" + nestCount + "," + id + "]");
AppendLine($"Parameters:{chunk.ParameterCount}");
AppendLine("Code -------------------------------------");
@@ -80,7 +82,9 @@ void AppendLine(string line)
index = 0;
foreach (var upValue in chunk.UpValues.ToArray())
{
- AppendLine($"[{index}]\t{upValue.Name}\t{(upValue.IsLocal ? 1 : 0)}\t{upValue.Index}");
+ AppendLine(
+ $"[{index}]\t{upValue.Name}\t{(upValue.IsLocal ? 1 : 0)}\t{upValue.Index}"
+ );
index++;
}
@@ -95,4 +99,4 @@ void AppendLine(string line)
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs
index 91cb3534..04402100 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Editor/LuacImporter.cs
@@ -10,6 +10,7 @@ namespace Lua.Unity.Editor
public sealed class LuacImporter : ScriptedImporter
{
static Texture2D icon;
+
public override void OnImportAsset(AssetImportContext ctx)
{
var bytes = File.ReadAllBytes(ctx.assetPath);
@@ -23,10 +24,10 @@ public override void OnImportAsset(AssetImportContext ctx)
icon = EditorGUIUtility.IconContent("ScriptableObject Icon").image as Texture2D;
}
}
- EditorGUIUtility.SetIconForObject (asset,icon );
+ EditorGUIUtility.SetIconForObject(asset, icon);
asset.bytes = bytes;
ctx.AddObjectToAsset("Main", asset);
ctx.SetMainObject(asset);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/AddressablesModuleLoader.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/AddressablesModuleLoader.cs
index e1f9aeda..8147e36d 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/AddressablesModuleLoader.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/AddressablesModuleLoader.cs
@@ -16,18 +16,21 @@ public sealed class AddressablesModuleLoader : ILuaModuleLoader
public bool Exists(string moduleName)
{
- if (cache.TryGetValue(moduleName, out _)) return true;
+ if (cache.TryGetValue(moduleName, out _))
+ return true;
var location = Addressables.LoadResourceLocationsAsync(moduleName).WaitForCompletion();
return location.Any();
}
- public async ValueTask LoadAsync(string moduleName, CancellationToken cancellationToken = default)
+ public async ValueTask LoadAsync(
+ string moduleName,
+ CancellationToken cancellationToken = default
+ )
{
if (cache.TryGetValue(moduleName, out var asset))
{
-
- return asset .GetModule( moduleName);
+ return asset.GetModule(moduleName);
}
var asyncOperation = Addressables.LoadAssetAsync(moduleName);
@@ -39,12 +42,15 @@ public async ValueTask LoadAsync(string moduleName, CancellationToken
}
cache.Add(moduleName, asset);
- return asset .GetModule( moduleName);
+ return asset.GetModule(moduleName);
}
}
+
internal static class AsyncOperationHandleExtensions
{
- public static AsyncOperationHandleAwaiter GetAwaiter(this AsyncOperationHandle asyncOperationHandle)
+ public static AsyncOperationHandleAwaiter GetAwaiter(
+ this AsyncOperationHandle asyncOperationHandle
+ )
{
return new AsyncOperationHandleAwaiter(asyncOperationHandle);
}
@@ -82,4 +88,4 @@ public AsyncOperationHandleAwaiter GetAwaiter()
}
}
}
-#endif
\ No newline at end of file
+#endif
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/AssemblyInfo.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/AssemblyInfo.cs
index e527f390..ffbcc2e3 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/AssemblyInfo.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/AssemblyInfo.cs
@@ -1,3 +1,3 @@
using System.Runtime.CompilerServices;
-[assembly: InternalsVisibleTo("Lua.Unity.Editor")]
\ No newline at end of file
+[assembly: InternalsVisibleTo("Lua.Unity.Editor")]
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAsset.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAsset.cs
index f370e397..b63c5129 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAsset.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAsset.cs
@@ -1,5 +1,4 @@
using UnityEngine;
-
#if UNITY_EDITOR
using UnityEditor;
#endif
@@ -8,17 +7,18 @@ namespace Lua.Unity
{
public sealed class LuaAsset : LuaAssetBase
{
- [SerializeField] internal string text;
+ [SerializeField]
+ internal string text;
public string Text => text;
public override LuaModule GetModule(string searchedName)
{
#if UNITY_EDITOR
- var moduleName = "@"+AssetDatabase.GetAssetPath(this);
+ var moduleName = "@" + AssetDatabase.GetAssetPath(this);
#else
- var moduleName = $"@{searchedName}.lua";
+ var moduleName = $"@{searchedName}.lua";
#endif
return new LuaModule(moduleName, text);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs
index 540835e5..4aaf675f 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaAssetBase.cs
@@ -2,9 +2,8 @@
namespace Lua.Unity
{
-
public abstract class LuaAssetBase : ScriptableObject
{
public abstract LuaModule GetModule(string searchedName);
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaThreadAssetExtensions.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaThreadAssetExtensions.cs
index 39fe47e1..5003d6fb 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaThreadAssetExtensions.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuaThreadAssetExtensions.cs
@@ -1,14 +1,19 @@
-using Lua.Runtime;
-using System;
+using System;
using System.Threading;
using System.Threading.Tasks;
+using Lua.Runtime;
namespace Lua.Unity
{
public static class LuaThreadAssetExtensions
{
-
- public static ValueTask ExecuteAsync(this LuaState state, LuaAssetBase luaAssetBase, string name, Memory buffer, CancellationToken cancellationToken = default)
+ public static ValueTask ExecuteAsync(
+ this LuaState state,
+ LuaAssetBase luaAssetBase,
+ string name,
+ Memory buffer,
+ CancellationToken cancellationToken = default
+ )
{
if (luaAssetBase == null)
{
@@ -16,15 +21,21 @@ public static ValueTask ExecuteAsync(this LuaState state, LuaAssetBase luaA
}
var module = luaAssetBase.GetModule(name);
- var closure = module.Type == LuaModuleType.Bytes
- ? state.Load(module.ReadBytes(), module.Name)
- : state.Load(module.ReadText(), module.Name);
+ var closure =
+ module.Type == LuaModuleType.Bytes
+ ? state.Load(module.ReadBytes(), module.Name)
+ : state.Load(module.ReadText(), module.Name);
return state.ExecuteAsync(closure, buffer, cancellationToken);
}
- public static ValueTask ExecuteAsync(this LuaState state, LuaAssetBase luaAssetBase, string name, CancellationToken cancellationToken = default)
+ public static ValueTask ExecuteAsync(
+ this LuaState state,
+ LuaAssetBase luaAssetBase,
+ string name,
+ CancellationToken cancellationToken = default
+ )
{
return state.ExecuteAsync(luaAssetBase, name, cancellationToken);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuacAsset.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuacAsset.cs
index 766edb2e..a9797b3c 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuacAsset.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/LuacAsset.cs
@@ -5,11 +5,13 @@ namespace Lua.Unity
public sealed class LuacAsset : LuaAssetBase
{
[HideInInspector]
- [SerializeField] internal byte[] bytes;
+ [SerializeField]
+ internal byte[] bytes;
public byte[] Bytes => bytes;
+
public override LuaModule GetModule(string searchedName)
{
- return new LuaModule(searchedName,bytes);
+ return new LuaModule(searchedName, bytes);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/ResourcesModuleLoader.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/ResourcesModuleLoader.cs
index 2f12fb2c..41b8a044 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/ResourcesModuleLoader.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/ResourcesModuleLoader.cs
@@ -4,6 +4,7 @@
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
+
namespace Lua.Unity
{
public sealed class ResourcesModuleLoader : ILuaModuleLoader
@@ -13,16 +14,21 @@ public sealed class ResourcesModuleLoader : ILuaModuleLoader
public bool Exists(string moduleName)
{
Debug.Log(moduleName);
- if (cache.TryGetValue(moduleName, out _)) return true;
+ if (cache.TryGetValue(moduleName, out _))
+ return true;
var asset = Resources.Load(moduleName);
- if (asset == null) return false;
+ if (asset == null)
+ return false;
cache.Add(moduleName, asset);
return true;
}
- public async ValueTask LoadAsync(string moduleName, CancellationToken cancellationToken = default)
+ public async ValueTask LoadAsync(
+ string moduleName,
+ CancellationToken cancellationToken = default
+ )
{
if (cache.TryGetValue(moduleName, out var asset))
{
@@ -39,7 +45,8 @@ public async ValueTask LoadAsync(string moduleName, CancellationToken
asset = (LuaAssetBase)request.asset;
cache.Add(moduleName, asset);
- return asset.GetModule(moduleName); }
+ return asset.GetModule(moduleName);
+ }
}
#if !UNITY_2023_1_OR_NEWER
@@ -70,10 +77,8 @@ public void UnsafeOnCompleted(Action continuation)
{
request.completed += x => continuation.Invoke();
}
-
- public void GetResult()
- {
- }
+
+ public void GetResult() { }
public ResourceRequestAwaiter GetAwaiter()
{
@@ -82,4 +87,4 @@ public ResourceRequestAwaiter GetAwaiter()
}
}
#endif
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs
index d3358752..bb7efe1d 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityApplicationOsEnvironment.cs
@@ -1,21 +1,23 @@
-using Lua.Platforms;
-using System;
+using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
+using Lua.Platforms;
using UnityEngine;
namespace Lua.Unity
{
public class UnityApplicationOsEnvironment : ILuaOsEnvironment
{
- public UnityApplicationOsEnvironment(Dictionary environmentVariables = null,bool allowToQuitOnExitCall = false)
+ public UnityApplicationOsEnvironment(
+ Dictionary environmentVariables = null,
+ bool allowToQuitOnExitCall = false
+ )
{
EnvironmentVariables = environmentVariables ?? new Dictionary();
AllowToQuitOnExitCall = allowToQuitOnExitCall;
}
-
public bool AllowToQuitOnExitCall { get; }
public Dictionary EnvironmentVariables { get; }
@@ -39,10 +41,12 @@ public ValueTask Exit(int exitCode, CancellationToken cancellationToken)
else
{
// If quitting is not allowed, we can just throw an exception or log a message.
- throw new InvalidOperationException("Application exit is not allowed in this environment.");
+ throw new InvalidOperationException(
+ "Application exit is not allowed in this environment."
+ );
}
}
public double GetTotalProcessorTime() => Time.time;
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs
index 52eb3b86..0c3a4b98 100644
--- a/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs
+++ b/src/Lua.Unity/Assets/Lua.Unity/Runtime/UnityStandardIO.cs
@@ -1,8 +1,8 @@
-using Lua.IO;
-using System;
+using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using Lua.IO;
namespace Lua.Unity
{
@@ -46,7 +46,10 @@ public DebugLogStream(bool isError = false)
private readonly StringBuilder stringBuilder = new();
- ValueTask ILuaStream.WriteAsync(ReadOnlyMemory content, CancellationToken cancellationToken)
+ ValueTask ILuaStream.WriteAsync(
+ ReadOnlyMemory content,
+ CancellationToken cancellationToken
+ )
{
stringBuilder.Append(content.Span);
return default;
@@ -74,4 +77,4 @@ public ValueTask Close(CancellationToken cancellationToken)
public void Dispose() { }
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Assets/Sandbox/Sandbox.cs b/src/Lua.Unity/Assets/Sandbox/Sandbox.cs
index da8a3bfb..a454dd19 100644
--- a/src/Lua.Unity/Assets/Sandbox/Sandbox.cs
+++ b/src/Lua.Unity/Assets/Sandbox/Sandbox.cs
@@ -1,37 +1,44 @@
using System;
+using System.Collections.Generic;
+using System.Linq;
using Lua;
using Lua.IO;
using Lua.Loaders;
using Lua.Platforms;
using Lua.Standard;
using Lua.Unity;
-using System.Collections.Generic;
-using System.Linq;
using UnityEngine;
public class Sandbox : MonoBehaviour
{
async void Start()
{
-
- var state = LuaState.Create( new LuaPlatform(
- FileSystem: new FileSystem(Application.streamingAssetsPath),
- OsEnvironment: new UnityApplicationOsEnvironment(),
- StandardIO: new UnityStandardIO(),
- TimeProvider: TimeProvider.System
- ));
- state.ModuleLoader = CompositeModuleLoader.Create(new AddressablesModuleLoader(), new ResourcesModuleLoader());
+ var state = LuaState.Create(
+ new LuaPlatform(
+ FileSystem: new FileSystem(Application.streamingAssetsPath),
+ OsEnvironment: new UnityApplicationOsEnvironment(),
+ StandardIO: new UnityStandardIO(),
+ TimeProvider: TimeProvider.System
+ )
+ );
+ state.ModuleLoader = CompositeModuleLoader.Create(
+ new AddressablesModuleLoader(),
+ new ResourcesModuleLoader()
+ );
state.OpenStandardLibraries();
- state.Environment["print"] = new LuaFunction("print", (context, ct) =>
- {
- Debug.Log(context.GetArgument(0));
- return new(0);
- });
+ state.Environment["print"] = new LuaFunction(
+ "print",
+ (context, ct) =>
+ {
+ Debug.Log(context.GetArgument(0));
+ return new(0);
+ }
+ );
try
{
await state.DoStringAsync(
- @"
+ @"
print('test start')
local foo = require 'foo'
foo.greet()
@@ -41,34 +48,36 @@ await state.DoStringAsync(
local s =require 'streaming'
s.f()
-", cancellationToken: destroyCancellationToken);
+",
+ cancellationToken: destroyCancellationToken
+ );
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
-
- MeshTopology[ ] topologies = Enum.GetValues(typeof(MeshTopology)) as MeshTopology[];
+
+ MeshTopology[] topologies = Enum.GetValues(typeof(MeshTopology)) as MeshTopology[];
public bool ContainsTriangle;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
- ContainsTriangle=(topologies.Contains( MeshTopology.Points));
-
+ ContainsTriangle = (topologies.Contains(MeshTopology.Points));
+
Debug.Break();
}
-
+
if (Input.GetKeyDown(KeyCode.A))
{
- ContainsTriangle=(ContainsInArray(topologies, MeshTopology.Points));
-
+ ContainsTriangle = (ContainsInArray(topologies, MeshTopology.Points));
+
Debug.Break();
}
}
-
+
bool ContainsInArray(T[] array, T value)
{
foreach (var item in array)
@@ -80,4 +89,4 @@ bool ContainsInArray(T[] array, T value)
}
return false;
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/System.Runtime.CompilerServices.Unsafe.6.0.0/buildTransitive/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.targets b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/System.Runtime.CompilerServices.Unsafe.6.0.0/buildTransitive/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.targets
index 3a582dff..0c582db5 100644
--- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/System.Runtime.CompilerServices.Unsafe.6.0.0/buildTransitive/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.targets
+++ b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/System.Runtime.CompilerServices.Unsafe.6.0.0/buildTransitive/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.targets
@@ -1,6 +1,8 @@
-
+
diff --git a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/System.Runtime.CompilerServices.Unsafe.6.0.0/lib/netstandard2.0/System.Runtime.CompilerServices.Unsafe.xml b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/System.Runtime.CompilerServices.Unsafe.6.0.0/lib/netstandard2.0/System.Runtime.CompilerServices.Unsafe.xml
index de129b80..0bb8f483 100644
--- a/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/System.Runtime.CompilerServices.Unsafe.6.0.0/lib/netstandard2.0/System.Runtime.CompilerServices.Unsafe.xml
+++ b/src/Lua.Unity/Packages/nuget-packages/InstalledPackages/System.Runtime.CompilerServices.Unsafe.6.0.0/lib/netstandard2.0/System.Runtime.CompilerServices.Unsafe.xml
@@ -55,7 +55,8 @@
The second reference to compare.
The type of reference.
- if and point to the same location; otherwise, .
+ if and point to the same location; otherwise, .
Casts the given object to the specified type.
@@ -64,7 +65,9 @@
The original object, casted to the given type.
- Reinterprets the given reference as a reference to a value of type .
+ Reinterprets the given reference as a reference to a value of type .
The reference to reinterpret.
The type of reference to reinterpret.
The desired type of the reference.
@@ -83,7 +86,9 @@
A reference to a value of type .
- Reinterprets the given location as a reference to a value of type .
+ Reinterprets the given location as a reference to a value of type .
The location of the value to reference.
The type of the interpreted location.
A reference to a value of type .
@@ -93,7 +98,9 @@
The reference to origin.
The reference to target.
The type of reference.
- Byte offset from origin to target i.e. - .
+ Byte offset from origin to target i.e. - .
Copies a value of type to the given location.
@@ -161,7 +168,8 @@
The second value to compare.
The type of the reference.
- if is greater than ; otherwise, .
+ if is greater than ; otherwise, .
Returns a value that indicates whether a specified reference is less than another specified reference.
@@ -169,19 +177,27 @@
The second value to compare.
The type of the reference.
- if is less than ; otherwise, .
+ if is less than ; otherwise, .
- Determines if a given reference to a value of type is a null reference.
+ Determines if a given reference to a value of type is a null reference.
The reference to check.
The type of the reference.
- if is a null reference; otherwise, .
+ if is a null reference; otherwise, .
- Returns a reference to a value of type that is a null reference.
+ Returns a reference to a value of type that is a null reference.
The type of the reference.
- A reference to a value of type that is a null reference.
+ A reference to a value of type that is a null reference.
Reads a value of type from the given location.
@@ -190,13 +206,17 @@
An object of type read from the given location.
- Reads a value of type from the given location without assuming architecture dependent alignment of the addresses.
+ Reads a value of type from the given location without assuming architecture dependent alignment of the addresses.
The location to read from.
The type to read.
An object of type read from the given location.
- Reads a value of type from the given location without assuming architecture dependent alignment of the addresses.
+ Reads a value of type from the given location without assuming architecture dependent alignment of the addresses.
The location to read from.
The type to read.
An object of type read from the given location.
@@ -258,16 +278,21 @@
The value to unbox.
The type to be unboxed.
- is , and is a non-nullable value type.
+ is , and is a non-nullable value type.
is not a boxed value type.
-or-
- is not a boxed .
+ is not a boxed .
- cannot be found.
- A to the boxed value .
+ cannot be found.
+ A to the boxed value .
Writes a value of type to the given location.
@@ -276,16 +301,20 @@
The type of value to write.
- Writes a value of type to the given location without assuming architecture dependent alignment of the addresses.
+ Writes a value of type to the given location without assuming architecture dependent alignment of the addresses.
The location to write to.
The value to write.
The type of value to write.
- Writes a value of type to the given location without assuming architecture dependent alignment of the addresses.
+ Writes a value of type to the given location without assuming architecture dependent alignment of the addresses.
The location to write to.
The value to write.
The type of value to write.
-
\ No newline at end of file
+
diff --git a/src/Lua.Unity/Packages/nuget-packages/NuGet.config b/src/Lua.Unity/Packages/nuget-packages/NuGet.config
index d968e9a8..20b4824f 100644
--- a/src/Lua.Unity/Packages/nuget-packages/NuGet.config
+++ b/src/Lua.Unity/Packages/nuget-packages/NuGet.config
@@ -15,4 +15,4 @@
-
\ No newline at end of file
+
diff --git a/src/Lua.Unity/Packages/nuget-packages/packages.config b/src/Lua.Unity/Packages/nuget-packages/packages.config
index 40a17ddf..f47ec313 100644
--- a/src/Lua.Unity/Packages/nuget-packages/packages.config
+++ b/src/Lua.Unity/Packages/nuget-packages/packages.config
@@ -3,4 +3,4 @@
-
\ No newline at end of file
+
diff --git a/src/Lua/CodeAnalysis/Compilation/BomUtility.cs b/src/Lua/CodeAnalysis/Compilation/BomUtility.cs
index bac21c6f..074c1caa 100644
--- a/src/Lua/CodeAnalysis/Compilation/BomUtility.cs
+++ b/src/Lua/CodeAnalysis/Compilation/BomUtility.cs
@@ -20,7 +20,10 @@ static class BomUtility
/// The text to check for BOM.
/// The encoding of the text.
/// The text without the BOM.
- public static ReadOnlySpan GetEncodingFromBytes(ReadOnlySpan text, out Encoding encoding)
+ public static ReadOnlySpan GetEncodingFromBytes(
+ ReadOnlySpan text,
+ out Encoding encoding
+ )
{
if (text.StartsWith(BomUtf8))
{
@@ -49,4 +52,4 @@ public static ReadOnlySpan GetEncodingFromBytes(ReadOnlySpan text, o
encoding = Encoding.UTF8;
return text;
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua/CodeAnalysis/Compilation/Declarements.cs b/src/Lua/CodeAnalysis/Compilation/Declarements.cs
index b72a9064..6db6dd16 100644
--- a/src/Lua/CodeAnalysis/Compilation/Declarements.cs
+++ b/src/Lua/CodeAnalysis/Compilation/Declarements.cs
@@ -1,5 +1,5 @@
-using Lua.Internal;
-using System.Runtime.CompilerServices;
+using System.Runtime.CompilerServices;
+using Lua.Internal;
namespace Lua.CodeAnalysis.Compilation;
@@ -40,23 +40,34 @@ unsafe struct AssignmentTarget(ref AssignmentTarget previous, ExprDesc exprDesc)
struct Label
{
public string Name;
- public int Pc, Line;
+ public int Pc,
+ Line;
public int ActiveVariableCount;
}
class Block : IPoolNode
{
public Block? Previous;
- public int FirstLabel, FirstGoto;
+ public int FirstLabel,
+ FirstGoto;
public int ActiveVariableCount;
- public bool HasUpValue, IsLoop;
+ public bool HasUpValue,
+ IsLoop;
+
Block() { }
ref Block? IPoolNode.NextNode => ref Previous;
static LinkedPool Pool;
- public static Block Get(Block? previous, int firstLabel, int firstGoto, int activeVariableCount, bool hasUpValue, bool isLoop)
+ public static Block Get(
+ Block? previous,
+ int firstLabel,
+ int firstGoto,
+ int activeVariableCount,
+ bool hasUpValue,
+ bool isLoop
+ )
{
if (!Pool.TryPop(out var block))
{
@@ -70,7 +81,6 @@ public static Block Get(Block? previous, int firstLabel, int firstGoto, int acti
block.HasUpValue = hasUpValue;
block.IsLoop = isLoop;
-
return block;
}
@@ -88,7 +98,8 @@ struct ExprDesc
public int Table;
public Kind TableType;
public int Info;
- public int T, F;
+ public int T,
+ F;
public double Value;
public readonly bool HasJumps()
@@ -127,5 +138,5 @@ enum Kind
Jump = 10,
Relocatable = 11,
Call = 12,
- VarArg = 13
-}
\ No newline at end of file
+ VarArg = 13,
+}
diff --git a/src/Lua/CodeAnalysis/Compilation/Dump.cs b/src/Lua/CodeAnalysis/Compilation/Dump.cs
index 4b0ad1e7..ed90dd2d 100644
--- a/src/Lua/CodeAnalysis/Compilation/Dump.cs
+++ b/src/Lua/CodeAnalysis/Compilation/Dump.cs
@@ -1,12 +1,12 @@
-using Lua.Internal;
-using Lua.Runtime;
-using System.Buffers;
+using System.Buffers;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
+using Lua.Internal;
+using Lua.Runtime;
namespace Lua.CodeAnalysis.Compilation;
@@ -18,9 +18,14 @@ unsafe struct Header
public static ReadOnlySpan LuaTail => [0x19, 0x93, 0x0d, 0x0a, 0x1a, 0x0a];
public fixed byte Signature[4];
- public byte Version, Format, Endianness, IntSize;
- public byte PointerSize, InstructionSize;
- public byte NumberSize, IntegralNumber;
+ public byte Version,
+ Format,
+ Endianness,
+ IntSize;
+ public byte PointerSize,
+ InstructionSize;
+ public byte NumberSize,
+ IntegralNumber;
public fixed byte Tail[6];
public const int Size = 18;
@@ -60,10 +65,19 @@ public void Validate(ReadOnlySpan name)
var minor = Version & 0xF;
if (major != Constants.VersionMajor || minor != Constants.VersionMinor)
{
- throw new LuaUndumpException($"{name.ToString()}: version mismatch in precompiled chunk {major}.{minor} != {Constants.VersionMajor}.{Constants.VersionMinor}");
+ throw new LuaUndumpException(
+ $"{name.ToString()}: version mismatch in precompiled chunk {major}.{minor} != {Constants.VersionMajor}.{Constants.VersionMinor}"
+ );
}
- if (IntSize != 4 || Format != 0 || IntegralNumber != 0 || PointerSize is not (4 or 8) || InstructionSize != 4 || NumberSize != 8)
+ if (
+ IntSize != 4
+ || Format != 0
+ || IntegralNumber != 0
+ || PointerSize is not (4 or 8)
+ || InstructionSize != 4
+ || NumberSize != 8
+ )
{
goto ErrIncompatible;
}
@@ -77,7 +91,7 @@ public void Validate(ReadOnlySpan name)
}
return;
- ErrIncompatible:
+ ErrIncompatible:
throw new LuaUndumpException($"{name.ToString()}: incompatible precompiled chunk");
}
}
@@ -123,7 +137,6 @@ public void Dump(Prototype prototype)
DumpFunction(prototype);
}
-
void DumpFunction(Prototype prototype)
{
WriteInt(prototype.LineDefined); // 4
@@ -233,7 +246,8 @@ void WriteConstants(ReadOnlySpan constants)
WriteByte((byte)c.Type);
switch (c.Type)
{
- case LuaValueType.Nil: break;
+ case LuaValueType.Nil:
+ break;
case LuaValueType.Boolean:
WriteBool(c.UnsafeReadDouble() != 0);
break;
@@ -278,7 +292,11 @@ void WriteUpValues(ReadOnlySpan upValues)
}
}
-unsafe ref struct UndumpState(ReadOnlySpan span, ReadOnlySpan name, StringInternPool internPool)
+unsafe ref struct UndumpState(
+ ReadOnlySpan span,
+ ReadOnlySpan name,
+ StringInternPool internPool
+)
{
public ReadOnlySpan Unread = span;
bool otherEndian;
@@ -382,7 +400,6 @@ public Prototype Undump()
return UndumpFunction();
}
-
Prototype UndumpFunction()
{
var lineDefined = ReadInt(); // 4
@@ -404,17 +421,32 @@ Prototype UndumpFunction()
ReadInToIntSpan(lineInfo.AsSpan());
var localVariables = ReadLocalVariables();
var upValueCount = ReadInt();
- Debug.Assert(upValueCount == upValues.Length, $"upvalue count mismatch: {upValueCount} != {upValues.Length}");
+ Debug.Assert(
+ upValueCount == upValues.Length,
+ $"upvalue count mismatch: {upValueCount} != {upValues.Length}"
+ );
foreach (ref var desc in upValues.AsSpan())
{
var name = ReadString();
desc.Name = name;
}
- return new(source, lineDefined, lastLineDefined, parameterCount, maxStackSize, isVarArg, constants, code, prototypes, lineInfo, localVariables, upValues);
+ return new(
+ source,
+ lineDefined,
+ lastLineDefined,
+ parameterCount,
+ maxStackSize,
+ isVarArg,
+ constants,
+ code,
+ prototypes,
+ lineInfo,
+ localVariables,
+ upValues
+ );
}
-
void ReadInToIntSpan(Span toWrite)
{
for (var i = 0; i < toWrite.Length; i++)
@@ -423,7 +455,6 @@ void ReadInToIntSpan(Span toWrite)
}
}
-
string ReadString()
{
var len = pointerSize == 4 ? ReadInt() : (int)ReadLong();
@@ -442,7 +473,10 @@ string ReadString()
var l = ReadByte();
Debug.Assert(l == 0);
- var chars = len <= 128 ? stackalloc char[len * 2] : (charArrayPooled = ArrayPool.Shared.Rent(len * 2));
+ var chars =
+ len <= 128
+ ? stackalloc char[len * 2]
+ : (charArrayPooled = ArrayPool.Shared.Rent(len * 2));
var count = Encoding.UTF8.GetChars(span, chars);
return internPool.Intern(chars[..count]);
}
@@ -465,7 +499,8 @@ LuaValue[] ReadConstants()
var type = (LuaValueType)ReadByte();
switch (type)
{
- case LuaValueType.Nil: break;
+ case LuaValueType.Nil:
+ break;
case LuaValueType.Boolean:
constants[i] = ReadByte() == 1;
break;
@@ -502,7 +537,12 @@ LocalVariable[] ReadLocalVariables()
var name = ReadString();
var startPc = ReadInt();
var endPc = ReadInt();
- localVariables[i] = new() { Name = name, StartPc = startPc, EndPc = endPc };
+ localVariables[i] = new()
+ {
+ Name = name,
+ StartPc = startPc,
+ EndPc = endPc,
+ };
}
return localVariables;
@@ -522,4 +562,4 @@ UpValueDesc[] ReadUpValues()
return upValues;
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua/CodeAnalysis/Compilation/Function.cs b/src/Lua/CodeAnalysis/Compilation/Function.cs
index 596f137b..72a9ffc9 100644
--- a/src/Lua/CodeAnalysis/Compilation/Function.cs
+++ b/src/Lua/CodeAnalysis/Compilation/Function.cs
@@ -1,13 +1,13 @@
-using Lua.Internal;
+using System.Diagnostics;
+using Lua.Internal;
using Lua.Runtime;
-using System.Diagnostics;
using Constants = Lua.Internal.Constants;
namespace Lua.CodeAnalysis.Compilation;
+using static Constants;
using static Debug;
using static Instruction;
-using static Constants;
class Function : IPoolNode
{
@@ -16,7 +16,8 @@ class Function : IPoolNode
public Function? Previous;
public Parser P = null!;
public Block Block = null!;
- public int JumpPc = NoJump, LastTarget;
+ public int JumpPc = NoJump,
+ LastTarget;
public int FreeRegisterCount;
public int ActiveVariableCount;
public int FirstLocal;
@@ -63,7 +64,6 @@ internal void Release()
public const int MaxLocalVariables = 200;
-
public const int OprAdd = 0;
public const int OprSub = 1;
@@ -114,7 +114,12 @@ public void OpenFunction(int line)
public ExprDesc CloseFunction()
{
- var e = P.Function.Previous!.ExpressionToNextRegister(MakeExpression(Kind.Relocatable, Previous!.EncodeABx(OpCode.Closure, 0, Previous!.Proto.PrototypeList.Length - 1)));
+ var e = P.Function.Previous!.ExpressionToNextRegister(
+ MakeExpression(
+ Kind.Relocatable,
+ Previous!.EncodeABx(OpCode.Closure, 0, Previous!.Proto.PrototypeList.Length - 1)
+ )
+ );
P.Function.ReturnNone();
P.Function.LeaveBlock();
Assert(P.Function.Block == null);
@@ -126,7 +131,14 @@ public ExprDesc CloseFunction()
public void EnterBlock(bool isLoop)
{
- var b = Block.Get(Block, P.ActiveLabels.Length, P.PendingGotos.Length, ActiveVariableCount, false, isLoop);
+ var b = Block.Get(
+ Block,
+ P.ActiveLabels.Length,
+ P.PendingGotos.Length,
+ ActiveVariableCount,
+ false,
+ isLoop
+ );
Block = b;
Assert(FreeRegisterCount == ActiveVariableCount);
}
@@ -172,19 +184,39 @@ public void MakeLocalVariable(string name)
{
var r = Proto.LocalVariablesList.Length;
Proto.LocalVariablesList.Add(new() { Name = name });
- P.CheckLimit(P.ActiveVariables.Length + 1 - FirstLocal, MaxLocalVariables, "local variables");
+ P.CheckLimit(
+ P.ActiveVariables.Length + 1 - FirstLocal,
+ MaxLocalVariables,
+ "local variables"
+ );
P.ActiveVariables.Add(r);
}
public void MakeGoto(string name, int line, int pc)
{
- P.PendingGotos.Add(new() { Name = name, Line = line, Pc = pc, ActiveVariableCount = ActiveVariableCount });
+ P.PendingGotos.Add(
+ new()
+ {
+ Name = name,
+ Line = line,
+ Pc = pc,
+ ActiveVariableCount = ActiveVariableCount,
+ }
+ );
FindLabel(P.PendingGotos.Length - 1);
}
public int MakeLabel(string name, int line)
{
- P.ActiveLabels.Add(new() { Name = name, Line = line, Pc = Proto.CodeList.Length, ActiveVariableCount = ActiveVariableCount });
+ P.ActiveLabels.Add(
+ new()
+ {
+ Name = name,
+ Line = line,
+ Pc = Proto.CodeList.Length,
+ ActiveVariableCount = ActiveVariableCount,
+ }
+ );
return P.ActiveLabels.Length - 1;
}
@@ -194,7 +226,9 @@ public void CloseGoto(int i, Label l)
Assert(g.Name == l.Name);
if (g.ActiveVariableCount < l.ActiveVariableCount)
{
- SemanticError($" at line {g.Line} jumps into the scope of local '{LocalVariable(g.ActiveVariableCount).Name}'");
+ SemanticError(
+ $" at line {g.Line} jumps into the scope of local '{LocalVariable(g.ActiveVariableCount).Name}'"
+ );
}
PatchList(g.Pc, l.Pc);
@@ -209,7 +243,10 @@ public int FindLabel(int i)
{
if (l.Name == g.Name)
{
- if (g.ActiveVariableCount > l.ActiveVariableCount && (b.HasUpValue || P.ActiveLabels.Length > b.FirstLabel))
+ if (
+ g.ActiveVariableCount > l.ActiveVariableCount
+ && (b.HasUpValue || P.ActiveLabels.Length > b.FirstLabel)
+ )
{
PatchClose(g.Pc, l.ActiveVariableCount);
}
@@ -235,7 +272,7 @@ public void CheckRepeatedLabel(string name)
public void FindGotos(int label)
{
- for (var i = Block.FirstGoto; i < P.PendingGotos.Length;)
+ for (var i = Block.FirstGoto; i < P.PendingGotos.Length; )
{
var l = P.ActiveLabels[label];
if (P.PendingGotos[i].Name == l.Name)
@@ -302,13 +339,17 @@ public static int Not(int b)
return b == 0 ? 1 : 0;
}
-
public static ExprDesc MakeExpression(Kind kind, int info)
{
- return new() { F = NoJump, T = NoJump, Kind = kind, Info = info };
+ return new()
+ {
+ F = NoJump,
+ T = NoJump,
+ Kind = kind,
+ Info = info,
+ };
}
-
public void SemanticError(string message)
{
P.Scanner.Token = default;
@@ -326,20 +367,17 @@ public void Unreachable()
Assert(false);
}
-
public ref Instruction Instruction(ExprDesc e)
{
return ref Proto.CodeList[e.Info];
}
-
[Conditional("DEBUG")]
public void AssertEqual(int a, int b)
{
Assert(a == b, $"{a} != {b}");
}
-
public int Encode(Instruction i)
{
Assert(Proto.CodeList.Length == Proto.LineInfoList.Length);
@@ -366,7 +404,6 @@ public int EncodeABx(OpCode op, int a, int bx)
return Encode(CreateABx(op, a, bx));
}
-
public int EncodeAsBx(OpCode op, int a, int sbx)
{
return EncodeABx(op, a, sbx + MaxArgSBx);
@@ -377,7 +414,6 @@ public int EncodeExtraArg(int a)
return Encode(CreateAx(OpCode.ExtraArg, a));
}
-
public int EncodeConstant(int r, int constant)
{
if (constant <= MaxArgBx)
@@ -395,7 +431,6 @@ public ExprDesc EncodeString(string s)
return MakeExpression(Kind.Constant, StringConstant(s));
}
-
public void LoadNil(int from, int n)
{
if (Proto.CodeList.Length > LastTarget) // no jumps to current position
@@ -621,7 +656,10 @@ public void PatchClose(int list, int level)
for (int next; list != NoJump; list = next)
{
next = Jump(list);
- Assert((Proto.CodeList[list].OpCode == OpCode.Jmp && Proto.CodeList[list].A == 0) || Proto.CodeList[list].A >= level);
+ Assert(
+ (Proto.CodeList[list].OpCode == OpCode.Jmp && Proto.CodeList[list].A == 0)
+ || Proto.CodeList[list].A >= level
+ );
Proto.CodeList[list].A = level;
}
}
@@ -650,7 +688,7 @@ public int Concatenate(int l1, int l2)
}
var list = l1;
- for (var next = Jump(list); next != NoJump;)
+ for (var next = Jump(list); next != NoJump; )
{
(list, next) = (next, Jump(next));
}
@@ -776,6 +814,7 @@ public ExprDesc DischargeVariables(ExprDesc e)
break;
case Kind.Indexed:
FreeRegister(e.Index);
+
{
if (e.TableType == Kind.Local)
{
@@ -995,7 +1034,12 @@ public void StoreVariable(ExprDesc v, ExprDesc e)
case Kind.Indexed:
var r = 0;
(e, r) = ExpressionToRegisterOrConstant(e);
- EncodeABC(v.TableType == Kind.Local ? OpCode.SetTable : OpCode.SetTabUp, v.Table, v.Index, r);
+ EncodeABC(
+ v.TableType == Kind.Local ? OpCode.SetTable : OpCode.SetTabUp,
+ v.Table,
+ v.Index,
+ r
+ );
break;
default:
@@ -1146,7 +1190,6 @@ public ExprDesc Indexed(ExprDesc t, ExprDesc k)
return r;
}
-
static double Arith(OpCode op, double v1, double v2)
{
switch (op)
@@ -1229,11 +1272,21 @@ public ExprDesc Prefix(int op, ExprDesc e, int line)
return e;
}
- return EncodeArithmetic(OpCode.Unm, ExpressionToAnyRegister(e), MakeExpression(Kind.Number, 0), line);
+ return EncodeArithmetic(
+ OpCode.Unm,
+ ExpressionToAnyRegister(e),
+ MakeExpression(Kind.Number, 0),
+ line
+ );
case OprNot:
return EncodeNot(e);
case OprLength:
- return EncodeArithmetic(OpCode.Len, ExpressionToAnyRegister(e), MakeExpression(Kind.Number, 0), line);
+ return EncodeArithmetic(
+ OpCode.Len,
+ ExpressionToAnyRegister(e),
+ MakeExpression(Kind.Number, 0),
+ line
+ );
}
throw new("unreachable");
@@ -1336,7 +1389,6 @@ public void FixLine(int line)
Proto.LineInfoList[Proto.CodeList.Length - 1] = line;
}
-
public void SetList(int @base, int elementCount, int storeCount)
{
Assert(storeCount != 0);
@@ -1441,7 +1493,14 @@ public void AdjustAssignment(int variableCount, int expressionCount, ExprDesc e)
public int MakeUpValue(string name, ExprDesc e)
{
P.CheckLimit(Proto.UpValuesList.Length + 1, MaxUpValue, "upvalues");
- Proto.UpValuesList.Add(new() { Name = name, IsLocal = e.Kind == Kind.Local, Index = e.Info });
+ Proto.UpValuesList.Add(
+ new()
+ {
+ Name = name,
+ IsLocal = e.Kind == Kind.Local,
+ Index = e.Info,
+ }
+ );
return Proto.UpValuesList.Length - 1;
}
@@ -1456,7 +1515,6 @@ static Block owningBlock(Block b1, int level)
return b1;
}
-
;
static (int, bool) find(Function f, string name)
@@ -1471,7 +1529,6 @@ static Block owningBlock(Block b1, int level)
return (0, false);
}
-
;
static (int, bool) findUpValue(Function f, string name)
@@ -1486,7 +1543,6 @@ static Block owningBlock(Block b1, int level)
return (0, false);
}
-
;
if (f == null)
@@ -1543,7 +1599,12 @@ public ExprDesc SingleVariable(string name)
return (pc, t);
}
- public void FlushFieldToConstructor(int tableRegister, int freeRegisterCount, ExprDesc k, Func v)
+ public void FlushFieldToConstructor(
+ int tableRegister,
+ int freeRegisterCount,
+ ExprDesc k,
+ Func v
+ )
{
var (_, rk) = ExpressionToRegisterOrConstant(k);
var (_, rv) = ExpressionToRegisterOrConstant(v());
@@ -1563,7 +1624,14 @@ public int FlushToConstructor(int tableRegister, int pending, int arrayCount, Ex
return pending;
}
- public void CloseConstructor(int pc, int tableRegister, int pending, int arrayCount, int hashCount, ExprDesc e)
+ public void CloseConstructor(
+ int pc,
+ int tableRegister,
+ int pending,
+ int arrayCount,
+ int hashCount,
+ ExprDesc e
+ )
{
if (pending != 0)
{
@@ -1630,4 +1698,4 @@ public Function CloseMainFunction()
Assert(Block == null);
return Previous!;
}
-}
\ No newline at end of file
+}
diff --git a/src/Lua/CodeAnalysis/Compilation/Parser.cs b/src/Lua/CodeAnalysis/Compilation/Parser.cs
index c0b8f59f..a44b327f 100644
--- a/src/Lua/CodeAnalysis/Compilation/Parser.cs
+++ b/src/Lua/CodeAnalysis/Compilation/Parser.cs
@@ -1,14 +1,14 @@
-using Lua.Internal;
-using Lua.Runtime;
-using System.Buffers;
+using System.Buffers;
using System.Runtime.CompilerServices;
+using Lua.Internal;
+using Lua.Runtime;
using static System.Diagnostics.Debug;
namespace Lua.CodeAnalysis.Compilation;
+using static Constants;
using static Function;
using static Scanner;
-using static Constants;
class Parser : IPoolNode, IDisposable
{
@@ -32,9 +32,7 @@ internal void Next()
internal FastListCore