authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-01-07 16:51:46-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-01-07 16:53:13-05:00
log66717db735b9ddac9298bf08fcf95e7e11629fee
tree54dea549c62d851da9269b09eba8e596450ee330
parentde1f57926f212f18a98884fa8b1d0df7f7bc7f03

replace `%return` with `try`

See #632 better fits the convention of using keywords for control flow

41 files changed, 812 insertions(+), 803 deletions(-)

doc/home.html.in+12-12
......@@ -75,10 +75,10 @@
7575
7676pub fn main() -&gt; %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
443443fn usage(exe: []const u8) -&gt; %void {
doc/langref.html.in+24-22
......@@ -268,10 +268,10 @@
268268
269269pub 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
58925892BlockOrExpression = Block | Expression
58935893
5894Expression = ReturnExpression | BreakExpression | AssignmentExpression
5894Expression = TryExpression | ReturnExpression | BreakExpression | AssignmentExpression
58955895
58965896AsmExpression = "asm" option("volatile") "(" String option(AsmOutput) ")"
58975897
......@@ -5915,7 +5915,7 @@ AssignmentExpression = UnwrapExpression AssignmentOperator UnwrapExpression | Un
59155915
59165916AssignmentOperator = "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "&lt;&lt;=" | "&gt;&gt;=" | "&amp;=" | "^=" | "|=" | "*%=" | "+%=" | "-%="
59175917
5918BlockExpression(body) = Block | IfExpression(body) | TryExpression(body) | TestExpression(body) | WhileExpression(body) | ForExpression(body) | SwitchExpression | CompTimeExpression(body)
5918BlockExpression(body) = Block | IfExpression(body) | IfErrorExpression(body) | TestExpression(body) | WhileExpression(body) | ForExpression(body) | SwitchExpression | CompTimeExpression(body)
59195919
59205920CompTimeExpression(body) = "comptime" body
59215921
......@@ -5929,7 +5929,9 @@ ForExpression(body) = option(Symbol ":") option("inline") "for" "(" Expression "
59295929
59305930BoolOrExpression = BoolAndExpression "or" BoolOrExpression | BoolAndExpression
59315931
5932ReturnExpression = option("%") "return" option(Expression)
5932ReturnExpression = "return" option(Expression)
5933
5934TryExpression = "try" Expression
59335935
59345936BreakExpression = "break" option(":" Symbol) option(Expression)
59355937
......@@ -5937,7 +5939,7 @@ Defer(body) = option("%") "defer" body
59375939
59385940IfExpression(body) = "if" "(" Expression ")" body option("else" BlockExpression(body))
59395941
5940TryExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
5942IfErrorExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
59415943
59425944TestExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body option("else" BlockExpression(body))
59435945
......@@ -5987,7 +5989,7 @@ ContainerInitBody = list(StructLiteralField, ",") | list(Expression, ",")
59875989
59885990StructLiteralField = "." Symbol "=" Expression
59895991
5990PrefixOp = "!" | "-" | "~" | "*" | ("&amp;" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%"
5992PrefixOp = "!" | "-" | "~" | "*" | ("&amp;" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%" | "try"
59915993
59925994PrimaryExpression = 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+8-8
......@@ -7,16 +7,16 @@ const allocator = std.debug.global_allocator;
77
88pub 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+9-9
......@@ -6,13 +6,13 @@ const Rand = std.rand.Rand;
66const os = std.os;
77
88pub 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+2-2
......@@ -2,8 +2,8 @@ const std = @import("std");
22
33pub 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}
src-self-hosted/main.zig+38-38
......@@ -40,18 +40,18 @@ const Cmd = enum {
4040};
4141
4242fn badArgs(comptime format: []const u8, args: ...) -> error {
43 var stderr = %return io.getStdErr();
43 var stderr = try io.getStdErr();
4444 var stderr_stream_adapter = io.FileOutStream.init(&stderr);
4545 const stderr_stream = &stderr_stream_adapter.stream;
46 %return stderr_stream.print(format ++ "\n\n", args);
47 %return printUsage(&stderr_stream_adapter.stream);
46 try stderr_stream.print(format ++ "\n\n", args);
47 try printUsage(&stderr_stream_adapter.stream);
4848 return error.InvalidCommandLineArguments;
4949}
5050
5151pub fn main2() -> %void {
5252 const allocator = std.heap.c_allocator;
5353
54 const args = %return os.argsAlloc(allocator);
54 const args = try os.argsAlloc(allocator);
5555 defer os.argsFree(allocator, args);
5656
5757 var cmd = Cmd.None;
......@@ -167,7 +167,7 @@ pub fn main2() -> %void {
167167 @panic("TODO --test-cmd-bin");
168168 } else if (arg[1] == 'L' and arg.len > 2) {
169169 // alias for --library-path
170 %return lib_dirs.append(arg[1..]);
170 try lib_dirs.append(arg[1..]);
171171 } else if (mem.eql(u8, arg, "--pkg-begin")) {
172172 @panic("TODO --pkg-begin");
173173 } else if (mem.eql(u8, arg, "--pkg-end")) {
......@@ -217,24 +217,24 @@ pub fn main2() -> %void {
217217 } else if (mem.eql(u8, arg, "--dynamic-linker")) {
218218 dynamic_linker_arg = args[arg_i];
219219 } else if (mem.eql(u8, arg, "-isystem")) {
220 %return clang_argv.append("-isystem");
221 %return clang_argv.append(args[arg_i]);
220 try clang_argv.append("-isystem");
221 try clang_argv.append(args[arg_i]);
222222 } else if (mem.eql(u8, arg, "-dirafter")) {
223 %return clang_argv.append("-dirafter");
224 %return clang_argv.append(args[arg_i]);
223 try clang_argv.append("-dirafter");
224 try clang_argv.append(args[arg_i]);
225225 } else if (mem.eql(u8, arg, "-mllvm")) {
226 %return clang_argv.append("-mllvm");
227 %return clang_argv.append(args[arg_i]);
226 try clang_argv.append("-mllvm");
227 try clang_argv.append(args[arg_i]);
228228
229 %return llvm_argv.append(args[arg_i]);
229 try llvm_argv.append(args[arg_i]);
230230 } else if (mem.eql(u8, arg, "--library-path") or mem.eql(u8, arg, "-L")) {
231 %return lib_dirs.append(args[arg_i]);
231 try lib_dirs.append(args[arg_i]);
232232 } else if (mem.eql(u8, arg, "--library")) {
233 %return link_libs.append(args[arg_i]);
233 try link_libs.append(args[arg_i]);
234234 } else if (mem.eql(u8, arg, "--object")) {
235 %return objects.append(args[arg_i]);
235 try objects.append(args[arg_i]);
236236 } else if (mem.eql(u8, arg, "--assembly")) {
237 %return asm_files.append(args[arg_i]);
237 try asm_files.append(args[arg_i]);
238238 } else if (mem.eql(u8, arg, "--cache-dir")) {
239239 cache_dir_arg = args[arg_i];
240240 } else if (mem.eql(u8, arg, "--target-arch")) {
......@@ -248,21 +248,21 @@ pub fn main2() -> %void {
248248 } else if (mem.eql(u8, arg, "-mios-version-min")) {
249249 mios_version_min = args[arg_i];
250250 } else if (mem.eql(u8, arg, "-framework")) {
251 %return frameworks.append(args[arg_i]);
251 try frameworks.append(args[arg_i]);
252252 } else if (mem.eql(u8, arg, "--linker-script")) {
253253 linker_script_arg = args[arg_i];
254254 } else if (mem.eql(u8, arg, "-rpath")) {
255 %return rpath_list.append(args[arg_i]);
255 try rpath_list.append(args[arg_i]);
256256 } else if (mem.eql(u8, arg, "--test-filter")) {
257 %return test_filters.append(args[arg_i]);
257 try test_filters.append(args[arg_i]);
258258 } else if (mem.eql(u8, arg, "--test-name-prefix")) {
259259 test_name_prefix_arg = args[arg_i];
260260 } else if (mem.eql(u8, arg, "--ver-major")) {
261 ver_major = %return std.fmt.parseUnsigned(u32, args[arg_i], 10);
261 ver_major = try std.fmt.parseUnsigned(u32, args[arg_i], 10);
262262 } else if (mem.eql(u8, arg, "--ver-minor")) {
263 ver_minor = %return std.fmt.parseUnsigned(u32, args[arg_i], 10);
263 ver_minor = try std.fmt.parseUnsigned(u32, args[arg_i], 10);
264264 } else if (mem.eql(u8, arg, "--ver-patch")) {
265 ver_patch = %return std.fmt.parseUnsigned(u32, args[arg_i], 10);
265 ver_patch = try std.fmt.parseUnsigned(u32, args[arg_i], 10);
266266 } else if (mem.eql(u8, arg, "--test-cmd")) {
267267 @panic("TODO --test-cmd");
268268 } else {
......@@ -367,13 +367,13 @@ pub fn main2() -> %void {
367367 const zig_root_source_file = if (cmd == Cmd.TranslateC) null else in_file_arg;
368368
369369 const chosen_cache_dir = cache_dir_arg ?? default_zig_cache_name;
370 const full_cache_dir = %return os.path.resolve(allocator, ".", chosen_cache_dir);
370 const full_cache_dir = try os.path.resolve(allocator, ".", chosen_cache_dir);
371371 defer allocator.free(full_cache_dir);
372372
373 const zig_lib_dir = %return resolveZigLibDir(allocator, zig_install_prefix);
373 const zig_lib_dir = try resolveZigLibDir(allocator, zig_install_prefix);
374374 %defer allocator.free(zig_lib_dir);
375375
376 const module = %return Module.create(allocator, root_name, zig_root_source_file,
376 const module = try Module.create(allocator, root_name, zig_root_source_file,
377377 Target.Native, build_kind, build_mode, zig_lib_dir, full_cache_dir);
378378 defer module.destroy();
379379
......@@ -424,7 +424,7 @@ pub fn main2() -> %void {
424424 module.rpath_list = rpath_list.toSliceConst();
425425
426426 for (link_libs.toSliceConst()) |name| {
427 _ = %return module.addLinkLib(name, true);
427 _ = try module.addLinkLib(name, true);
428428 }
429429
430430 module.windows_subsystem_windows = mwindows;
......@@ -455,8 +455,8 @@ pub fn main2() -> %void {
455455 module.link_objects = objects.toSliceConst();
456456 module.assembly_files = asm_files.toSliceConst();
457457
458 %return module.build();
459 %return module.link(out_file);
458 try module.build();
459 try module.link(out_file);
460460 },
461461 Cmd.TranslateC => @panic("TODO translate-c"),
462462 Cmd.Test => @panic("TODO test cmd"),
......@@ -464,16 +464,16 @@ pub fn main2() -> %void {
464464 }
465465 },
466466 Cmd.Version => {
467 var stdout_file = %return io.getStdErr();
468 %return stdout_file.write(std.cstr.toSliceConst(c.ZIG_VERSION_STRING));
469 %return stdout_file.write("\n");
467 var stdout_file = try io.getStdErr();
468 try stdout_file.write(std.cstr.toSliceConst(c.ZIG_VERSION_STRING));
469 try stdout_file.write("\n");
470470 },
471471 Cmd.Targets => @panic("TODO zig targets"),
472472 }
473473}
474474
475475fn printUsage(stream: &io.OutStream) -> %void {
476 %return stream.write(
476 try stream.write(
477477 \\Usage: zig [command] [options]
478478 \\
479479 \\Commands:
......@@ -549,8 +549,8 @@ fn printUsage(stream: &io.OutStream) -> %void {
549549}
550550
551551fn printZen() -> %void {
552 var stdout_file = %return io.getStdErr();
553 %return stdout_file.write(
552 var stdout_file = try io.getStdErr();
553 try stdout_file.write(
554554 \\
555555 \\ * Communicate intent precisely.
556556 \\ * Edge cases matter.
......@@ -586,13 +586,13 @@ fn resolveZigLibDir(allocator: &mem.Allocator, zig_install_prefix_arg: ?[]const
586586
587587/// Caller must free result
588588fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) -> %[]u8 {
589 const test_zig_dir = %return os.path.join(allocator, test_path, "lib", "zig");
589 const test_zig_dir = try os.path.join(allocator, test_path, "lib", "zig");
590590 %defer allocator.free(test_zig_dir);
591591
592 const test_index_file = %return os.path.join(allocator, test_zig_dir, "std", "index.zig");
592 const test_index_file = try os.path.join(allocator, test_zig_dir, "std", "index.zig");
593593 defer allocator.free(test_index_file);
594594
595 var file = %return io.File.openRead(test_index_file, allocator);
595 var file = try io.File.openRead(test_index_file, allocator);
596596 file.close();
597597
598598 return test_zig_dir;
......@@ -600,7 +600,7 @@ fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) -> %[]
600600
601601/// Caller must free result
602602fn findZigLibDir(allocator: &mem.Allocator) -> %[]u8 {
603 const self_exe_path = %return os.selfExeDirPath(allocator);
603 const self_exe_path = try os.selfExeDirPath(allocator);
604604 defer allocator.free(self_exe_path);
605605
606606 var cur_path: []const u8 = self_exe_path;
src-self-hosted/module.zig+13-13
......@@ -112,7 +112,7 @@ pub const Module = struct {
112112 pub fn create(allocator: &mem.Allocator, name: []const u8, root_src_path: ?[]const u8, target: &const Target,
113113 kind: Kind, build_mode: builtin.Mode, zig_lib_dir: []const u8, cache_dir: []const u8) -> %&Module
114114 {
115 var name_buffer = %return Buffer.init(allocator, name);
115 var name_buffer = try Buffer.init(allocator, name);
116116 %defer name_buffer.deinit();
117117
118118 const context = c.LLVMContextCreate() ?? return error.OutOfMemory;
......@@ -124,7 +124,7 @@ pub const Module = struct {
124124 const builder = c.LLVMCreateBuilderInContext(context) ?? return error.OutOfMemory;
125125 %defer c.LLVMDisposeBuilder(builder);
126126
127 const module_ptr = %return allocator.create(Module);
127 const module_ptr = try allocator.create(Module);
128128 %defer allocator.destroy(module_ptr);
129129
130130 *module_ptr = Module {
......@@ -200,7 +200,7 @@ pub const Module = struct {
200200
201201 pub fn build(self: &Module) -> %void {
202202 if (self.llvm_argv.len != 0) {
203 var c_compatible_args = %return std.cstr.NullTerminated2DArray.fromSlices(self.allocator,
203 var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.allocator,
204204 [][]const []const u8 { [][]const u8{"zig (LLVM option parsing)"}, self.llvm_argv, });
205205 defer c_compatible_args.deinit();
206206 c.ZigLLVMParseCommandLineOptions(self.llvm_argv.len + 1, c_compatible_args.ptr);
......@@ -208,13 +208,13 @@ pub const Module = struct {
208208
209209 const root_src_path = self.root_src_path ?? @panic("TODO handle null root src path");
210210 const root_src_real_path = os.path.real(self.allocator, root_src_path) %% |err| {
211 %return printError("unable to get real path '{}': {}", root_src_path, err);
211 try printError("unable to get real path '{}': {}", root_src_path, err);
212212 return err;
213213 };
214214 %defer self.allocator.free(root_src_real_path);
215215
216216 const source_code = io.readFileAllocExtra(root_src_real_path, self.allocator, 3) %% |err| {
217 %return printError("unable to open '{}': {}", root_src_real_path, err);
217 try printError("unable to open '{}': {}", root_src_real_path, err);
218218 return err;
219219 };
220220 %defer self.allocator.free(source_code);
......@@ -244,16 +244,16 @@ pub const Module = struct {
244244 var parser = Parser.init(&tokenizer, self.allocator, root_src_real_path);
245245 defer parser.deinit();
246246
247 const root_node = %return parser.parse();
247 const root_node = try parser.parse();
248248 defer parser.freeAst(root_node);
249249
250 var stderr_file = %return std.io.getStdErr();
250 var stderr_file = try std.io.getStdErr();
251251 var stderr_file_out_stream = std.io.FileOutStream.init(&stderr_file);
252252 const out_stream = &stderr_file_out_stream.stream;
253 %return parser.renderAst(out_stream, root_node);
253 try parser.renderAst(out_stream, root_node);
254254
255255 warn("====fmt:====\n");
256 %return parser.renderSource(out_stream, root_node);
256 try parser.renderSource(out_stream, root_node);
257257
258258 warn("====ir:====\n");
259259 warn("TODO\n\n");
......@@ -282,14 +282,14 @@ pub const Module = struct {
282282 }
283283 }
284284
285 const link_lib = %return self.allocator.create(LinkLib);
285 const link_lib = try self.allocator.create(LinkLib);
286286 *link_lib = LinkLib {
287287 .name = name,
288288 .path = null,
289289 .provided_explicitly = provided_explicitly,
290290 .symbols = ArrayList([]u8).init(self.allocator),
291291 };
292 %return self.link_libs_list.append(link_lib);
292 try self.link_libs_list.append(link_lib);
293293 if (is_libc) {
294294 self.libc_link_lib = link_lib;
295295 }
......@@ -298,8 +298,8 @@ pub const Module = struct {
298298};
299299
300300fn printError(comptime format: []const u8, args: ...) -> %void {
301 var stderr_file = %return std.io.getStdErr();
301 var stderr_file = try std.io.getStdErr();
302302 var stderr_file_out_stream = std.io.FileOutStream.init(&stderr_file);
303303 const out_stream = &stderr_file_out_stream.stream;
304 %return out_stream.print(format, args);
304 try out_stream.print(format, args);
305305}
src-self-hosted/parser.zig+149-149
......@@ -58,7 +58,7 @@ pub const Parser = struct {
5858 switch (*self) {
5959 DestPtr.Field => |ptr| *ptr = value,
6060 DestPtr.NullableField => |ptr| *ptr = value,
61 DestPtr.List => |list| %return list.append(value),
61 DestPtr.List => |list| try list.append(value),
6262 }
6363 }
6464 };
......@@ -126,10 +126,10 @@ pub const Parser = struct {
126126 defer self.deinitUtilityArrayList(stack);
127127
128128 const root_node = x: {
129 const root_node = %return self.createRoot();
129 const root_node = try self.createRoot();
130130 %defer self.allocator.destroy(root_node);
131131 // This stack append has to succeed for freeAst to work
132 %return stack.append(State.TopLevel);
132 try stack.append(State.TopLevel);
133133 break :x root_node;
134134 };
135135 assert(self.cleanup_root_node == null);
......@@ -194,18 +194,18 @@ pub const Parser = struct {
194194 Token.Id.Keyword_var, Token.Id.Keyword_const => {
195195 stack.append(State.TopLevel) %% unreachable;
196196 // TODO shouldn't need these casts
197 const var_decl_node = %return self.createAttachVarDecl(&root_node.decls, ctx.visib_token,
197 const var_decl_node = try self.createAttachVarDecl(&root_node.decls, ctx.visib_token,
198198 token, (?Token)(null), ctx.extern_token);
199 %return stack.append(State { .VarDecl = var_decl_node });
199 try stack.append(State { .VarDecl = var_decl_node });
200200 continue;
201201 },
202202 Token.Id.Keyword_fn => {
203203 stack.append(State.TopLevel) %% unreachable;
204204 // TODO shouldn't need these casts
205 const fn_proto = %return self.createAttachFnProto(&root_node.decls, token,
205 const fn_proto = try self.createAttachFnProto(&root_node.decls, token,
206206 ctx.extern_token, (?Token)(null), (?Token)(null), (?Token)(null));
207 %return stack.append(State { .FnDef = fn_proto });
208 %return stack.append(State { .FnProto = fn_proto });
207 try stack.append(State { .FnDef = fn_proto });
208 try stack.append(State { .FnProto = fn_proto });
209209 continue;
210210 },
211211 Token.Id.StringLiteral => {
......@@ -213,24 +213,24 @@ pub const Parser = struct {
213213 },
214214 Token.Id.Keyword_coldcc, Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => {
215215 stack.append(State.TopLevel) %% unreachable;
216 const fn_token = %return self.eatToken(Token.Id.Keyword_fn);
216 const fn_token = try self.eatToken(Token.Id.Keyword_fn);
217217 // TODO shouldn't need this cast
218 const fn_proto = %return self.createAttachFnProto(&root_node.decls, fn_token,
218 const fn_proto = try self.createAttachFnProto(&root_node.decls, fn_token,
219219 ctx.extern_token, (?Token)(token), (?Token)(null), (?Token)(null));
220 %return stack.append(State { .FnDef = fn_proto });
221 %return stack.append(State { .FnProto = fn_proto });
220 try stack.append(State { .FnDef = fn_proto });
221 try stack.append(State { .FnProto = fn_proto });
222222 continue;
223223 },
224224 else => return self.parseError(token, "expected variable declaration or function, found {}", @tagName(token.id)),
225225 }
226226 },
227227 State.VarDecl => |var_decl| {
228 var_decl.name_token = %return self.eatToken(Token.Id.Identifier);
228 var_decl.name_token = try self.eatToken(Token.Id.Identifier);
229229 stack.append(State { .VarDeclAlign = var_decl }) %% unreachable;
230230
231231 const next_token = self.getNextToken();
232232 if (next_token.id == Token.Id.Colon) {
233 %return stack.append(State { .TypeExpr = DestPtr {.NullableField = &var_decl.type_node} });
233 try stack.append(State { .TypeExpr = DestPtr {.NullableField = &var_decl.type_node} });
234234 continue;
235235 }
236236
......@@ -242,9 +242,9 @@ pub const Parser = struct {
242242
243243 const next_token = self.getNextToken();
244244 if (next_token.id == Token.Id.Keyword_align) {
245 _ = %return self.eatToken(Token.Id.LParen);
246 %return stack.append(State { .ExpectToken = Token.Id.RParen });
247 %return stack.append(State { .Expression = DestPtr{.NullableField = &var_decl.align_node} });
245 _ = try self.eatToken(Token.Id.LParen);
246 try stack.append(State { .ExpectToken = Token.Id.RParen });
247 try stack.append(State { .Expression = DestPtr{.NullableField = &var_decl.align_node} });
248248 continue;
249249 }
250250
......@@ -256,7 +256,7 @@ pub const Parser = struct {
256256 if (token.id == Token.Id.Equal) {
257257 var_decl.eq_token = token;
258258 stack.append(State { .ExpectToken = Token.Id.Semicolon }) %% unreachable;
259 %return stack.append(State {
259 try stack.append(State {
260260 .Expression = DestPtr {.NullableField = &var_decl.init_node},
261261 });
262262 continue;
......@@ -267,14 +267,14 @@ pub const Parser = struct {
267267 return self.parseError(token, "expected '=' or ';', found {}", @tagName(token.id));
268268 },
269269 State.ExpectToken => |token_id| {
270 _ = %return self.eatToken(token_id);
270 _ = try self.eatToken(token_id);
271271 continue;
272272 },
273273
274274 State.Expression => |dest_ptr| {
275275 // save the dest_ptr for later
276276 stack.append(state) %% unreachable;
277 %return stack.append(State.ExpectOperand);
277 try stack.append(State.ExpectOperand);
278278 continue;
279279 },
280280 State.ExpectOperand => {
......@@ -283,13 +283,13 @@ pub const Parser = struct {
283283 const token = self.getNextToken();
284284 switch (token.id) {
285285 Token.Id.Keyword_return => {
286 %return stack.append(State { .PrefixOp = %return self.createPrefixOp(token,
286 try stack.append(State { .PrefixOp = try self.createPrefixOp(token,
287287 ast.NodePrefixOp.PrefixOp.Return) });
288 %return stack.append(State.ExpectOperand);
288 try stack.append(State.ExpectOperand);
289289 continue;
290290 },
291291 Token.Id.Ampersand => {
292 const prefix_op = %return self.createPrefixOp(token, ast.NodePrefixOp.PrefixOp{
292 const prefix_op = try self.createPrefixOp(token, ast.NodePrefixOp.PrefixOp{
293293 .AddrOf = ast.NodePrefixOp.AddrOfInfo {
294294 .align_expr = null,
295295 .bit_offset_start_token = null,
......@@ -298,30 +298,30 @@ pub const Parser = struct {
298298 .volatile_token = null,
299299 }
300300 });
301 %return stack.append(State { .PrefixOp = prefix_op });
302 %return stack.append(State.ExpectOperand);
303 %return stack.append(State { .AddrOfModifiers = &prefix_op.op.AddrOf });
301 try stack.append(State { .PrefixOp = prefix_op });
302 try stack.append(State.ExpectOperand);
303 try stack.append(State { .AddrOfModifiers = &prefix_op.op.AddrOf });
304304 continue;
305305 },
306306 Token.Id.Identifier => {
307 %return stack.append(State {
308 .Operand = &(%return self.createIdentifier(token)).base
307 try stack.append(State {
308 .Operand = &(try self.createIdentifier(token)).base
309309 });
310 %return stack.append(State.AfterOperand);
310 try stack.append(State.AfterOperand);
311311 continue;
312312 },
313313 Token.Id.IntegerLiteral => {
314 %return stack.append(State {
315 .Operand = &(%return self.createIntegerLiteral(token)).base
314 try stack.append(State {
315 .Operand = &(try self.createIntegerLiteral(token)).base
316316 });
317 %return stack.append(State.AfterOperand);
317 try stack.append(State.AfterOperand);
318318 continue;
319319 },
320320 Token.Id.FloatLiteral => {
321 %return stack.append(State {
322 .Operand = &(%return self.createFloatLiteral(token)).base
321 try stack.append(State {
322 .Operand = &(try self.createFloatLiteral(token)).base
323323 });
324 %return stack.append(State.AfterOperand);
324 try stack.append(State.AfterOperand);
325325 continue;
326326 },
327327 else => return self.parseError(token, "expected primary expression, found {}", @tagName(token.id)),
......@@ -335,17 +335,17 @@ pub const Parser = struct {
335335 var token = self.getNextToken();
336336 switch (token.id) {
337337 Token.Id.EqualEqual => {
338 %return stack.append(State {
339 .InfixOp = %return self.createInfixOp(token, ast.NodeInfixOp.InfixOp.EqualEqual)
338 try stack.append(State {
339 .InfixOp = try self.createInfixOp(token, ast.NodeInfixOp.InfixOp.EqualEqual)
340340 });
341 %return stack.append(State.ExpectOperand);
341 try stack.append(State.ExpectOperand);
342342 continue;
343343 },
344344 Token.Id.BangEqual => {
345 %return stack.append(State {
346 .InfixOp = %return self.createInfixOp(token, ast.NodeInfixOp.InfixOp.BangEqual)
345 try stack.append(State {
346 .InfixOp = try self.createInfixOp(token, ast.NodeInfixOp.InfixOp.BangEqual)
347347 });
348 %return stack.append(State.ExpectOperand);
348 try stack.append(State.ExpectOperand);
349349 continue;
350350 },
351351 else => {
......@@ -357,7 +357,7 @@ pub const Parser = struct {
357357 switch (stack.pop()) {
358358 State.Expression => |dest_ptr| {
359359 // we're done
360 %return dest_ptr.store(expression);
360 try dest_ptr.store(expression);
361361 break;
362362 },
363363 State.InfixOp => |infix_op| {
......@@ -385,9 +385,9 @@ pub const Parser = struct {
385385 Token.Id.Keyword_align => {
386386 stack.append(state) %% unreachable;
387387 if (addr_of_info.align_expr != null) return self.parseError(token, "multiple align qualifiers");
388 _ = %return self.eatToken(Token.Id.LParen);
389 %return stack.append(State { .ExpectToken = Token.Id.RParen });
390 %return stack.append(State { .Expression = DestPtr{.NullableField = &addr_of_info.align_expr} });
388 _ = try self.eatToken(Token.Id.LParen);
389 try stack.append(State { .ExpectToken = Token.Id.RParen });
390 try stack.append(State { .Expression = DestPtr{.NullableField = &addr_of_info.align_expr} });
391391 continue;
392392 },
393393 Token.Id.Keyword_const => {
......@@ -422,8 +422,8 @@ pub const Parser = struct {
422422
423423 State.FnProto => |fn_proto| {
424424 stack.append(State { .FnProtoAlign = fn_proto }) %% unreachable;
425 %return stack.append(State { .ParamDecl = fn_proto });
426 %return stack.append(State { .ExpectToken = Token.Id.LParen });
425 try stack.append(State { .ParamDecl = fn_proto });
426 try stack.append(State { .ExpectToken = Token.Id.LParen });
427427
428428 const next_token = self.getNextToken();
429429 if (next_token.id == Token.Id.Identifier) {
......@@ -455,7 +455,7 @@ pub const Parser = struct {
455455 if (token.id == Token.Id.RParen) {
456456 continue;
457457 }
458 const param_decl = %return self.createAttachParamDecl(&fn_proto.params);
458 const param_decl = try self.createAttachParamDecl(&fn_proto.params);
459459 if (token.id == Token.Id.Keyword_comptime) {
460460 param_decl.comptime_token = token;
461461 token = self.getNextToken();
......@@ -481,8 +481,8 @@ pub const Parser = struct {
481481 }
482482
483483 stack.append(State { .ParamDecl = fn_proto }) %% unreachable;
484 %return stack.append(State.ParamDeclComma);
485 %return stack.append(State {
484 try stack.append(State.ParamDeclComma);
485 try stack.append(State {
486486 .TypeExpr = DestPtr {.Field = &param_decl.type_node}
487487 });
488488 continue;
......@@ -504,7 +504,7 @@ pub const Parser = struct {
504504 const token = self.getNextToken();
505505 switch(token.id) {
506506 Token.Id.LBrace => {
507 const block = %return self.createBlock(token);
507 const block = try self.createBlock(token);
508508 fn_proto.body_node = &block.base;
509509 stack.append(State { .Block = block }) %% unreachable;
510510 continue;
......@@ -524,7 +524,7 @@ pub const Parser = struct {
524524 else => {
525525 self.putBackToken(token);
526526 stack.append(State { .Block = block }) %% unreachable;
527 %return stack.append(State { .Statement = block });
527 try stack.append(State { .Statement = block });
528528 continue;
529529 },
530530 }
......@@ -538,9 +538,9 @@ pub const Parser = struct {
538538 const mut_token = self.getNextToken();
539539 if (mut_token.id == Token.Id.Keyword_var or mut_token.id == Token.Id.Keyword_const) {
540540 // TODO shouldn't need these casts
541 const var_decl = %return self.createAttachVarDecl(&block.statements, (?Token)(null),
541 const var_decl = try self.createAttachVarDecl(&block.statements, (?Token)(null),
542542 mut_token, (?Token)(comptime_token), (?Token)(null));
543 %return stack.append(State { .VarDecl = var_decl });
543 try stack.append(State { .VarDecl = var_decl });
544544 continue;
545545 }
546546 self.putBackToken(mut_token);
......@@ -552,16 +552,16 @@ pub const Parser = struct {
552552 const mut_token = self.getNextToken();
553553 if (mut_token.id == Token.Id.Keyword_var or mut_token.id == Token.Id.Keyword_const) {
554554 // TODO shouldn't need these casts
555 const var_decl = %return self.createAttachVarDecl(&block.statements, (?Token)(null),
555 const var_decl = try self.createAttachVarDecl(&block.statements, (?Token)(null),
556556 mut_token, (?Token)(null), (?Token)(null));
557 %return stack.append(State { .VarDecl = var_decl });
557 try stack.append(State { .VarDecl = var_decl });
558558 continue;
559559 }
560560 self.putBackToken(mut_token);
561561 }
562562
563563 stack.append(State { .ExpectToken = Token.Id.Semicolon }) %% unreachable;
564 %return stack.append(State { .Expression = DestPtr{.List = &block.statements} });
564 try stack.append(State { .Expression = DestPtr{.List = &block.statements} });
565565 continue;
566566 },
567567
......@@ -576,7 +576,7 @@ pub const Parser = struct {
576576 }
577577
578578 fn createRoot(self: &Parser) -> %&ast.NodeRoot {
579 const node = %return self.allocator.create(ast.NodeRoot);
579 const node = try self.allocator.create(ast.NodeRoot);
580580 %defer self.allocator.destroy(node);
581581
582582 *node = ast.NodeRoot {
......@@ -589,7 +589,7 @@ pub const Parser = struct {
589589 fn createVarDecl(self: &Parser, visib_token: &const ?Token, mut_token: &const Token, comptime_token: &const ?Token,
590590 extern_token: &const ?Token) -> %&ast.NodeVarDecl
591591 {
592 const node = %return self.allocator.create(ast.NodeVarDecl);
592 const node = try self.allocator.create(ast.NodeVarDecl);
593593 %defer self.allocator.destroy(node);
594594
595595 *node = ast.NodeVarDecl {
......@@ -612,7 +612,7 @@ pub const Parser = struct {
612612 fn createFnProto(self: &Parser, fn_token: &const Token, extern_token: &const ?Token,
613613 cc_token: &const ?Token, visib_token: &const ?Token, inline_token: &const ?Token) -> %&ast.NodeFnProto
614614 {
615 const node = %return self.allocator.create(ast.NodeFnProto);
615 const node = try self.allocator.create(ast.NodeFnProto);
616616 %defer self.allocator.destroy(node);
617617
618618 *node = ast.NodeFnProto {
......@@ -634,7 +634,7 @@ pub const Parser = struct {
634634 }
635635
636636 fn createParamDecl(self: &Parser) -> %&ast.NodeParamDecl {
637 const node = %return self.allocator.create(ast.NodeParamDecl);
637 const node = try self.allocator.create(ast.NodeParamDecl);
638638 %defer self.allocator.destroy(node);
639639
640640 *node = ast.NodeParamDecl {
......@@ -649,7 +649,7 @@ pub const Parser = struct {
649649 }
650650
651651 fn createBlock(self: &Parser, begin_token: &const Token) -> %&ast.NodeBlock {
652 const node = %return self.allocator.create(ast.NodeBlock);
652 const node = try self.allocator.create(ast.NodeBlock);
653653 %defer self.allocator.destroy(node);
654654
655655 *node = ast.NodeBlock {
......@@ -662,7 +662,7 @@ pub const Parser = struct {
662662 }
663663
664664 fn createInfixOp(self: &Parser, op_token: &const Token, op: &const ast.NodeInfixOp.InfixOp) -> %&ast.NodeInfixOp {
665 const node = %return self.allocator.create(ast.NodeInfixOp);
665 const node = try self.allocator.create(ast.NodeInfixOp);
666666 %defer self.allocator.destroy(node);
667667
668668 *node = ast.NodeInfixOp {
......@@ -676,7 +676,7 @@ pub const Parser = struct {
676676 }
677677
678678 fn createPrefixOp(self: &Parser, op_token: &const Token, op: &const ast.NodePrefixOp.PrefixOp) -> %&ast.NodePrefixOp {
679 const node = %return self.allocator.create(ast.NodePrefixOp);
679 const node = try self.allocator.create(ast.NodePrefixOp);
680680 %defer self.allocator.destroy(node);
681681
682682 *node = ast.NodePrefixOp {
......@@ -689,7 +689,7 @@ pub const Parser = struct {
689689 }
690690
691691 fn createIdentifier(self: &Parser, name_token: &const Token) -> %&ast.NodeIdentifier {
692 const node = %return self.allocator.create(ast.NodeIdentifier);
692 const node = try self.allocator.create(ast.NodeIdentifier);
693693 %defer self.allocator.destroy(node);
694694
695695 *node = ast.NodeIdentifier {
......@@ -700,7 +700,7 @@ pub const Parser = struct {
700700 }
701701
702702 fn createIntegerLiteral(self: &Parser, token: &const Token) -> %&ast.NodeIntegerLiteral {
703 const node = %return self.allocator.create(ast.NodeIntegerLiteral);
703 const node = try self.allocator.create(ast.NodeIntegerLiteral);
704704 %defer self.allocator.destroy(node);
705705
706706 *node = ast.NodeIntegerLiteral {
......@@ -711,7 +711,7 @@ pub const Parser = struct {
711711 }
712712
713713 fn createFloatLiteral(self: &Parser, token: &const Token) -> %&ast.NodeFloatLiteral {
714 const node = %return self.allocator.create(ast.NodeFloatLiteral);
714 const node = try self.allocator.create(ast.NodeFloatLiteral);
715715 %defer self.allocator.destroy(node);
716716
717717 *node = ast.NodeFloatLiteral {
......@@ -722,16 +722,16 @@ pub const Parser = struct {
722722 }
723723
724724 fn createAttachIdentifier(self: &Parser, dest_ptr: &const DestPtr, name_token: &const Token) -> %&ast.NodeIdentifier {
725 const node = %return self.createIdentifier(name_token);
725 const node = try self.createIdentifier(name_token);
726726 %defer self.allocator.destroy(node);
727 %return dest_ptr.store(&node.base);
727 try dest_ptr.store(&node.base);
728728 return node;
729729 }
730730
731731 fn createAttachParamDecl(self: &Parser, list: &ArrayList(&ast.Node)) -> %&ast.NodeParamDecl {
732 const node = %return self.createParamDecl();
732 const node = try self.createParamDecl();
733733 %defer self.allocator.destroy(node);
734 %return list.append(&node.base);
734 try list.append(&node.base);
735735 return node;
736736 }
737737
......@@ -739,18 +739,18 @@ pub const Parser = struct {
739739 extern_token: &const ?Token, cc_token: &const ?Token, visib_token: &const ?Token,
740740 inline_token: &const ?Token) -> %&ast.NodeFnProto
741741 {
742 const node = %return self.createFnProto(fn_token, extern_token, cc_token, visib_token, inline_token);
742 const node = try self.createFnProto(fn_token, extern_token, cc_token, visib_token, inline_token);
743743 %defer self.allocator.destroy(node);
744 %return list.append(&node.base);
744 try list.append(&node.base);
745745 return node;
746746 }
747747
748748 fn createAttachVarDecl(self: &Parser, list: &ArrayList(&ast.Node), visib_token: &const ?Token,
749749 mut_token: &const Token, comptime_token: &const ?Token, extern_token: &const ?Token) -> %&ast.NodeVarDecl
750750 {
751 const node = %return self.createVarDecl(visib_token, mut_token, comptime_token, extern_token);
751 const node = try self.createVarDecl(visib_token, mut_token, comptime_token, extern_token);
752752 %defer self.allocator.destroy(node);
753 %return list.append(&node.base);
753 try list.append(&node.base);
754754 return node;
755755 }
756756
......@@ -783,7 +783,7 @@ pub const Parser = struct {
783783
784784 fn eatToken(self: &Parser, id: @TagType(Token.Id)) -> %Token {
785785 const token = self.getNextToken();
786 %return self.expectToken(token, id);
786 try self.expectToken(token, id);
787787 return token;
788788 }
789789
......@@ -812,7 +812,7 @@ pub const Parser = struct {
812812 var stack = self.initUtilityArrayList(RenderAstFrame);
813813 defer self.deinitUtilityArrayList(stack);
814814
815 %return stack.append(RenderAstFrame {
815 try stack.append(RenderAstFrame {
816816 .node = &root_node.base,
817817 .indent = 0,
818818 });
......@@ -821,13 +821,13 @@ pub const Parser = struct {
821821 {
822822 var i: usize = 0;
823823 while (i < frame.indent) : (i += 1) {
824 %return stream.print(" ");
824 try stream.print(" ");
825825 }
826826 }
827 %return stream.print("{}\n", @tagName(frame.node.id));
827 try stream.print("{}\n", @tagName(frame.node.id));
828828 var child_i: usize = 0;
829829 while (frame.node.iterate(child_i)) |child| : (child_i += 1) {
830 %return stack.append(RenderAstFrame {
830 try stack.append(RenderAstFrame {
831831 .node = child,
832832 .indent = frame.indent + 2,
833833 });
......@@ -856,7 +856,7 @@ pub const Parser = struct {
856856 while (i != 0) {
857857 i -= 1;
858858 const decl = root_node.decls.items[i];
859 %return stack.append(RenderState {.TopLevelDecl = decl});
859 try stack.append(RenderState {.TopLevelDecl = decl});
860860 }
861861 }
862862
......@@ -870,42 +870,42 @@ pub const Parser = struct {
870870 const fn_proto = @fieldParentPtr(ast.NodeFnProto, "base", decl);
871871 if (fn_proto.visib_token) |visib_token| {
872872 switch (visib_token.id) {
873 Token.Id.Keyword_pub => %return stream.print("pub "),
874 Token.Id.Keyword_export => %return stream.print("export "),
873 Token.Id.Keyword_pub => try stream.print("pub "),
874 Token.Id.Keyword_export => try stream.print("export "),
875875 else => unreachable,
876876 }
877877 }
878878 if (fn_proto.extern_token) |extern_token| {
879 %return stream.print("{} ", self.tokenizer.getTokenSlice(extern_token));
879 try stream.print("{} ", self.tokenizer.getTokenSlice(extern_token));
880880 }
881 %return stream.print("fn");
881 try stream.print("fn");
882882
883883 if (fn_proto.name_token) |name_token| {
884 %return stream.print(" {}", self.tokenizer.getTokenSlice(name_token));
884 try stream.print(" {}", self.tokenizer.getTokenSlice(name_token));
885885 }
886886
887 %return stream.print("(");
887 try stream.print("(");
888888
889 %return stack.append(RenderState { .Text = "\n" });
889 try stack.append(RenderState { .Text = "\n" });
890890 if (fn_proto.body_node == null) {
891 %return stack.append(RenderState { .Text = ";" });
891 try stack.append(RenderState { .Text = ";" });
892892 }
893893
894 %return stack.append(RenderState { .FnProtoRParen = fn_proto});
894 try stack.append(RenderState { .FnProtoRParen = fn_proto});
895895 var i = fn_proto.params.len;
896896 while (i != 0) {
897897 i -= 1;
898898 const param_decl_node = fn_proto.params.items[i];
899 %return stack.append(RenderState { .ParamDecl = param_decl_node});
899 try stack.append(RenderState { .ParamDecl = param_decl_node});
900900 if (i != 0) {
901 %return stack.append(RenderState { .Text = ", " });
901 try stack.append(RenderState { .Text = ", " });
902902 }
903903 }
904904 },
905905 ast.Node.Id.VarDecl => {
906906 const var_decl = @fieldParentPtr(ast.NodeVarDecl, "base", decl);
907 %return stack.append(RenderState { .Text = "\n"});
908 %return stack.append(RenderState { .VarDecl = var_decl});
907 try stack.append(RenderState { .Text = "\n"});
908 try stack.append(RenderState { .VarDecl = var_decl});
909909
910910 },
911911 else => unreachable,
......@@ -914,111 +914,111 @@ pub const Parser = struct {
914914
915915 RenderState.VarDecl => |var_decl| {
916916 if (var_decl.visib_token) |visib_token| {
917 %return stream.print("{} ", self.tokenizer.getTokenSlice(visib_token));
917 try stream.print("{} ", self.tokenizer.getTokenSlice(visib_token));
918918 }
919919 if (var_decl.extern_token) |extern_token| {
920 %return stream.print("{} ", self.tokenizer.getTokenSlice(extern_token));
920 try stream.print("{} ", self.tokenizer.getTokenSlice(extern_token));
921921 if (var_decl.lib_name != null) {
922922 @panic("TODO");
923923 }
924924 }
925925 if (var_decl.comptime_token) |comptime_token| {
926 %return stream.print("{} ", self.tokenizer.getTokenSlice(comptime_token));
926 try stream.print("{} ", self.tokenizer.getTokenSlice(comptime_token));
927927 }
928 %return stream.print("{} ", self.tokenizer.getTokenSlice(var_decl.mut_token));
929 %return stream.print("{}", self.tokenizer.getTokenSlice(var_decl.name_token));
928 try stream.print("{} ", self.tokenizer.getTokenSlice(var_decl.mut_token));
929 try stream.print("{}", self.tokenizer.getTokenSlice(var_decl.name_token));
930930
931 %return stack.append(RenderState { .Text = ";" });
931 try stack.append(RenderState { .Text = ";" });
932932 if (var_decl.init_node) |init_node| {
933 %return stack.append(RenderState { .Expression = init_node });
934 %return stack.append(RenderState { .Text = " = " });
933 try stack.append(RenderState { .Expression = init_node });
934 try stack.append(RenderState { .Text = " = " });
935935 }
936936 if (var_decl.align_node) |align_node| {
937 %return stack.append(RenderState { .Text = ")" });
938 %return stack.append(RenderState { .Expression = align_node });
939 %return stack.append(RenderState { .Text = " align(" });
937 try stack.append(RenderState { .Text = ")" });
938 try stack.append(RenderState { .Expression = align_node });
939 try stack.append(RenderState { .Text = " align(" });
940940 }
941941 if (var_decl.type_node) |type_node| {
942 %return stream.print(": ");
943 %return stack.append(RenderState { .Expression = type_node });
942 try stream.print(": ");
943 try stack.append(RenderState { .Expression = type_node });
944944 }
945945 },
946946
947947 RenderState.ParamDecl => |base| {
948948 const param_decl = @fieldParentPtr(ast.NodeParamDecl, "base", base);
949949 if (param_decl.comptime_token) |comptime_token| {
950 %return stream.print("{} ", self.tokenizer.getTokenSlice(comptime_token));
950 try stream.print("{} ", self.tokenizer.getTokenSlice(comptime_token));
951951 }
952952 if (param_decl.noalias_token) |noalias_token| {
953 %return stream.print("{} ", self.tokenizer.getTokenSlice(noalias_token));
953 try stream.print("{} ", self.tokenizer.getTokenSlice(noalias_token));
954954 }
955955 if (param_decl.name_token) |name_token| {
956 %return stream.print("{}: ", self.tokenizer.getTokenSlice(name_token));
956 try stream.print("{}: ", self.tokenizer.getTokenSlice(name_token));
957957 }
958958 if (param_decl.var_args_token) |var_args_token| {
959 %return stream.print("{}", self.tokenizer.getTokenSlice(var_args_token));
959 try stream.print("{}", self.tokenizer.getTokenSlice(var_args_token));
960960 } else {
961 %return stack.append(RenderState { .Expression = param_decl.type_node});
961 try stack.append(RenderState { .Expression = param_decl.type_node});
962962 }
963963 },
964964 RenderState.Text => |bytes| {
965 %return stream.write(bytes);
965 try stream.write(bytes);
966966 },
967967 RenderState.Expression => |base| switch (base.id) {
968968 ast.Node.Id.Identifier => {
969969 const identifier = @fieldParentPtr(ast.NodeIdentifier, "base", base);
970 %return stream.print("{}", self.tokenizer.getTokenSlice(identifier.name_token));
970 try stream.print("{}", self.tokenizer.getTokenSlice(identifier.name_token));
971971 },
972972 ast.Node.Id.Block => {
973973 const block = @fieldParentPtr(ast.NodeBlock, "base", base);
974 %return stream.write("{");
975 %return stack.append(RenderState { .Text = "}"});
976 %return stack.append(RenderState.PrintIndent);
977 %return stack.append(RenderState { .Indent = indent});
978 %return stack.append(RenderState { .Text = "\n"});
974 try stream.write("{");
975 try stack.append(RenderState { .Text = "}"});
976 try stack.append(RenderState.PrintIndent);
977 try stack.append(RenderState { .Indent = indent});
978 try stack.append(RenderState { .Text = "\n"});
979979 var i = block.statements.len;
980980 while (i != 0) {
981981 i -= 1;
982982 const statement_node = block.statements.items[i];
983 %return stack.append(RenderState { .Statement = statement_node});
984 %return stack.append(RenderState.PrintIndent);
985 %return stack.append(RenderState { .Indent = indent + indent_delta});
986 %return stack.append(RenderState { .Text = "\n" });
983 try stack.append(RenderState { .Statement = statement_node});
984 try stack.append(RenderState.PrintIndent);
985 try stack.append(RenderState { .Indent = indent + indent_delta});
986 try stack.append(RenderState { .Text = "\n" });
987987 }
988988 },
989989 ast.Node.Id.InfixOp => {
990990 const prefix_op_node = @fieldParentPtr(ast.NodeInfixOp, "base", base);
991 %return stack.append(RenderState { .Expression = prefix_op_node.rhs });
991 try stack.append(RenderState { .Expression = prefix_op_node.rhs });
992992 switch (prefix_op_node.op) {
993993 ast.NodeInfixOp.InfixOp.EqualEqual => {
994 %return stack.append(RenderState { .Text = " == "});
994 try stack.append(RenderState { .Text = " == "});
995995 },
996996 ast.NodeInfixOp.InfixOp.BangEqual => {
997 %return stack.append(RenderState { .Text = " != "});
997 try stack.append(RenderState { .Text = " != "});
998998 },
999999 else => unreachable,
10001000 }
1001 %return stack.append(RenderState { .Expression = prefix_op_node.lhs });
1001 try stack.append(RenderState { .Expression = prefix_op_node.lhs });
10021002 },
10031003 ast.Node.Id.PrefixOp => {
10041004 const prefix_op_node = @fieldParentPtr(ast.NodePrefixOp, "base", base);
1005 %return stack.append(RenderState { .Expression = prefix_op_node.rhs });
1005 try stack.append(RenderState { .Expression = prefix_op_node.rhs });
10061006 switch (prefix_op_node.op) {
10071007 ast.NodePrefixOp.PrefixOp.Return => {
1008 %return stream.write("return ");
1008 try stream.write("return ");
10091009 },
10101010 ast.NodePrefixOp.PrefixOp.AddrOf => |addr_of_info| {
1011 %return stream.write("&");
1011 try stream.write("&");
10121012 if (addr_of_info.volatile_token != null) {
1013 %return stack.append(RenderState { .Text = "volatile "});
1013 try stack.append(RenderState { .Text = "volatile "});
10141014 }
10151015 if (addr_of_info.const_token != null) {
1016 %return stack.append(RenderState { .Text = "const "});
1016 try stack.append(RenderState { .Text = "const "});
10171017 }
10181018 if (addr_of_info.align_expr) |align_expr| {
1019 %return stream.print("align(");
1020 %return stack.append(RenderState { .Text = ") "});
1021 %return stack.append(RenderState { .Expression = align_expr});
1019 try stream.print("align(");
1020 try stack.append(RenderState { .Text = ") "});
1021 try stack.append(RenderState { .Expression = align_expr});
10221022 }
10231023 },
10241024 else => unreachable,
......@@ -1026,42 +1026,42 @@ pub const Parser = struct {
10261026 },
10271027 ast.Node.Id.IntegerLiteral => {
10281028 const integer_literal = @fieldParentPtr(ast.NodeIntegerLiteral, "base", base);
1029 %return stream.print("{}", self.tokenizer.getTokenSlice(integer_literal.token));
1029 try stream.print("{}", self.tokenizer.getTokenSlice(integer_literal.token));
10301030 },
10311031 ast.Node.Id.FloatLiteral => {
10321032 const float_literal = @fieldParentPtr(ast.NodeFloatLiteral, "base", base);
1033 %return stream.print("{}", self.tokenizer.getTokenSlice(float_literal.token));
1033 try stream.print("{}", self.tokenizer.getTokenSlice(float_literal.token));
10341034 },
10351035 else => unreachable,
10361036 },
10371037 RenderState.FnProtoRParen => |fn_proto| {
1038 %return stream.print(")");
1038 try stream.print(")");
10391039 if (fn_proto.align_expr != null) {
10401040 @panic("TODO");
10411041 }
10421042 if (fn_proto.return_type) |return_type| {
1043 %return stream.print(" -> ");
1043 try stream.print(" -> ");
10441044 if (fn_proto.body_node) |body_node| {
1045 %return stack.append(RenderState { .Expression = body_node});
1046 %return stack.append(RenderState { .Text = " "});
1045 try stack.append(RenderState { .Expression = body_node});
1046 try stack.append(RenderState { .Text = " "});
10471047 }
1048 %return stack.append(RenderState { .Expression = return_type});
1048 try stack.append(RenderState { .Expression = return_type});
10491049 }
10501050 },
10511051 RenderState.Statement => |base| {
10521052 switch (base.id) {
10531053 ast.Node.Id.VarDecl => {
10541054 const var_decl = @fieldParentPtr(ast.NodeVarDecl, "base", base);
1055 %return stack.append(RenderState { .VarDecl = var_decl});
1055 try stack.append(RenderState { .VarDecl = var_decl});
10561056 },
10571057 else => {
1058 %return stack.append(RenderState { .Text = ";"});
1059 %return stack.append(RenderState { .Expression = base});
1058 try stack.append(RenderState { .Text = ";"});
1059 try stack.append(RenderState { .Expression = base});
10601060 },
10611061 }
10621062 },
10631063 RenderState.Indent => |new_indent| indent = new_indent,
1064 RenderState.PrintIndent => %return stream.writeByteNTimes(' ', indent),
1064 RenderState.PrintIndent => try stream.writeByteNTimes(' ', indent),
10651065 }
10661066 }
10671067 }
......@@ -1096,12 +1096,12 @@ fn testParse(source: []const u8, allocator: &mem.Allocator) -> %[]u8 {
10961096 var parser = Parser.init(&tokenizer, allocator, "(memory buffer)");
10971097 defer parser.deinit();
10981098
1099 const root_node = %return parser.parse();
1099 const root_node = try parser.parse();
11001100 defer parser.freeAst(root_node);
11011101
1102 var buffer = %return std.Buffer.initSize(allocator, 0);
1102 var buffer = try std.Buffer.initSize(allocator, 0);
11031103 var buffer_out_stream = io.BufferOutStream.init(&buffer);
1104 %return parser.renderSource(&buffer_out_stream.stream, root_node);
1104 try parser.renderSource(&buffer_out_stream.stream, root_node);
11051105 return buffer.toOwnedSlice();
11061106}
11071107
src/ast_render.cpp+1-1
......@@ -85,7 +85,7 @@ static const char *visib_mod_string(VisibMod mod) {
8585static const char *return_string(ReturnKind kind) {
8686 switch (kind) {
8787 case ReturnKindUnconditional: return "return";
88 case ReturnKindError: return "%return";
88 case ReturnKindError: return "try";
8989 }
9090 zig_unreachable();
9191}
src/parser.cpp+33-29
......@@ -225,6 +225,7 @@ static AstNode *ast_parse_return_expr(ParseContext *pc, size_t *token_index);
225225static AstNode *ast_parse_grouped_expr(ParseContext *pc, size_t *token_index, bool mandatory);
226226static AstNode *ast_parse_container_decl(ParseContext *pc, size_t *token_index, bool mandatory);
227227static AstNode *ast_parse_primary_expr(ParseContext *pc, size_t *token_index, bool mandatory);
228static AstNode *ast_parse_try_expr(ParseContext *pc, size_t *token_index);
228229
229230static void ast_expect_token(ParseContext *pc, Token *token, TokenId token_id) {
230231 if (token->id == token_id) {
......@@ -1003,25 +1004,21 @@ static AstNode *ast_parse_addr_of(ParseContext *pc, size_t *token_index) {
10031004
10041005/*
10051006PrefixOpExpression : PrefixOp PrefixOpExpression | SuffixOpExpression
1006PrefixOp = "!" | "-" | "~" | "*" | ("&" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%"
1007PrefixOp = "!" | "-" | "~" | "*" | ("&amp;" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%" | "try"
10071008*/
10081009static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index, bool mandatory) {
10091010 Token *token = &pc->tokens->at(*token_index);
10101011 if (token->id == TokenIdAmpersand) {
10111012 return ast_parse_addr_of(pc, token_index);
10121013 }
1014 if (token->id == TokenIdKeywordTry) {
1015 return ast_parse_try_expr(pc, token_index);
1016 }
10131017 PrefixOp prefix_op = tok_to_prefix_op(token);
10141018 if (prefix_op == PrefixOpInvalid) {
10151019 return ast_parse_suffix_op_expr(pc, token_index, mandatory);
10161020 }
10171021
1018 if (prefix_op == PrefixOpError || prefix_op == PrefixOpMaybe) {
1019 Token *maybe_return = &pc->tokens->at(*token_index + 1);
1020 if (maybe_return->id == TokenIdKeywordReturn) {
1021 return ast_parse_return_expr(pc, token_index);
1022 }
1023 }
1024
10251022 *token_index += 1;
10261023
10271024
......@@ -1438,38 +1435,41 @@ static AstNode *ast_parse_if_try_test_expr(ParseContext *pc, size_t *token_index
14381435}
14391436
14401437/*
1441ReturnExpression : option("%") "return" option(Expression)
1438ReturnExpression : "return" option(Expression)
14421439*/
14431440static AstNode *ast_parse_return_expr(ParseContext *pc, size_t *token_index) {
14441441 Token *token = &pc->tokens->at(*token_index);
14451442
1446 NodeType node_type;
1447 ReturnKind kind;
1448
1449 if (token->id == TokenIdPercent) {
1450 Token *next_token = &pc->tokens->at(*token_index + 1);
1451 if (next_token->id == TokenIdKeywordReturn) {
1452 kind = ReturnKindError;
1453 node_type = NodeTypeReturnExpr;
1454 *token_index += 2;
1455 } else {
1456 return nullptr;
1457 }
1458 } else if (token->id == TokenIdKeywordReturn) {
1459 kind = ReturnKindUnconditional;
1460 node_type = NodeTypeReturnExpr;
1461 *token_index += 1;
1462 } else {
1443 if (token->id != TokenIdKeywordReturn) {
14631444 return nullptr;
14641445 }
1446 *token_index += 1;
14651447
1466 AstNode *node = ast_create_node(pc, node_type, token);
1467 node->data.return_expr.kind = kind;
1448 AstNode *node = ast_create_node(pc, NodeTypeReturnExpr, token);
1449 node->data.return_expr.kind = ReturnKindUnconditional;
14681450 node->data.return_expr.expr = ast_parse_expression(pc, token_index, false);
14691451
14701452 return node;
14711453}
14721454
1455/*
1456TryExpression : "try" Expression
1457*/
1458static AstNode *ast_parse_try_expr(ParseContext *pc, size_t *token_index) {
1459 Token *token = &pc->tokens->at(*token_index);
1460
1461 if (token->id != TokenIdKeywordTry) {
1462 return nullptr;
1463 }
1464 *token_index += 1;
1465
1466 AstNode *node = ast_create_node(pc, NodeTypeReturnExpr, token);
1467 node->data.return_expr.kind = ReturnKindError;
1468 node->data.return_expr.expr = ast_parse_expression(pc, token_index, true);
1469
1470 return node;
1471}
1472
14731473/*
14741474BreakExpression = "break" option(":" Symbol) option(Expression)
14751475*/
......@@ -2124,7 +2124,7 @@ static AstNode *ast_parse_block_or_expression(ParseContext *pc, size_t *token_in
21242124}
21252125
21262126/*
2127Expression = ReturnExpression | BreakExpression | AssignmentExpression
2127Expression = TryExpression | ReturnExpression | BreakExpression | AssignmentExpression
21282128*/
21292129static AstNode *ast_parse_expression(ParseContext *pc, size_t *token_index, bool mandatory) {
21302130 Token *token = &pc->tokens->at(*token_index);
......@@ -2133,6 +2133,10 @@ static AstNode *ast_parse_expression(ParseContext *pc, size_t *token_index, bool
21332133 if (return_expr)
21342134 return return_expr;
21352135
2136 AstNode *try_expr = ast_parse_try_expr(pc, token_index);
2137 if (try_expr)
2138 return try_expr;
2139
21362140 AstNode *break_expr = ast_parse_break_expr(pc, token_index);
21372141 if (break_expr)
21382142 return break_expr;
src/tokenizer.cpp+2
......@@ -141,6 +141,7 @@ static const struct ZigKeyword zig_keywords[] = {
141141 {"test", TokenIdKeywordTest},
142142 {"this", TokenIdKeywordThis},
143143 {"true", TokenIdKeywordTrue},
144 {"try", TokenIdKeywordTry},
144145 {"undefined", TokenIdKeywordUndefined},
145146 {"union", TokenIdKeywordUnion},
146147 {"unreachable", TokenIdKeywordUnreachable},
......@@ -1541,6 +1542,7 @@ const char * token_name(TokenId id) {
15411542 case TokenIdKeywordTest: return "test";
15421543 case TokenIdKeywordThis: return "this";
15431544 case TokenIdKeywordTrue: return "true";
1545 case TokenIdKeywordTry: return "try";
15441546 case TokenIdKeywordUndefined: return "undefined";
15451547 case TokenIdKeywordUnion: return "union";
15461548 case TokenIdKeywordUnreachable: return "unreachable";
src/tokenizer.hpp+1
......@@ -80,6 +80,7 @@ enum TokenId {
8080 TokenIdKeywordTest,
8181 TokenIdKeywordThis,
8282 TokenIdKeywordTrue,
83 TokenIdKeywordTry,
8384 TokenIdKeywordUndefined,
8485 TokenIdKeywordUnion,
8586 TokenIdKeywordUnreachable,
std/array_list.zig+5-5
......@@ -60,18 +60,18 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) -> type{
6060 }
6161
6262 pub fn append(l: &Self, item: &const T) -> %void {
63 const new_item_ptr = %return l.addOne();
63 const new_item_ptr = try l.addOne();
6464 *new_item_ptr = *item;
6565 }
6666
6767 pub fn appendSlice(l: &Self, items: []align(A) const T) -> %void {
68 %return l.ensureCapacity(l.len + items.len);
68 try l.ensureCapacity(l.len + items.len);
6969 mem.copy(T, l.items[l.len..], items);
7070 l.len += items.len;
7171 }
7272
7373 pub fn resize(l: &Self, new_len: usize) -> %void {
74 %return l.ensureCapacity(new_len);
74 try l.ensureCapacity(new_len);
7575 l.len = new_len;
7676 }
7777
......@@ -87,12 +87,12 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) -> type{
8787 better_capacity += better_capacity / 2 + 8;
8888 if (better_capacity >= new_capacity) break;
8989 }
90 l.items = %return l.allocator.alignedRealloc(T, A, l.items, better_capacity);
90 l.items = try l.allocator.alignedRealloc(T, A, l.items, better_capacity);
9191 }
9292
9393 pub fn addOne(l: &Self) -> %&T {
9494 const new_length = l.len + 1;
95 %return l.ensureCapacity(new_length);
95 try l.ensureCapacity(new_length);
9696 const result = &l.items[l.len];
9797 l.len = new_length;
9898 return result;
std/base64.zig+35-35
......@@ -379,37 +379,37 @@ test "base64" {
379379}
380380
381381fn testBase64() -> %void {
382 %return testAllApis("", "");
383 %return testAllApis("f", "Zg==");
384 %return testAllApis("fo", "Zm8=");
385 %return testAllApis("foo", "Zm9v");
386 %return testAllApis("foob", "Zm9vYg==");
387 %return testAllApis("fooba", "Zm9vYmE=");
388 %return testAllApis("foobar", "Zm9vYmFy");
389
390 %return testDecodeIgnoreSpace("", " ");
391 %return testDecodeIgnoreSpace("f", "Z g= =");
392 %return testDecodeIgnoreSpace("fo", " Zm8=");
393 %return testDecodeIgnoreSpace("foo", "Zm9v ");
394 %return testDecodeIgnoreSpace("foob", "Zm9vYg = = ");
395 %return testDecodeIgnoreSpace("fooba", "Zm9v YmE=");
396 %return testDecodeIgnoreSpace("foobar", " Z m 9 v Y m F y ");
382 try testAllApis("", "");
383 try testAllApis("f", "Zg==");
384 try testAllApis("fo", "Zm8=");
385 try testAllApis("foo", "Zm9v");
386 try testAllApis("foob", "Zm9vYg==");
387 try testAllApis("fooba", "Zm9vYmE=");
388 try testAllApis("foobar", "Zm9vYmFy");
389
390 try testDecodeIgnoreSpace("", " ");
391 try testDecodeIgnoreSpace("f", "Z g= =");
392 try testDecodeIgnoreSpace("fo", " Zm8=");
393 try testDecodeIgnoreSpace("foo", "Zm9v ");
394 try testDecodeIgnoreSpace("foob", "Zm9vYg = = ");
395 try testDecodeIgnoreSpace("fooba", "Zm9v YmE=");
396 try testDecodeIgnoreSpace("foobar", " Z m 9 v Y m F y ");
397397
398398 // test getting some api errors
399 %return testError("A", error.InvalidPadding);
400 %return testError("AA", error.InvalidPadding);
401 %return testError("AAA", error.InvalidPadding);
402 %return testError("A..A", error.InvalidCharacter);
403 %return testError("AA=A", error.InvalidCharacter);
404 %return testError("AA/=", error.InvalidPadding);
405 %return testError("A/==", error.InvalidPadding);
406 %return testError("A===", error.InvalidCharacter);
407 %return testError("====", error.InvalidCharacter);
408
409 %return testOutputTooSmallError("AA==");
410 %return testOutputTooSmallError("AAA=");
411 %return testOutputTooSmallError("AAAA");
412 %return testOutputTooSmallError("AAAAAA==");
399 try testError("A", error.InvalidPadding);
400 try testError("AA", error.InvalidPadding);
401 try testError("AAA", error.InvalidPadding);
402 try testError("A..A", error.InvalidCharacter);
403 try testError("AA=A", error.InvalidCharacter);
404 try testError("AA/=", error.InvalidPadding);
405 try testError("A/==", error.InvalidPadding);
406 try testError("A===", error.InvalidCharacter);
407 try testError("====", error.InvalidCharacter);
408
409 try testOutputTooSmallError("AA==");
410 try testOutputTooSmallError("AAA=");
411 try testOutputTooSmallError("AAAA");
412 try testOutputTooSmallError("AAAAAA==");
413413}
414414
415415fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) -> %void {
......@@ -424,8 +424,8 @@ fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) -> %v
424424 // Base64Decoder
425425 {
426426 var buffer: [0x100]u8 = undefined;
427 var decoded = buffer[0..%return standard_decoder.calcSize(expected_encoded)];
428 %return standard_decoder.decode(decoded, expected_encoded);
427 var decoded = buffer[0..try standard_decoder.calcSize(expected_encoded)];
428 try standard_decoder.decode(decoded, expected_encoded);
429429 assert(mem.eql(u8, decoded, expected_decoded));
430430 }
431431
......@@ -434,8 +434,8 @@ fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) -> %v
434434 const standard_decoder_ignore_nothing = Base64DecoderWithIgnore.init(
435435 standard_alphabet_chars, standard_pad_char, "");
436436 var buffer: [0x100]u8 = undefined;
437 var decoded = buffer[0..%return Base64DecoderWithIgnore.calcSizeUpperBound(expected_encoded.len)];
438 var written = %return standard_decoder_ignore_nothing.decode(decoded, expected_encoded);
437 var decoded = buffer[0..try Base64DecoderWithIgnore.calcSizeUpperBound(expected_encoded.len)];
438 var written = try standard_decoder_ignore_nothing.decode(decoded, expected_encoded);
439439 assert(written <= decoded.len);
440440 assert(mem.eql(u8, decoded[0..written], expected_decoded));
441441 }
......@@ -453,8 +453,8 @@ fn testDecodeIgnoreSpace(expected_decoded: []const u8, encoded: []const u8) -> %
453453 const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(
454454 standard_alphabet_chars, standard_pad_char, " ");
455455 var buffer: [0x100]u8 = undefined;
456 var decoded = buffer[0..%return Base64DecoderWithIgnore.calcSizeUpperBound(encoded.len)];
457 var written = %return standard_decoder_ignore_space.decode(decoded, encoded);
456 var decoded = buffer[0..try Base64DecoderWithIgnore.calcSizeUpperBound(encoded.len)];
457 var written = try standard_decoder_ignore_space.decode(decoded, encoded);
458458 assert(mem.eql(u8, decoded[0..written], expected_decoded));
459459}
460460
std/buf_map.zig+6-6
......@@ -29,16 +29,16 @@ pub const BufMap = struct {
2929
3030 pub fn set(self: &BufMap, key: []const u8, value: []const u8) -> %void {
3131 if (self.hash_map.get(key)) |entry| {
32 const value_copy = %return self.copy(value);
32 const value_copy = try self.copy(value);
3333 %defer self.free(value_copy);
34 _ = %return self.hash_map.put(key, value_copy);
34 _ = try self.hash_map.put(key, value_copy);
3535 self.free(entry.value);
3636 } else {
37 const key_copy = %return self.copy(key);
37 const key_copy = try self.copy(key);
3838 %defer self.free(key_copy);
39 const value_copy = %return self.copy(value);
39 const value_copy = try self.copy(value);
4040 %defer self.free(value_copy);
41 _ = %return self.hash_map.put(key_copy, value_copy);
41 _ = try self.hash_map.put(key_copy, value_copy);
4242 }
4343 }
4444
......@@ -68,7 +68,7 @@ pub const BufMap = struct {
6868 }
6969
7070 fn copy(self: &BufMap, value: []const u8) -> %[]const u8 {
71 const result = %return self.hash_map.allocator.alloc(u8, value.len);
71 const result = try self.hash_map.allocator.alloc(u8, value.len);
7272 mem.copy(u8, result, value);
7373 return result;
7474 }
std/buf_set.zig+3-3
......@@ -26,9 +26,9 @@ pub const BufSet = struct {
2626
2727 pub fn put(self: &BufSet, key: []const u8) -> %void {
2828 if (self.hash_map.get(key) == null) {
29 const key_copy = %return self.copy(key);
29 const key_copy = try self.copy(key);
3030 %defer self.free(key_copy);
31 _ = %return self.hash_map.put(key_copy, {});
31 _ = try self.hash_map.put(key_copy, {});
3232 }
3333 }
3434
......@@ -56,7 +56,7 @@ pub const BufSet = struct {
5656 }
5757
5858 fn copy(self: &BufSet, value: []const u8) -> %[]const u8 {
59 const result = %return self.hash_map.allocator.alloc(u8, value.len);
59 const result = try self.hash_map.allocator.alloc(u8, value.len);
6060 mem.copy(u8, result, value);
6161 return result;
6262 }
std/buffer.zig+6-6
......@@ -13,7 +13,7 @@ pub const Buffer = struct {
1313
1414 /// Must deinitialize with deinit.
1515 pub fn init(allocator: &Allocator, m: []const u8) -> %Buffer {
16 var self = %return initSize(allocator, m.len);
16 var self = try initSize(allocator, m.len);
1717 mem.copy(u8, self.list.items, m);
1818 return self;
1919 }
......@@ -21,7 +21,7 @@ pub const Buffer = struct {
2121 /// Must deinitialize with deinit.
2222 pub fn initSize(allocator: &Allocator, size: usize) -> %Buffer {
2323 var self = initNull(allocator);
24 %return self.resize(size);
24 try self.resize(size);
2525 return self;
2626 }
2727
......@@ -81,7 +81,7 @@ pub const Buffer = struct {
8181 }
8282
8383 pub fn resize(self: &Buffer, new_len: usize) -> %void {
84 %return self.list.resize(new_len + 1);
84 try self.list.resize(new_len + 1);
8585 self.list.items[self.len()] = 0;
8686 }
8787
......@@ -95,7 +95,7 @@ pub const Buffer = struct {
9595
9696 pub fn append(self: &Buffer, m: []const u8) -> %void {
9797 const old_len = self.len();
98 %return self.resize(old_len + m.len);
98 try self.resize(old_len + m.len);
9999 mem.copy(u8, self.list.toSlice()[old_len..], m);
100100 }
101101
......@@ -113,7 +113,7 @@ pub const Buffer = struct {
113113 pub fn appendByteNTimes(self: &Buffer, byte: u8, count: usize) -> %void {
114114 var prev_size: usize = self.len();
115115 const new_size = prev_size + count;
116 %return self.resize(new_size);
116 try self.resize(new_size);
117117
118118 var i: usize = prev_size;
119119 while (i < new_size) : (i += 1) {
......@@ -138,7 +138,7 @@ pub const Buffer = struct {
138138 }
139139
140140 pub fn replaceContents(self: &const Buffer, m: []const u8) -> %void {
141 %return self.resize(m.len);
141 try self.resize(m.len);
142142 mem.copy(u8, self.list.toSlice(), m);
143143 }
144144
std/build.zig+23-23
......@@ -250,13 +250,13 @@ pub const Builder = struct {
250250 %%wanted_steps.append(&self.default_step);
251251 } else {
252252 for (step_names) |step_name| {
253 const s = %return self.getTopLevelStepByName(step_name);
253 const s = try self.getTopLevelStepByName(step_name);
254254 %%wanted_steps.append(s);
255255 }
256256 }
257257
258258 for (wanted_steps.toSliceConst()) |s| {
259 %return self.makeOneStep(s);
259 try self.makeOneStep(s);
260260 }
261261 }
262262
......@@ -310,7 +310,7 @@ pub const Builder = struct {
310310
311311 s.loop_flag = false;
312312
313 %return s.make();
313 try s.make();
314314 }
315315
316316 fn getTopLevelStepByName(self: &Builder, name: []const u8) -> %&Step {
......@@ -680,7 +680,7 @@ pub const Builder = struct {
680680 if (os.path.isAbsolute(name)) {
681681 return name;
682682 }
683 const full_path = %return os.path.join(self.allocator, search_prefix, "bin",
683 const full_path = try os.path.join(self.allocator, search_prefix, "bin",
684684 self.fmt("{}{}", name, exe_extension));
685685 if (os.path.real(self.allocator, full_path)) |real_path| {
686686 return real_path;
......@@ -696,7 +696,7 @@ pub const Builder = struct {
696696 }
697697 var it = mem.split(PATH, []u8{os.path.delimiter});
698698 while (it.next()) |path| {
699 const full_path = %return os.path.join(self.allocator, path, self.fmt("{}{}", name, exe_extension));
699 const full_path = try os.path.join(self.allocator, path, self.fmt("{}{}", name, exe_extension));
700700 if (os.path.real(self.allocator, full_path)) |real_path| {
701701 return real_path;
702702 } else |_| {
......@@ -710,7 +710,7 @@ pub const Builder = struct {
710710 return name;
711711 }
712712 for (paths) |path| {
713 const full_path = %return os.path.join(self.allocator, path, self.fmt("{}{}", name, exe_extension));
713 const full_path = try os.path.join(self.allocator, path, self.fmt("{}{}", name, exe_extension));
714714 if (os.path.real(self.allocator, full_path)) |real_path| {
715715 return real_path;
716716 } else |_| {
......@@ -1345,10 +1345,10 @@ pub const LibExeObjStep = struct {
13451345 }
13461346 }
13471347
1348 %return builder.spawnChild(zig_args.toSliceConst());
1348 try builder.spawnChild(zig_args.toSliceConst());
13491349
13501350 if (self.kind == Kind.Lib and !self.static and self.target.wantSharedLibSymLinks()) {
1351 %return doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename,
1351 try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename,
13521352 self.name_only_filename);
13531353 }
13541354 }
......@@ -1423,7 +1423,7 @@ pub const LibExeObjStep = struct {
14231423
14241424 self.appendCompileFlags(&cc_args);
14251425
1426 %return builder.spawnChild(cc_args.toSliceConst());
1426 try builder.spawnChild(cc_args.toSliceConst());
14271427 },
14281428 Kind.Lib => {
14291429 for (self.source_files.toSliceConst()) |source_file| {
......@@ -1440,14 +1440,14 @@ pub const LibExeObjStep = struct {
14401440
14411441 const cache_o_src = %%os.path.join(builder.allocator, builder.cache_root, source_file);
14421442 const cache_o_dir = os.path.dirname(cache_o_src);
1443 %return builder.makePath(cache_o_dir);
1443 try builder.makePath(cache_o_dir);
14441444 const cache_o_file = builder.fmt("{}{}", cache_o_src, self.target.oFileExt());
14451445 %%cc_args.append("-o");
14461446 %%cc_args.append(builder.pathFromRoot(cache_o_file));
14471447
14481448 self.appendCompileFlags(&cc_args);
14491449
1450 %return builder.spawnChild(cc_args.toSliceConst());
1450 try builder.spawnChild(cc_args.toSliceConst());
14511451
14521452 %%self.object_files.append(cache_o_file);
14531453 }
......@@ -1466,14 +1466,14 @@ pub const LibExeObjStep = struct {
14661466 %%cc_args.append(builder.pathFromRoot(object_file));
14671467 }
14681468
1469 %return builder.spawnChild(cc_args.toSliceConst());
1469 try builder.spawnChild(cc_args.toSliceConst());
14701470
14711471 // ranlib
14721472 %%cc_args.resize(0);
14731473 %%cc_args.append("ranlib");
14741474 %%cc_args.append(output_path);
14751475
1476 %return builder.spawnChild(cc_args.toSliceConst());
1476 try builder.spawnChild(cc_args.toSliceConst());
14771477 } else {
14781478 %%cc_args.resize(0);
14791479 %%cc_args.append(cc);
......@@ -1537,10 +1537,10 @@ pub const LibExeObjStep = struct {
15371537 }
15381538 }
15391539
1540 %return builder.spawnChild(cc_args.toSliceConst());
1540 try builder.spawnChild(cc_args.toSliceConst());
15411541
15421542 if (self.target.wantSharedLibSymLinks()) {
1543 %return doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename,
1543 try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename,
15441544 self.name_only_filename);
15451545 }
15461546 }
......@@ -1556,7 +1556,7 @@ pub const LibExeObjStep = struct {
15561556
15571557 const cache_o_src = %%os.path.join(builder.allocator, builder.cache_root, source_file);
15581558 const cache_o_dir = os.path.dirname(cache_o_src);
1559 %return builder.makePath(cache_o_dir);
1559 try builder.makePath(cache_o_dir);
15601560 const cache_o_file = builder.fmt("{}{}", cache_o_src, self.target.oFileExt());
15611561 %%cc_args.append("-o");
15621562 %%cc_args.append(builder.pathFromRoot(cache_o_file));
......@@ -1570,7 +1570,7 @@ pub const LibExeObjStep = struct {
15701570 %%cc_args.append(builder.pathFromRoot(dir));
15711571 }
15721572
1573 %return builder.spawnChild(cc_args.toSliceConst());
1573 try builder.spawnChild(cc_args.toSliceConst());
15741574
15751575 %%self.object_files.append(cache_o_file);
15761576 }
......@@ -1619,7 +1619,7 @@ pub const LibExeObjStep = struct {
16191619 }
16201620 }
16211621
1622 %return builder.spawnChild(cc_args.toSliceConst());
1622 try builder.spawnChild(cc_args.toSliceConst());
16231623 },
16241624 }
16251625 }
......@@ -1770,7 +1770,7 @@ pub const TestStep = struct {
17701770 %%zig_args.append(lib_path);
17711771 }
17721772
1773 %return builder.spawnChild(zig_args.toSliceConst());
1773 try builder.spawnChild(zig_args.toSliceConst());
17741774 }
17751775};
17761776
......@@ -1847,9 +1847,9 @@ const InstallArtifactStep = struct {
18471847 LibExeObjStep.Kind.Exe => usize(0o755),
18481848 LibExeObjStep.Kind.Lib => if (self.artifact.static) usize(0o666) else usize(0o755),
18491849 };
1850 %return builder.copyFileMode(self.artifact.getOutputPath(), self.dest_file, mode);
1850 try builder.copyFileMode(self.artifact.getOutputPath(), self.dest_file, mode);
18511851 if (self.artifact.kind == LibExeObjStep.Kind.Lib and !self.artifact.static) {
1852 %return doAtomicSymLinks(builder.allocator, self.dest_file,
1852 try doAtomicSymLinks(builder.allocator, self.dest_file,
18531853 self.artifact.major_only_filename, self.artifact.name_only_filename);
18541854 }
18551855 }
......@@ -1872,7 +1872,7 @@ pub const InstallFileStep = struct {
18721872
18731873 fn make(step: &Step) -> %void {
18741874 const self = @fieldParentPtr(InstallFileStep, "step", step);
1875 %return self.builder.copyFile(self.src_path, self.dest_path);
1875 try self.builder.copyFile(self.src_path, self.dest_path);
18761876 }
18771877};
18781878
......@@ -1973,7 +1973,7 @@ pub const Step = struct {
19731973 if (self.done_flag)
19741974 return;
19751975
1976 %return self.makeFn(self);
1976 try self.makeFn(self);
19771977 self.done_flag = true;
19781978 }
19791979
std/cstr.zig+2-2
......@@ -43,7 +43,7 @@ fn testCStrFnsImpl() {
4343/// have a null byte after it.
4444/// Caller owns the returned memory.
4545pub fn addNullByte(allocator: &mem.Allocator, slice: []const u8) -> %[]u8 {
46 const result = %return allocator.alloc(u8, slice.len + 1);
46 const result = try allocator.alloc(u8, slice.len + 1);
4747 mem.copy(u8, result, slice);
4848 result[slice.len] = 0;
4949 return result;
......@@ -70,7 +70,7 @@ pub const NullTerminated2DArray = struct {
7070 const index_size = @sizeOf(usize) * new_len; // size of the ptrs
7171 byte_count += index_size;
7272
73 const buf = %return allocator.alignedAlloc(u8, @alignOf(?&u8), byte_count);
73 const buf = try allocator.alignedAlloc(u8, @alignOf(?&u8), byte_count);
7474 %defer allocator.free(buf);
7575
7676 var write_index = index_size;
std/debug/failing_allocator.zig+2-2
......@@ -33,7 +33,7 @@ pub const FailingAllocator = struct {
3333 if (self.index == self.fail_index) {
3434 return error.OutOfMemory;
3535 }
36 const result = %return self.internal_allocator.allocFn(self.internal_allocator, n, alignment);
36 const result = try self.internal_allocator.allocFn(self.internal_allocator, n, alignment);
3737 self.allocated_bytes += result.len;
3838 self.index += 1;
3939 return result;
......@@ -48,7 +48,7 @@ pub const FailingAllocator = struct {
4848 if (self.index == self.fail_index) {
4949 return error.OutOfMemory;
5050 }
51 const result = %return self.internal_allocator.reallocFn(self.internal_allocator, old_mem, new_size, alignment);
51 const result = try self.internal_allocator.reallocFn(self.internal_allocator, old_mem, new_size, alignment);
5252 self.allocated_bytes += new_size - old_mem.len;
5353 self.deallocations += 1;
5454 self.index += 1;
std/debug/index.zig+124-124
......@@ -29,7 +29,7 @@ fn getStderrStream() -> %&io.OutStream {
2929 if (stderr_stream) |st| {
3030 return st;
3131 } else {
32 stderr_file = %return io.getStdErr();
32 stderr_file = try io.getStdErr();
3333 stderr_file_out_stream = io.FileOutStream.init(&stderr_file);
3434 const st = &stderr_file_out_stream.stream;
3535 stderr_stream = st;
......@@ -118,18 +118,18 @@ pub fn writeStackTrace(out_stream: &io.OutStream, allocator: &mem.Allocator, tty
118118 .compile_unit_list = ArrayList(CompileUnit).init(allocator),
119119 };
120120 const st = &stack_trace;
121 st.self_exe_file = %return os.openSelfExe();
121 st.self_exe_file = try os.openSelfExe();
122122 defer st.self_exe_file.close();
123123
124 %return st.elf.openFile(allocator, &st.self_exe_file);
124 try st.elf.openFile(allocator, &st.self_exe_file);
125125 defer st.elf.close();
126126
127 st.debug_info = (%return st.elf.findSection(".debug_info")) ?? return error.MissingDebugInfo;
128 st.debug_abbrev = (%return st.elf.findSection(".debug_abbrev")) ?? return error.MissingDebugInfo;
129 st.debug_str = (%return st.elf.findSection(".debug_str")) ?? return error.MissingDebugInfo;
130 st.debug_line = (%return st.elf.findSection(".debug_line")) ?? return error.MissingDebugInfo;
131 st.debug_ranges = (%return st.elf.findSection(".debug_ranges"));
132 %return scanAllCompileUnits(st);
127 st.debug_info = (try st.elf.findSection(".debug_info")) ?? return error.MissingDebugInfo;
128 st.debug_abbrev = (try st.elf.findSection(".debug_abbrev")) ?? return error.MissingDebugInfo;
129 st.debug_str = (try st.elf.findSection(".debug_str")) ?? return error.MissingDebugInfo;
130 st.debug_line = (try st.elf.findSection(".debug_line")) ?? return error.MissingDebugInfo;
131 st.debug_ranges = (try st.elf.findSection(".debug_ranges"));
132 try scanAllCompileUnits(st);
133133
134134 var ignored_count: usize = 0;
135135
......@@ -147,25 +147,25 @@ pub fn writeStackTrace(out_stream: &io.OutStream, allocator: &mem.Allocator, tty
147147 const ptr_hex = if (@sizeOf(usize) == 4) "0x{x8}" else "0x{x16}";
148148
149149 const compile_unit = findCompileUnit(st, return_address) %% {
150 %return out_stream.print("???:?:?: " ++ DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n ???\n\n",
150 try out_stream.print("???:?:?: " ++ DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n ???\n\n",
151151 return_address);
152152 continue;
153153 };
154 const compile_unit_name = %return compile_unit.die.getAttrString(st, DW.AT_name);
154 const compile_unit_name = try compile_unit.die.getAttrString(st, DW.AT_name);
155155 if (getLineNumberInfo(st, compile_unit, usize(return_address) - 1)) |line_info| {
156156 defer line_info.deinit();
157 %return out_stream.print(WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++
157 try out_stream.print(WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++
158158 DIM ++ ptr_hex ++ " in ??? ({})" ++ RESET ++ "\n",
159159 line_info.file_name, line_info.line, line_info.column,
160160 return_address, compile_unit_name);
161161 if (printLineFromFile(st.allocator(), out_stream, line_info)) {
162162 if (line_info.column == 0) {
163 %return out_stream.write("\n");
163 try out_stream.write("\n");
164164 } else {
165165 {var col_i: usize = 1; while (col_i < line_info.column) : (col_i += 1) {
166 %return out_stream.writeByte(' ');
166 try out_stream.writeByte(' ');
167167 }}
168 %return out_stream.write(GREEN ++ "^" ++ RESET ++ "\n");
168 try out_stream.write(GREEN ++ "^" ++ RESET ++ "\n");
169169 }
170170 } else |err| switch (err) {
171171 error.EndOfFile, error.PathNotFound => {},
......@@ -173,7 +173,7 @@ pub fn writeStackTrace(out_stream: &io.OutStream, allocator: &mem.Allocator, tty
173173 }
174174 } else |err| switch (err) {
175175 error.MissingDebugInfo, error.InvalidDebugInfo => {
176 %return out_stream.print(ptr_hex ++ " in ??? ({})\n",
176 try out_stream.print(ptr_hex ++ " in ??? ({})\n",
177177 return_address, compile_unit_name);
178178 },
179179 else => return err,
......@@ -181,22 +181,22 @@ pub fn writeStackTrace(out_stream: &io.OutStream, allocator: &mem.Allocator, tty
181181 }
182182 },
183183 builtin.ObjectFormat.coff => {
184 %return out_stream.write("(stack trace unavailable for COFF object format)\n");
184 try out_stream.write("(stack trace unavailable for COFF object format)\n");
185185 },
186186 builtin.ObjectFormat.macho => {
187 %return out_stream.write("(stack trace unavailable for Mach-O object format)\n");
187 try out_stream.write("(stack trace unavailable for Mach-O object format)\n");
188188 },
189189 builtin.ObjectFormat.wasm => {
190 %return out_stream.write("(stack trace unavailable for WASM object format)\n");
190 try out_stream.write("(stack trace unavailable for WASM object format)\n");
191191 },
192192 builtin.ObjectFormat.unknown => {
193 %return out_stream.write("(stack trace unavailable for unknown object format)\n");
193 try out_stream.write("(stack trace unavailable for unknown object format)\n");
194194 },
195195 }
196196}
197197
198198fn printLineFromFile(allocator: &mem.Allocator, out_stream: &io.OutStream, line_info: &const LineInfo) -> %void {
199 var f = %return io.File.openRead(line_info.file_name, allocator);
199 var f = try io.File.openRead(line_info.file_name, allocator);
200200 defer f.close();
201201 // TODO fstat and make sure that the file has the correct size
202202
......@@ -205,12 +205,12 @@ fn printLineFromFile(allocator: &mem.Allocator, out_stream: &io.OutStream, line_
205205 var column: usize = 1;
206206 var abs_index: usize = 0;
207207 while (true) {
208 const amt_read = %return f.read(buf[0..]);
208 const amt_read = try f.read(buf[0..]);
209209 const slice = buf[0..amt_read];
210210
211211 for (slice) |byte| {
212212 if (line == line_info.line) {
213 %return out_stream.writeByte(byte);
213 try out_stream.writeByte(byte);
214214 if (byte == '\n') {
215215 return;
216216 }
......@@ -437,7 +437,7 @@ const LineNumberProgram = struct {
437437 const dir_name = if (file_entry.dir_index >= self.include_dirs.len) {
438438 return error.InvalidDebugInfo;
439439 } else self.include_dirs[file_entry.dir_index];
440 const file_name = %return os.path.join(self.file_entries.allocator, dir_name, file_entry.file_name);
440 const file_name = try os.path.join(self.file_entries.allocator, dir_name, file_entry.file_name);
441441 %defer self.file_entries.allocator.free(file_name);
442442 return LineInfo {
443443 .line = if (self.prev_line >= 0) usize(self.prev_line) else 0,
......@@ -461,73 +461,73 @@ const LineNumberProgram = struct {
461461fn readStringRaw(allocator: &mem.Allocator, in_stream: &io.InStream) -> %[]u8 {
462462 var buf = ArrayList(u8).init(allocator);
463463 while (true) {
464 const byte = %return in_stream.readByte();
464 const byte = try in_stream.readByte();
465465 if (byte == 0)
466466 break;
467 %return buf.append(byte);
467 try buf.append(byte);
468468 }
469469 return buf.toSlice();
470470}
471471
472472fn getString(st: &ElfStackTrace, offset: u64) -> %[]u8 {
473473 const pos = st.debug_str.offset + offset;
474 %return st.self_exe_file.seekTo(pos);
474 try st.self_exe_file.seekTo(pos);
475475 return st.readString();
476476}
477477
478478fn readAllocBytes(allocator: &mem.Allocator, in_stream: &io.InStream, size: usize) -> %[]u8 {
479 const buf = %return global_allocator.alloc(u8, size);
479 const buf = try global_allocator.alloc(u8, size);
480480 %defer global_allocator.free(buf);
481 if ((%return in_stream.read(buf)) < size) return error.EndOfFile;
481 if ((try in_stream.read(buf)) < size) return error.EndOfFile;
482482 return buf;
483483}
484484
485485fn parseFormValueBlockLen(allocator: &mem.Allocator, in_stream: &io.InStream, size: usize) -> %FormValue {
486 const buf = %return readAllocBytes(allocator, in_stream, size);
486 const buf = try readAllocBytes(allocator, in_stream, size);
487487 return FormValue { .Block = buf };
488488}
489489
490490fn parseFormValueBlock(allocator: &mem.Allocator, in_stream: &io.InStream, size: usize) -> %FormValue {
491 const block_len = %return in_stream.readVarInt(builtin.Endian.Little, usize, size);
491 const block_len = try in_stream.readVarInt(builtin.Endian.Little, usize, size);
492492 return parseFormValueBlockLen(allocator, in_stream, block_len);
493493}
494494
495495fn parseFormValueConstant(allocator: &mem.Allocator, in_stream: &io.InStream, signed: bool, size: usize) -> %FormValue {
496496 return FormValue { .Const = Constant {
497497 .signed = signed,
498 .payload = %return readAllocBytes(allocator, in_stream, size),
498 .payload = try readAllocBytes(allocator, in_stream, size),
499499 }};
500500}
501501
502502fn parseFormValueDwarfOffsetSize(in_stream: &io.InStream, is_64: bool) -> %u64 {
503 return if (is_64) %return in_stream.readIntLe(u64)
504 else u64(%return in_stream.readIntLe(u32)) ;
503 return if (is_64) try in_stream.readIntLe(u64)
504 else u64(try in_stream.readIntLe(u32)) ;
505505}
506506
507507fn parseFormValueTargetAddrSize(in_stream: &io.InStream) -> %u64 {
508 return if (@sizeOf(usize) == 4) u64(%return in_stream.readIntLe(u32))
509 else if (@sizeOf(usize) == 8) %return in_stream.readIntLe(u64)
508 return if (@sizeOf(usize) == 4) u64(try in_stream.readIntLe(u32))
509 else if (@sizeOf(usize) == 8) try in_stream.readIntLe(u64)
510510 else unreachable;
511511}
512512
513513fn parseFormValueRefLen(allocator: &mem.Allocator, in_stream: &io.InStream, size: usize) -> %FormValue {
514 const buf = %return readAllocBytes(allocator, in_stream, size);
514 const buf = try readAllocBytes(allocator, in_stream, size);
515515 return FormValue { .Ref = buf };
516516}
517517
518518fn parseFormValueRef(allocator: &mem.Allocator, in_stream: &io.InStream, comptime T: type) -> %FormValue {
519 const block_len = %return in_stream.readIntLe(T);
519 const block_len = try in_stream.readIntLe(T);
520520 return parseFormValueRefLen(allocator, in_stream, block_len);
521521}
522522
523523fn parseFormValue(allocator: &mem.Allocator, in_stream: &io.InStream, form_id: u64, is_64: bool) -> %FormValue {
524524 return switch (form_id) {
525 DW.FORM_addr => FormValue { .Address = %return parseFormValueTargetAddrSize(in_stream) },
525 DW.FORM_addr => FormValue { .Address = try parseFormValueTargetAddrSize(in_stream) },
526526 DW.FORM_block1 => parseFormValueBlock(allocator, in_stream, 1),
527527 DW.FORM_block2 => parseFormValueBlock(allocator, in_stream, 2),
528528 DW.FORM_block4 => parseFormValueBlock(allocator, in_stream, 4),
529529 DW.FORM_block => x: {
530 const block_len = %return readULeb128(in_stream);
530 const block_len = try readULeb128(in_stream);
531531 return parseFormValueBlockLen(allocator, in_stream, block_len);
532532 },
533533 DW.FORM_data1 => parseFormValueConstant(allocator, in_stream, false, 1),
......@@ -535,35 +535,35 @@ fn parseFormValue(allocator: &mem.Allocator, in_stream: &io.InStream, form_id: u
535535 DW.FORM_data4 => parseFormValueConstant(allocator, in_stream, false, 4),
536536 DW.FORM_data8 => parseFormValueConstant(allocator, in_stream, false, 8),
537537 DW.FORM_udata, DW.FORM_sdata => {
538 const block_len = %return readULeb128(in_stream);
538 const block_len = try readULeb128(in_stream);
539539 const signed = form_id == DW.FORM_sdata;
540540 return parseFormValueConstant(allocator, in_stream, signed, block_len);
541541 },
542542 DW.FORM_exprloc => {
543 const size = %return readULeb128(in_stream);
544 const buf = %return readAllocBytes(allocator, in_stream, size);
543 const size = try readULeb128(in_stream);
544 const buf = try readAllocBytes(allocator, in_stream, size);
545545 return FormValue { .ExprLoc = buf };
546546 },
547 DW.FORM_flag => FormValue { .Flag = (%return in_stream.readByte()) != 0 },
547 DW.FORM_flag => FormValue { .Flag = (try in_stream.readByte()) != 0 },
548548 DW.FORM_flag_present => FormValue { .Flag = true },
549 DW.FORM_sec_offset => FormValue { .SecOffset = %return parseFormValueDwarfOffsetSize(in_stream, is_64) },
549 DW.FORM_sec_offset => FormValue { .SecOffset = try parseFormValueDwarfOffsetSize(in_stream, is_64) },
550550
551551 DW.FORM_ref1 => parseFormValueRef(allocator, in_stream, u8),
552552 DW.FORM_ref2 => parseFormValueRef(allocator, in_stream, u16),
553553 DW.FORM_ref4 => parseFormValueRef(allocator, in_stream, u32),
554554 DW.FORM_ref8 => parseFormValueRef(allocator, in_stream, u64),
555555 DW.FORM_ref_udata => {
556 const ref_len = %return readULeb128(in_stream);
556 const ref_len = try readULeb128(in_stream);
557557 return parseFormValueRefLen(allocator, in_stream, ref_len);
558558 },
559559
560 DW.FORM_ref_addr => FormValue { .RefAddr = %return parseFormValueDwarfOffsetSize(in_stream, is_64) },
561 DW.FORM_ref_sig8 => FormValue { .RefSig8 = %return in_stream.readIntLe(u64) },
560 DW.FORM_ref_addr => FormValue { .RefAddr = try parseFormValueDwarfOffsetSize(in_stream, is_64) },
561 DW.FORM_ref_sig8 => FormValue { .RefSig8 = try in_stream.readIntLe(u64) },
562562
563 DW.FORM_string => FormValue { .String = %return readStringRaw(allocator, in_stream) },
564 DW.FORM_strp => FormValue { .StrPtr = %return parseFormValueDwarfOffsetSize(in_stream, is_64) },
563 DW.FORM_string => FormValue { .String = try readStringRaw(allocator, in_stream) },
564 DW.FORM_strp => FormValue { .StrPtr = try parseFormValueDwarfOffsetSize(in_stream, is_64) },
565565 DW.FORM_indirect => {
566 const child_form_id = %return readULeb128(in_stream);
566 const child_form_id = try readULeb128(in_stream);
567567 return parseFormValue(allocator, in_stream, child_form_id, is_64);
568568 },
569569 else => error.InvalidDebugInfo,
......@@ -576,23 +576,23 @@ fn parseAbbrevTable(st: &ElfStackTrace) -> %AbbrevTable {
576576 const in_stream = &in_file_stream.stream;
577577 var result = AbbrevTable.init(st.allocator());
578578 while (true) {
579 const abbrev_code = %return readULeb128(in_stream);
579 const abbrev_code = try readULeb128(in_stream);
580580 if (abbrev_code == 0)
581581 return result;
582 %return result.append(AbbrevTableEntry {
582 try result.append(AbbrevTableEntry {
583583 .abbrev_code = abbrev_code,
584 .tag_id = %return readULeb128(in_stream),
585 .has_children = (%return in_stream.readByte()) == DW.CHILDREN_yes,
584 .tag_id = try readULeb128(in_stream),
585 .has_children = (try in_stream.readByte()) == DW.CHILDREN_yes,
586586 .attrs = ArrayList(AbbrevAttr).init(st.allocator()),
587587 });
588588 const attrs = &result.items[result.len - 1].attrs;
589589
590590 while (true) {
591 const attr_id = %return readULeb128(in_stream);
592 const form_id = %return readULeb128(in_stream);
591 const attr_id = try readULeb128(in_stream);
592 const form_id = try readULeb128(in_stream);
593593 if (attr_id == 0 and form_id == 0)
594594 break;
595 %return attrs.append(AbbrevAttr {
595 try attrs.append(AbbrevAttr {
596596 .attr_id = attr_id,
597597 .form_id = form_id,
598598 });
......@@ -608,10 +608,10 @@ fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) -> %&const AbbrevTable
608608 return &header.table;
609609 }
610610 }
611 %return st.self_exe_file.seekTo(st.debug_abbrev.offset + abbrev_offset);
612 %return st.abbrev_table_list.append(AbbrevTableHeader {
611 try st.self_exe_file.seekTo(st.debug_abbrev.offset + abbrev_offset);
612 try st.abbrev_table_list.append(AbbrevTableHeader {
613613 .offset = abbrev_offset,
614 .table = %return parseAbbrevTable(st),
614 .table = try parseAbbrevTable(st),
615615 });
616616 return &st.abbrev_table_list.items[st.abbrev_table_list.len - 1].table;
617617}
......@@ -628,7 +628,7 @@ fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) -
628628 const in_file = &st.self_exe_file;
629629 var in_file_stream = io.FileInStream.init(in_file);
630630 const in_stream = &in_file_stream.stream;
631 const abbrev_code = %return readULeb128(in_stream);
631 const abbrev_code = try readULeb128(in_stream);
632632 const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) ?? return error.InvalidDebugInfo;
633633
634634 var result = Die {
......@@ -636,18 +636,18 @@ fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) -
636636 .has_children = table_entry.has_children,
637637 .attrs = ArrayList(Die.Attr).init(st.allocator()),
638638 };
639 %return result.attrs.resize(table_entry.attrs.len);
639 try result.attrs.resize(table_entry.attrs.len);
640640 for (table_entry.attrs.toSliceConst()) |attr, i| {
641641 result.attrs.items[i] = Die.Attr {
642642 .id = attr.attr_id,
643 .value = %return parseFormValue(st.allocator(), in_stream, attr.form_id, is_64),
643 .value = try parseFormValue(st.allocator(), in_stream, attr.form_id, is_64),
644644 };
645645 }
646646 return result;
647647}
648648
649649fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, target_address: usize) -> %LineInfo {
650 const compile_unit_cwd = %return compile_unit.die.getAttrString(st, DW.AT_comp_dir);
650 const compile_unit_cwd = try compile_unit.die.getAttrString(st, DW.AT_comp_dir);
651651
652652 const in_file = &st.self_exe_file;
653653 const debug_line_end = st.debug_line.offset + st.debug_line.size;
......@@ -658,10 +658,10 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
658658 const in_stream = &in_file_stream.stream;
659659
660660 while (this_offset < debug_line_end) : (this_index += 1) {
661 %return in_file.seekTo(this_offset);
661 try in_file.seekTo(this_offset);
662662
663663 var is_64: bool = undefined;
664 const unit_length = %return readInitialLength(in_stream, &is_64);
664 const unit_length = try readInitialLength(in_stream, &is_64);
665665 if (unit_length == 0)
666666 return error.MissingDebugInfo;
667667 const next_offset = unit_length + (if (is_64) usize(12) else usize(4));
......@@ -671,37 +671,37 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
671671 continue;
672672 }
673673
674 const version = %return in_stream.readInt(st.elf.endian, u16);
674 const version = try in_stream.readInt(st.elf.endian, u16);
675675 if (version != 2) return error.InvalidDebugInfo;
676676
677 const prologue_length = %return in_stream.readInt(st.elf.endian, u32);
678 const prog_start_offset = (%return in_file.getPos()) + prologue_length;
677 const prologue_length = try in_stream.readInt(st.elf.endian, u32);
678 const prog_start_offset = (try in_file.getPos()) + prologue_length;
679679
680 const minimum_instruction_length = %return in_stream.readByte();
680 const minimum_instruction_length = try in_stream.readByte();
681681 if (minimum_instruction_length == 0) return error.InvalidDebugInfo;
682682
683 const default_is_stmt = (%return in_stream.readByte()) != 0;
684 const line_base = %return in_stream.readByteSigned();
683 const default_is_stmt = (try in_stream.readByte()) != 0;
684 const line_base = try in_stream.readByteSigned();
685685
686 const line_range = %return in_stream.readByte();
686 const line_range = try in_stream.readByte();
687687 if (line_range == 0)
688688 return error.InvalidDebugInfo;
689689
690 const opcode_base = %return in_stream.readByte();
690 const opcode_base = try in_stream.readByte();
691691
692 const standard_opcode_lengths = %return st.allocator().alloc(u8, opcode_base - 1);
692 const standard_opcode_lengths = try st.allocator().alloc(u8, opcode_base - 1);
693693
694694 {var i: usize = 0; while (i < opcode_base - 1) : (i += 1) {
695 standard_opcode_lengths[i] = %return in_stream.readByte();
695 standard_opcode_lengths[i] = try in_stream.readByte();
696696 }}
697697
698698 var include_directories = ArrayList([]u8).init(st.allocator());
699 %return include_directories.append(compile_unit_cwd);
699 try include_directories.append(compile_unit_cwd);
700700 while (true) {
701 const dir = %return st.readString();
701 const dir = try st.readString();
702702 if (dir.len == 0)
703703 break;
704 %return include_directories.append(dir);
704 try include_directories.append(dir);
705705 }
706706
707707 var file_entries = ArrayList(FileEntry).init(st.allocator());
......@@ -709,13 +709,13 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
709709 &file_entries, target_address);
710710
711711 while (true) {
712 const file_name = %return st.readString();
712 const file_name = try st.readString();
713713 if (file_name.len == 0)
714714 break;
715 const dir_index = %return readULeb128(in_stream);
716 const mtime = %return readULeb128(in_stream);
717 const len_bytes = %return readULeb128(in_stream);
718 %return file_entries.append(FileEntry {
715 const dir_index = try readULeb128(in_stream);
716 const mtime = try readULeb128(in_stream);
717 const len_bytes = try readULeb128(in_stream);
718 try file_entries.append(FileEntry {
719719 .file_name = file_name,
720720 .dir_index = dir_index,
721721 .mtime = mtime,
......@@ -723,33 +723,33 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
723723 });
724724 }
725725
726 %return in_file.seekTo(prog_start_offset);
726 try in_file.seekTo(prog_start_offset);
727727
728728 while (true) {
729 const opcode = %return in_stream.readByte();
729 const opcode = try in_stream.readByte();
730730
731731 var sub_op: u8 = undefined; // TODO move this to the correct scope and fix the compiler crash
732732 if (opcode == DW.LNS_extended_op) {
733 const op_size = %return readULeb128(in_stream);
733 const op_size = try readULeb128(in_stream);
734734 if (op_size < 1)
735735 return error.InvalidDebugInfo;
736 sub_op = %return in_stream.readByte();
736 sub_op = try in_stream.readByte();
737737 switch (sub_op) {
738738 DW.LNE_end_sequence => {
739739 prog.end_sequence = true;
740 if (%return prog.checkLineMatch()) |info| return info;
740 if (try prog.checkLineMatch()) |info| return info;
741741 return error.MissingDebugInfo;
742742 },
743743 DW.LNE_set_address => {
744 const addr = %return in_stream.readInt(st.elf.endian, usize);
744 const addr = try in_stream.readInt(st.elf.endian, usize);
745745 prog.address = addr;
746746 },
747747 DW.LNE_define_file => {
748 const file_name = %return st.readString();
749 const dir_index = %return readULeb128(in_stream);
750 const mtime = %return readULeb128(in_stream);
751 const len_bytes = %return readULeb128(in_stream);
752 %return file_entries.append(FileEntry {
748 const file_name = try st.readString();
749 const dir_index = try readULeb128(in_stream);
750 const mtime = try readULeb128(in_stream);
751 const len_bytes = try readULeb128(in_stream);
752 try file_entries.append(FileEntry {
753753 .file_name = file_name,
754754 .dir_index = dir_index,
755755 .mtime = mtime,
......@@ -758,7 +758,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
758758 },
759759 else => {
760760 const fwd_amt = math.cast(isize, op_size - 1) %% return error.InvalidDebugInfo;
761 %return in_file.seekForward(fwd_amt);
761 try in_file.seekForward(fwd_amt);
762762 },
763763 }
764764 } else if (opcode >= opcode_base) {
......@@ -768,28 +768,28 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
768768 const inc_line = i32(line_base) + i32(adjusted_opcode % line_range);
769769 prog.line += inc_line;
770770 prog.address += inc_addr;
771 if (%return prog.checkLineMatch()) |info| return info;
771 if (try prog.checkLineMatch()) |info| return info;
772772 prog.basic_block = false;
773773 } else {
774774 switch (opcode) {
775775 DW.LNS_copy => {
776 if (%return prog.checkLineMatch()) |info| return info;
776 if (try prog.checkLineMatch()) |info| return info;
777777 prog.basic_block = false;
778778 },
779779 DW.LNS_advance_pc => {
780 const arg = %return readULeb128(in_stream);
780 const arg = try readULeb128(in_stream);
781781 prog.address += arg * minimum_instruction_length;
782782 },
783783 DW.LNS_advance_line => {
784 const arg = %return readILeb128(in_stream);
784 const arg = try readILeb128(in_stream);
785785 prog.line += arg;
786786 },
787787 DW.LNS_set_file => {
788 const arg = %return readULeb128(in_stream);
788 const arg = try readULeb128(in_stream);
789789 prog.file = arg;
790790 },
791791 DW.LNS_set_column => {
792 const arg = %return readULeb128(in_stream);
792 const arg = try readULeb128(in_stream);
793793 prog.column = arg;
794794 },
795795 DW.LNS_negate_stmt => {
......@@ -803,7 +803,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
803803 prog.address += inc_addr;
804804 },
805805 DW.LNS_fixed_advance_pc => {
806 const arg = %return in_stream.readInt(st.elf.endian, u16);
806 const arg = try in_stream.readInt(st.elf.endian, u16);
807807 prog.address += arg;
808808 },
809809 DW.LNS_set_prologue_end => {
......@@ -812,7 +812,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
812812 if (opcode - 1 >= standard_opcode_lengths.len)
813813 return error.InvalidDebugInfo;
814814 const len_bytes = standard_opcode_lengths[opcode - 1];
815 %return in_file.seekForward(len_bytes);
815 try in_file.seekForward(len_bytes);
816816 },
817817 }
818818 }
......@@ -833,31 +833,31 @@ fn scanAllCompileUnits(st: &ElfStackTrace) -> %void {
833833 const in_stream = &in_file_stream.stream;
834834
835835 while (this_unit_offset < debug_info_end) {
836 %return st.self_exe_file.seekTo(this_unit_offset);
836 try st.self_exe_file.seekTo(this_unit_offset);
837837
838838 var is_64: bool = undefined;
839 const unit_length = %return readInitialLength(in_stream, &is_64);
839 const unit_length = try readInitialLength(in_stream, &is_64);
840840 if (unit_length == 0)
841841 return;
842842 const next_offset = unit_length + (if (is_64) usize(12) else usize(4));
843843
844 const version = %return in_stream.readInt(st.elf.endian, u16);
844 const version = try in_stream.readInt(st.elf.endian, u16);
845845 if (version < 2 or version > 5) return error.InvalidDebugInfo;
846846
847847 const debug_abbrev_offset =
848 if (is_64) %return in_stream.readInt(st.elf.endian, u64)
849 else %return in_stream.readInt(st.elf.endian, u32);
848 if (is_64) try in_stream.readInt(st.elf.endian, u64)
849 else try in_stream.readInt(st.elf.endian, u32);
850850
851 const address_size = %return in_stream.readByte();
851 const address_size = try in_stream.readByte();
852852 if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo;
853853
854 const compile_unit_pos = %return st.self_exe_file.getPos();
855 const abbrev_table = %return getAbbrevTable(st, debug_abbrev_offset);
854 const compile_unit_pos = try st.self_exe_file.getPos();
855 const abbrev_table = try getAbbrevTable(st, debug_abbrev_offset);
856856
857 %return st.self_exe_file.seekTo(compile_unit_pos);
857 try st.self_exe_file.seekTo(compile_unit_pos);
858858
859 const compile_unit_die = %return st.allocator().create(Die);
860 *compile_unit_die = %return parseDie(st, abbrev_table, is_64);
859 const compile_unit_die = try st.allocator().create(Die);
860 *compile_unit_die = try parseDie(st, abbrev_table, is_64);
861861
862862 if (compile_unit_die.tag_id != DW.TAG_compile_unit)
863863 return error.InvalidDebugInfo;
......@@ -868,7 +868,7 @@ fn scanAllCompileUnits(st: &ElfStackTrace) -> %void {
868868 const pc_end = switch (*high_pc_value) {
869869 FormValue.Address => |value| value,
870870 FormValue.Const => |value| b: {
871 const offset = %return value.asUnsignedLe();
871 const offset = try value.asUnsignedLe();
872872 break :b (low_pc + offset);
873873 },
874874 else => return error.InvalidDebugInfo,
......@@ -887,7 +887,7 @@ fn scanAllCompileUnits(st: &ElfStackTrace) -> %void {
887887 }
888888 };
889889
890 %return st.compile_unit_list.append(CompileUnit {
890 try st.compile_unit_list.append(CompileUnit {
891891 .version = version,
892892 .is_64 = is_64,
893893 .pc_range = pc_range,
......@@ -911,10 +911,10 @@ fn findCompileUnit(st: &ElfStackTrace, target_address: u64) -> %&const CompileUn
911911 if (compile_unit.die.getAttrSecOffset(DW.AT_ranges)) |ranges_offset| {
912912 var base_address: usize = 0;
913913 if (st.debug_ranges) |debug_ranges| {
914 %return st.self_exe_file.seekTo(debug_ranges.offset + ranges_offset);
914 try st.self_exe_file.seekTo(debug_ranges.offset + ranges_offset);
915915 while (true) {
916 const begin_addr = %return in_stream.readIntLe(usize);
917 const end_addr = %return in_stream.readIntLe(usize);
916 const begin_addr = try in_stream.readIntLe(usize);
917 const end_addr = try in_stream.readIntLe(usize);
918918 if (begin_addr == 0 and end_addr == 0) {
919919 break;
920920 }
......@@ -937,7 +937,7 @@ fn findCompileUnit(st: &ElfStackTrace, target_address: u64) -> %&const CompileUn
937937}
938938
939939fn readInitialLength(in_stream: &io.InStream, is_64: &bool) -> %u64 {
940 const first_32_bits = %return in_stream.readIntLe(u32);
940 const first_32_bits = try in_stream.readIntLe(u32);
941941 *is_64 = (first_32_bits == 0xffffffff);
942942 if (*is_64) {
943943 return in_stream.readIntLe(u64);
......@@ -952,7 +952,7 @@ fn readULeb128(in_stream: &io.InStream) -> %u64 {
952952 var shift: usize = 0;
953953
954954 while (true) {
955 const byte = %return in_stream.readByte();
955 const byte = try in_stream.readByte();
956956
957957 var operand: u64 = undefined;
958958
......@@ -973,7 +973,7 @@ fn readILeb128(in_stream: &io.InStream) -> %i64 {
973973 var shift: usize = 0;
974974
975975 while (true) {
976 const byte = %return in_stream.readByte();
976 const byte = try in_stream.readByte();
977977
978978 var operand: i64 = undefined;
979979
std/elf.zig+53-53
......@@ -82,8 +82,8 @@ pub const Elf = struct {
8282
8383 /// Call close when done.
8484 pub fn openPath(elf: &Elf, allocator: &mem.Allocator, path: []const u8) -> %void {
85 %return elf.prealloc_file.open(path);
86 %return elf.openFile(allocator, &elf.prealloc_file);
85 try elf.prealloc_file.open(path);
86 try elf.openFile(allocator, &elf.prealloc_file);
8787 elf.auto_close_stream = true;
8888 }
8989
......@@ -97,28 +97,28 @@ pub const Elf = struct {
9797 const in = &file_stream.stream;
9898
9999 var magic: [4]u8 = undefined;
100 %return in.readNoEof(magic[0..]);
100 try in.readNoEof(magic[0..]);
101101 if (!mem.eql(u8, magic, "\x7fELF")) return error.InvalidFormat;
102102
103 elf.is_64 = switch (%return in.readByte()) {
103 elf.is_64 = switch (try in.readByte()) {
104104 1 => false,
105105 2 => true,
106106 else => return error.InvalidFormat,
107107 };
108108
109 elf.endian = switch (%return in.readByte()) {
109 elf.endian = switch (try in.readByte()) {
110110 1 => builtin.Endian.Little,
111111 2 => builtin.Endian.Big,
112112 else => return error.InvalidFormat,
113113 };
114114
115 const version_byte = %return in.readByte();
115 const version_byte = try in.readByte();
116116 if (version_byte != 1) return error.InvalidFormat;
117117
118118 // skip over padding
119 %return elf.in_file.seekForward(9);
119 try elf.in_file.seekForward(9);
120120
121 elf.file_type = switch (%return in.readInt(elf.endian, u16)) {
121 elf.file_type = switch (try in.readInt(elf.endian, u16)) {
122122 1 => FileType.Relocatable,
123123 2 => FileType.Executable,
124124 3 => FileType.Shared,
......@@ -126,7 +126,7 @@ pub const Elf = struct {
126126 else => return error.InvalidFormat,
127127 };
128128
129 elf.arch = switch (%return in.readInt(elf.endian, u16)) {
129 elf.arch = switch (try in.readInt(elf.endian, u16)) {
130130 0x02 => Arch.Sparc,
131131 0x03 => Arch.x86,
132132 0x08 => Arch.Mips,
......@@ -139,88 +139,88 @@ pub const Elf = struct {
139139 else => return error.InvalidFormat,
140140 };
141141
142 const elf_version = %return in.readInt(elf.endian, u32);
142 const elf_version = try in.readInt(elf.endian, u32);
143143 if (elf_version != 1) return error.InvalidFormat;
144144
145145 if (elf.is_64) {
146 elf.entry_addr = %return in.readInt(elf.endian, u64);
147 elf.program_header_offset = %return in.readInt(elf.endian, u64);
148 elf.section_header_offset = %return in.readInt(elf.endian, u64);
146 elf.entry_addr = try in.readInt(elf.endian, u64);
147 elf.program_header_offset = try in.readInt(elf.endian, u64);
148 elf.section_header_offset = try in.readInt(elf.endian, u64);
149149 } else {
150 elf.entry_addr = u64(%return in.readInt(elf.endian, u32));
151 elf.program_header_offset = u64(%return in.readInt(elf.endian, u32));
152 elf.section_header_offset = u64(%return in.readInt(elf.endian, u32));
150 elf.entry_addr = u64(try in.readInt(elf.endian, u32));
151 elf.program_header_offset = u64(try in.readInt(elf.endian, u32));
152 elf.section_header_offset = u64(try in.readInt(elf.endian, u32));
153153 }
154154
155155 // skip over flags
156 %return elf.in_file.seekForward(4);
156 try elf.in_file.seekForward(4);
157157
158 const header_size = %return in.readInt(elf.endian, u16);
158 const header_size = try in.readInt(elf.endian, u16);
159159 if ((elf.is_64 and header_size != 64) or
160160 (!elf.is_64 and header_size != 52))
161161 {
162162 return error.InvalidFormat;
163163 }
164164
165 const ph_entry_size = %return in.readInt(elf.endian, u16);
166 const ph_entry_count = %return in.readInt(elf.endian, u16);
167 const sh_entry_size = %return in.readInt(elf.endian, u16);
168 const sh_entry_count = %return in.readInt(elf.endian, u16);
169 elf.string_section_index = u64(%return in.readInt(elf.endian, u16));
165 const ph_entry_size = try in.readInt(elf.endian, u16);
166 const ph_entry_count = try in.readInt(elf.endian, u16);
167 const sh_entry_size = try in.readInt(elf.endian, u16);
168 const sh_entry_count = try in.readInt(elf.endian, u16);
169 elf.string_section_index = u64(try in.readInt(elf.endian, u16));
170170
171171 if (elf.string_section_index >= sh_entry_count) return error.InvalidFormat;
172172
173173 const sh_byte_count = u64(sh_entry_size) * u64(sh_entry_count);
174 const end_sh = %return math.add(u64, elf.section_header_offset, sh_byte_count);
174 const end_sh = try math.add(u64, elf.section_header_offset, sh_byte_count);
175175 const ph_byte_count = u64(ph_entry_size) * u64(ph_entry_count);
176 const end_ph = %return math.add(u64, elf.program_header_offset, ph_byte_count);
176 const end_ph = try math.add(u64, elf.program_header_offset, ph_byte_count);
177177
178 const stream_end = %return elf.in_file.getEndPos();
178 const stream_end = try elf.in_file.getEndPos();
179179 if (stream_end < end_sh or stream_end < end_ph) {
180180 return error.InvalidFormat;
181181 }
182182
183 %return elf.in_file.seekTo(elf.section_header_offset);
183 try elf.in_file.seekTo(elf.section_header_offset);
184184
185 elf.section_headers = %return elf.allocator.alloc(SectionHeader, sh_entry_count);
185 elf.section_headers = try elf.allocator.alloc(SectionHeader, sh_entry_count);
186186 %defer elf.allocator.free(elf.section_headers);
187187
188188 if (elf.is_64) {
189189 if (sh_entry_size != 64) return error.InvalidFormat;
190190
191191 for (elf.section_headers) |*elf_section| {
192 elf_section.name = %return in.readInt(elf.endian, u32);
193 elf_section.sh_type = %return in.readInt(elf.endian, u32);
194 elf_section.flags = %return in.readInt(elf.endian, u64);
195 elf_section.addr = %return in.readInt(elf.endian, u64);
196 elf_section.offset = %return in.readInt(elf.endian, u64);
197 elf_section.size = %return in.readInt(elf.endian, u64);
198 elf_section.link = %return in.readInt(elf.endian, u32);
199 elf_section.info = %return in.readInt(elf.endian, u32);
200 elf_section.addr_align = %return in.readInt(elf.endian, u64);
201 elf_section.ent_size = %return in.readInt(elf.endian, u64);
192 elf_section.name = try in.readInt(elf.endian, u32);
193 elf_section.sh_type = try in.readInt(elf.endian, u32);
194 elf_section.flags = try in.readInt(elf.endian, u64);
195 elf_section.addr = try in.readInt(elf.endian, u64);
196 elf_section.offset = try in.readInt(elf.endian, u64);
197 elf_section.size = try in.readInt(elf.endian, u64);
198 elf_section.link = try in.readInt(elf.endian, u32);
199 elf_section.info = try in.readInt(elf.endian, u32);
200 elf_section.addr_align = try in.readInt(elf.endian, u64);
201 elf_section.ent_size = try in.readInt(elf.endian, u64);
202202 }
203203 } else {
204204 if (sh_entry_size != 40) return error.InvalidFormat;
205205
206206 for (elf.section_headers) |*elf_section| {
207207 // TODO (multiple occurences) allow implicit cast from %u32 -> %u64 ?
208 elf_section.name = %return in.readInt(elf.endian, u32);
209 elf_section.sh_type = %return in.readInt(elf.endian, u32);
210 elf_section.flags = u64(%return in.readInt(elf.endian, u32));
211 elf_section.addr = u64(%return in.readInt(elf.endian, u32));
212 elf_section.offset = u64(%return in.readInt(elf.endian, u32));
213 elf_section.size = u64(%return in.readInt(elf.endian, u32));
214 elf_section.link = %return in.readInt(elf.endian, u32);
215 elf_section.info = %return in.readInt(elf.endian, u32);
216 elf_section.addr_align = u64(%return in.readInt(elf.endian, u32));
217 elf_section.ent_size = u64(%return in.readInt(elf.endian, u32));
208 elf_section.name = try in.readInt(elf.endian, u32);
209 elf_section.sh_type = try in.readInt(elf.endian, u32);
210 elf_section.flags = u64(try in.readInt(elf.endian, u32));
211 elf_section.addr = u64(try in.readInt(elf.endian, u32));
212 elf_section.offset = u64(try in.readInt(elf.endian, u32));
213 elf_section.size = u64(try in.readInt(elf.endian, u32));
214 elf_section.link = try in.readInt(elf.endian, u32);
215 elf_section.info = try in.readInt(elf.endian, u32);
216 elf_section.addr_align = u64(try in.readInt(elf.endian, u32));
217 elf_section.ent_size = u64(try in.readInt(elf.endian, u32));
218218 }
219219 }
220220
221221 for (elf.section_headers) |*elf_section| {
222222 if (elf_section.sh_type != SHT_NOBITS) {
223 const file_end_offset = %return math.add(u64, elf_section.offset, elf_section.size);
223 const file_end_offset = try math.add(u64, elf_section.offset, elf_section.size);
224224 if (stream_end < file_end_offset) return error.InvalidFormat;
225225 }
226226 }
......@@ -247,15 +247,15 @@ pub const Elf = struct {
247247 if (elf_section.sh_type == SHT_NULL) continue;
248248
249249 const name_offset = elf.string_section.offset + elf_section.name;
250 %return elf.in_file.seekTo(name_offset);
250 try elf.in_file.seekTo(name_offset);
251251
252252 for (name) |expected_c| {
253 const target_c = %return in.readByte();
253 const target_c = try in.readByte();
254254 if (target_c == 0 or expected_c != target_c) continue :section_loop;
255255 }
256256
257257 {
258 const null_byte = %return in.readByte();
258 const null_byte = try in.readByte();
259259 if (null_byte == 0) return elf_section;
260260 }
261261 }
......@@ -264,6 +264,6 @@ pub const Elf = struct {
264264 }
265265
266266 pub fn seekToSection(elf: &Elf, elf_section: &SectionHeader) -> %void {
267 %return elf.in_file.seekTo(elf_section.offset);
267 try elf.in_file.seekTo(elf_section.offset);
268268 }
269269};
std/fmt/index.zig+34-34
......@@ -40,13 +40,13 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
4040 State.Start => switch (c) {
4141 '{' => {
4242 if (start_index < i) {
43 %return output(context, fmt[start_index..i]);
43 try output(context, fmt[start_index..i]);
4444 }
4545 state = State.OpenBrace;
4646 },
4747 '}' => {
4848 if (start_index < i) {
49 %return output(context, fmt[start_index..i]);
49 try output(context, fmt[start_index..i]);
5050 }
5151 state = State.CloseBrace;
5252 },
......@@ -58,7 +58,7 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
5858 start_index = i;
5959 },
6060 '}' => {
61 %return formatValue(args[next_arg], context, output);
61 try formatValue(args[next_arg], context, output);
6262 next_arg += 1;
6363 state = State.Start;
6464 start_index = i + 1;
......@@ -110,7 +110,7 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
110110 },
111111 State.Integer => switch (c) {
112112 '}' => {
113 %return formatInt(args[next_arg], radix, uppercase, width, context, output);
113 try formatInt(args[next_arg], radix, uppercase, width, context, output);
114114 next_arg += 1;
115115 state = State.Start;
116116 start_index = i + 1;
......@@ -124,7 +124,7 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
124124 State.IntegerWidth => switch (c) {
125125 '}' => {
126126 width = comptime %%parseUnsigned(usize, fmt[width_start..i], 10);
127 %return formatInt(args[next_arg], radix, uppercase, width, context, output);
127 try formatInt(args[next_arg], radix, uppercase, width, context, output);
128128 next_arg += 1;
129129 state = State.Start;
130130 start_index = i + 1;
......@@ -134,7 +134,7 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
134134 },
135135 State.Float => switch (c) {
136136 '}' => {
137 %return formatFloatDecimal(args[next_arg], 0, context, output);
137 try formatFloatDecimal(args[next_arg], 0, context, output);
138138 next_arg += 1;
139139 state = State.Start;
140140 start_index = i + 1;
......@@ -148,7 +148,7 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
148148 State.FloatWidth => switch (c) {
149149 '}' => {
150150 width = comptime %%parseUnsigned(usize, fmt[width_start..i], 10);
151 %return formatFloatDecimal(args[next_arg], width, context, output);
151 try formatFloatDecimal(args[next_arg], width, context, output);
152152 next_arg += 1;
153153 state = State.Start;
154154 start_index = i + 1;
......@@ -159,7 +159,7 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
159159 State.BufWidth => switch (c) {
160160 '}' => {
161161 width = comptime %%parseUnsigned(usize, fmt[width_start..i], 10);
162 %return formatBuf(args[next_arg], width, context, output);
162 try formatBuf(args[next_arg], width, context, output);
163163 next_arg += 1;
164164 state = State.Start;
165165 start_index = i + 1;
......@@ -169,7 +169,7 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
169169 },
170170 State.Character => switch (c) {
171171 '}' => {
172 %return formatAsciiChar(args[next_arg], context, output);
172 try formatAsciiChar(args[next_arg], context, output);
173173 next_arg += 1;
174174 state = State.Start;
175175 start_index = i + 1;
......@@ -187,7 +187,7 @@ pub fn format(context: var, output: fn(@typeOf(context), []const u8)->%void,
187187 }
188188 }
189189 if (start_index < fmt.len) {
190 %return output(context, fmt[start_index..]);
190 try output(context, fmt[start_index..]);
191191 }
192192}
193193
......@@ -221,7 +221,7 @@ pub fn formatValue(value: var, context: var, output: fn(@typeOf(context), []cons
221221 }
222222 },
223223 builtin.TypeId.Error => {
224 %return output(context, "error.");
224 try output(context, "error.");
225225 return output(context, @errorName(value));
226226 },
227227 builtin.TypeId.Pointer => {
......@@ -247,12 +247,12 @@ pub fn formatAsciiChar(c: u8, context: var, output: fn(@typeOf(context), []const
247247pub fn formatBuf(buf: []const u8, width: usize,
248248 context: var, output: fn(@typeOf(context), []const u8)->%void) -> %void
249249{
250 %return output(context, buf);
250 try output(context, buf);
251251
252252 var leftover_padding = if (width > buf.len) (width - buf.len) else return;
253253 const pad_byte: u8 = ' ';
254254 while (leftover_padding > 0) : (leftover_padding -= 1) {
255 %return output(context, (&pad_byte)[0..1]);
255 try output(context, (&pad_byte)[0..1]);
256256 }
257257}
258258
......@@ -264,7 +264,7 @@ pub fn formatFloat(value: var, context: var, output: fn(@typeOf(context), []cons
264264 return output(context, "NaN");
265265 }
266266 if (math.signbit(x)) {
267 %return output(context, "-");
267 try output(context, "-");
268268 x = -x;
269269 }
270270 if (math.isPositiveInf(x)) {
......@@ -276,21 +276,21 @@ pub fn formatFloat(value: var, context: var, output: fn(@typeOf(context), []cons
276276
277277 var buffer: [32]u8 = undefined;
278278 const float_decimal = errol3(x, buffer[0..]);
279 %return output(context, float_decimal.digits[0..1]);
280 %return output(context, ".");
279 try output(context, float_decimal.digits[0..1]);
280 try output(context, ".");
281281 if (float_decimal.digits.len > 1) {
282282 const num_digits = if (@typeOf(value) == f32)
283283 math.min(usize(9), float_decimal.digits.len)
284284 else
285285 float_decimal.digits.len;
286 %return output(context, float_decimal.digits[1 .. num_digits]);
286 try output(context, float_decimal.digits[1 .. num_digits]);
287287 } else {
288 %return output(context, "0");
288 try output(context, "0");
289289 }
290290
291291 if (float_decimal.exp != 1) {
292 %return output(context, "e");
293 %return formatInt(float_decimal.exp - 1, 10, false, 0, context, output);
292 try output(context, "e");
293 try formatInt(float_decimal.exp - 1, 10, false, 0, context, output);
294294 }
295295}
296296
......@@ -302,7 +302,7 @@ pub fn formatFloatDecimal(value: var, precision: usize, context: var, output: fn
302302 return output(context, "NaN");
303303 }
304304 if (math.signbit(x)) {
305 %return output(context, "-");
305 try output(context, "-");
306306 x = -x;
307307 }
308308 if (math.isPositiveInf(x)) {
......@@ -317,8 +317,8 @@ pub fn formatFloatDecimal(value: var, precision: usize, context: var, output: fn
317317
318318 const num_left_digits = if (float_decimal.exp > 0) usize(float_decimal.exp) else 1;
319319
320 %return output(context, float_decimal.digits[0 .. num_left_digits]);
321 %return output(context, ".");
320 try output(context, float_decimal.digits[0 .. num_left_digits]);
321 try output(context, ".");
322322 if (float_decimal.digits.len > 1) {
323323 const num_valid_digtis = if (@typeOf(value) == f32) math.min(usize(7), float_decimal.digits.len)
324324 else
......@@ -328,9 +328,9 @@ pub fn formatFloatDecimal(value: var, precision: usize, context: var, output: fn
328328 math.min(precision, (num_valid_digtis-num_left_digits))
329329 else
330330 num_valid_digtis - num_left_digits;
331 %return output(context, float_decimal.digits[num_left_digits .. (num_left_digits + num_right_digits)]);
331 try output(context, float_decimal.digits[num_left_digits .. (num_left_digits + num_right_digits)]);
332332 } else {
333 %return output(context, "0");
333 try output(context, "0");
334334 }
335335}
336336
......@@ -351,7 +351,7 @@ fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize,
351351 const uint = @IntType(false, @typeOf(value).bit_count);
352352 if (value < 0) {
353353 const minus_sign: u8 = '-';
354 %return output(context, (&minus_sign)[0..1]);
354 try output(context, (&minus_sign)[0..1]);
355355 const new_value = uint(-(value + 1)) + 1;
356356 const new_width = if (width == 0) 0 else (width - 1);
357357 return formatIntUnsigned(new_value, base, uppercase, new_width, context, output);
......@@ -359,7 +359,7 @@ fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize,
359359 return formatIntUnsigned(uint(value), base, uppercase, width, context, output);
360360 } else {
361361 const plus_sign: u8 = '+';
362 %return output(context, (&plus_sign)[0..1]);
362 try output(context, (&plus_sign)[0..1]);
363363 const new_value = uint(value);
364364 const new_width = if (width == 0) 0 else (width - 1);
365365 return formatIntUnsigned(new_value, base, uppercase, new_width, context, output);
......@@ -391,7 +391,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize,
391391 const zero_byte: u8 = '0';
392392 var leftover_padding = padding - index;
393393 while (true) {
394 %return output(context, (&zero_byte)[0..1]);
394 try output(context, (&zero_byte)[0..1]);
395395 leftover_padding -= 1;
396396 if (leftover_padding == 0)
397397 break;
......@@ -428,7 +428,7 @@ pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) -> %T {
428428 if (buf.len == 0)
429429 return T(0);
430430 if (buf[0] == '-') {
431 return math.negate(%return parseUnsigned(T, buf[1..], radix));
431 return math.negate(try parseUnsigned(T, buf[1..], radix));
432432 } else if (buf[0] == '+') {
433433 return parseUnsigned(T, buf[1..], radix);
434434 } else {
......@@ -450,9 +450,9 @@ pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) -> %T {
450450 var x: T = 0;
451451
452452 for (buf) |c| {
453 const digit = %return charToDigit(c, radix);
454 x = %return math.mul(T, x, radix);
455 x = %return math.add(T, x, digit);
453 const digit = try charToDigit(c, radix);
454 x = try math.mul(T, x, radix);
455 x = try math.add(T, x, digit);
456456 }
457457
458458 return x;
......@@ -494,7 +494,7 @@ fn bufPrintWrite(context: &BufPrintContext, bytes: []const u8) -> %void {
494494
495495pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) -> %[]u8 {
496496 var context = BufPrintContext { .remaining = buf, };
497 %return format(&context, bufPrintWrite, fmt, args);
497 try format(&context, bufPrintWrite, fmt, args);
498498 return buf[0..buf.len - context.remaining.len];
499499}
500500
......@@ -502,7 +502,7 @@ pub fn allocPrint(allocator: &mem.Allocator, comptime fmt: []const u8, args: ...
502502 var size: usize = 0;
503503 // Cannot fail because `countSize` cannot fail.
504504 %%format(&size, countSize, fmt, args);
505 const buf = %return allocator.alloc(u8, size);
505 const buf = try allocator.alloc(u8, size);
506506 return bufPrint(buf, fmt, args);
507507}
508508
std/hash_map.zig+3-3
......@@ -83,14 +83,14 @@ pub fn HashMap(comptime K: type, comptime V: type,
8383 /// Returns the value that was already there.
8484 pub fn put(hm: &Self, key: K, value: &const V) -> %?V {
8585 if (hm.entries.len == 0) {
86 %return hm.initCapacity(16);
86 try hm.initCapacity(16);
8787 }
8888 hm.incrementModificationCount();
8989
9090 // if we get too full (60%), double the capacity
9191 if (hm.size * 5 >= hm.entries.len * 3) {
9292 const old_entries = hm.entries;
93 %return hm.initCapacity(hm.entries.len * 2);
93 try hm.initCapacity(hm.entries.len * 2);
9494 // dump all of the old elements into the new table
9595 for (old_entries) |*old_entry| {
9696 if (old_entry.used) {
......@@ -149,7 +149,7 @@ pub fn HashMap(comptime K: type, comptime V: type,
149149 }
150150
151151 fn initCapacity(hm: &Self, capacity: usize) -> %void {
152 hm.entries = %return hm.allocator.alloc(Entry, capacity);
152 hm.entries = try hm.allocator.alloc(Entry, capacity);
153153 hm.size = 0;
154154 hm.max_distance_from_start_index = 0;
155155 for (hm.entries) |*entry| {
std/heap.zig+1-1
......@@ -124,7 +124,7 @@ pub const IncrementingAllocator = struct {
124124 if (new_size <= old_mem.len) {
125125 return old_mem[0..new_size];
126126 } else {
127 const result = %return alloc(allocator, new_size, alignment);
127 const result = try alloc(allocator, new_size, alignment);
128128 mem.copy(u8, result, old_mem);
129129 return result;
130130 }
std/io.zig+34-34
......@@ -51,7 +51,7 @@ error EndOfFile;
5151
5252pub fn getStdErr() -> %File {
5353 const handle = if (is_windows)
54 %return os.windowsGetStdHandle(system.STD_ERROR_HANDLE)
54 try os.windowsGetStdHandle(system.STD_ERROR_HANDLE)
5555 else if (is_posix)
5656 system.STDERR_FILENO
5757 else
......@@ -61,7 +61,7 @@ pub fn getStdErr() -> %File {
6161
6262pub fn getStdOut() -> %File {
6363 const handle = if (is_windows)
64 %return os.windowsGetStdHandle(system.STD_OUTPUT_HANDLE)
64 try os.windowsGetStdHandle(system.STD_OUTPUT_HANDLE)
6565 else if (is_posix)
6666 system.STDOUT_FILENO
6767 else
......@@ -71,7 +71,7 @@ pub fn getStdOut() -> %File {
7171
7272pub fn getStdIn() -> %File {
7373 const handle = if (is_windows)
74 %return os.windowsGetStdHandle(system.STD_INPUT_HANDLE)
74 try os.windowsGetStdHandle(system.STD_INPUT_HANDLE)
7575 else if (is_posix)
7676 system.STDIN_FILENO
7777 else
......@@ -131,10 +131,10 @@ pub const File = struct {
131131 pub fn openRead(path: []const u8, allocator: ?&mem.Allocator) -> %File {
132132 if (is_posix) {
133133 const flags = system.O_LARGEFILE|system.O_RDONLY;
134 const fd = %return os.posixOpen(path, flags, 0, allocator);
134 const fd = try os.posixOpen(path, flags, 0, allocator);
135135 return openHandle(fd);
136136 } else if (is_windows) {
137 const handle = %return os.windowsOpen(path, system.GENERIC_READ, system.FILE_SHARE_READ,
137 const handle = try os.windowsOpen(path, system.GENERIC_READ, system.FILE_SHARE_READ,
138138 system.OPEN_EXISTING, system.FILE_ATTRIBUTE_NORMAL, allocator);
139139 return openHandle(handle);
140140 } else {
......@@ -156,10 +156,10 @@ pub const File = struct {
156156 pub fn openWriteMode(path: []const u8, mode: usize, allocator: ?&mem.Allocator) -> %File {
157157 if (is_posix) {
158158 const flags = system.O_LARGEFILE|system.O_WRONLY|system.O_CREAT|system.O_CLOEXEC|system.O_TRUNC;
159 const fd = %return os.posixOpen(path, flags, mode, allocator);
159 const fd = try os.posixOpen(path, flags, mode, allocator);
160160 return openHandle(fd);
161161 } else if (is_windows) {
162 const handle = %return os.windowsOpen(path, system.GENERIC_WRITE,
162 const handle = try os.windowsOpen(path, system.GENERIC_WRITE,
163163 system.FILE_SHARE_WRITE|system.FILE_SHARE_READ|system.FILE_SHARE_DELETE,
164164 system.CREATE_ALWAYS, system.FILE_ATTRIBUTE_NORMAL, allocator);
165165 return openHandle(handle);
......@@ -322,9 +322,9 @@ pub const File = struct {
322322
323323 fn write(self: &File, bytes: []const u8) -> %void {
324324 if (is_posix) {
325 %return os.posixWrite(self.handle, bytes);
325 try os.posixWrite(self.handle, bytes);
326326 } else if (is_windows) {
327 %return os.windowsWrite(self.handle, bytes);
327 try os.windowsWrite(self.handle, bytes);
328328 } else {
329329 @compileError("Unsupported OS");
330330 }
......@@ -344,12 +344,12 @@ pub const InStream = struct {
344344 /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and
345345 /// the contents read from the stream are lost.
346346 pub fn readAllBuffer(self: &InStream, buffer: &Buffer, max_size: usize) -> %void {
347 %return buffer.resize(0);
347 try buffer.resize(0);
348348
349349 var actual_buf_len: usize = 0;
350350 while (true) {
351351 const dest_slice = buffer.toSlice()[actual_buf_len..];
352 const bytes_read = %return self.readFn(self, dest_slice);
352 const bytes_read = try self.readFn(self, dest_slice);
353353 actual_buf_len += bytes_read;
354354
355355 if (bytes_read != dest_slice.len) {
......@@ -360,7 +360,7 @@ pub const InStream = struct {
360360 const new_buf_size = math.min(max_size, actual_buf_len + os.page_size);
361361 if (new_buf_size == actual_buf_len)
362362 return error.StreamTooLong;
363 %return buffer.resize(new_buf_size);
363 try buffer.resize(new_buf_size);
364364 }
365365 }
366366
......@@ -372,7 +372,7 @@ pub const InStream = struct {
372372 var buf = Buffer.initNull(allocator);
373373 defer buf.deinit();
374374
375 %return self.readAllBuffer(&buf, max_size);
375 try self.readAllBuffer(&buf, max_size);
376376 return buf.toOwnedSlice();
377377 }
378378
......@@ -381,10 +381,10 @@ pub const InStream = struct {
381381 /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and the contents
382382 /// read from the stream so far are lost.
383383 pub fn readUntilDelimiterBuffer(self: &InStream, buffer: &Buffer, delimiter: u8, max_size: usize) -> %void {
384 %return buf.resize(0);
384 try buf.resize(0);
385385
386386 while (true) {
387 var byte: u8 = %return self.readByte();
387 var byte: u8 = try self.readByte();
388388
389389 if (byte == delimiter) {
390390 return;
......@@ -394,7 +394,7 @@ pub const InStream = struct {
394394 return error.StreamTooLong;
395395 }
396396
397 %return buf.appendByte(byte);
397 try buf.appendByte(byte);
398398 }
399399 }
400400
......@@ -408,7 +408,7 @@ pub const InStream = struct {
408408 var buf = Buffer.initNull(allocator);
409409 defer buf.deinit();
410410
411 %return self.readUntilDelimiterBuffer(self, &buf, delimiter, max_size);
411 try self.readUntilDelimiterBuffer(self, &buf, delimiter, max_size);
412412 return buf.toOwnedSlice();
413413 }
414414
......@@ -421,20 +421,20 @@ pub const InStream = struct {
421421
422422 /// Same as `read` but end of stream returns `error.EndOfStream`.
423423 pub fn readNoEof(self: &InStream, buf: []u8) -> %void {
424 const amt_read = %return self.read(buf);
424 const amt_read = try self.read(buf);
425425 if (amt_read < buf.len) return error.EndOfStream;
426426 }
427427
428428 /// Reads 1 byte from the stream or returns `error.EndOfStream`.
429429 pub fn readByte(self: &InStream) -> %u8 {
430430 var result: [1]u8 = undefined;
431 %return self.readNoEof(result[0..]);
431 try self.readNoEof(result[0..]);
432432 return result[0];
433433 }
434434
435435 /// Same as `readByte` except the returned byte is signed.
436436 pub fn readByteSigned(self: &InStream) -> %i8 {
437 return @bitCast(i8, %return self.readByte());
437 return @bitCast(i8, try self.readByte());
438438 }
439439
440440 pub fn readIntLe(self: &InStream, comptime T: type) -> %T {
......@@ -447,7 +447,7 @@ pub const InStream = struct {
447447
448448 pub fn readInt(self: &InStream, endian: builtin.Endian, comptime T: type) -> %T {
449449 var bytes: [@sizeOf(T)]u8 = undefined;
450 %return self.readNoEof(bytes[0..]);
450 try self.readNoEof(bytes[0..]);
451451 return mem.readInt(bytes, T, endian);
452452 }
453453
......@@ -456,7 +456,7 @@ pub const InStream = struct {
456456 assert(size <= 8);
457457 var input_buf: [8]u8 = undefined;
458458 const input_slice = input_buf[0..size];
459 %return self.readNoEof(input_slice);
459 try self.readNoEof(input_slice);
460460 return mem.readInt(input_slice, T, endian);
461461 }
462462
......@@ -483,7 +483,7 @@ pub const OutStream = struct {
483483 const slice = (&byte)[0..1];
484484 var i: usize = 0;
485485 while (i < n) : (i += 1) {
486 %return self.writeFn(self, slice);
486 try self.writeFn(self, slice);
487487 }
488488 }
489489};
......@@ -493,9 +493,9 @@ pub const OutStream = struct {
493493/// size buffer is too small, and the provided allocator is null, `error.NameTooLong` is returned.
494494/// otherwise if the fixed size buffer is too small, allocator is used to obtain the needed memory.
495495pub fn writeFile(path: []const u8, data: []const u8, allocator: ?&mem.Allocator) -> %void {
496 var file = %return File.openWrite(path, allocator);
496 var file = try File.openWrite(path, allocator);
497497 defer file.close();
498 %return file.write(data);
498 try file.write(data);
499499}
500500
501501/// On success, caller owns returned buffer.
......@@ -505,15 +505,15 @@ pub fn readFileAlloc(path: []const u8, allocator: &mem.Allocator) -> %[]u8 {
505505/// On success, caller owns returned buffer.
506506/// Allocates extra_len extra bytes at the end of the file buffer, which are uninitialized.
507507pub fn readFileAllocExtra(path: []const u8, allocator: &mem.Allocator, extra_len: usize) -> %[]u8 {
508 var file = %return File.openRead(path, allocator);
508 var file = try File.openRead(path, allocator);
509509 defer file.close();
510510
511 const size = %return file.getEndPos();
512 const buf = %return allocator.alloc(u8, size + extra_len);
511 const size = try file.getEndPos();
512 const buf = try allocator.alloc(u8, size + extra_len);
513513 %defer allocator.free(buf);
514514
515515 var adapter = FileInStream.init(&file);
516 %return adapter.stream.readNoEof(buf[0..size]);
516 try adapter.stream.readNoEof(buf[0..size]);
517517 return buf;
518518}
519519
......@@ -565,11 +565,11 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize) -> type {
565565 // we can read more data from the unbuffered stream
566566 if (dest_space < buffer_size) {
567567 self.start_index = 0;
568 self.end_index = %return self.unbuffered_in_stream.read(self.buffer[0..]);
568 self.end_index = try self.unbuffered_in_stream.read(self.buffer[0..]);
569569 } else {
570570 // asking for so much data that buffering is actually less efficient.
571571 // forward the request directly to the unbuffered stream
572 const amt_read = %return self.unbuffered_in_stream.read(dest[dest_index..]);
572 const amt_read = try self.unbuffered_in_stream.read(dest[dest_index..]);
573573 return dest_index + amt_read;
574574 }
575575 } else {
......@@ -616,7 +616,7 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize) -> type {
616616 if (self.index == 0)
617617 return;
618618
619 %return self.unbuffered_out_stream.write(self.buffer[0..self.index]);
619 try self.unbuffered_out_stream.write(self.buffer[0..self.index]);
620620 self.index = 0;
621621 }
622622
......@@ -624,7 +624,7 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize) -> type {
624624 const self = @fieldParentPtr(Self, "stream", out_stream);
625625
626626 if (bytes.len >= self.buffer.len) {
627 %return self.flush();
627 try self.flush();
628628 return self.unbuffered_out_stream.write(bytes);
629629 }
630630 var src_index: usize = 0;
......@@ -636,7 +636,7 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize) -> type {
636636 self.index += copy_amt;
637637 assert(self.index <= self.buffer.len);
638638 if (self.index == self.buffer.len) {
639 %return self.flush();
639 try self.flush();
640640 }
641641 src_index += copy_amt;
642642 }
std/linked_list.zig+1-1
......@@ -188,7 +188,7 @@ pub fn LinkedList(comptime T: type) -> type {
188188 /// Returns:
189189 /// A pointer to the new node.
190190 pub fn createNode(list: &Self, data: &const T, allocator: &Allocator) -> %&Node {
191 var node = %return list.allocateNode(allocator);
191 var node = try list.allocateNode(allocator);
192192 *node = Node.init(data);
193193 return node;
194194 }
std/mem.zig+8-8
......@@ -27,7 +27,7 @@ pub const Allocator = struct {
2727 freeFn: fn (self: &Allocator, old_mem: []u8),
2828
2929 fn create(self: &Allocator, comptime T: type) -> %&T {
30 const slice = %return self.alloc(T, 1);
30 const slice = try self.alloc(T, 1);
3131 return &slice[0];
3232 }
3333
......@@ -42,8 +42,8 @@ pub const Allocator = struct {
4242 fn alignedAlloc(self: &Allocator, comptime T: type, comptime alignment: u29,
4343 n: usize) -> %[]align(alignment) T
4444 {
45 const byte_count = %return math.mul(usize, @sizeOf(T), n);
46 const byte_slice = %return self.allocFn(self, byte_count, alignment);
45 const byte_count = try math.mul(usize, @sizeOf(T), n);
46 const byte_slice = try self.allocFn(self, byte_count, alignment);
4747 // This loop should get optimized out in ReleaseFast mode
4848 for (byte_slice) |*byte| {
4949 *byte = undefined;
......@@ -63,8 +63,8 @@ pub const Allocator = struct {
6363 }
6464
6565 const old_byte_slice = ([]u8)(old_mem);
66 const byte_count = %return math.mul(usize, @sizeOf(T), n);
67 const byte_slice = %return self.reallocFn(self, old_byte_slice, byte_count, alignment);
66 const byte_count = try math.mul(usize, @sizeOf(T), n);
67 const byte_slice = try self.reallocFn(self, old_byte_slice, byte_count, alignment);
6868 // This loop should get optimized out in ReleaseFast mode
6969 for (byte_slice[old_byte_slice.len..]) |*byte| {
7070 *byte = undefined;
......@@ -142,7 +142,7 @@ pub const FixedBufferAllocator = struct {
142142 if (new_size <= old_mem.len) {
143143 return old_mem[0..new_size];
144144 } else {
145 const result = %return alloc(allocator, new_size, alignment);
145 const result = try alloc(allocator, new_size, alignment);
146146 copy(u8, result, old_mem);
147147 return result;
148148 }
......@@ -198,7 +198,7 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) -> bool {
198198
199199/// Copies ::m to newly allocated memory. Caller is responsible to free it.
200200pub fn dupe(allocator: &Allocator, comptime T: type, m: []const T) -> %[]T {
201 const new_buf = %return allocator.alloc(T, m.len);
201 const new_buf = try allocator.alloc(T, m.len);
202202 copy(T, new_buf, m);
203203 return new_buf;
204204}
......@@ -425,7 +425,7 @@ pub fn join(allocator: &Allocator, sep: u8, strings: ...) -> %[]u8 {
425425 }
426426 }
427427
428 const buf = %return allocator.alloc(u8, total_strings_len);
428 const buf = try allocator.alloc(u8, total_strings_len);
429429 %defer allocator.free(buf);
430430
431431 var buf_index: usize = 0;
std/net.zig+1-1
......@@ -133,7 +133,7 @@ pub fn connectAddr(addr: &Address, port: u16) -> %Connection {
133133
134134pub fn connect(hostname: []const u8, port: u16) -> %Connection {
135135 var addrs_buf: [1]Address = undefined;
136 const addrs_slice = %return lookup(hostname, addrs_buf[0..]);
136 const addrs_slice = try lookup(hostname, addrs_buf[0..]);
137137 const main_addr = &addrs_slice[0];
138138
139139 return connectAddr(main_addr, port);
std/os/child_process.zig+45-45
......@@ -75,7 +75,7 @@ pub const ChildProcess = struct {
7575 /// First argument in argv is the executable.
7676 /// On success must call deinit.
7777 pub fn init(argv: []const []const u8, allocator: &mem.Allocator) -> %&ChildProcess {
78 const child = %return allocator.create(ChildProcess);
78 const child = try allocator.create(ChildProcess);
7979 %defer allocator.destroy(child);
8080
8181 *child = ChildProcess {
......@@ -104,7 +104,7 @@ pub const ChildProcess = struct {
104104 }
105105
106106 pub fn setUserName(self: &ChildProcess, name: []const u8) -> %void {
107 const user_info = %return os.getUserInfo(name);
107 const user_info = try os.getUserInfo(name);
108108 self.uid = user_info.uid;
109109 self.gid = user_info.gid;
110110 }
......@@ -120,7 +120,7 @@ pub const ChildProcess = struct {
120120 }
121121
122122 pub fn spawnAndWait(self: &ChildProcess) -> %Term {
123 %return self.spawn();
123 try self.spawn();
124124 return self.wait();
125125 }
126126
......@@ -200,7 +200,7 @@ pub const ChildProcess = struct {
200200 child.cwd = cwd;
201201 child.env_map = env_map;
202202
203 %return child.spawn();
203 try child.spawn();
204204
205205 var stdout = Buffer.initNull(allocator);
206206 var stderr = Buffer.initNull(allocator);
......@@ -210,11 +210,11 @@ pub const ChildProcess = struct {
210210 var stdout_file_in_stream = io.FileInStream.init(&??child.stdout);
211211 var stderr_file_in_stream = io.FileInStream.init(&??child.stderr);
212212
213 %return stdout_file_in_stream.stream.readAllBuffer(&stdout, max_output_size);
214 %return stderr_file_in_stream.stream.readAllBuffer(&stderr, max_output_size);
213 try stdout_file_in_stream.stream.readAllBuffer(&stdout, max_output_size);
214 try stderr_file_in_stream.stream.readAllBuffer(&stderr, max_output_size);
215215
216216 return ExecResult {
217 .term = %return child.wait(),
217 .term = try child.wait(),
218218 .stdout = stdout.toOwnedSlice(),
219219 .stderr = stderr.toOwnedSlice(),
220220 };
......@@ -226,7 +226,7 @@ pub const ChildProcess = struct {
226226 return term;
227227 }
228228
229 %return self.waitUnwrappedWindows();
229 try self.waitUnwrappedWindows();
230230 return ??self.term;
231231 }
232232
......@@ -308,8 +308,8 @@ pub const ChildProcess = struct {
308308 // pid potentially wrote an error. This way we can do a blocking
309309 // read on the error pipe and either get @maxValue(ErrInt) (no error) or
310310 // an error code.
311 %return writeIntFd(self.err_pipe[1], @maxValue(ErrInt));
312 const err_int = %return readIntFd(self.err_pipe[0]);
311 try writeIntFd(self.err_pipe[1], @maxValue(ErrInt));
312 const err_int = try readIntFd(self.err_pipe[0]);
313313 // Here we potentially return the fork child's error
314314 // from the parent pid.
315315 if (err_int != @maxValue(ErrInt)) {
......@@ -335,18 +335,18 @@ pub const ChildProcess = struct {
335335 // TODO atomically set a flag saying that we already did this
336336 install_SIGCHLD_handler();
337337
338 const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) %return makePipe() else undefined;
338 const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try makePipe() else undefined;
339339 %defer if (self.stdin_behavior == StdIo.Pipe) { destroyPipe(stdin_pipe); };
340340
341 const stdout_pipe = if (self.stdout_behavior == StdIo.Pipe) %return makePipe() else undefined;
341 const stdout_pipe = if (self.stdout_behavior == StdIo.Pipe) try makePipe() else undefined;
342342 %defer if (self.stdout_behavior == StdIo.Pipe) { destroyPipe(stdout_pipe); };
343343
344 const stderr_pipe = if (self.stderr_behavior == StdIo.Pipe) %return makePipe() else undefined;
344 const stderr_pipe = if (self.stderr_behavior == StdIo.Pipe) try makePipe() else undefined;
345345 %defer if (self.stderr_behavior == StdIo.Pipe) { destroyPipe(stderr_pipe); };
346346
347347 const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore);
348348 const dev_null_fd = if (any_ignore)
349 %return os.posixOpen("/dev/null", posix.O_RDWR, 0, null)
349 try os.posixOpen("/dev/null", posix.O_RDWR, 0, null)
350350 else
351351 undefined
352352 ;
......@@ -359,14 +359,14 @@ pub const ChildProcess = struct {
359359 break :x env_map;
360360 } else x: {
361361 we_own_env_map = true;
362 env_map_owned = %return os.getEnvMap(self.allocator);
362 env_map_owned = try os.getEnvMap(self.allocator);
363363 break :x &env_map_owned;
364364 };
365365 defer { if (we_own_env_map) env_map_owned.deinit(); }
366366
367367 // This pipe is used to communicate errors between the time of fork
368368 // and execve from the child process to the parent process.
369 const err_pipe = %return makePipe();
369 const err_pipe = try makePipe();
370370 %defer destroyPipe(err_pipe);
371371
372372 block_SIGCHLD();
......@@ -452,14 +452,14 @@ pub const ChildProcess = struct {
452452 self.stderr_behavior == StdIo.Ignore);
453453
454454 const nul_handle = if (any_ignore)
455 %return os.windowsOpen("NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ,
455 try os.windowsOpen("NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ,
456456 windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, null)
457457 else
458458 undefined
459459 ;
460460 defer { if (any_ignore) os.close(nul_handle); }
461461 if (any_ignore) {
462 %return windowsSetHandleInfo(nul_handle, windows.HANDLE_FLAG_INHERIT, 0);
462 try windowsSetHandleInfo(nul_handle, windows.HANDLE_FLAG_INHERIT, 0);
463463 }
464464
465465
......@@ -467,7 +467,7 @@ pub const ChildProcess = struct {
467467 var g_hChildStd_IN_Wr: ?windows.HANDLE = null;
468468 switch (self.stdin_behavior) {
469469 StdIo.Pipe => {
470 %return windowsMakePipeIn(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, saAttr);
470 try windowsMakePipeIn(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, saAttr);
471471 },
472472 StdIo.Ignore => {
473473 g_hChildStd_IN_Rd = nul_handle;
......@@ -485,7 +485,7 @@ pub const ChildProcess = struct {
485485 var g_hChildStd_OUT_Wr: ?windows.HANDLE = null;
486486 switch (self.stdout_behavior) {
487487 StdIo.Pipe => {
488 %return windowsMakePipeOut(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, saAttr);
488 try windowsMakePipeOut(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, saAttr);
489489 },
490490 StdIo.Ignore => {
491491 g_hChildStd_OUT_Wr = nul_handle;
......@@ -503,7 +503,7 @@ pub const ChildProcess = struct {
503503 var g_hChildStd_ERR_Wr: ?windows.HANDLE = null;
504504 switch (self.stderr_behavior) {
505505 StdIo.Pipe => {
506 %return windowsMakePipeOut(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, saAttr);
506 try windowsMakePipeOut(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, saAttr);
507507 },
508508 StdIo.Ignore => {
509509 g_hChildStd_ERR_Wr = nul_handle;
......@@ -517,7 +517,7 @@ pub const ChildProcess = struct {
517517 }
518518 %defer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_ERR_Rd, g_hChildStd_ERR_Wr); };
519519
520 const cmd_line = %return windowsCreateCommandLine(self.allocator, self.argv);
520 const cmd_line = try windowsCreateCommandLine(self.allocator, self.argv);
521521 defer self.allocator.free(cmd_line);
522522
523523 var siStartInfo = windows.STARTUPINFOA {
......@@ -544,7 +544,7 @@ pub const ChildProcess = struct {
544544 var piProcInfo: windows.PROCESS_INFORMATION = undefined;
545545
546546 const cwd_slice = if (self.cwd) |cwd|
547 %return cstr.addNullByte(self.allocator, cwd)
547 try cstr.addNullByte(self.allocator, cwd)
548548 else
549549 null
550550 ;
......@@ -552,7 +552,7 @@ pub const ChildProcess = struct {
552552 const cwd_ptr = if (cwd_slice) |cwd| cwd.ptr else null;
553553
554554 const maybe_envp_buf = if (self.env_map) |env_map|
555 %return os.createWindowsEnvBlock(self.allocator, env_map)
555 try os.createWindowsEnvBlock(self.allocator, env_map)
556556 else
557557 null
558558 ;
......@@ -563,11 +563,11 @@ pub const ChildProcess = struct {
563563 // to match posix semantics
564564 const app_name = x: {
565565 if (self.cwd) |cwd| {
566 const resolved = %return os.path.resolve(self.allocator, cwd, self.argv[0]);
566 const resolved = try os.path.resolve(self.allocator, cwd, self.argv[0]);
567567 defer self.allocator.free(resolved);
568 break :x %return cstr.addNullByte(self.allocator, resolved);
568 break :x try cstr.addNullByte(self.allocator, resolved);
569569 } else {
570 break :x %return cstr.addNullByte(self.allocator, self.argv[0]);
570 break :x try cstr.addNullByte(self.allocator, self.argv[0]);
571571 }
572572 };
573573 defer self.allocator.free(app_name);
......@@ -578,12 +578,12 @@ pub const ChildProcess = struct {
578578 if (no_path_err != error.FileNotFound)
579579 return no_path_err;
580580
581 const PATH = %return os.getEnvVarOwned(self.allocator, "PATH");
581 const PATH = try os.getEnvVarOwned(self.allocator, "PATH");
582582 defer self.allocator.free(PATH);
583583
584584 var it = mem.split(PATH, ";");
585585 while (it.next()) |search_path| {
586 const joined_path = %return os.path.join(self.allocator, search_path, app_name);
586 const joined_path = try os.path.join(self.allocator, search_path, app_name);
587587 defer self.allocator.free(joined_path);
588588
589589 if (windowsCreateProcess(joined_path.ptr, cmd_line.ptr, envp_ptr, cwd_ptr,
......@@ -625,10 +625,10 @@ pub const ChildProcess = struct {
625625
626626 fn setUpChildIo(stdio: StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) -> %void {
627627 switch (stdio) {
628 StdIo.Pipe => %return os.posixDup2(pipe_fd, std_fileno),
628 StdIo.Pipe => try os.posixDup2(pipe_fd, std_fileno),
629629 StdIo.Close => os.close(std_fileno),
630630 StdIo.Inherit => {},
631 StdIo.Ignore => %return os.posixDup2(dev_null_fd, std_fileno),
631 StdIo.Ignore => try os.posixDup2(dev_null_fd, std_fileno),
632632 }
633633 }
634634
......@@ -656,35 +656,35 @@ fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?
656656/// Caller must dealloc.
657657/// Guarantees a null byte at result[result.len].
658658fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) -> %[]u8 {
659 var buf = %return Buffer.initSize(allocator, 0);
659 var buf = try Buffer.initSize(allocator, 0);
660660 defer buf.deinit();
661661
662662 for (argv) |arg, arg_i| {
663663 if (arg_i != 0)
664 %return buf.appendByte(' ');
664 try buf.appendByte(' ');
665665 if (mem.indexOfAny(u8, arg, " \t\n\"") == null) {
666 %return buf.append(arg);
666 try buf.append(arg);
667667 continue;
668668 }
669 %return buf.appendByte('"');
669 try buf.appendByte('"');
670670 var backslash_count: usize = 0;
671671 for (arg) |byte| {
672672 switch (byte) {
673673 '\\' => backslash_count += 1,
674674 '"' => {
675 %return buf.appendByteNTimes('\\', backslash_count * 2 + 1);
676 %return buf.appendByte('"');
675 try buf.appendByteNTimes('\\', backslash_count * 2 + 1);
676 try buf.appendByte('"');
677677 backslash_count = 0;
678678 },
679679 else => {
680 %return buf.appendByteNTimes('\\', backslash_count);
681 %return buf.appendByte(byte);
680 try buf.appendByteNTimes('\\', backslash_count);
681 try buf.appendByte(byte);
682682 backslash_count = 0;
683683 },
684684 }
685685 }
686 %return buf.appendByteNTimes('\\', backslash_count * 2);
687 %return buf.appendByte('"');
686 try buf.appendByteNTimes('\\', backslash_count * 2);
687 try buf.appendByte('"');
688688 }
689689
690690 return buf.toOwnedSlice();
......@@ -721,9 +721,9 @@ fn windowsSetHandleInfo(h: windows.HANDLE, mask: windows.DWORD, flags: windows.D
721721fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) -> %void {
722722 var rd_h: windows.HANDLE = undefined;
723723 var wr_h: windows.HANDLE = undefined;
724 %return windowsMakePipe(&rd_h, &wr_h, sattr);
724 try windowsMakePipe(&rd_h, &wr_h, sattr);
725725 %defer windowsDestroyPipe(rd_h, wr_h);
726 %return windowsSetHandleInfo(wr_h, windows.HANDLE_FLAG_INHERIT, 0);
726 try windowsSetHandleInfo(wr_h, windows.HANDLE_FLAG_INHERIT, 0);
727727 *rd = rd_h;
728728 *wr = wr_h;
729729}
......@@ -731,9 +731,9 @@ fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const S
731731fn windowsMakePipeOut(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) -> %void {
732732 var rd_h: windows.HANDLE = undefined;
733733 var wr_h: windows.HANDLE = undefined;
734 %return windowsMakePipe(&rd_h, &wr_h, sattr);
734 try windowsMakePipe(&rd_h, &wr_h, sattr);
735735 %defer windowsDestroyPipe(rd_h, wr_h);
736 %return windowsSetHandleInfo(rd_h, windows.HANDLE_FLAG_INHERIT, 0);
736 try windowsSetHandleInfo(rd_h, windows.HANDLE_FLAG_INHERIT, 0);
737737 *rd = rd_h;
738738 *wr = wr_h;
739739}
std/os/get_user_id.zig+2-2
......@@ -31,7 +31,7 @@ error CorruptPasswordFile;
3131// like NIS, AD, etc. See `man nss` or look at an strace for `id myuser`.
3232
3333pub fn posixGetUserInfo(name: []const u8) -> %UserInfo {
34 var in_stream = %return io.InStream.open("/etc/passwd", null);
34 var in_stream = try io.InStream.open("/etc/passwd", null);
3535 defer in_stream.close();
3636
3737 var buf: [os.page_size]u8 = undefined;
......@@ -41,7 +41,7 @@ pub fn posixGetUserInfo(name: []const u8) -> %UserInfo {
4141 var gid: u32 = 0;
4242
4343 while (true) {
44 const amt_read = %return in_stream.read(buf[0..]);
44 const amt_read = try in_stream.read(buf[0..]);
4545 for (buf[0..amt_read]) |byte| {
4646 switch (state) {
4747 State.Start => switch (byte) {
std/os/index.zig+69-69
......@@ -92,11 +92,11 @@ pub fn getRandomBytes(buf: []u8) -> %void {
9292 return;
9393 },
9494 Os.macosx, Os.ios => {
95 const fd = %return posixOpen("/dev/urandom", posix.O_RDONLY|posix.O_CLOEXEC,
95 const fd = try posixOpen("/dev/urandom", posix.O_RDONLY|posix.O_CLOEXEC,
9696 0, null);
9797 defer close(fd);
9898
99 %return posixRead(fd, buf);
99 try posixRead(fd, buf);
100100 },
101101 Os.windows => {
102102 var hCryptProv: windows.HCRYPTPROV = undefined;
......@@ -256,7 +256,7 @@ pub fn posixOpen(file_path: []const u8, flags: u32, perm: usize, allocator: ?&Al
256256 if (file_path.len < stack_buf.len) {
257257 path0 = stack_buf[0..file_path.len + 1];
258258 } else if (allocator) |a| {
259 path0 = %return a.alloc(u8, file_path.len + 1);
259 path0 = try a.alloc(u8, file_path.len + 1);
260260 need_free = true;
261261 } else {
262262 return error.NameTooLong;
......@@ -314,14 +314,14 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) -> %void {
314314
315315pub fn createNullDelimitedEnvMap(allocator: &Allocator, env_map: &const BufMap) -> %[]?&u8 {
316316 const envp_count = env_map.count();
317 const envp_buf = %return allocator.alloc(?&u8, envp_count + 1);
317 const envp_buf = try allocator.alloc(?&u8, envp_count + 1);
318318 mem.set(?&u8, envp_buf, null);
319319 %defer freeNullDelimitedEnvMap(allocator, envp_buf);
320320 {
321321 var it = env_map.iterator();
322322 var i: usize = 0;
323323 while (it.next()) |pair| : (i += 1) {
324 const env_buf = %return allocator.alloc(u8, pair.key.len + pair.value.len + 2);
324 const env_buf = try allocator.alloc(u8, pair.key.len + pair.value.len + 2);
325325 @memcpy(&env_buf[0], pair.key.ptr, pair.key.len);
326326 env_buf[pair.key.len] = '=';
327327 @memcpy(&env_buf[pair.key.len + 1], pair.value.ptr, pair.value.len);
......@@ -351,7 +351,7 @@ pub fn freeNullDelimitedEnvMap(allocator: &Allocator, envp_buf: []?&u8) {
351351pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap,
352352 allocator: &Allocator) -> %void
353353{
354 const argv_buf = %return allocator.alloc(?&u8, argv.len + 1);
354 const argv_buf = try allocator.alloc(?&u8, argv.len + 1);
355355 mem.set(?&u8, argv_buf, null);
356356 defer {
357357 for (argv_buf) |arg| {
......@@ -361,7 +361,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap,
361361 allocator.free(argv_buf);
362362 }
363363 for (argv) |arg, i| {
364 const arg_buf = %return allocator.alloc(u8, arg.len + 1);
364 const arg_buf = try allocator.alloc(u8, arg.len + 1);
365365 @memcpy(&arg_buf[0], arg.ptr, arg.len);
366366 arg_buf[arg.len] = 0;
367367
......@@ -369,7 +369,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap,
369369 }
370370 argv_buf[argv.len] = null;
371371
372 const envp_buf = %return createNullDelimitedEnvMap(allocator, env_map);
372 const envp_buf = try createNullDelimitedEnvMap(allocator, env_map);
373373 defer freeNullDelimitedEnvMap(allocator, envp_buf);
374374
375375 const exe_path = argv[0];
......@@ -381,7 +381,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap,
381381 // PATH.len because it is >= the largest search_path
382382 // +1 for the / to join the search path and exe_path
383383 // +1 for the null terminating byte
384 const path_buf = %return allocator.alloc(u8, PATH.len + exe_path.len + 2);
384 const path_buf = try allocator.alloc(u8, PATH.len + exe_path.len + 2);
385385 defer allocator.free(path_buf);
386386 var it = mem.split(PATH, ":");
387387 var seen_eacces = false;
......@@ -450,7 +450,7 @@ pub fn getEnvMap(allocator: &Allocator) -> %BufMap {
450450
451451 i += 1; // skip over null byte
452452
453 %return result.set(key, value);
453 try result.set(key, value);
454454 }
455455 } else {
456456 for (posix_environ_raw) |ptr| {
......@@ -462,7 +462,7 @@ pub fn getEnvMap(allocator: &Allocator) -> %BufMap {
462462 while (ptr[end_i] != 0) : (end_i += 1) {}
463463 const value = ptr[line_i + 1..end_i];
464464
465 %return result.set(key, value);
465 try result.set(key, value);
466466 }
467467 return result;
468468 }
......@@ -490,14 +490,14 @@ error EnvironmentVariableNotFound;
490490/// Caller must free returned memory.
491491pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) -> %[]u8 {
492492 if (is_windows) {
493 const key_with_null = %return cstr.addNullByte(allocator, key);
493 const key_with_null = try cstr.addNullByte(allocator, key);
494494 defer allocator.free(key_with_null);
495495
496 var buf = %return allocator.alloc(u8, 256);
496 var buf = try allocator.alloc(u8, 256);
497497 %defer allocator.free(buf);
498498
499499 while (true) {
500 const windows_buf_len = %return math.cast(windows.DWORD, buf.len);
500 const windows_buf_len = try math.cast(windows.DWORD, buf.len);
501501 const result = windows.GetEnvironmentVariableA(key_with_null.ptr, buf.ptr, windows_buf_len);
502502
503503 if (result == 0) {
......@@ -509,7 +509,7 @@ pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) -> %[]u8 {
509509 }
510510
511511 if (result > buf.len) {
512 buf = %return allocator.realloc(u8, buf, result);
512 buf = try allocator.realloc(u8, buf, result);
513513 continue;
514514 }
515515
......@@ -525,7 +525,7 @@ pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) -> %[]u8 {
525525pub fn getCwd(allocator: &Allocator) -> %[]u8 {
526526 switch (builtin.os) {
527527 Os.windows => {
528 var buf = %return allocator.alloc(u8, 256);
528 var buf = try allocator.alloc(u8, 256);
529529 %defer allocator.free(buf);
530530
531531 while (true) {
......@@ -539,7 +539,7 @@ pub fn getCwd(allocator: &Allocator) -> %[]u8 {
539539 }
540540
541541 if (result > buf.len) {
542 buf = %return allocator.realloc(u8, buf, result);
542 buf = try allocator.realloc(u8, buf, result);
543543 continue;
544544 }
545545
......@@ -547,12 +547,12 @@ pub fn getCwd(allocator: &Allocator) -> %[]u8 {
547547 }
548548 },
549549 else => {
550 var buf = %return allocator.alloc(u8, 1024);
550 var buf = try allocator.alloc(u8, 1024);
551551 %defer allocator.free(buf);
552552 while (true) {
553553 const err = posix.getErrno(posix.getcwd(buf.ptr, buf.len));
554554 if (err == posix.ERANGE) {
555 buf = %return allocator.realloc(u8, buf, buf.len * 2);
555 buf = try allocator.realloc(u8, buf, buf.len * 2);
556556 continue;
557557 } else if (err > 0) {
558558 return unexpectedErrorPosix(err);
......@@ -578,9 +578,9 @@ pub fn symLink(allocator: &Allocator, existing_path: []const u8, new_path: []con
578578}
579579
580580pub fn symLinkWindows(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) -> %void {
581 const existing_with_null = %return cstr.addNullByte(allocator, existing_path);
581 const existing_with_null = try cstr.addNullByte(allocator, existing_path);
582582 defer allocator.free(existing_with_null);
583 const new_with_null = %return cstr.addNullByte(allocator, new_path);
583 const new_with_null = try cstr.addNullByte(allocator, new_path);
584584 defer allocator.free(new_with_null);
585585
586586 if (windows.CreateSymbolicLinkA(existing_with_null.ptr, new_with_null.ptr, 0) == 0) {
......@@ -592,7 +592,7 @@ pub fn symLinkWindows(allocator: &Allocator, existing_path: []const u8, new_path
592592}
593593
594594pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) -> %void {
595 const full_buf = %return allocator.alloc(u8, existing_path.len + new_path.len + 2);
595 const full_buf = try allocator.alloc(u8, existing_path.len + new_path.len + 2);
596596 defer allocator.free(full_buf);
597597
598598 const existing_buf = full_buf;
......@@ -638,11 +638,11 @@ pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path:
638638 }
639639
640640 var rand_buf: [12]u8 = undefined;
641 const tmp_path = %return allocator.alloc(u8, new_path.len + base64.Base64Encoder.calcSize(rand_buf.len));
641 const tmp_path = try allocator.alloc(u8, new_path.len + base64.Base64Encoder.calcSize(rand_buf.len));
642642 defer allocator.free(tmp_path);
643643 mem.copy(u8, tmp_path[0..], new_path);
644644 while (true) {
645 %return getRandomBytes(rand_buf[0..]);
645 try getRandomBytes(rand_buf[0..]);
646646 b64_fs_encoder.encode(tmp_path[new_path.len..], rand_buf);
647647 if (symLink(allocator, existing_path, tmp_path)) {
648648 return rename(allocator, tmp_path, new_path);
......@@ -669,7 +669,7 @@ error FileNotFound;
669669error AccessDenied;
670670
671671pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) -> %void {
672 const buf = %return allocator.alloc(u8, file_path.len + 1);
672 const buf = try allocator.alloc(u8, file_path.len + 1);
673673 defer allocator.free(buf);
674674
675675 mem.copy(u8, buf, file_path);
......@@ -687,7 +687,7 @@ pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) -> %void
687687}
688688
689689pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) -> %void {
690 const buf = %return allocator.alloc(u8, file_path.len + 1);
690 const buf = try allocator.alloc(u8, file_path.len + 1);
691691 defer allocator.free(buf);
692692
693693 mem.copy(u8, buf, file_path);
......@@ -721,30 +721,30 @@ pub fn copyFile(allocator: &Allocator, source_path: []const u8, dest_path: []con
721721/// Guaranteed to be atomic.
722722pub fn copyFileMode(allocator: &Allocator, source_path: []const u8, dest_path: []const u8, mode: usize) -> %void {
723723 var rand_buf: [12]u8 = undefined;
724 const tmp_path = %return allocator.alloc(u8, dest_path.len + base64.Base64Encoder.calcSize(rand_buf.len));
724 const tmp_path = try allocator.alloc(u8, dest_path.len + base64.Base64Encoder.calcSize(rand_buf.len));
725725 defer allocator.free(tmp_path);
726726 mem.copy(u8, tmp_path[0..], dest_path);
727 %return getRandomBytes(rand_buf[0..]);
727 try getRandomBytes(rand_buf[0..]);
728728 b64_fs_encoder.encode(tmp_path[dest_path.len..], rand_buf);
729729
730 var out_file = %return io.File.openWriteMode(tmp_path, mode, allocator);
730 var out_file = try io.File.openWriteMode(tmp_path, mode, allocator);
731731 defer out_file.close();
732732 %defer _ = deleteFile(allocator, tmp_path);
733733
734 var in_file = %return io.File.openRead(source_path, allocator);
734 var in_file = try io.File.openRead(source_path, allocator);
735735 defer in_file.close();
736736
737737 var buf: [page_size]u8 = undefined;
738738 while (true) {
739 const amt = %return in_file.read(buf[0..]);
740 %return out_file.write(buf[0..amt]);
739 const amt = try in_file.read(buf[0..]);
740 try out_file.write(buf[0..amt]);
741741 if (amt != buf.len)
742742 return rename(allocator, tmp_path, dest_path);
743743 }
744744}
745745
746746pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) -> %void {
747 const full_buf = %return allocator.alloc(u8, old_path.len + new_path.len + 2);
747 const full_buf = try allocator.alloc(u8, old_path.len + new_path.len + 2);
748748 defer allocator.free(full_buf);
749749
750750 const old_buf = full_buf;
......@@ -797,7 +797,7 @@ pub fn makeDir(allocator: &Allocator, dir_path: []const u8) -> %void {
797797}
798798
799799pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) -> %void {
800 const path_buf = %return cstr.addNullByte(allocator, dir_path);
800 const path_buf = try cstr.addNullByte(allocator, dir_path);
801801 defer allocator.free(path_buf);
802802
803803 if (windows.CreateDirectoryA(path_buf.ptr, null) == 0) {
......@@ -811,7 +811,7 @@ pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) -> %void {
811811}
812812
813813pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) -> %void {
814 const path_buf = %return cstr.addNullByte(allocator, dir_path);
814 const path_buf = try cstr.addNullByte(allocator, dir_path);
815815 defer allocator.free(path_buf);
816816
817817 const err = posix.getErrno(posix.mkdir(path_buf.ptr, 0o755));
......@@ -837,7 +837,7 @@ pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) -> %void {
837837/// Calls makeDir recursively to make an entire path. Returns success if the path
838838/// already exists and is a directory.
839839pub fn makePath(allocator: &Allocator, full_path: []const u8) -> %void {
840 const resolved_path = %return path.resolve(allocator, full_path);
840 const resolved_path = try path.resolve(allocator, full_path);
841841 defer allocator.free(resolved_path);
842842
843843 var end_index: usize = resolved_path.len;
......@@ -875,7 +875,7 @@ pub fn makePath(allocator: &Allocator, full_path: []const u8) -> %void {
875875/// Returns ::error.DirNotEmpty if the directory is not empty.
876876/// To delete a directory recursively, see ::deleteTree
877877pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) -> %void {
878 const path_buf = %return allocator.alloc(u8, dir_path.len + 1);
878 const path_buf = try allocator.alloc(u8, dir_path.len + 1);
879879 defer allocator.free(path_buf);
880880
881881 mem.copy(u8, path_buf, dir_path);
......@@ -927,14 +927,14 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) -> %void {
927927 var full_entry_buf = ArrayList(u8).init(allocator);
928928 defer full_entry_buf.deinit();
929929
930 while (%return dir.next()) |entry| {
931 %return full_entry_buf.resize(full_path.len + entry.name.len + 1);
930 while (try dir.next()) |entry| {
931 try full_entry_buf.resize(full_path.len + entry.name.len + 1);
932932 const full_entry_path = full_entry_buf.toSlice();
933933 mem.copy(u8, full_entry_path, full_path);
934934 full_entry_path[full_path.len] = '/';
935935 mem.copy(u8, full_entry_path[full_path.len + 1..], entry.name);
936936
937 %return deleteTree(allocator, full_entry_path);
937 try deleteTree(allocator, full_entry_path);
938938 }
939939 }
940940 return deleteDir(allocator, full_path);
......@@ -973,7 +973,7 @@ pub const Dir = struct {
973973 };
974974
975975 pub fn open(allocator: &Allocator, dir_path: []const u8) -> %Dir {
976 const fd = %return posixOpen(dir_path, posix.O_RDONLY|posix.O_DIRECTORY|posix.O_CLOEXEC, 0, allocator);
976 const fd = try posixOpen(dir_path, posix.O_RDONLY|posix.O_DIRECTORY|posix.O_CLOEXEC, 0, allocator);
977977 return Dir {
978978 .allocator = allocator,
979979 .fd = fd,
......@@ -994,7 +994,7 @@ pub const Dir = struct {
994994 start_over: while (true) {
995995 if (self.index >= self.end_index) {
996996 if (self.buf.len == 0) {
997 self.buf = %return self.allocator.alloc(u8, page_size);
997 self.buf = try self.allocator.alloc(u8, page_size);
998998 }
999999
10001000 while (true) {
......@@ -1004,7 +1004,7 @@ pub const Dir = struct {
10041004 switch (err) {
10051005 posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable,
10061006 posix.EINVAL => {
1007 self.buf = %return self.allocator.realloc(u8, self.buf, self.buf.len * 2);
1007 self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2);
10081008 continue;
10091009 },
10101010 else => return unexpectedErrorPosix(err),
......@@ -1048,7 +1048,7 @@ pub const Dir = struct {
10481048};
10491049
10501050pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) -> %void {
1051 const path_buf = %return allocator.alloc(u8, dir_path.len + 1);
1051 const path_buf = try allocator.alloc(u8, dir_path.len + 1);
10521052 defer allocator.free(path_buf);
10531053
10541054 mem.copy(u8, path_buf, dir_path);
......@@ -1072,13 +1072,13 @@ pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) -> %void {
10721072
10731073/// Read value of a symbolic link.
10741074pub fn readLink(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
1075 const path_buf = %return allocator.alloc(u8, pathname.len + 1);
1075 const path_buf = try allocator.alloc(u8, pathname.len + 1);
10761076 defer allocator.free(path_buf);
10771077
10781078 mem.copy(u8, path_buf, pathname);
10791079 path_buf[pathname.len] = 0;
10801080
1081 var result_buf = %return allocator.alloc(u8, 1024);
1081 var result_buf = try allocator.alloc(u8, 1024);
10821082 %defer allocator.free(result_buf);
10831083 while (true) {
10841084 const ret_val = posix.readlink(path_buf.ptr, result_buf.ptr, result_buf.len);
......@@ -1097,7 +1097,7 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
10971097 };
10981098 }
10991099 if (ret_val == result_buf.len) {
1100 result_buf = %return allocator.realloc(u8, result_buf, result_buf.len * 2);
1100 result_buf = try allocator.realloc(u8, result_buf, result_buf.len * 2);
11011101 continue;
11021102 }
11031103 return allocator.shrink(u8, result_buf, ret_val);
......@@ -1320,7 +1320,7 @@ pub const ArgIteratorWindows = struct {
13201320 }
13211321
13221322 fn internalNext(self: &ArgIteratorWindows, allocator: &Allocator) -> %[]u8 {
1323 var buf = %return Buffer.initSize(allocator, 0);
1323 var buf = try Buffer.initSize(allocator, 0);
13241324 defer buf.deinit();
13251325
13261326 var backslash_count: usize = 0;
......@@ -1330,34 +1330,34 @@ pub const ArgIteratorWindows = struct {
13301330 0 => return buf.toOwnedSlice(),
13311331 '"' => {
13321332 const quote_is_real = backslash_count % 2 == 0;
1333 %return self.emitBackslashes(&buf, backslash_count / 2);
1333 try self.emitBackslashes(&buf, backslash_count / 2);
13341334 backslash_count = 0;
13351335
13361336 if (quote_is_real) {
13371337 self.seen_quote_count += 1;
13381338 if (self.seen_quote_count == self.quote_count and self.seen_quote_count % 2 == 1) {
1339 %return buf.appendByte('"');
1339 try buf.appendByte('"');
13401340 }
13411341 } else {
1342 %return buf.appendByte('"');
1342 try buf.appendByte('"');
13431343 }
13441344 },
13451345 '\\' => {
13461346 backslash_count += 1;
13471347 },
13481348 ' ', '\t' => {
1349 %return self.emitBackslashes(&buf, backslash_count);
1349 try self.emitBackslashes(&buf, backslash_count);
13501350 backslash_count = 0;
13511351 if (self.seen_quote_count % 2 == 1 and self.seen_quote_count != self.quote_count) {
1352 %return buf.appendByte(byte);
1352 try buf.appendByte(byte);
13531353 } else {
13541354 return buf.toOwnedSlice();
13551355 }
13561356 },
13571357 else => {
1358 %return self.emitBackslashes(&buf, backslash_count);
1358 try self.emitBackslashes(&buf, backslash_count);
13591359 backslash_count = 0;
1360 %return buf.appendByte(byte);
1360 try buf.appendByte(byte);
13611361 },
13621362 }
13631363 }
......@@ -1366,7 +1366,7 @@ pub const ArgIteratorWindows = struct {
13661366 fn emitBackslashes(self: &ArgIteratorWindows, buf: &Buffer, emit_count: usize) -> %void {
13671367 var i: usize = 0;
13681368 while (i < emit_count) : (i += 1) {
1369 %return buf.appendByte('\\');
1369 try buf.appendByte('\\');
13701370 }
13711371 }
13721372
......@@ -1430,24 +1430,24 @@ pub fn args() -> ArgIterator {
14301430pub fn argsAlloc(allocator: &mem.Allocator) -> %[]const []u8 {
14311431 // TODO refactor to only make 1 allocation.
14321432 var it = args();
1433 var contents = %return Buffer.initSize(allocator, 0);
1433 var contents = try Buffer.initSize(allocator, 0);
14341434 defer contents.deinit();
14351435
14361436 var slice_list = ArrayList(usize).init(allocator);
14371437 defer slice_list.deinit();
14381438
14391439 while (it.next(allocator)) |arg_or_err| {
1440 const arg = %return arg_or_err;
1440 const arg = try arg_or_err;
14411441 defer allocator.free(arg);
1442 %return contents.append(arg);
1443 %return slice_list.append(arg.len);
1442 try contents.append(arg);
1443 try slice_list.append(arg.len);
14441444 }
14451445
14461446 const contents_slice = contents.toSliceConst();
14471447 const slice_sizes = slice_list.toSliceConst();
1448 const slice_list_bytes = %return math.mul(usize, @sizeOf([]u8), slice_sizes.len);
1449 const total_bytes = %return math.add(usize, slice_list_bytes, contents_slice.len);
1450 const buf = %return allocator.alignedAlloc(u8, @alignOf([]u8), total_bytes);
1448 const slice_list_bytes = try math.mul(usize, @sizeOf([]u8), slice_sizes.len);
1449 const total_bytes = try math.add(usize, slice_list_bytes, contents_slice.len);
1450 const buf = try allocator.alignedAlloc(u8, @alignOf([]u8), total_bytes);
14511451 %defer allocator.free(buf);
14521452
14531453 const result_slice_list = ([][]u8)(buf[0..slice_list_bytes]);
......@@ -1560,10 +1560,10 @@ pub fn selfExePath(allocator: &mem.Allocator) -> %[]u8 {
15601560 return readLink(allocator, "/proc/self/exe");
15611561 },
15621562 Os.windows => {
1563 var out_path = %return Buffer.initSize(allocator, 0xff);
1563 var out_path = try Buffer.initSize(allocator, 0xff);
15641564 %defer out_path.deinit();
15651565 while (true) {
1566 const dword_len = %return math.cast(windows.DWORD, out_path.len());
1566 const dword_len = try math.cast(windows.DWORD, out_path.len());
15671567 const copied_amt = windows.GetModuleFileNameA(null, out_path.ptr(), dword_len);
15681568 if (copied_amt <= 0) {
15691569 const err = windows.GetLastError();
......@@ -1576,14 +1576,14 @@ pub fn selfExePath(allocator: &mem.Allocator) -> %[]u8 {
15761576 return out_path.toOwnedSlice();
15771577 }
15781578 const new_len = (out_path.len() << 1) | 0b1;
1579 %return out_path.resize(new_len);
1579 try out_path.resize(new_len);
15801580 }
15811581 },
15821582 Os.macosx, Os.ios => {
15831583 var u32_len: u32 = 0;
15841584 const ret1 = c._NSGetExecutablePath(undefined, &u32_len);
15851585 assert(ret1 != 0);
1586 const bytes = %return allocator.alloc(u8, u32_len);
1586 const bytes = try allocator.alloc(u8, u32_len);
15871587 %defer allocator.free(bytes);
15881588 const ret2 = c._NSGetExecutablePath(bytes.ptr, &u32_len);
15891589 assert(ret2 == 0);
......@@ -1602,13 +1602,13 @@ pub fn selfExeDirPath(allocator: &mem.Allocator) -> %[]u8 {
16021602 // the file path looks something like `/a/b/c/exe (deleted)`
16031603 // This path cannot be opened, but it's valid for determining the directory
16041604 // the executable was in when it was run.
1605 const full_exe_path = %return readLink(allocator, "/proc/self/exe");
1605 const full_exe_path = try readLink(allocator, "/proc/self/exe");
16061606 %defer allocator.free(full_exe_path);
16071607 const dir = path.dirname(full_exe_path);
16081608 return allocator.shrink(u8, full_exe_path, dir.len);
16091609 },
16101610 Os.windows, Os.macosx, Os.ios => {
1611 const self_exe_path = %return selfExePath(allocator);
1611 const self_exe_path = try selfExePath(allocator);
16121612 %defer allocator.free(self_exe_path);
16131613 const dirname = os.path.dirname(self_exe_path);
16141614 return allocator.shrink(u8, self_exe_path, dirname.len);
std/os/path.zig+21-21
......@@ -412,13 +412,13 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) -> %[]u8
412412 if (have_abs_path) {
413413 switch (have_drive_kind) {
414414 WindowsPath.Kind.Drive => {
415 result = %return allocator.alloc(u8, max_size);
415 result = try allocator.alloc(u8, max_size);
416416
417417 mem.copy(u8, result, result_disk_designator);
418418 result_index += result_disk_designator.len;
419419 },
420420 WindowsPath.Kind.NetworkShare => {
421 result = %return allocator.alloc(u8, max_size);
421 result = try allocator.alloc(u8, max_size);
422422 var it = mem.split(paths[first_index], "/\\");
423423 const server_name = ??it.next();
424424 const other_name = ??it.next();
......@@ -438,10 +438,10 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) -> %[]u8
438438 },
439439 WindowsPath.Kind.None => {
440440 assert(is_windows); // resolveWindows called on non windows can't use getCwd
441 const cwd = %return os.getCwd(allocator);
441 const cwd = try os.getCwd(allocator);
442442 defer allocator.free(cwd);
443443 const parsed_cwd = windowsParsePath(cwd);
444 result = %return allocator.alloc(u8, max_size + parsed_cwd.disk_designator.len + 1);
444 result = try allocator.alloc(u8, max_size + parsed_cwd.disk_designator.len + 1);
445445 mem.copy(u8, result, parsed_cwd.disk_designator);
446446 result_index += parsed_cwd.disk_designator.len;
447447 result_disk_designator = result[0..parsed_cwd.disk_designator.len];
......@@ -454,10 +454,10 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) -> %[]u8
454454 } else {
455455 assert(is_windows); // resolveWindows called on non windows can't use getCwd
456456 // TODO call get cwd for the result_disk_designator instead of the global one
457 const cwd = %return os.getCwd(allocator);
457 const cwd = try os.getCwd(allocator);
458458 defer allocator.free(cwd);
459459
460 result = %return allocator.alloc(u8, max_size + cwd.len + 1);
460 result = try allocator.alloc(u8, max_size + cwd.len + 1);
461461
462462 mem.copy(u8, result, cwd);
463463 result_index += cwd.len;
......@@ -542,12 +542,12 @@ pub fn resolvePosix(allocator: &Allocator, paths: []const []const u8) -> %[]u8 {
542542 var result_index: usize = 0;
543543
544544 if (have_abs) {
545 result = %return allocator.alloc(u8, max_size);
545 result = try allocator.alloc(u8, max_size);
546546 } else {
547547 assert(!is_windows); // resolvePosix called on windows can't use getCwd
548 const cwd = %return os.getCwd(allocator);
548 const cwd = try os.getCwd(allocator);
549549 defer allocator.free(cwd);
550 result = %return allocator.alloc(u8, max_size + cwd.len + 1);
550 result = try allocator.alloc(u8, max_size + cwd.len + 1);
551551 mem.copy(u8, result, cwd);
552552 result_index += cwd.len;
553553 }
......@@ -899,11 +899,11 @@ pub fn relative(allocator: &Allocator, from: []const u8, to: []const u8) -> %[]u
899899}
900900
901901pub fn relativeWindows(allocator: &Allocator, from: []const u8, to: []const u8) -> %[]u8 {
902 const resolved_from = %return resolveWindows(allocator, [][]const u8{from});
902 const resolved_from = try resolveWindows(allocator, [][]const u8{from});
903903 defer allocator.free(resolved_from);
904904
905905 var clean_up_resolved_to = true;
906 const resolved_to = %return resolveWindows(allocator, [][]const u8{to});
906 const resolved_to = try resolveWindows(allocator, [][]const u8{to});
907907 defer if (clean_up_resolved_to) allocator.free(resolved_to);
908908
909909 const parsed_from = windowsParsePath(resolved_from);
......@@ -942,7 +942,7 @@ pub fn relativeWindows(allocator: &Allocator, from: []const u8, to: []const u8)
942942 up_count += 1;
943943 }
944944 const up_index_end = up_count * "..\\".len;
945 const result = %return allocator.alloc(u8, up_index_end + to_rest.len);
945 const result = try allocator.alloc(u8, up_index_end + to_rest.len);
946946 %defer allocator.free(result);
947947
948948 var result_index: usize = 0;
......@@ -972,10 +972,10 @@ pub fn relativeWindows(allocator: &Allocator, from: []const u8, to: []const u8)
972972}
973973
974974pub fn relativePosix(allocator: &Allocator, from: []const u8, to: []const u8) -> %[]u8 {
975 const resolved_from = %return resolvePosix(allocator, [][]const u8{from});
975 const resolved_from = try resolvePosix(allocator, [][]const u8{from});
976976 defer allocator.free(resolved_from);
977977
978 const resolved_to = %return resolvePosix(allocator, [][]const u8{to});
978 const resolved_to = try resolvePosix(allocator, [][]const u8{to});
979979 defer allocator.free(resolved_to);
980980
981981 var from_it = mem.split(resolved_from, "/");
......@@ -992,7 +992,7 @@ pub fn relativePosix(allocator: &Allocator, from: []const u8, to: []const u8) ->
992992 up_count += 1;
993993 }
994994 const up_index_end = up_count * "../".len;
995 const result = %return allocator.alloc(u8, up_index_end + to_rest.len);
995 const result = try allocator.alloc(u8, up_index_end + to_rest.len);
996996 %defer allocator.free(result);
997997
998998 var result_index: usize = 0;
......@@ -1080,7 +1080,7 @@ error InputOutput;
10801080pub fn real(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
10811081 switch (builtin.os) {
10821082 Os.windows => {
1083 const pathname_buf = %return allocator.alloc(u8, pathname.len + 1);
1083 const pathname_buf = try allocator.alloc(u8, pathname.len + 1);
10841084 defer allocator.free(pathname_buf);
10851085
10861086 mem.copy(u8, pathname_buf, pathname);
......@@ -1099,7 +1099,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
10991099 };
11001100 }
11011101 defer os.close(h_file);
1102 var buf = %return allocator.alloc(u8, 256);
1102 var buf = try allocator.alloc(u8, 256);
11031103 %defer allocator.free(buf);
11041104 while (true) {
11051105 const buf_len = math.cast(windows.DWORD, buf.len) %% return error.NameTooLong;
......@@ -1116,7 +1116,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
11161116 }
11171117
11181118 if (result > buf.len) {
1119 buf = %return allocator.realloc(u8, buf, result);
1119 buf = try allocator.realloc(u8, buf, result);
11201120 continue;
11211121 }
11221122
......@@ -1140,10 +1140,10 @@ pub fn real(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
11401140 Os.macosx, Os.ios => {
11411141 // TODO instead of calling the libc function here, port the implementation
11421142 // to Zig, and then remove the NameTooLong error possibility.
1143 const pathname_buf = %return allocator.alloc(u8, pathname.len + 1);
1143 const pathname_buf = try allocator.alloc(u8, pathname.len + 1);
11441144 defer allocator.free(pathname_buf);
11451145
1146 const result_buf = %return allocator.alloc(u8, posix.PATH_MAX);
1146 const result_buf = try allocator.alloc(u8, posix.PATH_MAX);
11471147 %defer allocator.free(result_buf);
11481148
11491149 mem.copy(u8, pathname_buf, pathname);
......@@ -1168,7 +1168,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
11681168 return allocator.shrink(u8, result_buf, cstr.len(result_buf.ptr));
11691169 },
11701170 Os.linux => {
1171 const fd = %return os.posixOpen(pathname, posix.O_PATH|posix.O_NONBLOCK|posix.O_CLOEXEC, 0, allocator);
1171 const fd = try os.posixOpen(pathname, posix.O_PATH|posix.O_NONBLOCK|posix.O_CLOEXEC, 0, allocator);
11721172 defer os.close(fd);
11731173
11741174 var buf: ["/proc/self/fd/-2147483648".len]u8 = undefined;
std/os/windows/util.zig+3-3
......@@ -93,7 +93,7 @@ pub fn windowsOpen(file_path: []const u8, desired_access: windows.DWORD, share_m
9393 if (file_path.len < stack_buf.len) {
9494 path0 = stack_buf[0..file_path.len + 1];
9595 } else if (allocator) |a| {
96 path0 = %return a.alloc(u8, file_path.len + 1);
96 path0 = try a.alloc(u8, file_path.len + 1);
9797 need_free = true;
9898 } else {
9999 return error.NameTooLong;
......@@ -132,7 +132,7 @@ pub fn createWindowsEnvBlock(allocator: &mem.Allocator, env_map: &const BufMap)
132132 }
133133 break :x bytes_needed;
134134 };
135 const result = %return allocator.alloc(u8, bytes_needed);
135 const result = try allocator.alloc(u8, bytes_needed);
136136 %defer allocator.free(result);
137137
138138 var it = env_map.iterator();
......@@ -153,7 +153,7 @@ pub fn createWindowsEnvBlock(allocator: &mem.Allocator, env_map: &const BufMap)
153153
154154error DllNotFound;
155155pub fn windowsLoadDll(allocator: &mem.Allocator, dll_path: []const u8) -> %windows.HMODULE {
156 const padded_buff = %return cstr.addNullByte(allocator, dll_path);
156 const padded_buff = try cstr.addNullByte(allocator, dll_path);
157157 defer allocator.free(padded_buff);
158158 return windows.LoadLibraryA(padded_buff.ptr) ?? error.DllNotFound;
159159}
std/special/build_runner.zig+22-22
......@@ -23,15 +23,15 @@ pub fn main() -> %void {
2323 // skip my own exe name
2424 _ = arg_it.skip();
2525
26 const zig_exe = %return unwrapArg(arg_it.next(allocator) ?? {
26 const zig_exe = try unwrapArg(arg_it.next(allocator) ?? {
2727 warn("Expected first argument to be path to zig compiler\n");
2828 return error.InvalidArgs;
2929 });
30 const build_root = %return unwrapArg(arg_it.next(allocator) ?? {
30 const build_root = try unwrapArg(arg_it.next(allocator) ?? {
3131 warn("Expected second argument to be build root directory path\n");
3232 return error.InvalidArgs;
3333 });
34 const cache_root = %return unwrapArg(arg_it.next(allocator) ?? {
34 const cache_root = try unwrapArg(arg_it.next(allocator) ?? {
3535 warn("Expected third argument to be cache root directory path\n");
3636 return error.InvalidArgs;
3737 });
......@@ -58,36 +58,36 @@ pub fn main() -> %void {
5858 } else |err| err;
5959
6060 while (arg_it.next(allocator)) |err_or_arg| {
61 const arg = %return unwrapArg(err_or_arg);
61 const arg = try unwrapArg(err_or_arg);
6262 if (mem.startsWith(u8, arg, "-D")) {
6363 const option_contents = arg[2..];
6464 if (option_contents.len == 0) {
6565 warn("Expected option name after '-D'\n\n");
66 return usageAndErr(&builder, false, %return stderr_stream);
66 return usageAndErr(&builder, false, try stderr_stream);
6767 }
6868 if (mem.indexOfScalar(u8, option_contents, '=')) |name_end| {
6969 const option_name = option_contents[0..name_end];
7070 const option_value = option_contents[name_end + 1..];
7171 if (builder.addUserInputOption(option_name, option_value))
72 return usageAndErr(&builder, false, %return stderr_stream);
72 return usageAndErr(&builder, false, try stderr_stream);
7373 } else {
7474 if (builder.addUserInputFlag(option_contents))
75 return usageAndErr(&builder, false, %return stderr_stream);
75 return usageAndErr(&builder, false, try stderr_stream);
7676 }
7777 } else if (mem.startsWith(u8, arg, "-")) {
7878 if (mem.eql(u8, arg, "--verbose")) {
7979 builder.verbose = true;
8080 } else if (mem.eql(u8, arg, "--help")) {
81 return usage(&builder, false, %return stdout_stream);
81 return usage(&builder, false, try stdout_stream);
8282 } else if (mem.eql(u8, arg, "--prefix")) {
83 prefix = %return unwrapArg(arg_it.next(allocator) ?? {
83 prefix = try unwrapArg(arg_it.next(allocator) ?? {
8484 warn("Expected argument after --prefix\n\n");
85 return usageAndErr(&builder, false, %return stderr_stream);
85 return usageAndErr(&builder, false, try stderr_stream);
8686 });
8787 } else if (mem.eql(u8, arg, "--search-prefix")) {
88 const search_prefix = %return unwrapArg(arg_it.next(allocator) ?? {
88 const search_prefix = try unwrapArg(arg_it.next(allocator) ?? {
8989 warn("Expected argument after --search-prefix\n\n");
90 return usageAndErr(&builder, false, %return stderr_stream);
90 return usageAndErr(&builder, false, try stderr_stream);
9191 });
9292 builder.addSearchPrefix(search_prefix);
9393 } else if (mem.eql(u8, arg, "--verbose-tokenize")) {
......@@ -104,7 +104,7 @@ pub fn main() -> %void {
104104 builder.verbose_cimport = true;
105105 } else {
106106 warn("Unrecognized argument: {}\n\n", arg);
107 return usageAndErr(&builder, false, %return stderr_stream);
107 return usageAndErr(&builder, false, try stderr_stream);
108108 }
109109 } else {
110110 %%targets.append(arg);
......@@ -115,11 +115,11 @@ pub fn main() -> %void {
115115 root.build(&builder);
116116
117117 if (builder.validateUserInputDidItFail())
118 return usageAndErr(&builder, true, %return stderr_stream);
118 return usageAndErr(&builder, true, try stderr_stream);
119119
120120 builder.make(targets.toSliceConst()) %% |err| {
121121 if (err == error.InvalidStepName) {
122 return usageAndErr(&builder, true, %return stderr_stream);
122 return usageAndErr(&builder, true, try stderr_stream);
123123 }
124124 return err;
125125 };
......@@ -133,7 +133,7 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: &io.OutStream)
133133 }
134134
135135 // This usage text has to be synchronized with src/main.cpp
136 %return out_stream.print(
136 try out_stream.print(
137137 \\Usage: {} build [steps] [options]
138138 \\
139139 \\Steps:
......@@ -142,10 +142,10 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: &io.OutStream)
142142
143143 const allocator = builder.allocator;
144144 for (builder.top_level_steps.toSliceConst()) |top_level_step| {
145 %return out_stream.print(" {s22} {}\n", top_level_step.step.name, top_level_step.description);
145 try out_stream.print(" {s22} {}\n", top_level_step.step.name, top_level_step.description);
146146 }
147147
148 %return out_stream.write(
148 try out_stream.write(
149149 \\
150150 \\General Options:
151151 \\ --help Print this help and exit
......@@ -158,17 +158,17 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: &io.OutStream)
158158 );
159159
160160 if (builder.available_options_list.len == 0) {
161 %return out_stream.print(" (none)\n");
161 try out_stream.print(" (none)\n");
162162 } else {
163163 for (builder.available_options_list.toSliceConst()) |option| {
164 const name = %return fmt.allocPrint(allocator,
164 const name = try fmt.allocPrint(allocator,
165165 " -D{}=[{}]", option.name, Builder.typeIdName(option.type_id));
166166 defer allocator.free(name);
167 %return out_stream.print("{s24} {}\n", name, option.description);
167 try out_stream.print("{s24} {}\n", name, option.description);
168168 }
169169 }
170170
171 %return out_stream.write(
171 try out_stream.write(
172172 \\
173173 \\Advanced Options:
174174 \\ --build-file [file] Override path to build.zig
std/unicode.zig+1-1
......@@ -162,7 +162,7 @@ fn testValid(bytes: []const u8, expected_codepoint: u32) {
162162}
163163
164164fn testDecode(bytes: []const u8) -> %u32 {
165 const length = %return utf8ByteSequenceLength(bytes[0]);
165 const length = try utf8ByteSequenceLength(bytes[0]);
166166 if (bytes.len < length) return error.UnexpectedEof;
167167 std.debug.assert(bytes.len == length);
168168 return utf8Decode(bytes);
test/cases/error.zig+2-2
......@@ -2,7 +2,7 @@ const assert = @import("std").debug.assert;
22const mem = @import("std").mem;
33
44pub fn foo() -> %i32 {
5 const x = %return bar();
5 const x = try bar();
66 return x + 1;
77}
88
......@@ -77,7 +77,7 @@ test "error return in assignment" {
7777
7878fn doErrReturnInAssignment() -> %void {
7979 var x : i32 = undefined;
80 x = %return makeANonErr();
80 x = try makeANonErr();
8181}
8282
8383fn makeANonErr() -> %i32 {
test/cases/ir_block_deps.zig+2-2
......@@ -4,8 +4,8 @@ fn foo(id: u64) -> %i32 {
44 return switch (id) {
55 1 => getErrInt(),
66 2 => {
7 const size = %return getErrInt();
8 return %return getErrInt();
7 const size = try getErrInt();
8 return try getErrInt();
99 },
1010 else => error.ItBroke,
1111 };
test/cases/switch_prong_err_enum.zig+1-1
......@@ -16,7 +16,7 @@ const FormValue = union(enum) {
1616
1717fn doThing(form_id: u64) -> %FormValue {
1818 return switch (form_id) {
19 17 => FormValue { .Address = %return readOnce() },
19 17 => FormValue { .Address = try readOnce() },
2020 else => error.InvalidDebugInfo,
2121 };
2222}
test/compare_output.zig+8-8
......@@ -402,7 +402,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
402402 \\ %%stdout.print("before\n");
403403 \\ defer %%stdout.print("defer1\n");
404404 \\ %defer %%stdout.print("deferErr\n");
405 \\ %return its_gonna_fail();
405 \\ try its_gonna_fail();
406406 \\ defer %%stdout.print("defer3\n");
407407 \\ %%stdout.print("after\n");
408408 \\}
......@@ -422,7 +422,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
422422 \\ %%stdout.print("before\n");
423423 \\ defer %%stdout.print("defer1\n");
424424 \\ %defer %%stdout.print("deferErr\n");
425 \\ %return its_gonna_pass();
425 \\ try its_gonna_pass();
426426 \\ defer %%stdout.print("defer3\n");
427427 \\ %%stdout.print("after\n");
428428 \\}
......@@ -454,14 +454,14 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
454454 \\
455455 \\pub fn main() -> %void {
456456 \\ var args_it = os.args();
457 \\ var stdout_file = %return io.getStdOut();
457 \\ var stdout_file = try io.getStdOut();
458458 \\ var stdout_adapter = io.FileOutStream.init(&stdout_file);
459459 \\ const stdout = &stdout_adapter.stream;
460460 \\ var index: usize = 0;
461461 \\ _ = args_it.skip();
462462 \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) {
463 \\ const arg = %return arg_or_err;
464 \\ %return stdout.print("{}: {}\n", index, arg);
463 \\ const arg = try arg_or_err;
464 \\ try stdout.print("{}: {}\n", index, arg);
465465 \\ }
466466 \\}
467467 ,
......@@ -495,14 +495,14 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
495495 \\
496496 \\pub fn main() -> %void {
497497 \\ var args_it = os.args();
498 \\ var stdout_file = %return io.getStdOut();
498 \\ var stdout_file = try io.getStdOut();
499499 \\ var stdout_adapter = io.FileOutStream.init(&stdout_file);
500500 \\ const stdout = &stdout_adapter.stream;
501501 \\ var index: usize = 0;
502502 \\ _ = args_it.skip();
503503 \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) {
504 \\ const arg = %return arg_or_err;
505 \\ %return stdout.print("{}: {}\n", index, arg);
504 \\ const arg = try arg_or_err;
505 \\ try stdout.print("{}: {}\n", index, arg);
506506 \\ }
507507 \\}
508508 ,
test/compile_errors.zig+3-3
......@@ -1051,9 +1051,9 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
10511051 \\export fn entry() -> usize { return @sizeOf(@typeOf(f)); }
10521052 , ".tmp_source.zig:3:26: error: expected signed integer type, found 'u32'");
10531053
1054 cases.add("%return in function with non error return type",
1054 cases.add("try in function with non error return type",
10551055 \\export fn f() {
1056 \\ %return something();
1056 \\ try something();
10571057 \\}
10581058 \\fn something() -> %void { }
10591059 ,
......@@ -1290,7 +1290,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
12901290 \\pub fn testTrickyDefer() -> %void {
12911291 \\ defer canFail() %% {};
12921292 \\
1293 \\ defer %return canFail();
1293 \\ defer try canFail();
12941294 \\
12951295 \\ const a = maybeInt() ?? return;
12961296 \\}