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

Add arithmetic right shift to stdlib #629

Merged
merged 2 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions examples/pos/bitshifts.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
0
4
16
14
60
0
1
32
8
4
4
3
0
-2
-8
-64
-1
-1
-2
-2
-8
-2
-32
-1
33 changes: 33 additions & 0 deletions examples/pos/bitshifts.effekt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
def main() = {
// + << +
println(0.bitwiseShl(1)) // 0
println(1.bitwiseShl(2)) // 4
println(2.bitwiseShl(3)) // 16
println(7.bitwiseShl(1)) // 14
println(15.bitwiseShl(2)) // 60

// + >> +
println(1.bitwiseShr(1)) // 0
println(8.bitwiseShr(3)) // 1
println(1024.bitwiseShr(5)) // 32
println(16.bitwiseShr(1)) // 8
println(16.bitwiseShr(2)) // 4
println(32.bitwiseShr(3)) // 4
println(7.bitwiseShr(1)) // 3
println(3.bitwiseShr(2)) // 0

// - >> +
println(-1.bitwiseShl(1)) // -2
println(-2.bitwiseShl(2)) // -8
println(-8.bitwiseShl(3)) // -64

// - << +
println(-1.bitwiseShr(1)) // -1
println(-2.bitwiseShr(1)) // -1
println(-4.bitwiseShr(1)) // -2
println(-8.bitwiseShr(2)) // -2
println(-16.bitwiseShr(1)) // -8
println(-16.bitwiseShr(3)) // -2
println(-1024.bitwiseShr(5)) // -32
println(-1.bitwiseShr(30)) // -1
}
8 changes: 8 additions & 0 deletions libraries/common/effekt.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -550,11 +550,19 @@ def infixAnd { first: => Bool } { second: => Bool }: Bool =

// Bitwise operations
// ==================

/// Arithmetic left shift
extern pure def bitwiseShl(x: Int, y: Int): Int =
js "(${x} << ${y})"
chez "(ash ${x} ${y})"
llvm "%z = shl %Int ${x}, ${y} ret %Int %z"

/// Arithmetic right shift
extern pure def bitwiseShr(x: Int, y: Int): Int =
js "(${x} >> ${y})"
chez "(ash ${x} (- ${y}))"
llvm "%z = ashr %Int ${x}, ${y} ret %Int %z"

extern pure def bitwiseAnd(x: Int, y: Int): Int =
js "(${x} & ${y})"
chez "(logand ${x} ${y})"
Expand Down