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

Expand :|| and :! #47

Merged
merged 4 commits into from
Nov 12, 2024
Merged

Expand :|| and :! #47

merged 4 commits into from
Nov 12, 2024

Conversation

jackalcooper
Copy link
Contributor

@jackalcooper jackalcooper commented Nov 11, 2024

  • expand :|| and :!
  • cast condition to i1 in if

Summary by CodeRabbit

  • New Features

    • Introduced support for the logical OR operator :|| in binary operations.
    • Added new functions for integer addition with improved error handling: add_or_error_with_cond_br and add.
    • Enhanced handling of negation with the new expand_macro function for the Kernel.! operator.
  • Bug Fixes

    • Enhanced type safety in binary operations and conditional expressions to prevent type mismatches.
  • Documentation

    • Updated tests to reflect new function signatures and improved error handling.

Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The pull request introduces several modifications to the Charms.Defm.Expander and Charms.Prelude modules, enhancing the handling of MLIR operations, binary operations, and error management. Key changes include reordering parameters in functions for unique MLIR variables and parameters, the addition of a negation macro, and type safety improvements in conditional expressions. Additionally, the Charms.Prelude module now supports the logical OR operator and includes enhanced type validation. The test suite has also been updated to reflect these changes, with new functions for integer addition and improved error handling.

Changes

File Change Summary
lib/charms/defm/expander.ex - Reordered parameters in uniq_mlir_var and uniq_mlir_params functions.
- Added expand_macro for Kernel.! operator for negation.
- Modified expand_if_clause_body for type safety.
lib/charms/prelude.ex - Updated @binary_ops to include `:
test/defm_test.exs - Added AddTwoInt module with add_or_error_with_cond_br and add functions for integer addition.
- Updated tests to reflect new function signatures and improved error handling.

Possibly related PRs

  • Update state.remotes when expanding calls #26: The changes in the Charms.Defm.Expander module regarding the handling of MLIR operations and the expansion of Elixir AST are directly related to the modifications made in the main PR, which also focuses on the Charms.Defm.Expander module and its functions.
  • Remove variables with charms_internal_ prefix in expander's quotes #30: This PR also modifies the Charms.Defm.Expander module, particularly with the introduction of new private functions for unique variable handling, which aligns with the changes in the main PR that involve function signature updates and enhancements in the same module.
  • Attach custom diagnostic server in JIT and expander #44: The introduction of a custom diagnostic server in the JIT and expander modules enhances error handling, which is relevant to the improvements made in the main PR regarding error reporting and handling in the Charms.Defm.Expander module.
  • Uncomment assertions of locals #46: The modifications to the Charms.Defm.Expander module, particularly in the context of error handling and macro expansion, are relevant to the changes made in the main PR, which also focuses on enhancing the structure and clarity of the code in the same module.

🐰 In the land of code, where rabbits play,
New functions hop in, brightening the day.
With XOR for negation, and checks that are tight,
Our MLIR's ready, all set for flight!
So let's add and expand, with joy in our hearts,
For each little change, a new journey starts! 🐇✨


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: 3

🧹 Outside diff range and nitpick comments (3)
lib/charms/prelude.ex (1)

29-33: Consider extracting duplicated type validation logic

The integer type validation logic is duplicated between wrap_arg and constant_of_same_type. Consider extracting this into a private helper function.

Here's a suggested refactor:

+ defp validate_integer_type!(t) do
+   if MLIR.CAPI.mlirTypeIsAInteger(t) |> Beaver.Native.to_term() do
+     :ok
+   else
+     raise ArgumentError, "Not an integer type, #{to_string(t)}"
+   end
+ end

  defp constant_of_same_type(i, v, opts) do
    mlir ctx: opts[:ctx], block: opts[:block] do
      t = MLIR.CAPI.mlirValueGetType(v)
-     if MLIR.CAPI.mlirTypeIsAInteger(t) |> Beaver.Native.to_term() do
-       Arith.constant(value: Attribute.integer(t, i)) >>> t
-     else
-       raise ArgumentError, "Not an integer type for constant, #{to_string(t)}"
-     end
+     validate_integer_type!(t)
+     Arith.constant(value: Attribute.integer(t, i)) >>> t
    end
  end

  defp wrap_arg({i, t}, opts) when is_integer(i) do
    mlir ctx: opts[:ctx], block: opts[:block] do
      case i do
        %MLIR.Value{} -> i
        i when is_integer(i) ->
-         if MLIR.CAPI.mlirTypeIsAInteger(t) |> Beaver.Native.to_term() do
-           Arith.constant(value: Attribute.integer(t, i)) >>> t
-         else
-           raise ArgumentError, "Not an integer type, #{to_string(t)}"
-         end
+         validate_integer_type!(t)
+         Arith.constant(value: Attribute.integer(t, i)) >>> t
      end
    end
  end
test/defm_test.exs (2)

105-110: Consider adding edge case tests

While the basic functionality is tested, consider adding tests for:

  • Maximum integer values to verify overflow handling
  • Negative numbers for add0 (which requires positive numbers)
  • Multiple error cases for add_or_error

Example test cases to add:

# Test maximum integer handling
assert_raise ArgumentError, fn -> 
  AddTwoInt.add(System.max_integer(), 1).(engine) 
end

# Test negative number handling for add0
assert_raise ArgumentError, fn -> 
  AddTwoInt.add0(-1, 2).(engine) 
end

Line range hint 146-163: Consider more specific error message patterns

The current regex patterns are quite broad. Consider making them more specific to catch exact error conditions while still maintaining flexibility.

Example of more specific pattern:

-~r"Failed to expand macro Elixir.DifferentCalls.something/1.+function something not found in module DifferentCalls"
+~r"Failed to expand macro Elixir\.DifferentCalls\.something/1.*function something not found in module DifferentCalls$"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2773941 and 61f500b.

📒 Files selected for processing (3)
  • lib/charms/defm/expander.ex (9 hunks)
  • lib/charms/prelude.ex (3 hunks)
  • test/defm_test.exs (5 hunks)
🔇 Additional comments (11)
lib/charms/prelude.ex (3)

13-18: LGTM! Good type safety improvement

The added type validation ensures that constants are only created for integer types, with a clear error message. This is a good defensive programming practice.


65-67: LGTM! Clean implementation of logical OR

The implementation of :|| using Arith.ori follows the established pattern of other binary operators and maintains consistency in the codebase.


8-8: LGTM, but verify :! operator implementation

The addition of :|| to @binary_ops is correct. However, the PR objectives mention expanding both :|| and :! operators, but :! is not included in the binary operators list.

Let's check if :! is implemented elsewhere:

test/defm_test.exs (1)

5-27: Consider adding memory cleanup for allocated pointers

The function allocates memory for pointers but doesn't explicitly free them. While LLVM might handle this automatically, it's worth verifying the memory management strategy.

Consider implementing a with-cleanup pattern or ensuring the runtime properly handles pointer cleanup.

lib/charms/defm/expander.ex (7)

282-284: Proper usage of uniq_mlir_var with updated parameter order

The function uniq_mlir_var is correctly called with the new parameter order (val, state), which aligns with the updated function signature.


473-473: Consistent usage of uniq_mlir_params with updated parameter order

The call to uniq_mlir_params(args, state) reflects the updated parameter order, maintaining consistency throughout the code.


695-709: Effective exception handling in prelude intrinsic expansion

The try...rescue block appropriately handles exceptions during the expansion of prelude intrinsics. The error message provides clear and informative feedback, aiding in debugging any issues that may arise.


1286-1286: Consistent usage of uniq_mlir_params with updated parameter order

The function uniq_mlir_params is correctly used with (args, state), maintaining consistency with the updated function signature.


1322-1322: Appropriate use of uniq_mlir_params in local function expansion

The call to uniq_mlir_params(args, state) in expand_local reflects the updated parameter order, ensuring consistency across the codebase.


1409-1409: Correct application of uniq_mlir_var in beam_env_from_defm!

The function uniq_mlir_var(e, state) is used correctly, adhering to the updated parameter order.


1420-1426: Overloaded uniq_mlir_var functions enhance flexibility

The introduction of an overloaded uniq_mlir_var/0 function complements the existing uniq_mlir_var/2 function. This provides flexibility in generating unique MLIR variables both with and without initial values.

test/defm_test.exs Outdated Show resolved Hide resolved
lib/charms/defm/expander.ex Show resolved Hide resolved
lib/charms/defm/expander.ex Outdated Show resolved Hide resolved
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: 2

🧹 Outside diff range and nitpick comments (1)
test/defm_test.exs (1)

105-110: Add test cases for boundary conditions and overflow

The current test suite should be expanded to include:

  1. Integer overflow scenarios
  2. Boundary value testing (MIN_INT, MAX_INT)
  3. Edge cases for add0's positive number requirement

Consider adding these test cases:

# Test integer overflow
assert_raise ArgumentError, fn -> AddTwoInt.add(9223372036854775807, 1).(engine) end

# Test boundary values
assert AddTwoInt.add(-9223372036854775808, 0).(engine) == -9223372036854775808
assert AddTwoInt.add(9223372036854775807, 0).(engine) == 9223372036854775807

# Test add0 with zero and negative numbers
assert_raise ArgumentError, fn -> AddTwoInt.add0(0, 1).(engine) end
assert_raise ArgumentError, fn -> AddTwoInt.add0(-1, 1).(engine) end
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f939796 and 85d01d1.

📒 Files selected for processing (1)
  • test/defm_test.exs (5 hunks)
🔇 Additional comments (1)
test/defm_test.exs (1)

64-89: LGTM! Well-structured error message assertions

The use of dynamic line numbers and regex patterns makes the tests more maintainable and robust.

test/defm_test.exs Outdated Show resolved Hide resolved
test/defm_test.exs Outdated Show resolved Hide resolved
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)
test/defm_test.exs (3)

5-27: Consider refactoring error handling approach

The conditional branching approach using cond_br is more complex than necessary. The simpler if-else pattern used in the add function achieves the same result with better readability.

Consider simplifying to:

-  defm add_or_error_with_cond_br(env, a, b, error) :: Term.t() do
-    ptr_a = Pointer.allocate(i32())
-    ptr_b = Pointer.allocate(i32())
-
-    arg_err =
-      block do
-        func.return(error)
-      end
-
-    cond_br enif_get_int(env, a, ptr_a) != 0 do
-      cond_br 0 != enif_get_int(env, b, ptr_b) do
-        a = Pointer.load(i32(), ptr_a)
-        b = Pointer.load(i32(), ptr_b)
-        sum = value llvm.add(a, b) :: i32()
-        term = enif_make_int(env, sum)
-        func.return(term)
-      else
-        ^arg_err
-      end
-    else
-      ^arg_err
-    end
-  end
+  defm add_or_error_with_cond_br(env, a, b, error) :: Term.t() do
+    ptr_a = Pointer.allocate(i32())
+    ptr_b = Pointer.allocate(i32())
+
+    if enif_get_int(env, a, ptr_a) != 0 && enif_get_int(env, b, ptr_b) != 0 do
+      a = Pointer.load(i32(), ptr_a)
+      b = Pointer.load(i32(), ptr_b)
+      sum = value llvm.add(a, b) :: i32()
+      enif_make_int(env, sum)
+    else
+      error
+    end
+  end

92-95: Add boundary test cases for integer operations

The current test cases only verify basic addition functionality. Consider adding tests for:

  • Edge cases (MIN_INT32, MAX_INT32)
  • Overflow scenarios
  • Zero value handling

Example additional test cases:

# Test maximum integer values
assert AddTwoInt.add(2_147_483_647, 1).(engine) == -2_147_483_648  # INT32_MAX + 1
# Test minimum integer values
assert AddTwoInt.add(-2_147_483_648, -1).(engine) == 2_147_483_647  # INT32_MIN - 1

131-132: Improve error message pattern matching

The regex pattern for undefined function error could be more specific to avoid potential false matches.

Consider using a more precise pattern:

-~r"Failed to expand macro Elixir.DifferentCalls.something/1.+function something not found in module DifferentCalls"
+~r"^Failed to expand macro Elixir\.DifferentCalls\.something/1.*function something not found in module DifferentCalls$"

Also applies to: 134-134

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 85d01d1 and 6dc5378.

📒 Files selected for processing (1)
  • test/defm_test.exs (5 hunks)
🔇 Additional comments (1)
test/defm_test.exs (1)

6-7: ⚠️ Potential issue

Integer type inconsistency issue

Both functions use i32 which could lead to integer overflow issues. Previous review comments have flagged this inconsistency with i64 usage in other parts of the codebase.

Also applies to: 30-31

@jackalcooper jackalcooper merged commit 97485cf into main Nov 12, 2024
1 check passed
@jackalcooper jackalcooper deleted the not_or_operator branch November 12, 2024 08:12
@coderabbitai coderabbitai bot mentioned this pull request Dec 1, 2024
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