Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
sclamp.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2025 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
23
24case OP_SCLAMP: {
25 /* Two's complement wrap to signed N-bit range:
26 - Mask to N bits
27 - If sign bit is set, sign-extend to 64-bit
28 This yields values in [-2^(N-1) .. 2^(N-1)-1]. */
29 Value v = pop_value(vm);
30 int bits = inst.operand;
31 int64_t vi = (v.type == VAL_INT) ? v.i : 0;
32
33 int64_t out = 0;
34 if (bits <= 0) {
35 out = 0;
36 } else {
37 uint64_t mask = (bits >= 64) ? UINT64_MAX : ((1ULL << bits) - 1ULL);
38 uint64_t wrapped = ((uint64_t)vi) & mask;
39 if (bits >= 64) {
40 /* 64-bit: already full width; interpret as signed */
41 out = (int64_t)wrapped;
42 } else {
43 uint64_t sign_bit = 1ULL << (bits - 1);
44 if (wrapped & sign_bit) {
45 /* sign-extend */
46 out = (int64_t)(wrapped | (~mask));
47 } else {
48 out = (int64_t)wrapped;
49 }
50 }
51 }
52
55 break;
56}
Value out
Definition apop.c:38
@ OP_SCLAMP
Definition bytecode.h:98
Value v
Definition cast.c:22
int64_t vi
Definition sclamp.c:31
push_value(vm, make_int(out))
uint64_t wrapped
Definition sclamp.c:38
int bits
Definition sclamp.c:30
free_value(v)
Tagged union representing a Fun value.
Definition value.h:68
uint64_t mask
Definition uclamp.c:29
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ VAL_INT
Definition value.h:51