Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update method builder #352

Merged
merged 2 commits into from
Jul 9, 2024
Merged

update method builder #352

merged 2 commits into from
Jul 9, 2024

Conversation

NMSAzulX
Copy link
Collaborator

@NMSAzulX NMSAzulX commented Jul 9, 2024

Summary by CodeRabbit

  • New Features

    • Introduced WithSlimMethodBuilder method in StringExtension allowing configuration of NatashaSlimMethodBuilder instances for more streamlined method creation.
    • Provided overloaded WithSlimMethodBuilder methods that accept configuration parameters for advanced customizations.
  • Refactor

    • Updated SystemDelegateExtension methods to utilize NatashaSlimMethodBuilder for delegate generation, simplifying method signatures and improving consistency.
  • Enhancements

    • Improved the interface for dynamically creating and compiling methods with NatashaSlimMethodBuilder, offering more flexible usage patterns and configurations.

Copy link

coderabbitai bot commented Jul 9, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes primarily involve the NatashaSlimMethodBuilder class and related extensions in the Natasha.CSharp.Extension.MethodCreator namespace. Methods have been added or modified to refine the dynamic creation and compilation of methods, improving usability and flexibility by adding configuration options and simplifying method signatures.

Changes

File Path Change Summary
src/Natasha.CSharp/Ex...Creator/NatashaSlimMethodBuilder.cs No significant changes to the declarations of the NatashaSlimMethodBuilder class methods.
src/Natasha.CSharp/Ex...Creator/StringExtension.cs Replaced WithAssemblyBuilder method with WithSlimMethodBuilder, added overloads for configuration, removed WithMetadata and related methods.
src/Natasha.CSharp/Ex...reator/SystemDelegateExtension.cs Updated method signatures in SystemDelegateExtension to take a NatashaSlimMethodBuilder parameter for generating delegates.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant NatashaSlimMethodBuilder
    participant AssemblyCSharpBuilder
    participant NatashaLoadContext

    User->>+NatashaSlimMethodBuilder: Create Instance with "script"
    NatashaSlimMethodBuilder->>User: Return Builder Instance

    User->>+NatashaSlimMethodBuilder: Configure using AssemblyCSharpBuilder
    NatashaSlimMethodBuilder->>+AssemblyCSharpBuilder: Apply Configuration
    AssemblyCSharpBuilder-->>-NatashaSlimMethodBuilder: Config Applied

    User->>+NatashaSlimMethodBuilder: Configure using NatashaLoadContext
    NatashaSlimMethodBuilder->>+NatashaLoadContext: Apply Configuration
    NatashaLoadContext-->>-NatashaSlimMethodBuilder: Config Applied

    User->>+NatashaSlimMethodBuilder: Generate Delegate
    NatashaSlimMethodBuilder->>User: Delegate Returned
Loading

Poem

In the land of code where structures weave,
A builder slim left us to believe,
With configurations, it molds with flair,
Dynamic methods growing everywhere.
Sing, oh bytes, in harmony bright,
For Natasha's craft shines through the night. 🌙✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@NMSAzulX
Copy link
Collaborator Author

NMSAzulX commented Jul 9, 2024

@coderabbitai review

Copy link

coderabbitai bot commented Jul 9, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@NMSAzulX
Copy link
Collaborator Author

NMSAzulX commented Jul 9, 2024

未检测到合适的 ISSUE 推荐给您。感谢您的反馈!

该条自动推荐信息来自于 nms-bot.

Copy link

github-actions bot commented Jul 9, 2024

UT Test - Ubuntu

1 tests   1 ✅  0s ⏱️
1 suites  0 💤
1 files    0 ❌

Results for commit 3e5af70.

Copy link

github-actions bot commented Jul 9, 2024

UT Test - Windows

1 tests   1 ✅  0s ⏱️
1 suites  0 💤
1 files    0 ❌

Results for commit 3e5af70.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a47d409 and 3e5af70.

Files selected for processing (3)
  • src/Natasha.CSharp/Extension/Natasha.CSharp.Extension.MethodCreator/NatashaSlimMethodBuilder.cs (1 hunks)
  • src/Natasha.CSharp/Extension/Natasha.CSharp.Extension.MethodCreator/StringExtension.cs (1 hunks)
  • src/Natasha.CSharp/Extension/Natasha.CSharp.Extension.MethodCreator/SystemDelegateExtension.cs (1 hunks)
Additional comments not posted (14)
src/Natasha.CSharp/Extension/Natasha.CSharp.Extension.MethodCreator/StringExtension.cs (3)

10-14: LGTM!

The method correctly initializes NatashaSlimMethodBuilder and configures it using AssemblyCSharpBuilder.


17-21: LGTM!

The method correctly initializes NatashaSlimMethodBuilder and configures it using NatashaLoadContext.


24-28: LGTM!

The method correctly initializes NatashaSlimMethodBuilder and configures it using WithSimpleBuilder.

src/Natasha.CSharp/Extension/Natasha.CSharp.Extension.MethodCreator/NatashaSlimMethodBuilder.cs (9)

15-20: LGTM!

The constructor correctly initializes Usings, Builder, and Script.


21-25: LGTM!

The method correctly sets PrivateObjects and returns the builder instance.


27-31: LGTM!

The method correctly sets _builderConfig and returns the builder instance.


32-36: LGTM!

The method correctly sets _ctxConfig and returns the builder instance.


37-43: LGTM!

The method correctly configures the builder using UseRandomLoadContext, UseSimpleMode, and ConfigLoadContext.


45-49: LGTM!

The method correctly adds the provided usings to the Usings set.


51-55: LGTM!

The method correctly configures the builder to add reference and using code for the specified type.


116-119: LGTM!

The method correctly delegates to ToDelegate<T> with the "async" modifier.


120-127: LGTM!

The methods correctly delegate to ToDelegate<T> with the appropriate modifiers.

src/Natasha.CSharp/Extension/Natasha.CSharp.Extension.MethodCreator/SystemDelegateExtension.cs (2)

9-55: LGTM!

The methods correctly delegate to ToDelegate<T> for various Action types.


61-107: LGTM!

The methods correctly delegate to ToDelegate<T> for various Func types.

Comment on lines 57 to 67
public NatashaSlimMethodBuilder WithMetadata(params Type[] types)
{
if (types!=null && types.Length == 0)
{
foreach (var type in types)
{
Builder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode(type));
}
}
return this;
}
Copy link

Choose a reason for hiding this comment

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

Fix the condition check for empty types array.

The condition check for types.Length == 0 should be types.Length > 0 to avoid unnecessary iteration.

-  if (types!=null && types.Length == 0)
+  if (types!=null && types.Length > 0)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public NatashaSlimMethodBuilder WithMetadata(params Type[] types)
{
if (types!=null && types.Length == 0)
{
foreach (var type in types)
{
Builder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode(type));
}
}
return this;
}
public NatashaSlimMethodBuilder WithMetadata(params Type[] types)
{
if (types!=null && types.Length > 0)
{
foreach (var type in types)
{
Builder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode(type));
}
}
return this;
}

Comment on lines +69 to +115
public T ToDelegate<T>(string modifier = "") where T : Delegate
{
_builderConfig?.Invoke(Builder);
_ctxConfig?.Invoke(Builder.LoadContext);

var className = $"N{Guid.NewGuid():N}";
var methodInfo = typeof(T).GetMethod("Invoke")!;

var returnTypeScript = methodInfo.ReturnType.GetDevelopName();
var parameterScript = new StringBuilder();

var methodParameters = methodInfo.GetParameters();
for (int i = 0; i < methodParameters.Length; i += 1)
{
var paramType = methodParameters[i].ParameterType;
Builder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode(paramType));
parameterScript.Append($"{paramType.GetDevelopName()} arg{i + 1},");
}
if (parameterScript.Length > 0)
{
parameterScript.Length -= 1;
}

StringBuilder usingCode = new();
foreach (var item in Usings)
{

usingCode.AppendLine($"using {item};");

}
var fullScript = $"{usingCode} public static class {className} {{ public static {(modifier ?? string.Empty)} {returnTypeScript} Invoke({parameterScript}){{ {Script} }} }}";
if (PrivateObjects!=null)
{
Builder.Add(fullScript.ToAccessPrivateTree(PrivateObjects));
}
else
{
Builder.Add(fullScript);
}
var asm = Builder.GetAssembly();
var type = asm.GetType(className);
if (type != null)
{
return (T)Delegate.CreateDelegate(typeof(T), type.GetMethod("Invoke")!);
}
throw new Exception($"未找到 {className} 类型!");
}
Copy link

