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

Use get_if instead of holds_alternative to avoid repetition #703

Merged
merged 1 commit into from
Sep 29, 2024
Merged

Conversation

elazarg
Copy link
Collaborator

@elazarg elazarg commented Sep 29, 2024

Also some more modernization, a-la #673.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced type safety and clarity in handling Instruction types across various components.
    • Introduced a new static function for calculating lower and upper bounds in memory access.
  • Bug Fixes

    • Streamlined error handling in multiple locations to improve clarity and reduce complexity.
  • Refactor

    • Updated function signatures to pass parameters by reference, enhancing performance.
    • Replaced std::holds_alternative with std::get_if for safer type checking across the codebase.
  • Documentation

    • Improved comments and code structure for better maintainability and readability.

also some more modernization

Signed-off-by: Elazar Gershuni <[email protected]>
Copy link

coderabbitai bot commented Sep 29, 2024

Walkthrough

The pull request introduces a series of changes across multiple source files, primarily focusing on enhancing type safety and clarity in handling Instruction types. Key modifications include replacing std::holds_alternative and std::get with std::get_if for safer type checking, updating function signatures to accept parameters by reference, and improving error handling logic. The changes aim to streamline the code, reduce the risk of exceptions, and maintain existing functionality while ensuring better type handling practices.

Changes

Files Change Summary
src/asm_cfg.cpp Replaced std::holds_alternative and std::get with std::get_if for safer type checking in handling Instruction variants. Updated function signatures to pass parameters by reference for efficiency.
src/asm_marshal.cpp Similar changes to src/asm_cfg.cpp, focusing on using std::get_if for accessing variants and modifying function signatures to accept parameters by reference.
src/asm_ostream.cpp Enhanced type casting, variable declarations, and introduced std::ranges for improved readability. Updated function signatures to accept parameters by reference.
src/asm_ostream.hpp Changed print function signature to accept label_to_print as a reference to improve performance. Updated logic in operator<< for Value type to use std::get_if.
src/asm_unmarshal.cpp Enhanced type safety by adding const qualifiers to function parameters and using static_cast for type conversions. Modified multiple function signatures to accept parameters as const references.
src/assertions.cpp Updated AssertExtractor class methods to accept parameters as constant references. Simplified logic for checking and extracting values from variants using std::get_if.
src/crab/cfg.hpp Modified get_assertions function signature to pass label as a reference for improved performance.
src/crab/ebpf_domain.cpp Refactored access checks and introduced a new static function for calculating bounds. Updated logic to use std::get_if for safer type extraction.
src/crab/fwd_analyzer.cpp Adjusted parameter types to pass by reference for efficiency. Simplified type handling and checks using std::get_if.
src/ebpf_yaml.cpp Modified error handling in run_conformance_test_case to use std::get_if for streamlined error message logging.
src/main/check.cpp Simplified error handling logic in the main function using std::get_if for improved readability.
src/test/test_marshal.cpp Updated vector declarations to a more generic style and simplified error message retrieval using std::get_if.
src/test/test_print.cpp Simplified the retrieval of InstructionSeq from prog_or_error using std::get_if for improved error handling.
src/test/test_verify.cpp Streamlined handling of unmarshal function results by using std::get_if for direct access to InstructionSeq.

Possibly related PRs

🐇 In a world of types and checks so fine,
A rabbit hops through code, feeling divine.
With std::get_if, the path is clear,
No more holds or gets to fear!
Efficiency blooms, clarity reigns,
In the garden of code, joy remains! 🌸


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

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

🧹 Outside diff range comments (1)
src/test/test_print.cpp (1)

Line range hint 1-73: Consider further modernization opportunities

While the current changes effectively modernize the variant handling, there are a couple of additional areas where modern C++ features could potentially be applied:

  1. The PRINT_CASE macro could be replaced with a function template using std::source_location (C++20) for improved debugging information. This would provide more precise location information and make the code more type-safe.

  2. File path handling could be improved using std::filesystem (C++17) for more robust and portable path manipulations. This would replace string concatenations with more idiomatic path operations.

