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

fix: remove narrowing conversion from std::size_t to int #3932

Merged
merged 3 commits into from
Dec 5, 2024

Conversation

AJPfleger
Copy link
Contributor

@AJPfleger AJPfleger commented Dec 2, 2024

I went through the cases, where we did cast<int> from std::size_t and implemented solutions to avoid this.

closes:

Summary by CodeRabbit

  • Bug Fixes

    • Improved type safety in various algorithms by changing loop index types from int to std::size_t.
    • Enhanced clarity in boundary condition checks within algorithms.
  • Documentation

    • Corrected comments for clarity in the DigitizationAlgorithm class.
  • Chores

    • Streamlined conditional logic in the IndexedGridFiller and RefittingAlgorithm classes for better readability and maintenance.

@AJPfleger AJPfleger added this to the next milestone Dec 2, 2024
Copy link

coderabbitai bot commented Dec 2, 2024

Walkthrough

Changes made enhance type safety and clarity in several components of the codebase. The IndexedGridFiller.cpp file simplifies the logic for calculating boundary values. The DigitizationAlgorithm.hpp file corrects a typo and improves type safety in a loop. Adjustments in RefittingAlgorithm.cpp and TrackFittingAlgorithm.cpp ensure safe comparisons between signed and unsigned integers. Lastly, UncorrelatedHitSmearer.hpp updates loop indices to std::size_t, promoting type safety. No alterations to public entity declarations were made.

Changes

File Path Change Summary
Core/src/Detector/detail/IndexedGridFiller.cpp Simplified logic for bmin and bmax calculations; removed unnecessary type casting.
Examples/Algorithms/Digitization/include/ActsExamples/Digitization/DigitizationAlgorithm.hpp Corrected comment typo; updated loop variable type from int to std::size_t.
Examples/Algorithms/TrackFitting/src/RefittingAlgorithm.cpp Enhanced type safety in execute method; ensured proper clearing of vectors before processing.
Examples/Algorithms/TrackFitting/src/TrackFittingAlgorithm.cpp Updated type handling in execute method for m_cfg.pickTrack comparison.
Fatras/include/ActsFatras/Digitization/UncorrelatedHitSmearer.hpp Changed loop index type from int to std::size_t in smearing functions.

Possibly related issues

Possibly related PRs

Suggested labels

Component - Plugins, automerge, Track Finding

Suggested reviewers

  • dimitra97
  • paulgessinger

In code we trust, with types so bright,
Yoda's wisdom guides us right.
Simplified logic, clarity gained,
In the realm of code, no more strained.
With safety in mind, our paths align,
Together we code, our futures 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.

@github-actions github-actions bot added Component - Core Affects the Core module Component - Fatras Affects the Fatras module Component - Examples Affects the Examples module Track Fitting labels Dec 2, 2024
Copy link

github-actions bot commented Dec 2, 2024

📊: Physics performance monitoring for 78e3315

Full contents

physmon summary

@AJPfleger AJPfleger marked this pull request as ready for review December 2, 2024 19:50
@AJPfleger AJPfleger linked an issue Dec 2, 2024 that may be closed by this pull request
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: 0

🧹 Outside diff range and nitpick comments (4)
Fatras/include/ActsFatras/Digitization/UncorrelatedHitSmearer.hpp (1)

89-89: Approve this change, I do! Hmmmm.

Wise choice it is, to use std::size_t for array indexing. Safer path this leads to, preventing dark side of narrowing conversions it does. Aligned with container's natural size type, this change now is.

Remember young padawan, when dealing with containers in future code:

  • Use std::size_t for sizes and indices, you must
  • Avoid narrowing conversions to signed types, you shall
  • Let the container's natural types guide you, always
Core/src/Detector/detail/IndexedGridFiller.cpp (1)

73-76: Simplify the understep calculation, we can.

Correct the logic is, but simpler it could be. A refactor suggestion, I have.

-      if (bmin <= expand) {
-        std::size_t understep = expand - bmin;
-        fill_linear(nBins - understep, nBins);
-      }
+      if (bmin <= expand) {
+        fill_linear(nBins - (expand - bmin), nBins);
+      }
Examples/Algorithms/TrackFitting/src/RefittingAlgorithm.cpp (1)

67-68: A pattern in the Force, I sense.

Consistent with TrackFittingAlgorithm.cpp, this change is. Type safety through static_cast to std::size_t, wisdom brings.

