Skip to content

Commit 66717db

Browse files
committed
replace %return with try
See #632 better fits the convention of using keywords for control flow
1 parent de1f579 commit 66717db

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+812
-803
lines changed

doc/home.html.in

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,10 @@
7575

7676
pub fn main() -> %void {
7777
// If this program is run without stdout attached, exit with an error.
78-
var stdout_file = %return std.io.getStdOut();
78+
var stdout_file = try std.io.getStdOut();
7979
// If this program encounters pipe failure when printing to stdout, exit
8080
// with an error.
81-
%return stdout_file.write("Hello, world!\n");
81+
try stdout_file.write("Hello, world!\n");
8282
}</code></pre>
8383
<p>Build this with:</p>
8484
<pre>zig build-exe hello.zig</pre>
@@ -105,9 +105,9 @@ export fn main(argc: c_int, argv: &amp;&amp;u8) -&gt; c_int {
105105
var x: T = 0;
106106

107107
for (buf) |c| {
108-
const digit = %return charToDigit(c, radix);
109-
x = %return mulOverflow(T, x, radix);
110-
x = %return addOverflow(T, x, digit);
108+
const digit = try charToDigit(c, radix);
109+
x = try mulOverflow(T, x, radix);
110+
x = try addOverflow(T, x, digit);
111111
}
112112

113113
return x;
@@ -234,14 +234,14 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K)-&gt
234234