These suggestions are not directly related to the current PR's scope but could be considered for future modernization efforts.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 6842a10 and 36d07f6.

📒 Files selected for processing (14)
  • src/asm_cfg.cpp (9 hunks)
  • src/asm_marshal.cpp (4 hunks)
  • src/asm_ostream.cpp (11 hunks)
  • src/asm_ostream.hpp (2 hunks)
  • src/asm_unmarshal.cpp (31 hunks)
  • src/assertions.cpp (5 hunks)
  • src/crab/cfg.hpp (1 hunks)
  • src/crab/ebpf_domain.cpp (6 hunks)
  • src/crab/fwd_analyzer.cpp (7 hunks)
  • src/ebpf_yaml.cpp (1 hunks)
  • src/main/check.cpp (1 hunks)
  • src/test/test_marshal.cpp (1 hunks)
  • src/test/test_print.cpp (1 hunks)
  • src/test/test_verify.cpp (3 hunks)
🧰 Additional context used
📓 Learnings (1)
src/crab/ebpf_domain.cpp (1)
Learnt from: elazarg
PR: vbpf/ebpf-verifier#692
File: src/crab/ebpf_domain.cpp:1366-1367
Timestamp: 2024-09-27T00:34:47.474Z
Learning: The project is compiled with C++20.
🪛 cppcheck
src/assertions.cpp

[error] 193-193: Syntax Error

(internalAstError)

src/test/test_marshal.cpp

[performance] 321-321: Function parameter 'expected_error_message' should be passed by const reference.

(passedByValue)

🔇 Additional comments (78)
src/test/test_print.cpp (1)

29-31: Excellent use of std::get_if to simplify variant handling

The changes effectively replace std::holds_alternative and std::get with std::get_if, which aligns with the PR objective. This modification offers several benefits:

  1. It combines the type check and value retrieval into a single operation, reducing code complexity.
  2. It potentially improves efficiency by avoiding multiple accesses to the variant.
  3. It follows modern C++ practices, enhancing code maintainability.

The error handling is appropriately adjusted with the REQUIRE(program != nullptr) check. The subsequent dereference in the print function call is correct given that get_if returns a pointer.

These changes successfully modernize the code and reduce redundancy as intended.

src/asm_ostream.hpp (2)

32-33: Approved: Improved parameter passing for print function

The change from std::optional<const label_t> to const std::optional<const label_t>& for the label_to_print parameter is a good optimization. Passing by const reference avoids unnecessary copies, potentially improving performance, especially for larger label_t types. This change aligns well with modern C++ best practices and the PR's objective of modernizing the codebase.


Line range hint 1-70: Overall assessment: Positive improvements

The changes in this file align well with the PR objectives of modernizing the codebase and reducing repetition. Both modifications (the function signature update and the variant handling improvement) contribute to better performance and more idiomatic C++ code. These changes enhance the overall quality of the codebase without introducing any apparent issues.

src/crab/fwd_analyzer.cpp (8)

22-22: Improved efficiency in constructor parameter passing

The change from label_t to const label_t& in the constructor parameter is a good optimization. It avoids unnecessary copying and follows best practices for passing non-primitive types.


51-51: Simplified type alias declaration

The removal of the typename keyword in the iterator type alias is correct and simplifies the code. This change maintains the same functionality while making the code more concise.


77-77: Optimized parameter passing in extrapolate method

Changing the first parameter from ebpf_domain_t to const ebpf_domain_t& is a good optimization. It avoids unnecessary copying and clearly indicates that the parameter won't be modified within the function.


87-87: Consistent optimization in refine method

The change from ebpf_domain_t to const ebpf_domain_t& for the first parameter is consistent with the extrapolate method. This optimization improves efficiency and maintains a clear indication of the parameter's immutability within the function.


128-129: Improved variant handling with std::get_if

The change from std::holds_alternative and std::get to std::get_if is an excellent improvement. It simplifies the code by combining the type check and value retrieval into a single operation, making it more concise and potentially more efficient. This change also provides a safer way to access the variant by returning a pointer, which can be easily checked for nullness.

This modification aligns well with the PR objective of replacing holds_alternative with get_if to reduce redundancy.


193-194: Consistent improvement in variant handling

The change to use std::get_if instead of std::holds_alternative and std::get is consistent with the earlier modification in the run_forward_analyzer function. This change simplifies the code, provides safer variant access, and aligns with the PR objective of reducing redundancy.


214-215: Consistent application of variant handling improvement

This change to use std::get_if is consistent with the previous modifications in the file. It further demonstrates a thorough application of this improvement throughout the codebase, enhancing readability and safety while supporting the PR's objective of reducing redundancy.


Line range hint 1-232: Summary of changes and overall assessment

The changes in this file consistently improve code efficiency and safety, particularly in the areas of:

  1. Parameter passing optimization (using const references)
  2. Simplified type alias declarations
  3. Enhanced variant handling using std::get_if

These modifications align well with the PR objectives, reducing redundancy and modernizing the code. The changes are applied consistently throughout the file, demonstrating a thorough approach to the improvement.

Overall, these changes enhance the code quality without altering its core functionality. No issues or concerns were identified during this review.

src/main/check.cpp (1)

223-224: Excellent use of std::get_if for concise error handling

This change effectively replaces the previous holds_alternative check with get_if, as per the PR objective. The new implementation is more concise and potentially more efficient, combining the type check and value retrieval into a single operation. It maintains the same error handling logic while improving code readability.

src/asm_marshal.cpp (4)

112-114: Improved type safety with std::get_if

The use of std::get_if here is a good improvement. It combines the check for the correct variant type and access to its value in a single, safe operation. This change reduces the chance of errors and improves code readability.


312-314: Improved efficiency and consistency in size function

The changes to the size function are beneficial:

  1. Taking a const reference (const Instruction&) instead of a value improves efficiency by avoiding unnecessary copies.
  2. Using std::get_if is consistent with the changes made elsewhere in the file and provides a safe way to check and access the Bin variant.

These modifications enhance both performance and code consistency.


312-312: Improved efficiency in size function signature

The change in the size function signature from static int size(Instruction inst) to static int size(const Instruction& inst) is a good improvement. Taking a const reference instead of a value avoids unnecessary copying of the Instruction object, which can lead to better performance, especially if Instruction is a larger struct.

This change is consistent with modern C++ best practices and aligns well with the modifications made within the function body.


Line range hint 1-349: Overall improvements in type safety, readability, and efficiency

The changes made to this file consistently improve the code quality:

  1. The use of std::get_if throughout the file enhances type safety when accessing variants.
  2. The modifications to the size function, both in its signature and body, improve efficiency by avoiding unnecessary copies.
  3. The changes make the code more readable and consistent with modern C++ best practices.

These improvements align well with the PR objectives of reducing redundancy and modernizing the codebase. The changes should lead to more robust and maintainable code.

src/asm_cfg.cpp (9)

22-23: Improved type safety and code simplicity

The change from std::holds_alternative to std::get_if is a good improvement. It combines type checking and value retrieval into a single operation, which is both safer and more concise. This modification reduces the risk of exceptions and simplifies the code.


55-56: Consistent improvement in type safety

The change to use std::get_if in the add_cfg_nodes function is consistent with the previous modifications. This continues to improve type safety and simplify the code throughout the file.


76-79: Consistent application of type-safe checks

The changes in this segment continue the pattern of replacing std::holds_alternative with std::get_if. This consistent application of the new pattern throughout the file is commendable. It not only improves type safety but also makes the code more concise and easier to read.


136-136: Improved parameter constness

The addition of const to the must_have_exit parameter is a good practice. It clearly communicates that the function doesn't modify this value, potentially preventing accidental modifications and improving code readability.


163-164: Improved code efficiency and readability

The change to use auto jump_target = get_jump(inst) is a good improvement. It simplifies the code and potentially improves efficiency by avoiding multiple calls to get_jump. This change also enhances readability by clearly separating the retrieval of the jump target from its usage.


183-184: Consistent application of type-safe checks

The use of std::get_if here maintains consistency with the earlier changes in the file. This continued application of the pattern improves type safety and maintains a consistent coding style throughout the function.


192-192: Improved parameter passing efficiency

The changes to both reverse functions to take their parameters by const reference are good improvements. This can enhance performance by avoiding unnecessary copying, especially for larger structs. While it doesn't change the functionality, it's a good practice that can lead to more efficient code.

Also applies to: 217-217


336-337: Consistent application of type-safe checks

The changes in the collect_stats function to use std::get_if maintain consistency with the modifications made throughout the file. This continued application of the pattern improves type safety and maintains a consistent coding style, which enhances the overall quality and readability of the code.

Also applies to: 341-342, 346-347


Line range hint 1-384: Summary: Successful modernization and improved type safety

The changes made in this file successfully achieve the objectives outlined in the PR description. The consistent replacement of std::holds_alternative with std::get_if throughout the file has several benefits:

  1. Improved type safety by combining type checking and value retrieval.
  2. Reduced code redundancy and improved readability.
  3. Potential performance improvements by avoiding unnecessary function calls.

Additionally, the updates to function signatures to use const references for parameters contribute to better performance and clearer intent.

These modifications align well with modern C++ practices and should make the code more robust and maintainable. Great job on consistently applying these improvements throughout the file!

src/ebpf_yaml.cpp (1)

341-342: Improved error handling using std::get_if

The change from std::holds_alternative<string> to std::get_if<std::string> is a good improvement. This modification:

  1. Reduces code verbosity by combining the type check and value retrieval into a single operation.
  2. Eliminates the potential for exceptions that could be thrown by std::get.
  3. Maintains the same logical flow while making the code more efficient.

This change aligns well with the PR objective of replacing holds_alternative with get_if to avoid repetition.

src/asm_ostream.cpp (7)

Line range hint 123-127: Improved type safety with explicit casting

The use of static_cast<Value>(Imm{0}) instead of directly comparing with Imm{0} enhances type safety and makes the intention clearer. This change aligns with modern C++ best practices for explicit type conversions.


141-143: Enhanced const-correctness

The change from auto to const auto for the op variable improves code clarity and enforces const-correctness. This modification makes the code more self-documenting and helps prevent accidental modifications of the variable.


Line range hint 227-240: Modernized code with std::ranges

The transition from std::find_if to std::ranges::find_if is a positive change that leverages C++20 features. This modification simplifies the syntax, improves readability, and makes the code more concise. It's a good step towards adopting modern C++ practices.


271-272: Consistent application of const-correctness

The consistent change from auto to const auto across multiple variable declarations enhances code clarity and enforces const-correctness. This modification makes the code more self-documenting and helps prevent accidental modifications of the variables. The consistent application of this principle throughout the code is commendable.

Also applies to: 285-301


Line range hint 380-387: Improved performance and type safety

The function signature change to take a const reference (const Instruction&) instead of a copy can improve performance, especially for larger Instruction objects. Additionally, the use of std::get_if provides a safer way to check and access variant types compared to std::holds_alternative. These changes align with modern C++ best practices for performance and type safety.


Line range hint 402-433: Comprehensive improvements in performance, clarity, and type safety

This section demonstrates several positive changes:

  1. The function signature update to take a const reference for label_to_print can improve performance by avoiding unnecessary copies.
  2. Consistent use of const auto improves code clarity and enforces const-correctness.
  3. The introduction of std::get_if provides a safer way to check and access variant types.

These changes collectively align with modern C++ best practices, enhancing performance, clarity, and type safety throughout the code.


Line range hint 1-533: Summary: Successful modernization and improvement of code quality

The changes in this file consistently demonstrate a commitment to modernizing the codebase and improving code quality. Key improvements include:

  1. Enhanced type safety through explicit casting and the use of std::get_if.
  2. Improved const-correctness with consistent use of const auto.
  3. Adoption of modern C++ features like std::ranges.
  4. Performance optimizations by using const references in function parameters.

