Skip to content

Commit

Permalink
replace %return with try
Browse files Browse the repository at this point in the history
See #632

better fits the convention of using keywords for control flow
  • Loading branch information
andrewrk committed Jan 7, 2018
1 parent de1f579 commit 66717db
Show file tree
Hide file tree
Showing 41 changed files with 812 additions and 803 deletions.
24 changes: 12 additions & 12 deletions doc/home.html.in
Expand Up @@ -75,10 +75,10 @@

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

for (buf) |c| {
const digit = %return charToDigit(c, radix);
x = %return mulOverflow(T, x, radix);
x = %return addOverflow(T, x, digit);
const digit = try charToDigit(c, radix);
x = try mulOverflow(T, x, radix);
x = try addOverflow(T, x, digit);
}

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

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

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

fn initCapacity(hm: &amp;Self, capacity: usize) -&gt; %void {
hm.entries = %return hm.allocator.alloc(Entry, capacity);
hm.entries = try hm.allocator.alloc(Entry, capacity);
hm.size = 0;
hm.max_distance_from_start_index = 0;
for (hm.entries) |*entry| {
Expand Down Expand Up @@ -420,7 +420,7 @@ pub fn main() -&gt; %void {
const arg = os.args.at(arg_i);
if (mem.eql(u8, arg, "-")) {
catted_anything = true;
%return cat_stream(&amp;io.stdin);
try cat_stream(&amp;io.stdin);
} else if (arg[0] == '-') {
return usage(exe);
} else {
Expand All @@ -431,13 +431,13 @@ pub fn main() -&gt; %void {
defer is.close();

catted_anything = true;
%return cat_stream(&amp;is);
try cat_stream(&amp;is);
}
}
if (!catted_anything) {
%return cat_stream(&amp;io.stdin);
try cat_stream(&amp;io.stdin);
}
%return io.stdout.flush();
try io.stdout.flush();
}

fn usage(exe: []const u8) -&gt; %void {
Expand Down
46 changes: 24 additions & 22 deletions doc/langref.html.in
Expand Up @@ -268,10 +268,10 @@

pub fn main() -&gt; %void {
// If this program is run without stdout attached, exit with an error.
var stdout_file = %return std.io.getStdOut();
var stdout_file = try std.io.getStdOut();
// If this program encounters pipe failure when printing to stdout, exit
// with an error.
%return stdout_file.write("Hello, world!\n");
try stdout_file.write("Hello, world!\n");
}</code></pre>
<pre><code class="sh">$ zig build-exe hello.zig
$ ./hello
Expand Down Expand Up @@ -3224,14 +3224,14 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
// ...
}</code></pre>
<p>
There is a shortcut for this. The <code>%return</code> expression:
There is a shortcut for this. The <code>try</code> expression:
</p>
<pre><code class="zig">fn doAThing(str: []u8) -&gt; %void {
const number = %return parseU64(str, 10);
const number = try parseU64(str, 10);
// ...
}</code></pre>
<p>
<code>%return</code> evaluates an error union expression. If it is an error, it returns
<code>try</code> evaluates an error union expression. If it is an error, it returns
from the current function with the same error. Otherwise, the expression results in
the unwrapped value.
</p>
Expand Down Expand Up @@ -3278,7 +3278,7 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
Example:
</p>
<pre><code class="zig">fn createFoo(param: i32) -&gt; %Foo {
const foo = %return tryToAllocateFoo();
const foo = try tryToAllocateFoo();
// now we have allocated foo. we need to free it if the function fails.
// but we want to return it if the function succeeds.
%defer deallocateFoo(foo);
Expand Down Expand Up @@ -3928,11 +3928,11 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
switch (state) {
State.Start =&gt; switch (c) {
'{' =&gt; {
if (start_index &lt; i) %return self.write(format[start_index...i]);
if (start_index &lt; i) try self.write(format[start_index...i]);
state = State.OpenBrace;
},
'}' =&gt; {
if (start_index &lt; i) %return self.write(format[start_index...i]);
if (start_index &lt; i) try self.write(format[start_index...i]);
state = State.CloseBrace;
},
else =&gt; {},
Expand All @@ -3943,7 +3943,7 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
start_index = i;
},
'}' =&gt; {
%return self.printValue(args[next_arg]);
try self.printValue(args[next_arg]);
next_arg += 1;
state = State.Start;
start_index = i + 1;
Expand All @@ -3968,9 +3968,9 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
}
}
if (start_index &lt; format.len) {
%return self.write(format[start_index...format.len]);
try self.write(format[start_index...format.len]);
}
%return self.flush();
try self.flush();
}</code></pre>
<p>
This is a proof of concept implementation; the actual function in the standard library has more
Expand All @@ -3984,12 +3984,12 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
and emits a function that actually looks like this:
</p>
<pre><code class="zig">pub fn printf(self: &amp;OutStream, arg0: i32, arg1: []const u8) -&gt; %void {
%return self.write("here is a string: '");
%return self.printValue(arg0);
%return self.write("' here is a number: ");
%return self.printValue(arg1);
%return self.write("\n");
%return self.flush();
try self.write("here is a string: '");
try self.printValue(arg0);
try self.write("' here is a number: ");
try self.printValue(arg1);
try self.write("\n");
try self.flush();
}</code></pre>
<p>
<code>printValue</code> is a function that takes a parameter of any type, and does different things depending
Expand Down Expand Up @@ -5891,7 +5891,7 @@ TypeExpr = PrefixOpExpression | "var"

BlockOrExpression = Block | Expression

Expression = ReturnExpression | BreakExpression | AssignmentExpression
Expression = TryExpression | ReturnExpression | BreakExpression | AssignmentExpression

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

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

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

BlockExpression(body) = Block | IfExpression(body) | TryExpression(body) | TestExpression(body) | WhileExpression(body) | ForExpression(body) | SwitchExpression | CompTimeExpression(body)
BlockExpression(body) = Block | IfExpression(body) | IfErrorExpression(body) | TestExpression(body) | WhileExpression(body) | ForExpression(body) | SwitchExpression | CompTimeExpression(body)

CompTimeExpression(body) = "comptime" body

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

BoolOrExpression = BoolAndExpression "or" BoolOrExpression | BoolAndExpression

ReturnExpression = option("%") "return" option(Expression)
ReturnExpression = "return" option(Expression)

TryExpression = "try" Expression

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

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

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

TryExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
IfErrorExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)

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

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

StructLiteralField = "." Symbol "=" Expression

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

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

Expand Down
16 changes: 8 additions & 8 deletions example/cat/main.zig
Expand Up @@ -7,16 +7,16 @@ const allocator = std.debug.global_allocator;

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

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

catted_anything = true;
%return cat_file(&stdout_file, &file);
try cat_file(&stdout_file, &file);
}
}
if (!catted_anything) {
var stdin_file = %return io.getStdIn();
%return cat_file(&stdout_file, &stdin_file);
var stdin_file = try io.getStdIn();
try cat_file(&stdout_file, &stdin_file);
}
}

Expand Down
18 changes: 9 additions & 9 deletions example/guess_number/main.zig
Expand Up @@ -6,13 +6,13 @@ const Rand = std.rand.Rand;
const os = std.os;

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

var stdin_file = %return io.getStdIn();
var stdin_file = try io.getStdIn();

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

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

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

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

const guess = fmt.parseUnsigned(u8, line_buf[0..line_len - 1], 10) %% {
%return stdout.print("Invalid number.\n");
try stdout.print("Invalid number.\n");
continue;
};
if (guess > answer) {
%return stdout.print("Guess lower.\n");
try stdout.print("Guess lower.\n");
} else if (guess < answer) {
%return stdout.print("Guess higher.\n");
try stdout.print("Guess higher.\n");
} else {
%return stdout.print("You win!\n");
try stdout.print("You win!\n");
return;
}
}
Expand Down
4 changes: 2 additions & 2 deletions example/hello_world/hello.zig
Expand Up @@ -2,8 +2,8 @@ const std = @import("std");

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

0 comments on commit 66717db

Please sign in to comment.