| 1 | const builtin = @import("builtin"); |
| 2 | const std = @import("std"); |
| 3 | const expect = std.testing.expect; |
| 4 | const mem = std.mem; |
| 5 | const reflection = @This(); |
| 6 | |
| 7 | test "reflection: function return type, var args, and param types" { |
| 8 | comptime { |
| 9 | const info = @typeInfo(@TypeOf(dummy)).@"fn"; |
| 10 | try expect(info.return_type.? == i32); |
| 11 | try expect(!info.attrs.varargs); |
| 12 | try expect(info.param_types.len == 3); |
| 13 | try expect(info.param_types[0].? == bool); |
| 14 | try expect(info.param_types[1].? == i32); |
| 15 | try expect(info.param_types[2].? == f32); |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | fn dummy(a: bool, b: i32, c: f32) i32 { |
| 20 | if (false) { |
| 21 | a; |
| 22 | b; |
| 23 | c; |
| 24 | } |
| 25 | return 1234; |
| 26 | } |
| 27 | |
| 28 | test "reflection: @field" { |
| 29 | if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO |
| 30 | |
| 31 | var f = Foo{ |
| 32 | .one = 42, |
| 33 | .two = true, |
| 34 | .three = {}, |
| 35 | }; |
| 36 | |
| 37 | try expect(f.one == f.one); |
| 38 | try expect(@field(f, "o" ++ "ne") == f.one); |
| 39 | try expect(@field(f, "t" ++ "wo") == f.two); |
| 40 | try expect(@field(f, "th" ++ "ree") == f.three); |
| 41 | try expect(@field(Foo, "const" ++ "ant") == Foo.constant); |
| 42 | try expect(@field(Bar, "O" ++ "ne") == Bar.One); |
| 43 | try expect(@field(Bar, "T" ++ "wo") == Bar.Two); |
| 44 | try expect(@field(Bar, "Th" ++ "ree") == Bar.Three); |
| 45 | try expect(@field(Bar, "F" ++ "our") == Bar.Four); |
| 46 | try expect(@field(reflection, "dum" ++ "my")(true, 1, 2) == dummy(true, 1, 2)); |
| 47 | @field(f, "o" ++ "ne") = 4; |
| 48 | try expect(f.one == 4); |
| 49 | } |
| 50 | |
| 51 | const Foo = struct { |
| 52 | const constant = 52; |
| 53 | |
| 54 | one: i32, |
| 55 | two: bool, |
| 56 | three: void, |
| 57 | }; |
| 58 | |
| 59 | const Bar = union(enum) { |
| 60 | One: void, |
| 61 | Two: i32, |
| 62 | Three: bool, |
| 63 | Four: f64, |
| 64 | }; |