These changes align well with the PR objectives of reducing redundancy and modernizing the codebase. The modifications make the code more robust, self-documenting, and easier to maintain without altering the core functionality.

src/crab/cfg.hpp (1)

619-619: Approved: Improved parameter passing for get_assertions

The change from std::optional<label_t> label to const std::optional<label_t>& label is a good improvement. Passing the label parameter by const reference instead of by value can enhance performance by avoiding unnecessary copies, especially if label_t is a non-trivial type or if this function is called frequently.

This modification aligns well with modern C++ best practices for passing read-only complex types and contributes to the PR's objective of reducing redundancy and modernizing the codebase. The change is backwards compatible and doesn't affect the function's behavior.

src/asm_unmarshal.cpp (21)

14-15: LGTM: Improved const-correctness

The addition of the const qualifier to the opcode parameter is a good practice. It clearly indicates that the function doesn't modify the input and can potentially help the compiler with optimizations.


25-26: LGTM: Consistent const-correctness improvement

The addition of the const qualifier to the width parameter is consistent with the previous change and improves the overall const-correctness of the codebase.


39-40: LGTM: Improved type safety with static_cast

The change from C-style casts to static_cast<int> is a good improvement. static_cast is safer and more explicit about the conversion being performed. It also allows for better compile-time checking and makes the code more maintainable.


44-46: LGTM: Consistent improvements in const-correctness and type safety

The changes in the make_opcode_message function are well-aligned with the previous improvements. The addition of const qualifiers and the use of static_cast<int> enhance both const-correctness and type safety. These modifications contribute to a more robust and maintainable codebase.


52-54: LGTM: Improved const-correctness and potential performance gain

The modifications to the InvalidInstruction struct constructors are beneficial:

  1. Adding const qualifiers improves const-correctness.
  2. Changing the std::string parameter to a const reference (const std::string&) can improve performance by avoiding unnecessary copying of the string.

These changes contribute to a more efficient and robust implementation.


Line range hint 62-72: LGTM: Consistent const-correctness improvements

The addition of const qualifiers to the opcode parameters in both getMemIsLoad and getMemWidth functions is consistent with the previous changes. This continues to enhance the const-correctness of the codebase, making the functions' intentions clearer and potentially allowing for compiler optimizations.


92-93: LGTM: Enhanced const-correctness and explicit return type

The changes to the shift32 function are positive:

  1. Adding const qualifiers to both parameters improves const-correctness.
  2. Explicitly specifying the return type as Instruction enhances code readability and can help catch potential errors if the return type changes in the future.

These modifications contribute to a more robust and self-documenting codebase.


105-107: LGTM: Improved const-correctness and variable immutability

The changes in the getAluOp function are beneficial:

  1. Adding const qualifiers to both parameters enhances const-correctness.
  2. Declaring the is64 variable as const prevents accidental modifications and clearly communicates that its value should not change after initialization.

These improvements contribute to code safety and can potentially aid compiler optimizations.


229-230: LGTM: Consistent const-correctness improvements

The changes in the getAtomicOp function maintain consistency with previous modifications:

  1. Adding const qualifiers to both parameters enhances const-correctness.
  2. Declaring the op variable as const in the switch statement prevents accidental modifications and clearly communicates that its value should not change after initialization.

These improvements contribute to a more robust and maintainable codebase.


244-246: LGTM: Improved const-correctness and function encapsulation

The changes to the sign_extend and zero_extend functions are beneficial:

  1. Adding const qualifiers to the imm parameters enhances const-correctness.
  2. Marking the functions as static limits their visibility to this translation unit, improving encapsulation. This is particularly useful if these functions are only used within this file, as it prevents name conflicts and clarifies the functions' scope.

These modifications contribute to a more robust and well-structured codebase.


Line range hint 248-262: LGTM: Enhanced type safety and consistent improvements