Choose a reason for hiding this comment

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

Handle potential null reference for methodInfo.

The methodInfo variable should be checked for null before accessing its properties.

-  var methodInfo = typeof(T).GetMethod("Invoke")!;
+  var methodInfo = typeof(T).GetMethod("Invoke");
+  if (methodInfo == null)
+  {
+      throw new InvalidOperationException($"The delegate type {typeof(T)} does not have an Invoke method.");
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public T ToDelegate<T>(string modifier = "") where T : Delegate
{
_builderConfig?.Invoke(Builder);
_ctxConfig?.Invoke(Builder.LoadContext);
var className = $"N{Guid.NewGuid():N}";
var methodInfo = typeof(T).GetMethod("Invoke")!;
var returnTypeScript = methodInfo.ReturnType.GetDevelopName();
var parameterScript = new StringBuilder();
var methodParameters = methodInfo.GetParameters();
for (int i = 0; i < methodParameters.Length; i += 1)
{
var paramType = methodParameters[i].ParameterType;
Builder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode(paramType));
parameterScript.Append($"{paramType.GetDevelopName()} arg{i + 1},");
}
if (parameterScript.Length > 0)
{
parameterScript.Length -= 1;
}
StringBuilder usingCode = new();
foreach (var item in Usings)
{
usingCode.AppendLine($"using {item};");
}
var fullScript = $"{usingCode} public static class {className} {{ public static {(modifier ?? string.Empty)} {returnTypeScript} Invoke({parameterScript}){{ {Script} }} }}";
if (PrivateObjects!=null)
{
Builder.Add(fullScript.ToAccessPrivateTree(PrivateObjects));
}
else
{
Builder.Add(fullScript);
}
var asm = Builder.GetAssembly();
var type = asm.GetType(className);
if (type != null)
{
return (T)Delegate.CreateDelegate(typeof(T), type.GetMethod("Invoke")!);
}
throw new Exception($"未找到 {className} 类型!");
}
public T ToDelegate<T>(string modifier = "") where T : Delegate
{
_builderConfig?.Invoke(Builder);
_ctxConfig?.Invoke(Builder.LoadContext);
var className = $"N{Guid.NewGuid():N}";
var methodInfo = typeof(T).GetMethod("Invoke");
if (methodInfo == null)
{
throw new InvalidOperationException($"The delegate type {typeof(T)} does not have an Invoke method.");
}
var returnTypeScript = methodInfo.ReturnType.GetDevelopName();
var parameterScript = new StringBuilder();
var methodParameters = methodInfo.GetParameters();
for (int i = 0; i < methodParameters.Length; i += 1)
{
var paramType = methodParameters[i].ParameterType;
Builder.ConfigLoadContext(ctx => ctx.AddReferenceAndUsingCode(paramType));
parameterScript.Append($"{paramType.GetDevelopName()} arg{i + 1},");
}
if (parameterScript.Length > 0)
{
parameterScript.Length -= 1;
}
StringBuilder usingCode = new();
foreach (var item in Usings)
{
usingCode.AppendLine($"using {item};");
}
var fullScript = $"{usingCode} public static class {className} {{ public static {(modifier ?? string.Empty)} {returnTypeScript} Invoke({parameterScript}){{ {Script} }} }}";
if (PrivateObjects!=null)
{
Builder.Add(fullScript.ToAccessPrivateTree(PrivateObjects));
}
else
{
Builder.Add(fullScript);
}
var asm = Builder.GetAssembly();
var type = asm.GetType(className);
if (type != null)
{
return (T)Delegate.CreateDelegate(typeof(T), type.GetMethod("Invoke")!);
}
throw new Exception($"未找到 {className} 类型!");
}

@NMSAzulX NMSAzulX merged commit 6f3b709 into dev.next Jul 9, 2024
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
No open projects
Development

Successfully merging this pull request may close these issues.

1 participant