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

Move PluginClassInfo & Add code regions #23

Merged
merged 3 commits into from
Mar 15, 2025
Merged

Conversation

Jack251970
Copy link
Collaborator

@Jack251970 Jack251970 commented Mar 11, 2025

Important

I have thoroughly tested the generator diagnostics and code fixes related to the PluginInitContext and I believe them are ready to move to production.

Move PluginClassInfo to Shared project

Let ContextAvailabilityAnalyzer.cs and LocalizeSourceGenerator.cs both use this class. Add CodeFixLocation property for code fix.

Add regions

In ContextAvailabilityAnalyzer.cs and ContextAvailabilityAnalyzerCodeFixProvider.cs for code quality.

Test

  1. Source generator diagnostic FLSG0002 ~ FLSG0006 can work.
  2. Code fixer diagnostic FLAN0002 ~ FLAN0005 can work.

Copy link
Contributor

coderabbitai bot commented Mar 11, 2025

📝 Walkthrough

Walkthrough

This PR reorganizes and refactors the plugin analysis logic. The ContextAvailabilityAnalyzer now uses a helper method to retrieve plugin class information. A new PluginClassInfo class is introduced in the shared project, and the helper methods in the Helper class are extended to support plugin context retrieval. In parallel, similar functionality is removed from the source generator, and some region directives have been added to enhance code organization. Additionally, a package reference update in the shared project file shifts from a general Roslyn package to one focused on C#.

Changes

File(s) Change Summary
Flow.Launcher.Localization.Analyzers/.../ContextAvailabilityAnalyzer.cs
Flow.Launcher.Localization.Analyzers/.../ContextAvailabilityAnalyzerCodeFixProvider.cs
- Added region directives for code organization.
- In ContextAvailabilityAnalyzer, refactored AnalyzeNode to call Helper.GetPluginClassInfo and removed the IsPluginEntryClass method.
- In the CodeFixProvider, reorganized methods between regions without functional changes.
Flow.Launcher.Localization.Shared/.../Classes.cs Added new class PluginClassInfo to encapsulate plugin metadata (location, class name, property name, access attributes, and a computed context accessor).
Flow.Launcher.Localization.Shared/.../Helper.cs Introduced new regions and added the public method GetPluginClassInfo, along with several helper methods for retrieving plugin context properties and their locations.
Flow.Launcher.Localization.Shared/.../Flow.Launcher.Localization.Shared.csproj Updated package reference by replacing Microsoft.CodeAnalysis.Common with Microsoft.CodeAnalysis.CSharp at version 4.13.0.
Flow.Launcher.Localization.SourceGenerators/.../LocalizeSourceGenerator.cs Removed local implementations of GetPluginClassInfo, PluginClassInfo, and GetLocation; replaced with an inline lambda that calls Helper.GetPluginClassInfo.

Sequence Diagram(s)

sequenceDiagram
    participant Analyzer
    participant Helper
    participant PluginClassInfo
    Analyzer->>Helper: GetPluginClassInfo(ClassDeclarationSyntax, SemanticModel, ct)
    Helper-->>Analyzer: Returns PluginClassInfo or null
    alt PluginClassInfo exists
       Analyzer->>Analyzer: Validate properties (IsStatic, IsPrivate, IsProtected)
    else No plugin found
       Analyzer->>Analyzer: Exit analysis early
    end
Loading
sequenceDiagram
    participant SourceGenerator
    participant Helper
    participant PluginClassInfo
    SourceGenerator->>Helper: Inline lambda: GetPluginClassInfo(...)
    Helper-->>SourceGenerator: Returns PluginClassInfo or null
    SourceGenerator->>SourceGenerator: Proceed with source generation based on plugin info
Loading

Possibly related PRs

  • Replace more strings with constants #19: The changes in the main PR, specifically the refactoring of the AnalyzeNode method in ContextAvailabilityAnalyzer, utilize the Helper.GetPluginClassInfo method, indicating a direct connection in how plugin class information is handled.
  • Add FLLUseDependencyInjection property group & Move all constants to Shared project #18: The changes in the main PR are related to the modifications in the ContextAvailabilityAnalyzer class, which now utilizes the GetPluginClassInfo method from the Helper class introduced in the retrieved PR, indicating a direct connection at the code level.
  • Improve diagnostics #20: The changes in the main PR, particularly the refactoring of the AnalyzeNode method to utilize Helper.GetPluginClassInfo, are directly related to the modifications in the retrieved PR, which also involves the GetValidPluginInfo method that validates plugin classes using similar logic for context properties.

Suggested labels

bug

Suggested reviewers

  • Yusyuriv

Poem

I'm a little rabbit, hopping through the code,
Regions and helpers lighten the load.
Plugin details now clear as day,
With smart refactors leading the way.
In bytes and bugs, we dance with glee,
Celebrating cleaner code endlessly!
🐇💻

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70820fc and dfda18c.

📒 Files selected for processing (2)
  • Flow.Launcher.Localization.Analyzers/Localize/ContextAvailabilityAnalyzer.cs (3 hunks)
  • Flow.Launcher.Localization.Shared/Classes.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Flow.Launcher.Localization.Shared/Classes.cs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: gitStream.cm
  • GitHub Check: build
🔇 Additional comments (6)
Flow.Launcher.Localization.Analyzers/Localize/ContextAvailabilityAnalyzer.cs (6)

14-15: Good addition of code regions for better organization

The introduction of regions helps organize the code into logical sections, making it more maintainable and easier to navigate. The separation between "DiagnosticAnalyzer" and "Analyze Methods" clearly delineates the analyzer configuration from its analytical logic.

Also applies to: 30-33, 104-104


38-42: Improved early return with clarifying comment

The addition of this comment clearly explains why we skip the context property check when dependency injection is used. This improves code readability and helps future developers understand the flow control logic.


46-51: Good refactoring to use Helper.GetPluginClassInfo

Moving the plugin class information retrieval to a shared helper method is an excellent refactoring. This centralizes the logic, making it reusable between the analyzer and source generator as mentioned in the PR objectives. The early return with a clear comment helps maintainability.


53-54: Improved property checking with PluginClassInfo

Using the properties from the pluginClassInfo object instead of directly accessing the property symbols makes the code cleaner and more maintainable. The added comment on line 53 also clarifies the purpose of this code section.

Also applies to: 56-56, 65-65


60-60: Use of CodeFixLocation for diagnostic reporting

Using the pluginClassInfo.CodeFixLocation property for diagnostic reporting locations centralizes the logic for determining where code fixes should be applied. This is a good improvement that aligns with the PR objective of adding a CodeFixLocation property for code fixes.

Also applies to: 69-69


74-76: Helpful comments for error reporting scenarios

The added comments clearly explain the different scenarios and their corresponding error reporting logic. This makes the code more maintainable and easier to understand, particularly when modifications are needed in the future.

Also applies to: 79-79, 97-101

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (5)
Flow.Launcher.Localization.Shared/Helper.cs (1)

28-60: Check for namespace collisions in IsPluginEntryClass.

IsPluginEntryClass matches the interface name by i.Name == Constants.PluginInterfaceName. Consider also verifying i.ContainingNamespace if a similarly named interface exists. Otherwise, the code thoroughly handles null checks and correct fallback paths.

-return namedTypeSymbol?.Interfaces.Any(i => i.Name == Constants.PluginInterfaceName) ?? false;
+return namedTypeSymbol?.Interfaces.Any(i =>
+    i.Name == Constants.PluginInterfaceName &&
+    i.ContainingNamespace.ToDisplayString() == "Flow.Launcher.Plugin") ?? false;
Flow.Launcher.Localization.Shared/Classes.cs (3)

13-13: Fix typo in property name

There's a typo in the property name: CodeFixLocatioin should be CodeFixLocation.

-public Location CodeFixLocatioin { get; }
+public Location CodeFixLocation { get; }

26-26: Update property assignment to match corrected property name

Since the property name should be corrected, the assignment in the constructor needs to be updated as well.

-            CodeFixLocatioin = codeFixLocatioin;
+            CodeFixLocation = codeFixLocatioin;

18-18: Update parameter name to match corrected property name

The parameter name in the constructor should also be updated to match the corrected property name.

-        public PluginClassInfo(Location location, string className, string propertyName, bool isStatic, bool isPrivate, bool isProtected, Location codeFixLocatioin)
+        public PluginClassInfo(Location location, string className, string propertyName, bool isStatic, bool isPrivate, bool isProtected, Location codeFixLocation)
Flow.Launcher.Localization.Analyzers/Localize/ContextAvailabilityAnalyzer.cs (1)

60-60: Update property references to match corrected property name

Since the property name in PluginClassInfo should be corrected from CodeFixLocatioin to CodeFixLocation, references to it should be updated accordingly.

-                        pluginClassInfo.CodeFixLocatioin
+                        pluginClassInfo.CodeFixLocation

Also applies to: 69-69

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6171e92 and 70820fc.

📒 Files selected for processing (6)
  • Flow.Launcher.Localization.Analyzers/Localize/ContextAvailabilityAnalyzer.cs (3 hunks)
  • Flow.Launcher.Localization.Shared/Classes.cs (1 hunks)
  • Flow.Launcher.Localization.Shared/Flow.Launcher.Localization.Shared.csproj (1 hunks)
  • Flow.Launcher.Localization.Shared/Helper.cs (2 hunks)
  • Flow.Launcher.Localization.SourceGenerators/Localize/LocalizeSourceGenerator.cs (1 hunks)
  • Flow.Launcher.Localization.Analyzers/Localize/ContextAvailabilityAnalyzerCodeFixProvider.cs (4 hunks)
🔇 Additional comments (13)
Flow.Launcher.Localization.Shared/Flow.Launcher.Localization.Shared.csproj (1)

11-11:

✅ Verification successful

Confirm necessity of switched package reference.