The changes in the getBinValue function are positive:

  1. Adding const qualifiers to parameters and marking the function as static is consistent with previous improvements.
  2. The use of std::get_if instead of direct comparisons is a significant improvement in type safety. std::get_if returns a pointer to the held value if it exists, or nullptr if it doesn't, providing a safer way to check and access variant types. This change helps prevent potential undefined behavior that could occur with incorrect variant access.

These modifications contribute to a more robust and safer implementation.


Line range hint 263-286: LGTM: Consistent improvements in const-correctness and encapsulation

The changes to the getJmpOp function maintain consistency with previous modifications:

  1. Adding const qualifiers to both parameters enhances const-correctness.
  2. Marking the function as static improves encapsulation by limiting its visibility to this translation unit.

These changes contribute to the overall improvement in code quality and maintainability of the codebase.


Line range hint 286-362: LGTM: Comprehensive improvements in const-correctness and type safety

The changes in the makeMemOp function are substantial and beneficial:

  1. Adding const qualifiers to parameters enhances const-correctness.
  2. Declaring local variables as const (e.g., width, isLD, isLoad, isImm, basereg) prevents accidental modifications and can aid compiler optimizations.
  3. The use of std::get_if for variant access is consistent with previous changes and improves type safety by providing null-checking.

These modifications significantly contribute to the robustness and safety of the code, making it less prone to errors and more maintainable.


Line range hint 393-425: LGTM: Consistent improvements in const-correctness and type safety

The changes in the makeAluOp function maintain consistency with previous modifications:

  1. Adding const qualifiers to parameters enhances const-correctness.
  2. Declaring local variables as const (e.g., is64) prevents accidental modifications and can aid compiler optimizations.
  3. The use of std::get_if for variant access improves type safety by providing implicit null-checking.

These changes contribute to the overall improvement in code quality, maintainability, and type safety of the codebase.


Line range hint 427-466: LGTM: Thorough application of const-correctness

The changes in the makeLddw function demonstrate a comprehensive approach to improving const-correctness:

  1. Adding const qualifiers to most parameters (except insts) enhances const-correctness and clearly communicates which inputs should not be modified.
  2. Declaring local variables as const (e.g., next) prevents accidental modifications and can aid compiler optimizations.

This thorough application of const-correctness contributes to code safety and maintainability by making the function's intentions clearer and reducing the risk of unintended modifications.


Line range hint 467-489: LGTM: Consistent improvements in const-correctness and encapsulation

The changes to the toArgSingleKind and toArgPairKind functions maintain consistency with previous modifications:

  1. Adding const qualifiers to parameters enhances const-correctness.
  2. Marking the functions as static improves encapsulation by limiting their visibility to this translation unit.

These changes contribute to the overall improvement in code quality and maintainability of the codebase, following the pattern established in other functions.


Line range hint 490-554: LGTM: Comprehensive application of const-correctness

The changes in the makeCall function demonstrate a thorough approach to improving const-correctness:

  1. Adding the const qualifier to the imm parameter enhances const-correctness of the function input.
  2. Declaring local variables and the args array as const prevents accidental modifications and can aid compiler optimizations.
  3. The consistent application of const throughout the function body improves code safety and readability.

These modifications contribute significantly to the robustness and maintainability of the code by clearly communicating intentions and reducing the risk of unintended modifications.


558-565: LGTM: Consistent improvements in const-correctness and encapsulation

The changes to the getJumpTarget function maintain consistency with previous modifications:

  1. Adding const qualifiers to all parameters enhances const-correctness.
  2. Marking the function as static improves encapsulation by limiting its visibility to this translation unit.
  3. Declaring new_pc as const prevents accidental modifications and can aid compiler optimizations.

These changes contribute to the overall improvement in code quality, safety, and maintainability of the codebase, following the pattern established in other functions.


Line range hint 568-594: LGTM: Consistent improvements and enhanced type safety

The changes to the makeCallLocal and makeCallx functions are positive and consistent with previous modifications:

  1. Adding const qualifiers to parameters and marking the functions as static enhances const-correctness and encapsulation.
  2. The use of static_cast in makeCallx instead of a C-style cast is a significant improvement in type safety. It's more explicit about the conversion being performed and allows for better compile-time checking.

These modifications contribute to the overall improvement in code quality, maintainability, and type safety of the codebase.


Line range hint 596-816: LGTM: Consistent and comprehensive improvements throughout the file

The changes in the makeJmp function and subsequent code, including the make_call function at the end of the file, demonstrate a consistent approach to improving code quality:

  1. Adding const qualifiers to function parameters enhances const-correctness.
  2. Declaring local variables as const (e.g., is64, op, offset, target, cond) prevents accidental modifications and can aid compiler optimizations.
  3. The use of std::get_if for variant access improves type safety by providing implicit null-checking.

These modifications maintain consistency with the improvements made throughout the entire file, contributing to a more robust, maintainable, and type-safe codebase.


Line range hint 1-818: Overall: Excellent improvements in code quality and safety

The changes made throughout the src/asm_unmarshal.cpp file demonstrate a systematic and thorough approach to improving code quality, safety, and maintainability. Key improvements include:

  1. Consistent application of const qualifiers to function parameters and local variables, enhancing const-correctness.
  2. Improved type safety through the use of static_cast and std::get_if for variant access.
  3. Better encapsulation by marking appropriate functions as static.
  4. More explicit and safer handling of types and conversions.

These changes contribute to a more robust, maintainable, and potentially more performant codebase. The consistent application of these improvements across the entire file indicates a well-planned refactoring effort that will likely make the code easier to reason about and less prone to errors.

Great job on this refactoring effort!

src/test/test_verify.cpp (5)

41-44: Improved code efficiency and readability

The change from using std::holds_alternative and std::get to std::get_if is a good improvement. It simplifies the code by combining the check and retrieval of the InstructionSeq into a single operation, making it more concise and potentially more efficient.


57-60: Consistent improvement in code structure

The changes in this segment mirror those made earlier, consistently replacing std::holds_alternative and std::get with std::get_if. This uniformity in changes enhances the overall code quality and maintainability.


601-604: Consistently applied code improvement

The same pattern of replacing std::holds_alternative and std::get with std::get_if is applied here as well. This consistent application of the new pattern throughout different parts of the file is commendable and aligns well with the PR objectives.


609-612: Comprehensive and consistent code refactoring

This final instance of replacing std::holds_alternative and std::get with std::get_if completes the consistent application of this change throughout the file. These changes collectively contribute to a more streamlined and potentially more efficient codebase, fully aligning with the PR objectives.


Line range hint 41-612: Summary: Successful implementation of PR objectives

The changes made in this file consistently replace the use of std::holds_alternative followed by std::get with std::get_if. This refactoring aligns perfectly with the PR objectives, reducing redundancy and potentially improving code efficiency. The consistent application of this change throughout the file enhances overall code quality and maintainability.

src/test/test_marshal.cpp (1)

302-306: Excellent modernization of the check_unmarshal_fail function!

The changes in this function are well-implemented and align with the PR objectives:

  1. The use of std::vector without explicit type parameters leverages C++17's class template argument deduction (CTAD), which improves code readability.
  2. Replacing std::holds_alternative and std::get with std::get_if simplifies the error checking process and makes the code more concise.

These modifications contribute to a more modern and maintainable codebase.

src/crab/ebpf_domain.cpp (5)

1642-1649: LGTM: New helper function improves code organization.

The new lb_ub_access_pair function is a well-designed addition that encapsulates the logic for calculating lower and upper bounds for access checks. It handles both immediate and register-based width calculations efficiently, which should reduce code duplication and improve maintainability.


Line range hint 1660-1704: LGTM: Improved code organization and consistency in ValidAccess operator.

The changes to the ValidAccess operator improve code organization and consistency by utilizing the new lb_ub_access_pair function. This refactoring simplifies the handling of different memory types (packet, stack, context, shared) while maintaining the existing logic. The minor adjustment in the packet access check, using an empty optional for comparison checks, is a sensible optimization.


1225-1227: LGTM: Improved safety and efficiency in Assume operator.

The changes to the Assume operator enhance both safety and efficiency. The use of std::get_if instead of std::holds_alternative followed by std::get is a more robust approach, reducing the risk of undefined behavior. This change also improves code readability and maintains the existing logic while providing better error handling for unsupported cases.


Line range hint 2013-2023: LGTM: Enhanced safety and efficiency in Mem operator.

The modifications to the Mem operator significantly improve both safety and efficiency. The switch to std::get_if from std::holds_alternative followed by std::get is a more robust approach, minimizing the risk of undefined behavior. This change not only enhances code readability but also maintains the existing logic while providing improved error handling for various cases. The overall structure of the function has been streamlined, making it easier to understand and maintain.


Line range hint 1-3000: Overall improvements enhance code quality and maintainability.

The changes made to src/crab/ebpf_domain.cpp consistently improve the code's safety, efficiency, and readability. Key improvements include:

  1. Introduction of the lb_ub_access_pair function, which reduces code duplication and improves maintainability.
  2. Refactoring of the ValidAccess, Assume, and Mem operators to use more efficient and safer constructs.
  3. Enhanced error handling and code organization throughout the file.

These modifications align well with the project's goals of enhancing the abstract interpretation framework for eBPF programs. The changes should contribute to easier maintenance and potential future extensions of the codebase.

src/assertions.cpp (12)

130-130: Efficient parameter passing by const reference

Passing cond as a const Condition& in explicate avoids unnecessary copies and improves performance.


147-147: Ensure reg_right is valid before use

After safely extracting reg_right, confirm that it is valid before using it in ValidAccess.


151-151: Validate comparability of operands

The Comparable assertion correctly ensures that cond.left and reg_right can be compared. Ensure both registers have been validated.


156-156: Consistent use of const references

Using const Assume& ins in operator() promotes efficiency by avoiding unnecessary copies.


158-161: Simplify conditional logic in operator()(const Jmp& ins)

Properly checks if ins.cond exists before calling explicate, which prevents potential null reference issues.


Line range hint 165-187: Robust memory access validation in operator()(const Mem& ins)

The changes enhance the validation of memory accesses and handle both stack and non-stack pointers appropriately.


181-187: Correct validation for store operations

The nested conditions ensure that, for non-privileged code performing a store operation, the value register is validated based on the width.


210-250: Ensure safe variant extraction in operator()(const Bin& ins)

When extracting from ins.v, the code correctly uses std::get_if<Reg>(&ins.v) to prevent exceptions if ins.v does not hold a Reg.


216-220: Handle potential absence of register operand

In the MOVSX operations, ensure that the case where ins.v is not a Reg is appropriately handled, returning an empty assertion set when necessary.


221-227: Proper assertions for ADD operation operands

The code adds type constraints and check for addable operands, ensuring that addition operations are safe and valid.


228-238: Accurate comparability checks for SUB operation

The assertions correctly enforce that the operands in the subtraction are comparable and handle both pointer and number types.


242-248: Validation of divisors in division operations

By asserting ValidDivisor, the code prevents division by zero and ensures that the divisor is of the correct type for the operation.

src/asm_ostream.hpp Show resolved Hide resolved
src/asm_marshal.cpp Show resolved Hide resolved
src/asm_marshal.cpp Show resolved Hide resolved
src/asm_cfg.cpp Show resolved Hide resolved
src/asm_cfg.cpp Show resolved Hide resolved
src/assertions.cpp Show resolved Hide resolved
src/assertions.cpp Show resolved Hide resolved
src/assertions.cpp Show resolved Hide resolved
src/assertions.cpp Show resolved Hide resolved
src/assertions.cpp Show resolved Hide resolved
@coveralls
Copy link

Coverage Status

coverage: 90.333% (+0.02%) from 90.31%
when pulling 36d07f6 on get_if
into 6842a10 on main.

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