235235
pub fn put(hm: &amp;Self, key: K, value: V) -&gt; %void {
236236
if (hm.entries.len == 0) {
237-
%return hm.initCapacity(16);
237+
try hm.initCapacity(16);
238238
}
239239
hm.incrementModificationCount();
240240

241241
// if we get too full (60%), double the capacity
242242
if (hm.size * 5 &gt;= hm.entries.len * 3) {
243243
const old_entries = hm.entries;
244-
%return hm.initCapacity(hm.entries.len * 2);
244+
try hm.initCapacity(hm.entries.len * 2);
245245
// dump all of the old elements into the new table
246246
for (old_entries) |*old_entry| {
247247
if (old_entry.used) {
@@ -296,7 +296,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K)-&gt
296296
}
297297

298298
fn initCapacity(hm: &amp;Self, capacity: usize) -&gt; %void {
299-
hm.entries = %return hm.allocator.alloc(Entry, capacity);
299+
hm.entries = try hm.allocator.alloc(Entry, capacity);
300300
hm.size = 0;
301301
hm.max_distance_from_start_index = 0;
302302
for (hm.entries) |*entry| {
@@ -420,7 +420,7 @@ pub fn main() -&gt; %void {
420420
const arg = os.args.at(arg_i);
421421
if (mem.eql(u8, arg, "-")) {
422422
catted_anything = true;
423-
%return cat_stream(&amp;io.stdin);
423+
try cat_stream(&amp;io.stdin);
424424
} else if (arg[0] == '-') {
425425
return usage(exe);
426426
} else {
@@ -431,13 +431,13 @@ pub fn main() -&gt; %void {
431431
defer is.close();
432432

433433
catted_anything = true;
434-
%return cat_stream(&amp;is);
434+
try cat_stream(&amp;is);
435435
}
436436
}
437437
if (!catted_anything) {
438-
%return cat_stream(&amp;io.stdin);
438+
try cat_stream(&amp;io.stdin);
439439
}
440-
%return io.stdout.flush();
440+
try io.stdout.flush();
441441
}
442442

443443
fn usage(exe: []const u8) -&gt; %void {

doc/langref.html.in

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -268,10 +268,10 @@
268268

269269
pub fn main() -&gt; %void {
270270
// If this program is run without stdout attached, exit with an error.
271-
var stdout_file = %return std.io.getStdOut();
271+
var stdout_file = try std.io.getStdOut();
272272
// If this program encounters pipe failure when printing to stdout, exit
273273
// with an error.
274-
%return stdout_file.write("Hello, world!\n");
274+
try stdout_file.write("Hello, world!\n");
275275
}</code></pre>
276276
<pre><code class="sh">$ zig build-exe hello.zig
277277
$ ./hello
@@ -3224,14 +3224,14 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
32243224
// ...
32253225
}</code></pre>
32263226
<p>
3227-
There is a shortcut for this. The <code>%return</code> expression:
3227+
There is a shortcut for this. The <code>try</code> expression:
32283228
</p>
32293229
<pre><code class="zig">fn doAThing(str: []u8) -&gt; %void {
3230-
const number = %return parseU64(str, 10);
3230+
const number = try parseU64(str, 10);
32313231
// ...
32323232
}</code></pre>
32333233
<p>
3234-
<code>%return</code> evaluates an error union expression. If it is an error, it returns
3234+
<code>try</code> evaluates an error union expression. If it is an error, it returns
32353235
from the current function with the same error. Otherwise, the expression results in
32363236
the unwrapped value.
32373237
</p>
@@ -3278,7 +3278,7 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
32783278
Example:
32793279
</p>
32803280
<pre><code class="zig">fn createFoo(param: i32) -&gt; %Foo {
3281-
const foo = %return tryToAllocateFoo();
3281+
const foo = try tryToAllocateFoo();
32823282
// now we have allocated foo. we need to free it if the function fails.
32833283
// but we want to return it if the function succeeds.
32843284
%defer deallocateFoo(foo);
@@ -3928,11 +3928,11 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
39283928
switch (state) {
39293929
State.Start =&gt; switch (c) {
39303930
'{' =&gt; {
3931-
if (start_index &lt; i) %return self.write(format[start_index...i]);
3931+
if (start_index &lt; i) try self.write(format[start_index...i]);
39323932
state = State.OpenBrace;
39333933
},
39343934
'}' =&gt; {
3935-
if (start_index &lt; i) %return self.write(format[start_index...i]);
3935+
if (start_index &lt; i) try self.write(format[start_index...i]);
39363936
state = State.CloseBrace;
39373937
},
39383938
else =&gt; {},
@@ -3943,7 +3943,7 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
39433943
start_index = i;
39443944
},
39453945
'}' =&gt; {
3946-
%return self.printValue(args[next_arg]);
3946+
try self.printValue(args[next_arg]);
39473947
next_arg += 1;
39483948
state = State.Start;
39493949
start_index = i + 1;
@@ -3968,9 +3968,9 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
39683968
}
39693969
}
39703970
if (start_index &lt; format.len) {
3971-
%return self.write(format[start_index...format.len]);
3971+
try self.write(format[start_index...format.len]);
39723972
}
3973-
%return self.flush();
3973+
try self.flush();
39743974
}</code></pre>
39753975
<p>
39763976
This is a proof of concept implementation; the actual function in the standard library has more
@@ -3984,12 +3984,12 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
39843984
and emits a function that actually looks like this:
39853985
</p>
39863986
<pre><code class="zig">pub fn printf(self: &amp;OutStream, arg0: i32, arg1: []const u8) -&gt; %void {
3987-
%return self.write("here is a string: '");
3988-
%return self.printValue(arg0);
3989-
%return self.write("' here is a number: ");
3990-
%return self.printValue(arg1);
3991-
%return self.write("\n");
3992-
%return self.flush();
3987+
try self.write("here is a string: '");
3988+
try self.printValue(arg0);
3989+
try self.write("' here is a number: ");
3990+
try self.printValue(arg1);
3991+
try self.write("\n");
3992+
try self.flush();
39933993
}</code></pre>
39943994
<p>
39953995
<code>printValue</code> is a function that takes a parameter of any type, and does different things depending
@@ -5891,7 +5891,7 @@ TypeExpr = PrefixOpExpression | "var"
58915891

58925892
BlockOrExpression = Block | Expression
58935893

5894-
Expression = ReturnExpression | BreakExpression | AssignmentExpression
5894+
Expression = TryExpression | ReturnExpression | BreakExpression | AssignmentExpression
58955895

58965896
AsmExpression = "asm" option("volatile") "(" String option(AsmOutput) ")"
58975897

@@ -5915,7 +5915,7 @@ AssignmentExpression = UnwrapExpression AssignmentOperator UnwrapExpression | Un
59155915

59165916
AssignmentOperator = "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "&lt;&lt;=" | "&gt;&gt;=" | "&amp;=" | "^=" | "|=" | "*%=" | "+%=" | "-%="
59175917

5918-
BlockExpression(body) = Block | IfExpression(body) | TryExpression(body) | TestExpression(body) | WhileExpression(body) | ForExpression(body) | SwitchExpression | CompTimeExpression(body)
5918+
BlockExpression(body) = Block | IfExpression(body) | IfErrorExpression(body) | TestExpression(body) | WhileExpression(body) | ForExpression(body) | SwitchExpression | CompTimeExpression(body)
59195919

59205920
CompTimeExpression(body) = "comptime" body
59215921

@@ -5929,15 +5929,17 @@ ForExpression(body) = option(Symbol ":") option("inline") "for" "(" Expression "
59295929

59305930
BoolOrExpression = BoolAndExpression "or" BoolOrExpression | BoolAndExpression
59315931

5932-
ReturnExpression = option("%") "return" option(Expression)
5932+
ReturnExpression = "return" option(Expression)
5933+
5934+
TryExpression = "try" Expression
59335935

59345936
BreakExpression = "break" option(":" Symbol) option(Expression)
59355937

59365938
Defer(body) = option("%") "defer" body
59375939

59385940
IfExpression(body) = "if" "(" Expression ")" body option("else" BlockExpression(body))
59395941

5940-
TryExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
5942+
IfErrorExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
59415943

59425944
TestExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body option("else" BlockExpression(body))
59435945

@@ -5987,7 +5989,7 @@ ContainerInitBody = list(StructLiteralField, ",") | list(Expression, ",")
59875989

59885990
StructLiteralField = "." Symbol "=" Expression
59895991

5990-
PrefixOp = "!" | "-" | "~" | "*" | ("&amp;" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%"
5992+
PrefixOp = "!" | "-" | "~" | "*" | ("&amp;" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%" | "try"
59915993

59925994
PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ("error" "." Symbol) | ContainerDecl | ("continue" option(":" Symbol))
59935995

example/cat/main.zig

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,16 @@ const allocator = std.debug.global_allocator;
77

88
pub fn main() -> %void {
99
var args_it = os.args();
10-
const exe = %return unwrapArg(??args_it.next(allocator));
10+
const exe = try unwrapArg(??args_it.next(allocator));
1111
var catted_anything = false;
12-
var stdout_file = %return io.getStdOut();
12+
var stdout_file = try io.getStdOut();
1313

1414
while (args_it.next(allocator)) |arg_or_err| {
15-
const arg = %return unwrapArg(arg_or_err);
15+
const arg = try unwrapArg(arg_or_err);
1616
if (mem.eql(u8, arg, "-")) {
1717
catted_anything = true;
18-
var stdin_file = %return io.getStdIn();
19-
%return cat_file(&stdout_file, &stdin_file);
18+
var stdin_file = try io.getStdIn();
19+
try cat_file(&stdout_file, &stdin_file);
2020
} else if (arg[0] == '-') {
2121
return usage(exe);
2222
} else {
@@ -27,12 +27,12 @@ pub fn main() -> %void {
2727
defer file.close();
2828

2929
catted_anything = true;
30-
%return cat_file(&stdout_file, &file);
30+
try cat_file(&stdout_file, &file);
3131
}
3232
}
3333
if (!catted_anything) {
34-
var stdin_file = %return io.getStdIn();
35-
%return cat_file(&stdout_file, &stdin_file);
34+
var stdin_file = try io.getStdIn();
35+
try cat_file(&stdout_file, &stdin_file);
3636
}
3737
}
3838

example/guess_number/main.zig

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@ const Rand = std.rand.Rand;
66
const os = std.os;
77

88
pub fn main() -> %void {
9-
var stdout_file = %return io.getStdOut();
9+
var stdout_file = try io.getStdOut();
1010
var stdout_file_stream = io.FileOutStream.init(&stdout_file);
1111
const stdout = &stdout_file_stream.stream;
1212

13-
var stdin_file = %return io.getStdIn();
13+
var stdin_file = try io.getStdIn();
1414

15-
%return stdout.print("Welcome to the Guess Number Game in Zig.\n");
15+
try stdout.print("Welcome to the Guess Number Game in Zig.\n");
1616

1717
var seed_bytes: [@sizeOf(usize)]u8 = undefined;
1818
%%os.getRandomBytes(seed_bytes[0..]);
@@ -22,24 +22,24 @@ pub fn main() -> %void {
2222
const answer = rand.range(u8, 0, 100) + 1;
2323

2424
while (true) {
25-
%return stdout.print("\nGuess a number between 1 and 100: ");
25+
try stdout.print("\nGuess a number between 1 and 100: ");
2626
var line_buf : [20]u8 = undefined;
2727

2828
const line_len = stdin_file.read(line_buf[0..]) %% |err| {
29-
%return stdout.print("Unable to read from stdin: {}\n", @errorName(err));
29+
try stdout.print("Unable to read from stdin: {}\n", @errorName(err));
3030
return err;
3131
};
3232

3333
const guess = fmt.parseUnsigned(u8, line_buf[0..line_len - 1], 10) %% {
34-
%return stdout.print("Invalid number.\n");
34+
try stdout.print("Invalid number.\n");
3535
continue;
3636
};
3737
if (guess > answer) {
38-
%return stdout.print("Guess lower.\n");
38+
try stdout.print("Guess lower.\n");
3939
} else if (guess < answer) {
40-
%return stdout.print("Guess higher.\n");
40+
try stdout.print("Guess higher.\n");
4141
} else {
42-
%return stdout.print("You win!\n");
42+
try stdout.print("You win!\n");
4343
return;
4444
}
4545
}

example/hello_world/hello.zig

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ const std = @import("std");
22

33
pub fn main() -> %void {
44
// If this program is run without stdout attached, exit with an error.
5-
var stdout_file = %return std.io.getStdOut();
5+
var stdout_file = try std.io.getStdOut();
66
// If this program encounters pipe failure when printing to stdout, exit
77
// with an error.
8-
%return stdout_file.write("Hello, world!\n");
8+
try stdout_file.write("Hello, world!\n");
99
}

0 commit comments

Comments
 (0)