Consider a common utility function for track picking logic, share this pattern across algorithms we should.

Examples/Algorithms/TrackFitting/src/TrackFittingAlgorithm.cpp (1)

106-107: Consistent with RefittingAlgorithm.cpp, this change is.

The same pattern of type safety improvement, I observe. Yet, duplicate this logic across files, we should not.

Extract this common pattern into a utility function, we should:

// In a common header file
inline bool shouldProcessTrack(std::int64_t pickTrack, std::size_t currentTrack) {
    return pickTrack <= -1 || static_cast<std::size_t>(pickTrack) == currentTrack;
}

Then use it in both algorithms:

-    if (m_cfg.pickTrack > -1 &&
-        static_cast<std::size_t>(m_cfg.pickTrack) != itrack) {
+    if (!shouldProcessTrack(m_cfg.pickTrack, itrack)) {
       continue;
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c4c5f95 and 77b8243.

📒 Files selected for processing (5)
  • Core/src/Detector/detail/IndexedGridFiller.cpp (1 hunks)
  • Examples/Algorithms/Digitization/include/ActsExamples/Digitization/DigitizationAlgorithm.hpp (2 hunks)
  • Examples/Algorithms/TrackFitting/src/RefittingAlgorithm.cpp (1 hunks)
  • Examples/Algorithms/TrackFitting/src/TrackFittingAlgorithm.cpp (1 hunks)
  • Fatras/include/ActsFatras/Digitization/UncorrelatedHitSmearer.hpp (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Examples/Algorithms/Digitization/include/ActsExamples/Digitization/DigitizationAlgorithm.hpp
🔇 Additional comments (3)
Fatras/include/ActsFatras/Digitization/UncorrelatedHitSmearer.hpp (1)

Line range hint 89-101: Strong with the Force, this implementation is!

Robust error handling observe I do:

  • Gracefully propagate errors through Result type, it does
  • Maintain existing safety checks, it continues to do
  • Clear and maintainable, the code remains

A balanced approach to type safety and error handling, achieved you have.

Core/src/Detector/detail/IndexedGridFiller.cpp (2)

50-54: Improved type safety in boundary calculations, hmmmm.

Removed narrowing conversions, safer the code now is. Direct comparison with std::size_t, cleaner and more explicit it becomes.


61-61: Verify the closed case boundary condition, we must.

Changed the condition has been, from static_cast to direct comparison. Ensure correct behavior across boundary cases, we should.

✅ Verification successful

Correct and safe, the boundary condition is, hmmmm.

Found the implementation context I have, and clear it is that the condition handles boundary cases with wisdom:

  • Checks for sufficient bin space it does (2 * span < nBins)
  • Guards against overflow it does (bmax + expand <= nBins)
  • Protects against underflow it does (bmin > expand)
  • Falls back to safe linear filling when conditions not met, it does

The Force is strong with this code change, as direct size_t comparison more natural it is than casting to int. Maintain the same logical safeguards it does, while cleaner it becomes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for tests covering the closed case boundary condition
rg -l "AxisBoundaryType::Closed.*binSequence" --type cpp

Length of output: 58


Script:

#!/bin/bash
# Search for tests related to IndexedGridFiller and boundary conditions
rg -l "IndexedGridFiller.*test" --type cpp

# Search for any test files containing "Closed" and "Grid"
rg -l "Closed.*Grid.*test|Grid.*Closed.*test" --type cpp

# Look for the actual implementation of closed case handling
ast-grep --pattern 'if ($$$span$$$nBins$$$) {
  $$$
}'  Core/src/Detector/detail/IndexedGridFiller.cpp -A 10

Length of output: 213


Script:

#!/bin/bash
# Search for test files in Tests directory
fd "test.*\.cpp$" Tests/

# Look for the implementation context
rg -B 5 -A 10 "2 \* span < nBins" Core/src/Detector/detail/IndexedGridFiller.cpp

# Find any usage of IndexedGridFiller
rg -l "IndexedGridFiller" --type cpp

Length of output: 22231

@kodiakhq kodiakhq bot merged commit 4b27593 into acts-project:main Dec 5, 2024
48 checks passed
@AJPfleger AJPfleger deleted the int-casts branch December 5, 2024 17:03
@github-actions github-actions bot removed the automerge label Dec 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component - Core Affects the Core module Component - Examples Affects the Examples module Component - Fatras Affects the Fatras module Track Fitting
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Address casting from unsigned to signed types across the codebase
4 participants