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

增加对私有操作的支持 #351

Merged
merged 1 commit into from
Jul 8, 2024
Merged

增加对私有操作的支持 #351

merged 1 commit into from
Jul 8, 2024

Conversation

NMSAzulX
Copy link
Collaborator

@NMSAzulX NMSAzulX commented Jul 8, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new methods for handling syntax and scripts in the compilation process.
    • Added ToAccessPrivateTree extension method for parsing scripts into CompilationUnitSyntax.
    • Introduced IgnoresAccessChecksToAttribute to allow ignoring assembly access checks.
    • Added NatashaPrivateAssemblySyntaxHelper class for managing private assembly syntax with new Handle method.
  • Enhancements

    • Improved method signatures and functionality for better handling of compilation units and syntax trees.

Copy link

coderabbitai bot commented Jul 8, 2024

Walkthrough

The recent changes focus on enhancing the Natasha.CSharp library by introducing new methods for compiling C# code, refining existing methods to accept additional parameters, and adding capabilities for handling private assembly syntax. This update includes greater flexibility in manipulating syntax trees and processing private assemblies, with new utilities for ignoring access checks and generating assembly-level attributes.

Changes

File Path Change Summary
.../AssemblyCSharpBuilder.Syntax.cs Added methods for adding CompilationUnitSyntax and SyntaxTree with optional file paths
Updated Add methods to accept additional filePath parameters
.../Component/Syntax/NatashaCSharpSyntax.cs Modified FormartTree to work with CompilationUnitSyntax instead of SyntaxTree, added import
.../Extension/NatashaStringExtension.cs New method ToAccessPrivateTree to parse a script to CompilationUnitSyntax handling private assembly syntax
.../Utils/IgnoresAccessChecksToAttribute.cs Introduced IgnoresAccessChecksToAttribute to ignore access checks for specified assemblies
.../Utils/NatashaPrivateAssemblySyntaxHelper.cs Added static class NatashaPrivateAssemblySyntaxHelper for processing CompilationUnitSyntax with private attributes

Poem

In code lands vast and syntax trees,
Natasha weaves with subtle ease.
With attributes to bridge the lines,
And private checks that redefine.
Assemble now, compile with grace,
For we have paved a smarter place.


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 NMSAzulX added the pr_src 此次提交包含 [源码工程] 相关的改动. label Jul 8, 2024
@NMSAzulX
Copy link
Collaborator Author

NMSAzulX commented Jul 8, 2024

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

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

@NMSAzulX
Copy link
Collaborator Author

NMSAzulX commented Jul 8, 2024

@coderabbitai review

Copy link

coderabbitai bot commented Jul 8, 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.

Copy link

github-actions bot commented Jul 8, 2024

UT Test - Ubuntu

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

Results for commit 30737b9.

Copy link

github-actions bot commented Jul 8, 2024

UT Test - Windows

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

Results for commit 30737b9.

@NMSAzulX NMSAzulX merged commit a47d409 into dev.next Jul 8, 2024
8 checks passed
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: 9

Outside diff range and nitpick comments (2)
src/Natasha.CSharp/Natasha.CSharp.Compiler/Component/Syntax/NatashaCSharpSyntax.cs (1)

Line range hint 98-108:
Consider adding error handling and logging, and fix the typographical error in the method name.

The method lacks error handling and logging, and the method name contains a typographical error.

public static SyntaxTree FormatTree(CompilationUnitSyntax root, CSharpParseOptions? options, Encoding encoding, string filePath = "")
{
    if (options == null)
    {
        options = _options;
    }

    try
    {
        return CSharpSyntaxTree.ParseText(root.NormalizeWhitespace().SyntaxTree.ToString(), options, filePath, encoding: encoding);
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error formatting tree: {ex.Message}");
        throw;
    }
}
src/Natasha.CSharp/Natasha.CSharp.Compiler/CompileUnit/AssemblyCSharpBuilder.Syntax.cs (1)

Line range hint 102-124:
Consider adding error handling and logging.

The method lacks error handling and logging.