Switching from a generic Roslyn package to Microsoft.CodeAnalysis.CSharp is logically consistent given the new C#-specific features in the shared classes. Please ensure there's no lingering dependency on Microsoft.CodeAnalysis.Common in the rest of the codebase that could cause build or analyzer issues.


🏁 Script executed:

#!/bin/bash
# Searches the entire codebase for references to Microsoft.CodeAnalysis.Common
rg --json "Microsoft\.CodeAnalysis\.Common"

Length of output: 301


Verified: No lingering dependency on Microsoft.CodeAnalysis.Common

I searched the entire repository for any references to Microsoft.CodeAnalysis.Common (including within all csproj files) and found none. This confirms that switching to a C#-specific package reference is appropriate and won’t cause any build or analyzer issues.

  • File in question: Flow.Launcher.Localization.Shared/Flow.Launcher.Localization.Shared.csproj (line 11)
  • The package reference <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.13.0" /> correctly replaces the generic Roslyn dependency.
Flow.Launcher.Localization.Shared/Helper.cs (2)

1-6: Namespaces align well with Roslyn requirements.

These imports are consistent with the Roslyn Analyzer APIs used elsewhere in the file. No issues detected.


78-82:

❓ Verification inconclusive

Verify that DeclaringSyntaxReferences collection is never empty.

GetDeclaredSymbol(property)?.DeclaringSyntaxReferences[0] is assumed valid. If a reflection-based scenario or unusual syntax tree state returns an empty array, this could throw an index error. Ensure that property is always a valid Roslyn symbol, to avoid potential runtime exceptions.


🏁 Script executed:

#!/bin/bash
# Collect declarations of Properties that might lack references
ast-grep --pattern $'property_declaration' | rg -A 5 'DeclaringSyntaxReferences'

Length of output: 77


Manual Verification Required: Guard Against Empty DeclaringSyntaxReferences

The current implementation assumes that the symbol returned by semanticModel.GetDeclaredSymbol(property) always has at least one entry in its DeclaringSyntaxReferences collection. Since no evidence was found confirming this assumption (and our initial command produced no output), please manually verify that for all property declarations, the following holds true:

  • semanticModel.GetDeclaredSymbol(property) is non-null.
  • The DeclaringSyntaxReferences collection is never empty before accessing its first element.

If there is any risk of the collection being empty (for example, in reflection-based scenarios or when the syntax tree is in an unusual state), consider adding a safeguard such as a length check or a null-check before trying to index the array.

Flow.Launcher.Localization.SourceGenerators/Localize/LocalizeSourceGenerator.cs (1)

59-60: Great reuse of shared method.

Replacing localized plugin checks with Helper.GetPluginClassInfo consolidates logic and simplifies maintenance. This direct call aligns with the new shared architecture.

Flow.Launcher.Localization.Shared/Classes.cs (1)

1-28: Good implementation of the PluginClassInfo class

The class is well-structured with proper encapsulation, immutable properties, and a clear purpose. Moving this to a shared project is a good decision since it's now usable by both the analyzer and source generator.

Flow.Launcher.Localization.Analyzers/Localize/ContextAvailabilityAnalyzerCodeFixProvider.cs (3)

20-87: Good organization with region directives

Adding region directives to organize the code improves readability and maintainability. The CodeFixProvider region appropriately encapsulates the core provider functionality.


89-152: Well-organized fix methods region

The "Fix Methods" region groups related functionality together, making the code more navigable.


153-197: Appropriate utility methods extraction

Moving GetStaticContextPropertyDeclaration and GetFormattedDocument to a "Utils" region makes the code more organized and highlights their reusable nature.

Flow.Launcher.Localization.Analyzers/Localize/ContextAvailabilityAnalyzer.cs (5)

14-30: Good organization with region directives

Adding region directives for the DiagnosticAnalyzer section improves code readability and organization.


32-34: Well-structured Analyze Methods region

The "Analyze Methods" region appropriately encapsulates the analysis logic separate from the analyzer setup.


46-51: Good refactoring to use PluginClassInfo

Using Helper.GetPluginClassInfo instead of inline detection logic improves code maintainability and reusability. The early return with a descriptive comment is also good practice.


53-76: Well-structured plugin class validation

The code now uses the properties from pluginClassInfo for validation checks, which makes the code more readable and maintainable.


78-102: Good explanatory comments

Adding comments to explain the different validation checks for context properties and fields improves code readability and helps maintain the codebase.

@Jack251970 Jack251970 changed the title Move Plugin class info to Shared project & Add regions Move PluginClassInfo & Add code regions Mar 11, 2025
@Jack251970 Jack251970 requested a review from Yusyuriv March 11, 2025 08:05
@Jack251970 Jack251970 added the enhancement New feature or request label Mar 11, 2025
@Jack251970 Jack251970 requested a review from Yusyuriv March 15, 2025 06:05
@Jack251970 Jack251970 merged commit 24712e5 into main Mar 15, 2025
2 checks passed
@Jack251970 Jack251970 deleted the plugin_class_info branch March 15, 2025 06:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants