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 thiserror to version 2 #1055

Merged
merged 1 commit into from
Nov 30, 2024

Conversation

MarkusPettersson98
Copy link
Contributor

@MarkusPettersson98 MarkusPettersson98 commented Nov 29, 2024

This PR simply upgrades thiserror to the latest major release. My motivation for doing this is to help the ecosystem move towards this new major version since it is a very nice release and a lot of crates depend on it 😊

Summary by CodeRabbit

  • New Features

    • Introduced a new dependency, miette, enhancing error reporting capabilities.
    • Added a method to the Error struct for setting a file path, improving error context.
    • Enhanced the ErrorVariant struct with a method to generate detailed error messages.
  • Bug Fixes

    • Updated the thiserror dependency to a newer version, potentially improving error handling and stability.

@MarkusPettersson98 MarkusPettersson98 requested a review from a team as a code owner November 29, 2024 21:03
@MarkusPettersson98 MarkusPettersson98 requested review from NoahTheDuke and removed request for a team November 29, 2024 21:03
Copy link
Contributor

coderabbitai bot commented Nov 29, 2024

Walkthrough

The pull request introduces updates to the Cargo.toml files for both the pest and pest_debugger packages. The thiserror dependency version is upgraded from "1" to "2" in both packages. Additionally, the pest package sees the introduction of the miette dependency, specified as version 7.2.0 with the feature fancy, included in both the main and development dependencies sections. Furthermore, enhancements to error handling are made in the pest/src/error.rs file by adding new methods to the Error and ErrorVariant structures.

Changes

File Change Summary
debugger/Cargo.toml Updated thiserror dependency version from "1" to "2".
pest/Cargo.toml Updated thiserror dependency version from 1.0.37 to 2. Added miette dependency version 7.2.0 under both [dependencies] and [dev-dependencies] with feature fancy.
pest/src/error.rs Added method with_path to Error struct and method message to ErrorVariant enum for enhanced error handling.

Possibly related PRs

  • feat: added upstream miette support #1038: The changes in this PR involve updating the Cargo.toml file for the pest package to include a new optional dependency on miette, which is relevant as it relates to error handling improvements, similar to the changes made in the main PR regarding the thiserror crate version update.
  • bump version and adjust CI guards #1039: This PR includes updates to the Cargo.toml files for multiple packages, including pest, which also reflects a version bump. While it primarily focuses on version management, it is related to the overall dependency management context of the main PR.

Suggested reviewers

  • tomtau
  • NoahTheDuke

🐰 In the garden, changes bloom,
Dependencies shift, making room.
From one to two, we leap and cheer,
New features sprout, the path is clear.
With miette now, our tools align,
In the world of Rust, we brightly shine! 🌼


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>, 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 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

🧹 Outside diff range and nitpick comments (3)
debugger/Cargo.toml (2)

30-30: Consider updating CHANGELOG and documentation

Since this is a major version upgrade of a core error handling dependency, please ensure that:

  1. The CHANGELOG is updated to reflect this breaking change
  2. Any error-related documentation is reviewed and updated if necessary

30-30: Consider adding miette integration

Since the main pest crate added miette alongside this upgrade, consider if pest_debugger would benefit from miette integration for consistent error reporting across the workspace.

pest/Cargo.toml (1)

31-33: Consider documenting the error handling strategy

With the introduction of miette alongside thiserror v2, it would be valuable to:

  1. Document the intended error handling strategy
  2. Provide migration guidelines for downstream crates
  3. Add examples showing the preferred error handling patterns

Would you like me to help draft documentation for the new error handling approach?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e457389 and 8844bf4.

📒 Files selected for processing (2)
  • debugger/Cargo.toml (1 hunks)
  • pest/Cargo.toml (1 hunks)
🔇 Additional comments (4)
debugger/Cargo.toml (1)

30-30: Verify workspace-wide consistency of thiserror v2 upgrade

The upgrade to thiserror = "2" is a major version bump that could introduce breaking changes.

Let's verify the consistency across the workspace and check for potential breaking changes:

✅ Verification successful

Upgrade to thiserror v2 is consistent across workspace and error types look compatible

The verification shows:

  • All instances of thiserror in the workspace are consistently using version 2
  • Error types in both pest and debugger crates are using standard thiserror derive macros that are compatible with v2
  • The minimum Rust version (1.61) is maintained consistently across the workspace and meets thiserror v2 requirements
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify thiserror version consistency across workspace and check for potential breaking changes

# Check thiserror versions across all Cargo.toml files
echo "Checking thiserror versions across workspace:"
fd Cargo.toml --type f --exec rg -A 1 'thiserror.*='

# Look for potential error type definitions that might need updates
echo -e "\nChecking for error type definitions that might need updates:"
rg -t rust '#\[derive\(.*Error.*\)' -A 5

# Check minimum rust version requirements
echo -e "\nChecking rust-version fields:"
fd Cargo.toml --type f --exec rg 'rust-version.*='

Length of output: 1527

pest/Cargo.toml (3)

33-33: Verify miette configuration and necessity

The miette dependency is added twice with identical configurations:

  1. As an optional regular dependency
  2. As a dev dependency

Consider:

  1. Whether both entries are necessary
  2. If the fancy feature is required in both contexts

Also applies to: 34-34

✅ Verification successful

Miette configuration is appropriate but can be simplified

The dual miette entries serve different purposes:

  1. The optional dependency is correctly used with the miette-error feature for production code
  2. The dev dependency is needed for testing the miette integration (verified in src/error.rs tests)

However, since both entries use identical configuration, they can be consolidated by moving the dev dependency under the optional one with dev = true:

miette = { version = "7.2.0", optional = true, features = ["fancy"], dev = true }

The "fancy" feature is appropriately used as it's needed for the error formatting demonstrated in:

  • examples/parens.rs for pretty error output
  • src/error.rs test assertions that verify the formatted error output
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify miette usage and latest version

# Check latest version
cargo search miette --limit 1

# Look for miette usage in tests vs main code
rg "use.*miette" --type rust

# Check if fancy feature is used
rg "miette.*fancy|fancy.*miette" --type rust

Length of output: 278


Script:

#!/bin/bash
# Let's verify the miette usage more thoroughly

# Check where miette is used in the codebase
rg "miette" --type rust -A 5

# Look for test files using miette
fd "test.*\.rs$" --exec rg "miette" {}

# Check Cargo.toml for miette entries
rg "miette" pest/Cargo.toml

Length of output: 3248


Line range hint 15-24: Review feature flag configuration

The feature flags look well-structured, but let's verify:

  1. The necessity of bundling std, pretty-print, and thiserror in miette-error feature
  2. Whether these feature combinations are tested
✅ Verification successful

Feature flag dependencies are correctly configured

The feature flag configuration is well-structured and the dependencies make sense:

  1. The miette-error feature correctly depends on:

    • std since miette requires standard library features
    • pretty-print for error formatting capabilities
    • thiserror which is consistent with error handling needs
    • miette as the core dependency
  2. The feature is properly used in the codebase:

    • Properly gated in pest/src/error.rs with #[cfg(feature = "miette-error")]
    • Has example usage in pest/examples/parens.rs
    • Imports and uses miette's core functionality (Diagnostic, LabeledSpan, SourceCode)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify feature flag usage and testing

# Look for feature flag testing
rg --type rust "cfg\(feature.*miette" 

# Check if all feature combinations are tested
fd Cargo.toml | xargs rg "features.*test"

Length of output: 378


Script:

#!/bin/bash
# Let's verify the feature dependencies and their usage

# Check the miette-error feature definition in Cargo.toml
rg "miette-error.*=" -A 5 pest/Cargo.toml

# Check where miette is used in the codebase
rg "use.*miette" --type rust

# Look for feature-gated miette imports
rg "#\[cfg\(feature.*miette.*\)\].*use" --type rust -A 1

# Check test files for feature combinations
fd "test.*\.rs$" | xargs rg "cfg\(feature"

Length of output: 4928


31-31: Verify ecosystem compatibility with thiserror v2

The major version upgrade of thiserror could have breaking changes. Let's verify the ecosystem readiness and potential impacts.

✅ Verification successful

Based on the analysis of the codebase, I can now provide a final response:

thiserror v2 upgrade is safe to proceed

The upgrade from thiserror v1 to v2 is safe because:

  • The crate is used correctly with the #[cfg_attr(feature = "std", derive(thiserror::Error))] pattern
  • Error implementations are straightforward and follow thiserror's standard patterns
  • The dependency is optional and only used when the "std" feature is enabled
  • Both pest and pest_debugger crates are already using thiserror v2 consistently
  • The error types are well-encapsulated and not exposed in public APIs that could affect downstream users
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check thiserror v2 adoption and compatibility

# Check latest version and release info
cargo search thiserror --limit 1

# Check reverse dependencies to assess ecosystem impact
cargo search --limit 50 "^thiserror" | grep "thiserror.*v2"

# Look for any potential upgrade issues in the codebase
rg -l 'Error|error' | xargs rg 'derive\(Error\)|impl Error'

Length of output: 350


Script:

#!/bin/bash
# Let's try a different approach to analyze error implementations and thiserror usage

# Find files that use thiserror
rg -l "thiserror"

# Look for Error trait implementations and derives
rg -l "derive\(Error\)" 

# Check Cargo.toml files for thiserror dependencies
fd "Cargo.toml" --exec grep -l "thiserror"

# Look at actual error implementations
rg "#\[derive\(Error\)\]" -A 3 -B 1

Length of output: 236


Script:

#!/bin/bash
# Let's examine the actual error implementations and thiserror usage

# Check error.rs content to understand error types
cat pest/src/error.rs

# Look at debugger lib.rs for error usage
cat debugger/src/lib.rs

# Check both Cargo.toml files to understand dependency relationships
cat pest/Cargo.toml
cat debugger/Cargo.toml

Length of output: 55264

@tomtau tomtau enabled auto-merge (squash) November 30, 2024 00:09
Copy link
Contributor

@tomtau tomtau left a comment

Choose a reason for hiding this comment

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

it seems this very slightly changed the error formatting in the miette output: https://github.com/pest-parser/pest/actions/runs/12090563797/job/33720850291?pr=1055#step:6:286
could you adjust the expected output?

@MarkusPettersson98
Copy link
Contributor Author

Looking into it!

auto-merge was automatically disabled November 30, 2024 09:51

Head branch was pushed to by a user without write access

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

🧹 Outside diff range and nitpick comments (3)
pest/src/error.rs (3)

Line range hint 281-285: Consider changing with_path to take &mut self instead of consuming self.

The with_path method currently takes ownership of self (mut self), which consumes the Error instance. This may not be necessary and could prevent callers from reusing the Error instance after setting the path. Consider changing the method signature to take a mutable reference &mut self to modify the instance in place without consuming it.

Apply this diff to adjust the method:

-pub fn with_path(mut self, path: &str) -> Error<R> {
+pub fn with_path(&mut self, path: &str) {
     self.path = Some(path.to_owned());

-    self
 }

This change allows the method to modify the existing Error instance without consuming it, enhancing usability and aligning with Rust conventions for builder patterns when ownership transfer is not needed.


Line range hint 382-399: Move documentation comments outside the method body in ErrorVariant::message.

The documentation comments for the message method are placed inside the method body. In Rust, doc comments (///) should be placed directly above the method signature to ensure proper association with the method and correct generation of external documentation.

Apply this diff to correct the documentation placement:

+    /// Returns the error message for [`ErrorVariant`].
+    ///
+    /// If [`ErrorVariant`] is [`CustomError`], it returns a
+    /// [`Cow::Borrowed`] reference to the `message`. If [`ErrorVariant`] is [`ParsingError`], a
+    /// [`Cow::Owned`] message is constructed indicating expected and unexpected tokens.
+    ///
+    /// [`ErrorVariant`]: enum.ErrorVariant.html
+    /// [`CustomError`]: enum.ErrorVariant.html#variant.CustomError
+    /// [`ParsingError`]: enum.ErrorVariant.html#variant.ParsingError
+    /// [`Cow::Owned`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html#variant.Owned
+    /// [`Cow::Borrowed`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html#variant.Borrowed
+    ///
     pub fn message(&self) -> Cow<'_, str> {
-        ///
-        /// Returns the error message for [`ErrorVariant`]
-        ///
-        /// If [`ErrorVariant`] is [`CustomError`], it returns a
-        /// [`Cow::Borrowed`] reference to [`message`]. If [`ErrorVariant`] is [`ParsingError`], a
-        /// [`Cow::Owned`] containing "expected [ErrorVariant::ParsingError::positives] [ErrorVariant::ParsingError::negatives]" is returned.
-        ///
-        /// [`ErrorVariant`]: enum.ErrorVariant.html
-        /// [`CustomError`]: enum.ErrorVariant.html#variant.CustomError
-        /// [`ParsingError`]: enum.ErrorVariant.html#variant.ParsingError
-        /// [`Cow::Owned`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html#variant.Owned
-        /// [`Cow::Borrowed`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html#variant.Borrowed
-        /// [`message`]: enum.ErrorVariant.html#variant.CustomError.field.message
-        /// # Examples
-        ///
-        /// ```
-        /// # use pest::error::ErrorVariant;
-        /// let variant = ErrorVariant::<()>::CustomError {
-        ///     message: String::from("unexpected error")
-        /// };
-        ///
-        /// println!("{}", variant.message());
+        // Method implementation...
         match self {

This adjustment ensures that doc comments are correctly associated with the message method and will be included in generated documentation.


Line range hint 1173-1185: Fix the syntax error in the miette_error test function.

There's a syntax error in the assert_eq! macro within the miette_error test function. The format string and the variables are improperly specified, leading to a compilation error.

Apply this diff to correct the syntax:

             format!("{:?}", miette_error),
-            [
-                "",
-                "  \u{1b}[31m×\u{1b}[0m Failure to parse at {:?}", self.0.line_col),
-                "   ╭────",
-                " \u{1b}[2m1\u{1b}[0m │ def",
-                "   · \u{1b}[35;1m┬\u{1b}[0m",
-                "   · \u{1b}[35;1m╰── \u{1b}[35;1munexpected 4, 5, or 6; expected 1, 2, or 3\u{1b}[0m\u{1b}[0m",
-                "   ╰────",
-                "\u{1b}[36m  help: \u{1b}[0munexpected 4, 5, or 6; expected 1, 2, or 3\n"
-            ]
-            .join("\n")
+            format!(
+                "{}\n  \u{1b}[31m×\u{1b}[0m Failure to parse at {:?}\n   ╭────\n \u{1b}[2m1\u{1b}[0m │ def\n   · \u{1b}[35;1m┬\u{1b}[0m\n   · \u{1b}[35;1m╰── \u{1b}[35;1munexpected 4, 5, or 6; expected 1, 2, or 3\u{1b}[0m\u{1b}[0m\n   ╰────\n\u{1b}[36m  help: \u{1b}[0munexpected 4, 5, or 6; expected 1, 2, or 3\n",
+                "",
+                error.line_col()
+            ),

This modification ensures that the format string is correctly constructed and the variable error.line_col() is properly interpolated.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8844bf4 and d8d5da7.

📒 Files selected for processing (3)
  • debugger/Cargo.toml (1 hunks)
  • pest/Cargo.toml (1 hunks)
  • pest/src/error.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • debugger/Cargo.toml
  • pest/Cargo.toml

@tomtau tomtau merged commit 14d96d8 into pest-parser:master Nov 30, 2024
9 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.

2 participants