authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-06-12 19:38:59-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-06-12 19:38:59-04:00
log86adc1ef39ed12ebe9eb6d3b7cf8eea481dd060d
treee1c37b84aeadf6cf2948b265f0694bff53cfce79
parent13d3255e2a71836b9981aa4115676c79d41f275f

add docs and missing test case for merging error sets

See #367

3 files changed, 66 insertions(+), 1 deletions(-)

doc/langref.html.in+44-1
......@@ -3117,7 +3117,50 @@ test "error union" {
31173117 comptime assert(@typeOf(foo).ErrorSet == error);
31183118}
31193119 {#code_end#}
3120 <p>TODO the <code>||</code> operator for error sets</p>
3120 {#header_open|Merging Error Sets#}
3121 <p>
3122 Use the <code>||</code> operator to merge two error sets together. The resulting
3123 error set contains the errors of both error sets. Doc comments from the left-hand
3124 side override doc comments from the right-hand side. In this example, the doc
3125 comments for <code>C.PathNotFound</code> is <code>A doc comment</code>.
3126 </p>
3127 <p>
3128 This is especially useful for functions which return different error sets depending
3129 on {#link|comptime#} branches. For example, the Zig standard library uses
3130 <code>LinuxFileOpenError || WindowsFileOpenError</code> for the error set of opening
3131 files.
3132 </p>
3133 {#code_begin|test#}
3134const A = error{
3135 NotDir,
3136
3137 /// A doc comment
3138 PathNotFound,
3139};
3140const B = error{
3141 OutOfMemory,
3142
3143 /// B doc comment
3144 PathNotFound,
3145};
3146
3147const C = A || B;
3148
3149fn foo() C!void {
3150 return error.NotDir;
3151}
3152
3153test "merge error sets" {
3154 if (foo()) {
3155 @panic("unexpected");
3156 } else |err| switch (err) {
3157 error.OutOfMemory => @panic("unexpected"),
3158 error.PathNotFound => @panic("unexpected"),
3159 error.NotDir => {},
3160 }
3161}
3162 {#code_end#}
3163 {#header_close#}
31213164 {#header_open|Inferred Error Sets#}
31223165 <p>
31233166 Because many functions in Zig return a possible error, Zig supports inferring the error set.
test/behavior.zig+1
......@@ -31,6 +31,7 @@ comptime {
3131 _ = @import("cases/incomplete_struct_param_tld.zig");
3232 _ = @import("cases/ir_block_deps.zig");
3333 _ = @import("cases/math.zig");
34 _ = @import("cases/merge_error_sets.zig");
3435 _ = @import("cases/misc.zig");
3536 _ = @import("cases/namespace_depends_on_compile_var/index.zig");
3637 _ = @import("cases/new_stack_call.zig");
test/cases/merge_error_sets.zig created+21
......@@ -0,0 +1,21 @@
1const A = error{
2 PathNotFound,
3 NotDir,
4};
5const B = error{OutOfMemory};
6
7const C = A || B;
8
9fn foo() C!void {
10 return error.NotDir;
11}
12
13test "merge error sets" {
14 if (foo()) {
15 @panic("unexpected");
16 } else |err| switch (err) {
17 error.OutOfMemory => @panic("unexpected"),
18 error.PathNotFound => @panic("unexpected"),
19 error.NotDir => {},
20 }
21}