private AssemblyCSharpBuilder InternalAddScript(string script, Encoding? encoding = null, string filePath = "")
{
    if (_scriptHandle != null)
    {
        script = _scriptHandle(script);
    }
    
    try
    {
        var tree = NatashaCSharpSyntax.ParseTree(script, filePath, _options, encoding);
        var exception = NatashaExceptionAnalyzer.GetSyntaxException(tree);
        if (exception != null)
        {
            _exception = exception;
            throw exception;
        }
        else
        {
            lock (SyntaxTrees)
            {
                SyntaxTrees.Add(tree);
            }
        }
        return this;
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error adding script: {ex.Message}");
        throw;
    }
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 323a5ef and 30737b9.

Files selected for processing (5)
  • src/Natasha.CSharp/Natasha.CSharp.Compiler/CompileUnit/AssemblyCSharpBuilder.Syntax.cs (6 hunks)
  • src/Natasha.CSharp/Natasha.CSharp.Compiler/Component/Syntax/NatashaCSharpSyntax.cs (3 hunks)
  • src/Natasha.CSharp/Natasha.CSharp.Compiler/Extension/NatashaStringExtension.cs (1 hunks)
  • src/Natasha.CSharp/Natasha.CSharp.Compiler/Utils/IgnoresAccessChecksToAttribute.cs (1 hunks)
  • src/Natasha.CSharp/Natasha.CSharp.Compiler/Utils/NatashaPrivateAssemblySyntaxHelper.cs (1 hunks)
Files skipped from review due to trivial changes (1)
  • src/Natasha.CSharp/Natasha.CSharp.Compiler/Utils/IgnoresAccessChecksToAttribute.cs

Comment on lines +8 to +18
public static CompilationUnitSyntax ToAccessPrivateTree(this string script, params object[] objects)
{
var tree = CSharpSyntaxTree.ParseText(script);
var treeRoot = tree.GetCompilationUnitRoot();
var rootResult = NatashaPrivateAssemblySyntaxHelper.Handle(tree.GetCompilationUnitRoot(), objects);
if (rootResult == null)
{
return treeRoot;
}
return rootResult;
}
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling and logging.

The method lacks error handling and logging, which could help in debugging and understanding failures.

public static CompilationUnitSyntax ToAccessPrivateTree(this string script, params object[] objects)
{
    try
    {
        var tree = CSharpSyntaxTree.ParseText(script);
        var treeRoot = tree.GetCompilationUnitRoot();
        var rootResult = NatashaPrivateAssemblySyntaxHelper.Handle(tree.GetCompilationUnitRoot(), objects);
        if (rootResult == null)
        {
            return treeRoot;
        }
        return rootResult;
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error processing script: {ex.Message}");
        throw;
    }
}

Comment on lines +18 to +35
public static CompilationUnitSyntax? Handle(CompilationUnitSyntax rootSyntax, params object[] objects)
{
if (objects == null || objects.Length == 0)
{
return null;
}
HashSet<Type> types = new(objects.Select(obj =>
{
if (obj is Type type)
{
return type;
}
else
{
return obj.GetType();
}
})!);
return InternalHandle(rootSyntax, types);
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling, logging, and thorough validation.

The method lacks error handling and logging, and the objects parameter could be validated more thoroughly.

public static CompilationUnitSyntax? Handle(CompilationUnitSyntax rootSyntax, params object[] objects)
{
    if (objects == null || objects.Length == 0)
    {
        return null;
    }
    
    try
    {
        HashSet<Type> types = new(objects.Select(obj =>
        {
            if (obj is Type type)
            {
                return type;
            }
            else if (obj != null)
            {
                return obj.GetType();
            }
            else
            {
                throw new ArgumentException("Object in the array is null.");
            }
        })!);
        
        return InternalHandle(rootSyntax, types);
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error handling root syntax: {ex.Message}");
        throw;
    }
}

Comment on lines +38 to +72
internal static CompilationUnitSyntax InternalHandle(CompilationUnitSyntax rootSyntax, HashSet<Type> types)
{
HashSet<Assembly> assemblies = [];
foreach (var type in types)
{
var assembly = type.Assembly;
if (!assemblies.Contains(assembly))
{
assemblies.Add(assembly);
}
}

// 创建 assembly 级别的属性列表
var assemblyAttributeList = assemblies.Select(asm =>
{
var attrSyntax = SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(
SyntaxFactory
.IdentifierName("assembly:System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute"))
.AddArgumentListArguments(
SyntaxFactory.AttributeArgument(
SyntaxFactory.ParseExpression($"\"{asm.GetName().Name!}\"")))));
return attrSyntax
.ReplaceToken(
attrSyntax.CloseBracketToken,
attrSyntax
.CloseBracketToken
.WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine)));
}).ToArray();


// 将属性列表添加到 assembly 节点
rootSyntax = rootSyntax.AddAttributeLists(assemblyAttributeList);
return rootSyntax;
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling, logging, and optimizing the use of HashSet<Assembly>.

The method lacks error handling and logging, and the use of HashSet<Assembly> could be optimized.

internal static CompilationUnitSyntax InternalHandle(CompilationUnitSyntax rootSyntax, HashSet<Type> types)
{
    try
    {
        HashSet<Assembly> assemblies = new();
        foreach (var type in types)
        {
            var assembly = type.Assembly;
            if (!assemblies.Contains(assembly))
            {
                assemblies.Add(assembly);
            }
        }

        // 创建 assembly 级别的属性列表
        var assemblyAttributeList = assemblies.Select(asm =>
        {
            var attrSyntax = SyntaxFactory.AttributeList(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.Attribute(
                            SyntaxFactory
                                .IdentifierName("assembly:System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute"))
                            .AddArgumentListArguments(
                                SyntaxFactory.AttributeArgument(
                                    SyntaxFactory.ParseExpression($"\"{asm.GetName().Name!}\"")))));
            return attrSyntax
                .ReplaceToken(
                    attrSyntax.CloseBracketToken,
                    attrSyntax
                        .CloseBracketToken
                        .WithTrailingTrivia(SyntaxFactory.EndOfLine(Environment.NewLine)));
        }).ToArray();

        // 将属性列表添加到 assembly 节点
        rootSyntax = rootSyntax.AddAttributeLists(assemblyAttributeList);
        return rootSyntax;
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error processing root syntax: {ex.Message}");
        throw;
    }
}

Comment on lines +89 to +92
public AssemblyCSharpBuilder Add(string script, Encoding? encoding = null, string filePath = "")
{
return Add(script, _parsingBehavior, encoding);
return Add(script, _parsingBehavior, encoding, filePath);
}
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling and logging.

The method lacks error handling and logging.

public AssemblyCSharpBuilder Add(string script, Encoding? encoding = null, string filePath = "")
{
    try
    {
        return Add(script, _parsingBehavior, encoding, filePath);
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error adding script: {ex.Message}");
        throw;
    }
}

Comment on lines +93 to +95
public AssemblyCSharpBuilder Add(CompilationUnitSyntax root, Encoding? encoding = null, string filePath = "")
{
return Add(root, _parsingBehavior, encoding, filePath);
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling and logging.

The method lacks error handling and logging.

public AssemblyCSharpBuilder Add(CompilationUnitSyntax root, Encoding? encoding = null, string filePath = "")
{
    try
    {
        return Add(root, _parsingBehavior, encoding, filePath);
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error adding root syntax: {ex.Message}");
        throw;
    }
}

Comment on lines +132 to +148
private AssemblyCSharpBuilder InternalAddRootSyntax(CompilationUnitSyntax root, Encoding? encoding = null, string filePath = "")
{
var tree = NatashaCSharpSyntax.FormartTree(root, _options, encoding, filePath);
var exception = NatashaExceptionAnalyzer.GetSyntaxException(tree);
if (exception != null)
{
throw exception;
}
else
{
lock (SyntaxTrees)
{
SyntaxTrees.Add(tree);
}
}
return this;
}
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling and logging.

The method lacks error handling and logging.

private AssemblyCSharpBuilder InternalAddRootSyntax(CompilationUnitSyntax root, Encoding? encoding = null, string filePath = "")
{
    try
    {
        var tree = NatashaCSharpSyntax.FormartTree(root, _options, encoding, filePath);
        var exception = NatashaExceptionAnalyzer.GetSyntaxException(tree);
        if (exception != null)
        {
            throw exception;
        }
        else
        {
            lock (SyntaxTrees)
            {
                SyntaxTrees.Add(tree);
            }
        }
        return this;
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error adding root syntax: {ex.Message}");
        throw;
    }
}

Comment on lines +154 to +158
public AssemblyCSharpBuilder FastAddScriptWithoutCheck(string script, Encoding? encoding = null, string filePath = "")
{
SyntaxTrees.Add(NatashaCSharpSyntax.ParseTree(script, filePath, _options, encoding));
return this;
}
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling and logging.

The method lacks error handling and logging.

public AssemblyCSharpBuilder FastAddScriptWithoutCheck(string script, Encoding? encoding = null, string filePath = "")
{
    try
    {
        SyntaxTrees.Add(NatashaCSharpSyntax.ParseTree(script, filePath, _options, encoding));
        return this;
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error adding script without check: {ex.Message}");
        throw;
    }
}

Comment on lines +164 to +174
public AssemblyCSharpBuilder FastAddSynataxWithoutCheck(CompilationUnitSyntax root, Encoding? encoding = null, string? filePath = null)
{
SyntaxTrees.Add(NatashaCSharpSyntax.ParseTree(script, _options, encoding));
if (encoding != null || filePath != null)
{
SyntaxTrees.Add(CSharpSyntaxTree.Create(root, _options, filePath?? root.SyntaxTree.FilePath, encoding ?? root.SyntaxTree.Encoding));
}
else
{
SyntaxTrees.Add(root.SyntaxTree);
}

Copy link

Choose a reason for hiding this comment

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

Consider adding error handling and logging, and fix the typographical error in the method name.

The method lacks error handling and logging, and the method name contains a typographical error.

public AssemblyCSharpBuilder FastAddSyntaxWithoutCheck(CompilationUnitSyntax root, Encoding? encoding = null, string? filePath = null)
{
    try
    {
        if (encoding != null || filePath != null)
        {
            SyntaxTrees.Add(CSharpSyntaxTree.Create(root, _options, filePath ?? root.SyntaxTree.FilePath, encoding ?? root.SyntaxTree.Encoding));
        }
        else
        {
            SyntaxTrees.Add(root.SyntaxTree);
        }
        return this;
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error adding syntax without check: {ex.Message}");
        throw;
    }
}

Comment on lines +220 to +260
public AssemblyCSharpBuilder Add(string script, UsingLoadBehavior usingLoadBehavior, Encoding? encoding = null, string filePath = "")
{
var usingScript = string.Empty;
switch (usingLoadBehavior)
{
case UsingLoadBehavior.WithDefault:
return AddScript(NatashaLoadContext.DefaultContext.UsingRecorder + script, encoding);
usingScript = NatashaLoadContext.DefaultContext.UsingRecorder.ToString();
break;
case UsingLoadBehavior.WithCurrent:
if (Domain!.Name == NatashaLoadContext.DefaultName)
{
return AddScript(NatashaLoadContext.DefaultContext.UsingRecorder + script, encoding);
usingScript = NatashaLoadContext.DefaultContext.UsingRecorder.ToString();
}
return AddScript(LoadContext!.UsingRecorder + script, encoding);
else
{
usingScript = LoadContext!.UsingRecorder.ToString();
}
break;
case UsingLoadBehavior.WithAll:
if (Domain!.Name == NatashaLoadContext.DefaultName)
{
return AddScript(NatashaLoadContext.DefaultContext.UsingRecorder + script, encoding);
usingScript = NatashaLoadContext.DefaultContext.UsingRecorder.ToString();
}
StringBuilder usingBuilder = new();
foreach (var item in LoadContext!.UsingRecorder._usings)
else
{
if (!NatashaLoadContext.DefaultContext.UsingRecorder.HasUsing(item))
StringBuilder usingBuilder = new();
foreach (var item in LoadContext!.UsingRecorder._usings)
{
usingBuilder.AppendLine($"using {item};");
if (!NatashaLoadContext.DefaultContext.UsingRecorder.HasUsing(item))
{
usingBuilder.AppendLine($"using {item};");
}
}
usingScript = NatashaLoadContext.DefaultContext.UsingRecorder.ToString() + usingBuilder;
}
break;
default:
break;
}
return InternalAddScript(usingScript + script, encoding, filePath);
}
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling and logging.

The method lacks error handling and logging.

public AssemblyCSharpBuilder Add(string script, UsingLoadBehavior usingLoadBehavior, Encoding? encoding = null, string filePath = "")
{
    try
    {
        var usingScript = string.Empty;
        switch (usingLoadBehavior)
        {
            case UsingLoadBehavior.WithDefault:
                usingScript = NatashaLoadContext.DefaultContext.UsingRecorder.ToString();
                break;
            case UsingLoadBehavior.WithCurrent:
                if (Domain!.Name == NatashaLoadContext.DefaultName)
                {
                    usingScript = NatashaLoadContext.DefaultContext.UsingRecorder.ToString();
                }
                else
                {
                    usingScript = LoadContext!.UsingRecorder.ToString();
                }
                break;
            case UsingLoadBehavior.WithAll:
                if (Domain!.Name == NatashaLoadContext.DefaultName)
                {
                    usingScript = NatashaLoadContext.DefaultContext.UsingRecorder.ToString();
                }
                else
                {
                    StringBuilder usingBuilder = new();
                    foreach (var item in LoadContext!.UsingRecorder._usings)
                    {
                        if (!NatashaLoadContext.DefaultContext.UsingRecorder.HasUsing(item))
                        {
                            usingBuilder.AppendLine($"using {item};");
                        }
                    }
                    usingScript = NatashaLoadContext.DefaultContext.UsingRecorder.ToString() + usingBuilder;
                }
                break;
            default:
                break;
        }
        return InternalAddScript(usingScript + script, encoding, filePath);
    }
    catch (Exception ex)
    {
        // Log the error
        Console.WriteLine($"Error adding script with using load behavior: {ex.Message}");
        throw;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pr_src 此次提交包含 [源码工程] 相关的改动.
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

None yet

1 participant