Skip to content

if wip#380

Merged
thedavidmeister merged 3 commits into
mainfrom
2025-07-23-if
Jul 25, 2025
Merged

if wip#380
thedavidmeister merged 3 commits into
mainfrom
2025-07-23-if

Conversation

@thedavidmeister
Copy link
Copy Markdown
Contributor

@thedavidmeister thedavidmeister commented Jul 23, 2025

Motivation

Solution

Checks

By submitting this for review, I'm confirming I've done the following:

  • made this PR as small as possible
  • unit-tested any new functionality
  • linked any relevant issues or PRs
  • included screenshots (if this involves a front-end change)

Summary by CodeRabbit

  • New Features

    • Introduced a new "if" operation that uses floating-point logic for conditional evaluation.
  • Bug Fixes

    • Improved input and output validation for the "if" operation, ensuring correct behavior and error handling for invalid input/output lengths.
  • Tests

    • Added comprehensive tests for the new "if" operation, including integrity checks and runtime evaluation.
    • Removed legacy tests for the old "if" operation implementation.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 23, 2025

Walkthrough

This update replaces the "if" operation implementation from LibOpIfNP to LibOpIf, updating all relevant references, metadata, and function pointers to use the new floating-point based version. The test suite for the old implementation is removed and replaced with a new suite for LibOpIf, verifying integrity and runtime behavior with the new float logic.

Changes

File(s) Change Summary
src/lib/op/LibAllStandardOps.sol Switched all references from LibOpIfNP to LibOpIf, incremented op count, updated metadata and function arrays
src/lib/op/logic/LibOpIf.sol Renamed library, refactored to use Float type and float-based zero checks, updated signatures and logic
test/src/lib/op/logic/LibOpIf.t.sol Added new test contract for LibOpIf covering integrity and float-based runtime behavior
test/src/lib/op/logic/LibOpIfNP.t.sol Removed old test contract for LibOpIfNP

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Interpreter
    participant LibOpIf

    User->>Interpreter: Executes "if" opcode
    Interpreter->>LibOpIf: Calls run() with stack (Float values)
    LibOpIf->>LibOpIf: Checks condition using Float.isZero()
    LibOpIf-->>Interpreter: Returns result (true/false branch as Float)
    Interpreter-->>User: Returns final output
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Possibly related PRs

  • 2025 07 16 iszero #366: Replaces and upgrades the "is-zero" operation from LibOpIsZeroNP to LibOpIsZero with floating-point stack handling, following a similar pattern of opcode replacement and integration.
  • 2025 07 20 gte #373: Upgrades "greater-than-or-equal-to" and "less-than-or-equal-to" operations from NP variants to float-based versions, updating metadata and tests in a manner analogous to this PR.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c7be90e and e15ef86.

📒 Files selected for processing (1)
  • test/src/lib/op/logic/LibOpIf.t.sol (1 hunks)
🔇 Additional comments (1)
test/src/lib/op/logic/LibOpIf.t.sol (1)

36-113: Great test coverage for the refactored LibOpIf operation!

The runtime logic tests and core conditional logic tests that were previously missing have been properly implemented. The test suite now comprehensively covers:

  • Runtime execution verification
  • Zero/non-zero condition handling
  • Edge cases like zero with exponents
  • String input behavior
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2025-07-23-if

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d33dafc and e4dd208.

⛔ Files ignored due to path filters (3)
  • src/generated/Rainterpreter.pointers.sol is excluded by !**/generated/**
  • src/generated/RainterpreterExpressionDeployer.pointers.sol is excluded by !**/generated/**
  • src/generated/RainterpreterParser.pointers.sol is excluded by !**/generated/**
📒 Files selected for processing (4)
  • src/lib/op/LibAllStandardOps.sol (6 hunks)
  • src/lib/op/logic/LibOpIf.sol (2 hunks)
  • test/src/lib/op/logic/LibOpIf.t.sol (1 hunks)
  • test/src/lib/op/logic/LibOpIfNP.t.sol (0 hunks)
💤 Files with no reviewable changes (1)
  • test/src/lib/op/logic/LibOpIfNP.t.sol
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: thedavidmeister
PR: rainlanguage/rain.interpreter#360
File: src/lib/op/erc20/LibOpERC20Allowance.sol:0-0
Timestamp: 2025-07-15T11:31:28.010Z
Learning: In the rainlanguage/rain.interpreter project, forge (Foundry's formatting tool) handles code formatting automatically, so formatting-related suggestions are not actionable.
Learnt from: 0xgleb
PR: rainlanguage/rain.interpreter#333
File: .github/workflows/git-clean.yaml:4-7
Timestamp: 2025-06-07T11:15:44.415Z
Learning: In GitHub workflows for the rainlanguage/rain.interpreter repository, maintain consistency between workflow files when implementing concurrency controls. The user prefers using `${{ github.ref }}` over `${{ github.ref_name }}` for concurrency group naming to ensure consistency across all workflow files (git-clean.yaml and rainix.yaml).
test/src/lib/op/logic/LibOpIf.t.sol (1)

Learnt from: thedavidmeister
PR: #368
File: test/src/lib/op/math/uint256/LibOpUint256Mul.t.sol:56-69
Timestamp: 2025-07-17T14:15:14.886Z
Learning: In multiplication overflow detection tests like LibOpUint256MulTest, when performing sequential multiplication (a * b * c * d...), encountering a zero value means the final result will always be zero regardless of subsequent values. Since zero multiplied by any value (including MAX_UINT256) cannot overflow, it's safe and correct to break out of the overflow detection loop early when zero is encountered.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: rainix (ubuntu-latest, test-wasm-build)
  • GitHub Check: rainix (macos-latest, rainix-rs-test)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-static)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-test)
  • GitHub Check: rainix (ubuntu-latest, rainix-sol-test)
  • GitHub Check: rainix (ubuntu-latest, rainix-sol-static)
  • GitHub Check: rainix (macos-latest, rainix-rs-artifacts)
  • GitHub Check: rainix (ubuntu-latest, rainix-sol-artifacts)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-artifacts)
  • GitHub Check: git-clean
🔇 Additional comments (5)
src/lib/op/LibAllStandardOps.sol (2)

57-57: Import change looks good.

The import has been correctly updated from LibOpIfNP to LibOpIf to reflect the new implementation.


112-112: ALL_STANDARD_OPS_LENGTH matches actual operations count.

Verified that there are 56 active AuthoringMetaV2 entries in the wordsFixed initializer (excluding the placeholder), which aligns with ALL_STANDARD_OPS_LENGTH = 56. No changes required.

src/lib/op/logic/LibOpIf.sol (2)

8-9: Good use of Float type for condition evaluation.

The switch to Float type and LibDecimalFloat provides better handling of decimal values and floating-point zero semantics compared to raw integer checks.


39-47: Reference implementation correctly matches runtime behavior.

The reference function properly implements the conditional logic using the ternary operator. Note that when the condition is zero, it returns inputs[2] (third value), and when non-zero, it returns inputs[1] (second value), which matches the runtime implementation.

test/src/lib/op/logic/LibOpIf.t.sol (1)

20-37: Integrity test is comprehensive.

The test properly validates that the operation always requires exactly 3 inputs and produces 1 output, regardless of operand data.

Comment on lines +227 to +230
AuthoringMetaV2(
"if",
"If the first input is nonzero, the second input is used. Otherwise, the third input is used. If is eagerly evaluated."
),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Metadata description needs clarification.

The description states "If is eagerly evaluated" which is important but could be clearer. Consider expanding to explain that both the true and false branches are evaluated before the condition is checked, which differs from short-circuit evaluation.

-            AuthoringMetaV2(
-                "if",
-                "If the first input is nonzero, the second input is used. Otherwise, the third input is used. If is eagerly evaluated."
-            ),
+            AuthoringMetaV2(
+                "if",
+                "If the first input is nonzero, the second input is used. Otherwise, the third input is used. Both branches are eagerly evaluated before the condition is checked."
+            ),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AuthoringMetaV2(
"if",
"If the first input is nonzero, the second input is used. Otherwise, the third input is used. If is eagerly evaluated."
),
AuthoringMetaV2(
"if",
"If the first input is nonzero, the second input is used. Otherwise, the third input is used. Both branches are eagerly evaluated before the condition is checked."
),
🤖 Prompt for AI Agents
In src/lib/op/LibAllStandardOps.sol around lines 227 to 230, the metadata
description for "if" is unclear about eager evaluation. Update the description
to explicitly state that both the true and false branches are evaluated before
the condition is checked, clarifying that this differs from short-circuit
evaluation. Make the explanation concise but clear to improve understanding.

Comment on lines 24 to 37
function run(InterpreterState memory, OperandV2, Pointer stackTop) internal pure returns (Pointer) {
Float condition;
assembly ("memory-safe") {
let condition := mload(stackTop)
condition := mload(stackTop)
stackTop := add(stackTop, 0x40)
mstore(stackTop, mload(sub(stackTop, mul(0x20, iszero(iszero(condition))))))
}

bool isZero = condition.isZero();

assembly ("memory-safe") {
mstore(stackTop, mload(sub(stackTop, mul(0x20, iszero(isZero)))))
}
return stackTop;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Complex stack manipulation logic needs clarification.

The assembly block at line 34 uses a double negation pattern (iszero(isZero)) which makes the logic harder to follow. The current implementation selects between the values at different stack offsets based on the condition.

Consider adding a comment to clarify the stack layout and selection logic.

 bool isZero = condition.isZero();
 
 assembly ("memory-safe") {
+    // If condition is zero (isZero=true), select the third value (offset 0)
+    // If condition is non-zero (isZero=false), select the second value (offset -0x20)
     mstore(stackTop, mload(sub(stackTop, mul(0x20, iszero(isZero)))))
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function run(InterpreterState memory, OperandV2, Pointer stackTop) internal pure returns (Pointer) {
Float condition;
assembly ("memory-safe") {
let condition := mload(stackTop)
condition := mload(stackTop)
stackTop := add(stackTop, 0x40)
mstore(stackTop, mload(sub(stackTop, mul(0x20, iszero(iszero(condition))))))
}
bool isZero = condition.isZero();
assembly ("memory-safe") {
mstore(stackTop, mload(sub(stackTop, mul(0x20, iszero(isZero)))))
}
return stackTop;
}
function run(InterpreterState memory, OperandV2, Pointer stackTop) internal pure returns (Pointer) {
Float condition;
assembly ("memory-safe") {
condition := mload(stackTop)
stackTop := add(stackTop, 0x40)
}
bool isZero = condition.isZero();
assembly ("memory-safe") {
// If condition is zero (isZero=true), select the third value (offset 0)
// If condition is non-zero (isZero=false), select the second value (offset -0x20)
mstore(stackTop, mload(sub(stackTop, mul(0x20, iszero(isZero)))))
}
return stackTop;
}
🤖 Prompt for AI Agents
In src/lib/op/logic/LibOpIf.sol around lines 24 to 37, the assembly code uses a
double negation pattern with iszero(isZero) that makes the stack manipulation
logic hard to understand. Add a clear comment explaining the stack layout and
how the selection between stack values is performed based on the condition,
describing why the offset is adjusted by mul(0x20, iszero(isZero)) and what
values are being chosen.

Comment thread test/src/lib/op/logic/LibOpIf.t.sol Outdated
Comment thread test/src/lib/op/logic/LibOpIf.t.sol Outdated
Copy link
Copy Markdown
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: 2

♻️ Duplicate comments (1)
test/src/lib/op/logic/LibOpIf.t.sol (1)

47-113: Add tests for core conditional logic.

While the error cases and edge cases are well tested, there are no tests verifying the basic if-then-else functionality with different numeric conditions.

Add test cases to verify:

  1. When condition is non-zero (truthy), the second input is returned
  2. When condition is zero (falsy), the third input is returned
  3. Different representations of zero (0, 0.0, 0e18) are handled correctly

Example test to add:

/// Test basic if-then-else with non-zero condition
function testOpIfEvalNonZeroCondition() external {
    checkHappy("_: if(1 10 20);", Float.unwrap(LibDecimalFloat.packLossless(10, 0)), "");
}

/// Test basic if-then-else with zero condition
function testOpIfEvalZeroCondition() external {
    checkHappy("_: if(0 10 20);", Float.unwrap(LibDecimalFloat.packLossless(20, 0)), "");
}

/// Test with decimal zero
function testOpIfEvalDecimalZero() external {
    checkHappy("_: if(0.0 10 20);", Float.unwrap(LibDecimalFloat.packLossless(20, 0)), "");
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e4dd208 and c7be90e.

📒 Files selected for processing (1)
  • test/src/lib/op/logic/LibOpIf.t.sol (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: rainix (macos-latest, rainix-rs-artifacts)
  • GitHub Check: rainix (macos-latest, rainix-rs-test)
  • GitHub Check: git-clean

Comment thread test/src/lib/op/logic/LibOpIf.t.sol
Comment thread test/src/lib/op/logic/LibOpIf.t.sol
@thedavidmeister thedavidmeister merged commit cff75d7 into main Jul 25, 2025
11 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.

1 participant