| 1 | const std = @import("std"); |
| 2 | const builtin = @import("builtin"); |
| 3 | const expect = std.testing.expect; |
| 4 | const expectEqual = std.testing.expectEqual; |
| 5 | |
| 6 | test "bool literals" { |
| 7 | try expect(true); |
| 8 | try expect(!false); |
| 9 | } |
| 10 | |
| 11 | test "cast bool to int" { |
| 12 | if (builtin.zig_backend == .stage2_riscv64) return error.SkipZigTest; |
| 13 | |
| 14 | const t = true; |
| 15 | const f = false; |
| 16 | try expectEqual(@as(u32, 1), @intFromBool(t)); |
| 17 | try expectEqual(@as(u32, 0), @intFromBool(f)); |
| 18 | try expectEqual(-1, @as(i1, @bitCast(@intFromBool(t)))); |
| 19 | try expectEqual(0, @as(i1, @bitCast(@intFromBool(f)))); |
| 20 | try expectEqual(u1, @TypeOf(@intFromBool(t))); |
| 21 | try expectEqual(u1, @TypeOf(@intFromBool(f))); |
| 22 | try nonConstCastIntFromBool(t, f); |
| 23 | } |
| 24 | |
| 25 | fn nonConstCastIntFromBool(t: bool, f: bool) !void { |
| 26 | try expectEqual(@as(u32, 1), @intFromBool(t)); |
| 27 | try expectEqual(@as(u32, 0), @intFromBool(f)); |
| 28 | try expectEqual(@as(i1, -1), @as(i1, @bitCast(@intFromBool(t)))); |
| 29 | try expectEqual(@as(i1, 0), @as(i1, @bitCast(@intFromBool(f)))); |
| 30 | try expectEqual(u1, @TypeOf(@intFromBool(t))); |
| 31 | try expectEqual(u1, @TypeOf(@intFromBool(f))); |
| 32 | } |
| 33 | |
| 34 | test "bool cmp" { |
| 35 | try expect(testBoolCmp(true, false) == false); |
| 36 | } |
| 37 | fn testBoolCmp(a: bool, b: bool) bool { |
| 38 | return a == b; |
| 39 | } |
| 40 | |
| 41 | const global_f = false; |
| 42 | const global_t = true; |
| 43 | const not_global_f = !global_f; |
| 44 | const not_global_t = !global_t; |
| 45 | test "compile time bool not" { |
| 46 | try expect(not_global_f); |
| 47 | try expect(!not_global_t); |
| 48 | } |
| 49 | |
| 50 | test "short circuit" { |
| 51 | try testShortCircuit(false, true); |
| 52 | try comptime testShortCircuit(false, true); |
| 53 | } |
| 54 | |
| 55 | fn testShortCircuit(f: bool, t: bool) !void { |
| 56 | var hit_1 = f; |
| 57 | var hit_2 = f; |
| 58 | var hit_3 = f; |
| 59 | var hit_4 = f; |
| 60 | |
| 61 | if (t or x: { |
| 62 | try expect(f); |
| 63 | break :x f; |
| 64 | }) { |
| 65 | hit_1 = t; |
| 66 | } |
| 67 | if (f or x: { |
| 68 | hit_2 = t; |
| 69 | break :x f; |
| 70 | }) { |
| 71 | try expect(f); |
| 72 | } |
| 73 | |
| 74 | if (t and x: { |
| 75 | hit_3 = t; |
| 76 | break :x f; |
| 77 | }) { |
| 78 | try expect(f); |
| 79 | } |
| 80 | if (f and x: { |
| 81 | try expect(f); |
| 82 | break :x f; |
| 83 | }) { |
| 84 | try expect(f); |
| 85 | } else { |
| 86 | hit_4 = t; |
| 87 | } |
| 88 | try expect(hit_1); |
| 89 | try expect(hit_2); |
| 90 | try expect(hit_3); |
| 91 | try expect(hit_4); |
| 92 | } |
| 93 | |
| 94 | test "or with noreturn operand" { |
| 95 | const S = struct { |
| 96 | fn foo(a: u32, b: u32) bool { |
| 97 | return a == 5 or b == 2 or @panic("oh no"); |
| 98 | } |
| 99 | }; |
| 100 | _ = S.foo(2, 2); |
| 101 | } |