From 86adc1ef39ed12ebe9eb6d3b7cf8eea481dd060d Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 12 Jun 2018 19:38:59 -0400 Subject: [PATCH] add docs and missing test case for merging error sets See #367 --- doc/langref.html.in | 45 ++++++++++++++++++++++++++++++++- test/behavior.zig | 1 + test/cases/merge_error_sets.zig | 21 +++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 test/cases/merge_error_sets.zig diff --git a/doc/langref.html.in b/doc/langref.html.in index 3a7dbd1e9..290ed77e7 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -3117,7 +3117,50 @@ test "error union" { comptime assert(@typeOf(foo).ErrorSet == error); } {#code_end#} -

TODO the || operator for error sets

+ {#header_open|Merging Error Sets#} +

+ Use the || operator to merge two error sets together. The resulting + error set contains the errors of both error sets. Doc comments from the left-hand + side override doc comments from the right-hand side. In this example, the doc + comments for C.PathNotFound is A doc comment. +

+

+ This is especially useful for functions which return different error sets depending + on {#link|comptime#} branches. For example, the Zig standard library uses + LinuxFileOpenError || WindowsFileOpenError for the error set of opening + files. +

+ {#code_begin|test#} +const A = error{ + NotDir, + + /// A doc comment + PathNotFound, +}; +const B = error{ + OutOfMemory, + + /// B doc comment + PathNotFound, +}; + +const C = A || B; + +fn foo() C!void { + return error.NotDir; +} + +test "merge error sets" { + if (foo()) { + @panic("unexpected"); + } else |err| switch (err) { + error.OutOfMemory => @panic("unexpected"), + error.PathNotFound => @panic("unexpected"), + error.NotDir => {}, + } +} + {#code_end#} + {#header_close#} {#header_open|Inferred Error Sets#}

Because many functions in Zig return a possible error, Zig supports inferring the error set. diff --git a/test/behavior.zig b/test/behavior.zig index 3341fe717..eb8b643bb 100644 --- a/test/behavior.zig +++ b/test/behavior.zig @@ -31,6 +31,7 @@ comptime { _ = @import("cases/incomplete_struct_param_tld.zig"); _ = @import("cases/ir_block_deps.zig"); _ = @import("cases/math.zig"); + _ = @import("cases/merge_error_sets.zig"); _ = @import("cases/misc.zig"); _ = @import("cases/namespace_depends_on_compile_var/index.zig"); _ = @import("cases/new_stack_call.zig"); diff --git a/test/cases/merge_error_sets.zig b/test/cases/merge_error_sets.zig new file mode 100644 index 000000000..189bd16a4 --- /dev/null +++ b/test/cases/merge_error_sets.zig @@ -0,0 +1,21 @@ +const A = error{ + PathNotFound, + NotDir, +}; +const B = error{OutOfMemory}; + +const C = A || B; + +fn foo() C!void { + return error.NotDir; +} + +test "merge error sets" { + if (foo()) { + @panic("unexpected"); + } else |err| switch (err) { + error.OutOfMemory => @panic("unexpected"), + error.PathNotFound => @panic("unexpected"), + error.NotDir => {}, + } +}