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

feat: Add error messaging for rule file parsing failures #968

Merged
merged 2 commits into from Mar 7, 2024

Conversation

StevenLove
Copy link
Contributor

@StevenLove StevenLove commented Mar 6, 2024

As stated in #722 the LSP doesn't report errors clearly if there is a problem parsing rule files.

Code structure

In this PR I needed to get the potential Error from find_rules accessible to the LanguageClient in order to report it to the user. I chose to do this by taking the Result<RuleCollection<SgLang>> from find_rules and passing into the Backend struct without unwrapping it. Then any time we need to access the rules inside Backend we just have to pattern match the Result. Handling the error inside Backend is trivial as we just publish no diagnostics and no code actions.

There are other approaches to consider like just calling find_rules from inside Backend instead of passing it into the constructor. Because the logging is async, it is preferable to await the log in one of Backend's async handlers like publish_diagnostics rather than in the Backend::new() constructor. It might belong better in Backend::on_open, but this could depend on which method we choose to alert the user.

How to alert the user

I went with option 1 below, but we can do any combination so let me know what you think.

  1. Show a popup with show_message
Screen Shot 2024-03-05 at 8 48 46 PM
  1. Publish a diagnostic to the top of the file
Screen Shot 2024-03-05 at 9 27 56 PM
  1. Log a message quietly to the output panel with log_message
Screen Shot 2024-03-05 at 9 28 11 PM

Summary by CodeRabbit

  • New Features
    • Enhanced error handling in the language server protocol (LSP) backend for more robust operation.
  • Refactor
    • Improved internal error handling mechanisms using anyhow for clearer, more manageable code.
  • Chores
    • Added anyhow as a dependency to improve error handling capabilities.

Copy link
Contributor

coderabbitai bot commented Mar 6, 2024

Walkthrough

The update introduces anyhow for improved error handling across the language server protocol implementation. Specifically, it focuses on the Backend struct and associated methods within the LSP, ensuring that rule loading and diagnostics are robust against failures by wrapping operations in anyhow::Result. This change streamlines error management and enhances the reliability of the server's functionality.

Changes

Files Changes
crates/lsp/Cargo.toml Added anyhow as a workspace dependency.
crates/lsp/src/... - Backend struct's rules now uses anyhow::Result.
- Improved error handling in various methods.

🐇✨
In the realm of code, where errors hide and seek,
A rabbit hopped in, with a solution unique.
With anyhow in hand, and a hop, skip, and a leap,
It wrapped up the troubles, making the future less bleak.
🌟📜 "To better days ahead," it squeaked.

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-tests 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 tests 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 tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 745ccca and 6e0b477.
Files ignored due to path filters (1)
  • Cargo.lock is excluded by: !**/*.lock
Files selected for processing (3)
  • crates/cli/src/lsp.rs (1 hunks)
  • crates/lsp/Cargo.toml (1 hunks)
  • crates/lsp/src/lib.rs (5 hunks)
Additional comments: 4
crates/lsp/Cargo.toml (1)
  • 16-16: The addition of anyhow as a workspace dependency is appropriate and aligns with the PR's objectives to improve error handling within the LSP component. This change follows best practices for dependency management in Rust projects.
crates/cli/src/lsp.rs (1)
  • 11-11: Storing the result of find_rules in config_result and using it when creating the Backend is a good practice. This change enhances error handling flexibility within the Backend, aligning with the PR's objectives to improve error messaging and handling.
crates/lsp/src/lib.rs (2)
  • 26-26: The modification of the rules field in the Backend struct to hold an anyhow::Result wrapping RuleCollection is a significant improvement. This change enables more graceful error handling related to rule parsing, aligning with the PR's objectives to enhance error messaging and handling.
  • 253-269: The error handling in the publish_diagnostics method, including the use of show_message to display error messages to the user, is well-implemented. This approach effectively communicates parsing errors, aligning with the PR's objectives to enhance error messaging and handling.

Copy link

codecov bot commented Mar 6, 2024

Codecov Report

Attention: Patch coverage is 4.00000% with 24 lines in your changes are missing coverage. Please review.

Project coverage is 71.58%. Comparing base (745ccca) to head (12027b5).

Files Patch % Lines
crates/lsp/src/lib.rs 5.00% 19 Missing ⚠️
crates/cli/src/lsp.rs 0.00% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #968      +/-   ##
==========================================
- Coverage   71.88%   71.58%   -0.31%     
==========================================
  Files          72       72              
  Lines        4706     4726      +20     
==========================================
  Hits         3383     3383              
- Misses       1323     1343      +20     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@StevenLove
Copy link
Contributor Author

I like publishing a diagnostic to a user. If the user is trying to use ast-grep as a linter, they will already be looking for diagnostics so the error is right where they will see it. One challenge is that the diagnostic is visible on every file and we may want to restrict it to only the files that the user is targeting, but in the case of malformed rule files we can't have confidence that we know exactly which languages are targeted.

@@ -239,7 +239,7 @@ fn url_to_code_description(url: &Option<String>) -> Option<CodeDescription> {
}

impl<L: LSPLang> Backend<L> {
pub fn new(client: Client, rules: RuleCollection<L>) -> Self {
pub fn new(client: Client, rules: anyhow::Result<RuleCollection<L>>) -> Self {
Copy link
Member

Choose a reason for hiding this comment

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

This change will assume lsp must be used with anyhow. However, IMHO LSP should be neutral to error handling.
What about Using std::Result<RuleCollection, String> here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have modified the LSP to use std::result::Result and avoid anyhow::Result. The find_rules function still creates an anyhow::Result but before we pass it in to the Backend::new constructor, we convert it into a std::result::Result.

Can you help me understand the cost associated with using the different Results from different libraries? I chose anyhow because it has some convenience functions and it is being used in other parts of the ast-grep rust project (though not in the LSP).

crates/lsp/src/lib.rs Show resolved Hide resolved
@HerringtonDarkholme
Copy link
Member

Thanks for the update!

If the user is trying to use ast-grep as a linter, they will already be looking for diagnostics so the error is right where they will see it

I think it will be too annoying for users to see diagnostics every file. Showing it once on start up will be a better choice.

Also, I notice that currently one rule file error will abort the whole rule collection finding. It is better to have valid rules usable still. I will change the behavior later and keep this PR simple.

@StevenLove
Copy link
Contributor Author

Also, I notice that currently one rule file error will abort the whole rule collection finding. It is better to have valid rules usable still.

I agree and I am looking at ways to achieve this. I was able to quickly change cli/src/config.rs read_directory_yaml to just filter out the rules with errors and call configs.extend() on the good rules. But then we would have swallowed the errors and not reported them to the user. I think it is necessary to maintain both the errors and the good RuleConfigs

We can structure the code such that the RuleCollection (shown below) either adds a new Vec<Error> or all of the RuleConfigs inside of the tenured RuleBucket and ContingentRule are all turned into Result<RuleConfig<L>>

pub struct RuleCollection<L: Language + Eq> {
  tenured: Vec<RuleBucket<L>>,
  contingent: Vec<ContingentRule<L>>,
}

Does that sound right to you?

@HerringtonDarkholme
Copy link
Member

Thanks for researching the code! But let's make the PR simple and small. So just reporting the error to client is good.

Regarding to the error, I will like to have an additional struct to store RuleCollection + errors. So correct code path will not pay extra overhead for rare wrong cases.

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 6e0b477 and 12027b5.
Files selected for processing (2)
  • crates/cli/src/lsp.rs (1 hunks)
  • crates/lsp/src/lib.rs (6 hunks)
Files skipped from review as they are similar to previous changes (2)
  • crates/cli/src/lsp.rs
  • crates/lsp/src/lib.rs

Copy link
Member

@HerringtonDarkholme HerringtonDarkholme left a comment

Choose a reason for hiding this comment

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

thanks!

@HerringtonDarkholme HerringtonDarkholme merged commit 6b3702a into ast-grep:main Mar 7, 2024
2 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants