From a61b1c2f5a010dd070b4749e27087b729ae50deb Mon Sep 17 00:00:00 2001 From: Thomas Coratger <60488569+tcoratger@users.noreply.github.com> Date: Fri, 22 Mar 2024 14:34:15 +0100 Subject: [PATCH] Fix `MaybeRelocatable` subtraction to unlock `if_reloc_equal` (#491) * Unlock if_reloc_equal by fixing mayberelocatable sub * add unit test --- src/integration_tests.zig | 4 +--- src/vm/memory/relocatable.zig | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/integration_tests.zig b/src/integration_tests.zig index 663b9640..f493be39 100644 --- a/src/integration_tests.zig +++ b/src/integration_tests.zig @@ -103,9 +103,7 @@ pub fn main() void { .{ .pathname = "cairo_programs/if_and_prime.json", .layout = "all_cairo" }, .{ .pathname = "cairo_programs/if_in_function.json", .layout = "all_cairo" }, .{ .pathname = "cairo_programs/if_list.json", .layout = "all_cairo" }, - - // TODO: panic: integer overflow - // .{ .pathname = "cairo_programs/if_reloc_equal.json", .layout = "all_cairo" }, + .{ .pathname = "cairo_programs/if_reloc_equal.json", .layout = "all_cairo" }, // TODO: panic index out of bounds // .{ .pathname = "cairo_programs/integration_with_alloc_locals.json", .layout = "all_cairo" }, // TODO: panic index outt of bound diff --git a/src/vm/memory/relocatable.zig b/src/vm/memory/relocatable.zig index 29672ce2..cb908c29 100644 --- a/src/vm/memory/relocatable.zig +++ b/src/vm/memory/relocatable.zig @@ -551,7 +551,12 @@ pub const MaybeRelocatable = union(enum) { // If `other` is also `relocatable`, call `sub` method on `self_value` .relocatable => |r| blk: { if (self_value.segment_index == r.segment_index) { - break :blk MaybeRelocatable.fromInt(u64, self_value.offset - r.offset); + const res: i128 = @as(i128, self_value.offset) - @as(i128, r.offset); + + break :blk if (res < 0) + MaybeRelocatable.fromFelt(Felt252.fromInt(u128, @intCast(-res)).neg()) + else + MaybeRelocatable.fromFelt(Felt252.fromInt(u128, @intCast(res))); } break :blk CairoVMError.TypeMismatchNotRelocatable; @@ -1492,3 +1497,16 @@ test "MaybeRelocatable.mul: should return Felt multiplication operation if both (try result2.intoFelt()).toInteger(), ); } + +test "MaybeRelocatable.sub: wiht negative relocatable subtraction" { + const a = MaybeRelocatable.fromSegment(4, 0); + const b = MaybeRelocatable.fromSegment(4, 5); + + try expectEqual( + MaybeRelocatable.fromInt( + u256, + 3618502788666131213697322783095070105623107215331596699973092056135872020476, + ), + try a.sub(b), + ); +}