authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-01-08 10:34:45-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-01-08 10:34:45-05:00
log5a8d87f5042b5ab86de7c72df4ce84a314878e40
treed9a8e14011994c5ebdf4525ea5c5b647aae91a6e
parent38658a597bc22697c2038c21bdec9f04c9973eb8
parent598170756cd91b6f300921d256baa72141ec3098

Merge branch 'master' into llvm6


64 files changed, 1564 insertions(+), 1165 deletions(-)

CMakeLists.txt+1
......@@ -440,6 +440,7 @@ set(ZIG_STD_FILES
440440 "os/windows/error.zig"
441441 "os/windows/index.zig"
442442 "os/windows/util.zig"
443 "os/zen.zig"
443444 "rand.zig"
444445 "sort.zig"
445446 "special/bootstrap.zig"
doc/docgen.zig+1-1
......@@ -45,7 +45,7 @@ const State = enum {
4545fn gen(in: &io.InStream, out: &io.OutStream) {
4646 var state = State.Start;
4747 while (true) {
48 const byte = in.readByte() %% |err| {
48 const byte = in.readByte() catch |err| {
4949 if (err == error.EndOfStream) {
5050 return;
5151 }
doc/home.html.in+18-18
......@@ -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;
......@@ -142,7 +142,7 @@ pub fn addOverflow(comptime T: type, a: T, b: T) -&gt; %T {
142142}
143143
144144fn getNumberWithDefault(s: []u8) -&gt; u32 {
145 parseUnsigned(u32, s, 10) %% 42
145 parseUnsigned(u32, s, 10) catch 42
146146}
147147
148148fn getNumberOrCrash(s: []u8) -&gt; u32 {
......@@ -150,8 +150,8 @@ fn getNumberOrCrash(s: []u8) -&gt; u32 {
150150}
151151
152152fn addTwoTogetherOrReturnErr(a_str: []u8, b_str: []u8) -&gt; %u32 {
153 const a = parseUnsigned(u32, a_str, 10) %% |err| return err;
154 const b = parseUnsigned(u32, b_str, 10) %% |err| return err;
153 const a = parseUnsigned(u32, a_str, 10) catch |err| return err;
154 const b = parseUnsigned(u32, b_str, 10) catch |err| return err;
155155 return a + b;
156156}</code></pre>
157157 <h3 id="hashmap">HashMap with Custom Allocator</h3>
......@@ -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,24 +420,24 @@ 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 {
427 var is = io.InStream.open(arg, null) %% |err| {
427 var is = io.InStream.open(arg, null) catch |err| {
428428 %%io.stderr.printf("Unable to open file: {}\n", @errorName(err));
429429 return err;
430430 };
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 {
......@@ -449,7 +449,7 @@ fn cat_stream(is: &amp;io.InStream) -&gt; %void {
449449 var buf: [1024 * 4]u8 = undefined;
450450
451451 while (true) {
452 const bytes_read = is.read(buf[0..]) %% |err| {
452 const bytes_read = is.read(buf[0..]) catch |err| {
453453 %%io.stderr.printf("Unable to read from stream: {}\n", @errorName(err));
454454 return err;
455455 };
......@@ -458,7 +458,7 @@ fn cat_stream(is: &amp;io.InStream) -&gt; %void {
458458 break;
459459 }
460460
461 io.stdout.write(buf[0..bytes_read]) %% |err| {
461 io.stdout.write(buf[0..bytes_read]) catch |err| {
462462 %%io.stderr.printf("Unable to write to stdout: {}\n", @errorName(err));
463463 return err;
464464 };
doc/langref.html.in+40-39
......@@ -264,15 +264,14 @@
264264 please <a href="https://github.com/zig-lang/www.ziglang.org/issues/new?title=I%20searched%20for%20___%20in%20the%20docs%20and%20didn%27t%20find%20it">file an issue</a> or <a href="https://webchat.freenode.net/?channels=%23zig">say something on IRC</a>.
265265 </p>
266266 <h2 id="hello-world">Hello World</h2>
267 <pre><code class="zig">const io = @import("std").io;
267 <pre><code class="zig">const std = @import("std");
268268
269269pub fn main() -&gt; %void {
270270 // If this program is run without stdout attached, exit with an error.
271 var stdout_file = %return io.getStdOut();
272 const stdout = &amp;stdout_file.out_stream;
271 var stdout_file = try std.io.getStdOut();
273272 // If this program encounters pipe failure when printing to stdout, exit
274273 // with an error.
275 %return stdout.print("Hello, world!\n");
274 try stdout_file.write("Hello, world!\n");
276275}</code></pre>
277276 <pre><code class="sh">$ zig build-exe hello.zig
278277$ ./hello
......@@ -1212,8 +1211,8 @@ unwrapped == 1234</code></pre>
12121211 </td>
12131212 </tr>
12141213 <tr>
1215 <td><pre><code class="zig">a %% b
1216a %% |err| b</code></pre></td>
1214 <td><pre><code class="zig">a catch b
1215a catch |err| b</code></pre></td>
12171216 <td>
12181217 <ul>
12191218 <li><a href="#errors">Error Unions</a></li>
......@@ -1227,7 +1226,7 @@ a %% |err| b</code></pre></td>
12271226 </td>
12281227 <td>
12291228 <pre><code class="zig">const value: %u32 = null;
1230const unwrapped = value %% 1234;
1229const unwrapped = value catch 1234;
12311230unwrapped == 1234</code></pre>
12321231 </td>
12331232 </tr>
......@@ -1239,7 +1238,7 @@ unwrapped == 1234</code></pre>
12391238 </ul>
12401239 </td>
12411240 <td>Equivalent to:
1242 <pre><code class="zig">a %% unreachable</code></pre>
1241 <pre><code class="zig">a catch unreachable</code></pre>
12431242 </td>
12441243 <td>
12451244 <pre><code class="zig">const value: %u32 = 5678;
......@@ -1483,7 +1482,7 @@ x{}
14831482== != &lt; &gt; &lt;= &gt;=
14841483and
14851484or
1486?? %%
1485?? catch
14871486= *= /= %= += -= &lt;&lt;= &gt;&gt;= &amp;= ^= |=</code></pre>
14881487 <h2 id="arrays">Arrays</h2>
14891488 <pre><code class="zig">const assert = @import("std").debug.assert;
......@@ -1830,7 +1829,7 @@ Test 1/1 pointer alignment safety...incorrect alignment
18301829 return root.main();
18311830 ^
18321831/home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:47:13: 0x0000000000216050 in ??? (test)
1833 callMain(argc, argv, envp) %% std.os.posix.exit(1);
1832 callMain(argc, argv, envp) catch std.os.posix.exit(1);
18341833 ^
18351834/home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:34:25: 0x0000000000215fa0 in ??? (test)
18361835 posixCallMainAndExit()
......@@ -1886,7 +1885,7 @@ lib/zig/std/special/bootstrap.zig:60:21: 0x00000000002149e7 in ??? (test)
18861885 return root.main();
18871886 ^
18881887lib/zig/std/special/bootstrap.zig:47:13: 0x00000000002148a0 in ??? (test)
1889 callMain(argc, argv, envp) %% std.os.posix.exit(1);
1888 callMain(argc, argv, envp) catch std.os.posix.exit(1);
18901889 ^
18911890lib/zig/std/special/bootstrap.zig:34:25: 0x00000000002147f0 in ??? (test)
18921891 posixCallMainAndExit()
......@@ -2966,7 +2965,7 @@ lib/zig/std/special/bootstrap.zig:60:21: 0x0000000000214947 in ??? (test)
29662965 return root.main();
29672966 ^
29682967lib/zig/std/special/bootstrap.zig:47:13: 0x0000000000214800 in ??? (test)
2969 callMain(argc, argv, envp) %% std.os.posix.exit(1);
2968 callMain(argc, argv, envp) catch std.os.posix.exit(1);
29702969 ^
29712970lib/zig/std/special/bootstrap.zig:34:25: 0x0000000000214750 in ??? (test)
29722971 posixCallMainAndExit()
......@@ -3020,7 +3019,7 @@ extern fn bar(value: u32);</code></pre>
30203019 <pre><code class="zig">pub extern "kernel32" stdcallcc fn ExitProcess(exit_code: c_uint) -&gt; noreturn;
30213020
30223021fn foo() {
3023 const value = bar() %% ExitProcess(1);
3022 const value = bar() catch ExitProcess(1);
30243023 assert(value == 1234);
30253024}
30263025
......@@ -3210,7 +3209,7 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
32103209 </ul>
32113210 <p>If you want to provide a default value, you can use the <code>%%</code> binary operator:</p>
32123211 <pre><code class="zig">fn doAThing(str: []u8) {
3213 const number = parseU64(str, 10) %% 13;
3212 const number = parseU64(str, 10) catch 13;
32143213 // ...
32153214}</code></pre>
32163215 <p>
......@@ -3221,18 +3220,18 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
32213220 <p>Let's say you wanted to return the error if you got one, otherwise continue with the
32223221 function logic:</p>
32233222 <pre><code class="zig">fn doAThing(str: []u8) -&gt; %void {
3224 const number = parseU64(str, 10) %% |err| return err;
3223 const number = parseU64(str, 10) catch |err| return err;
32253224 // ...
32263225}</code></pre>
32273226 <p>
3228 There is a shortcut for this. The <code>%return</code> expression:
3227 There is a shortcut for this. The <code>try</code> expression:
32293228 </p>
32303229 <pre><code class="zig">fn doAThing(str: []u8) -&gt; %void {
3231 const number = %return parseU64(str, 10);
3230 const number = try parseU64(str, 10);
32323231 // ...
32333232}</code></pre>
32343233 <p>
3235 <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
32363235 from the current function with the same error. Otherwise, the expression results in
32373236 the unwrapped value.
32383237 </p>
......@@ -3240,7 +3239,7 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
32403239 Maybe you know with complete certainty that an expression will never be an error.
32413240 In this case you can do this:
32423241 </p>
3243 <pre><code class="zig">const number = parseU64("1234", 10) %% unreachable;</code></pre>
3242 <pre><code class="zig">const number = parseU64("1234", 10) catch unreachable;</code></pre>
32443243 <p>
32453244 Here we know for sure that "1234" will parse successfully. So we put the
32463245 <code>unreachable</code> value on the right hand side. <code>unreachable</code> generates
......@@ -3251,7 +3250,7 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
32513250 <p>Again there is a syntactic shortcut for this:</p>
32523251 <pre><code class="zig">const number = %%parseU64("1234", 10);</code></pre>
32533252 <p>
3254 The <code>%%</code> <em>prefix</em> operator is equivalent to <code class="zig">expression %% unreachable</code>. It unwraps an error union type,
3253 The <code>%%</code> <em>prefix</em> operator is equivalent to <code class="zig">expression catch unreachable</code>. It unwraps an error union type,
32553254 and panics in debug mode if the value was an error.
32563255 </p>
32573256 <p>
......@@ -3279,7 +3278,7 @@ pub fn parseU64(buf: []const u8, radix: u8) -&gt; %u64 {
32793278 Example:
32803279 </p>
32813280 <pre><code class="zig">fn createFoo(param: i32) -&gt; %Foo {
3282 const foo = %return tryToAllocateFoo();
3281 const foo = try tryToAllocateFoo();
32833282 // now we have allocated foo. we need to free it if the function fails.
32843283 // but we want to return it if the function succeeds.
32853284 %defer deallocateFoo(foo);
......@@ -3929,11 +3928,11 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
39293928 switch (state) {
39303929 State.Start =&gt; switch (c) {
39313930 '{' =&gt; {
3932 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]);
39333932 state = State.OpenBrace;
39343933 },
39353934 '}' =&gt; {
3936 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]);
39373936 state = State.CloseBrace;
39383937 },
39393938 else =&gt; {},
......@@ -3944,7 +3943,7 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
39443943 start_index = i;
39453944 },
39463945 '}' =&gt; {
3947 %return self.printValue(args[next_arg]);
3946 try self.printValue(args[next_arg]);
39483947 next_arg += 1;
39493948 state = State.Start;
39503949 start_index = i + 1;
......@@ -3969,9 +3968,9 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
39693968 }
39703969 }
39713970 if (start_index &lt; format.len) {
3972 %return self.write(format[start_index...format.len]);
3971 try self.write(format[start_index...format.len]);
39733972 }
3974 %return self.flush();
3973 try self.flush();
39753974}</code></pre>
39763975 <p>
39773976 This is a proof of concept implementation; the actual function in the standard library has more
......@@ -3985,12 +3984,12 @@ pub fn printf(self: &amp;OutStream, comptime format: []const u8, args: ...) -&gt
39853984 and emits a function that actually looks like this:
39863985 </p>
39873986 <pre><code class="zig">pub fn printf(self: &amp;OutStream, arg0: i32, arg1: []const u8) -&gt; %void {
3988 %return self.write("here is a string: '");
3989 %return self.printValue(arg0);
3990 %return self.write("' here is a number: ");
3991 %return self.printValue(arg1);
3992 %return self.write("\n");
3993 %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();
39943993}</code></pre>
39953994 <p>
39963995 <code>printValue</code> is a function that takes a parameter of any type, and does different things depending
......@@ -4985,7 +4984,7 @@ Test 1/1 safety check...reached unreachable code
49854984 return root.main();
49864985 ^
49874986/home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:37:13: 0x00000000002148d0 in ??? (test)
4988 callMain(argc, argv, envp) %% exit(1);
4987 callMain(argc, argv, envp) catch exit(1);
49894988 ^
49904989/home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:30:20: 0x0000000000214820 in ??? (test)
49914990 callMainAndExit()
......@@ -5892,7 +5891,7 @@ TypeExpr = PrefixOpExpression | "var"
58925891
58935892BlockOrExpression = Block | Expression
58945893
5895Expression = ReturnExpression | BreakExpression | AssignmentExpression
5894Expression = TryExpression | ReturnExpression | BreakExpression | AssignmentExpression
58965895
58975896AsmExpression = "asm" option("volatile") "(" String option(AsmOutput) ")"
58985897
......@@ -5910,13 +5909,13 @@ UnwrapExpression = BoolOrExpression (UnwrapNullable | UnwrapError) | BoolOrExpre
59105909
59115910UnwrapNullable = "??" Expression
59125911
5913UnwrapError = "%%" option("|" Symbol "|") Expression
5912UnwrapError = "catch" option("|" Symbol "|") Expression
59145913
59155914AssignmentExpression = UnwrapExpression AssignmentOperator UnwrapExpression | UnwrapExpression
59165915
59175916AssignmentOperator = "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "&lt;&lt;=" | "&gt;&gt;=" | "&amp;=" | "^=" | "|=" | "*%=" | "+%=" | "-%="
59185917
5919BlockExpression(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)
59205919
59215920CompTimeExpression(body) = "comptime" body
59225921
......@@ -5930,7 +5929,9 @@ ForExpression(body) = option(Symbol ":") option("inline") "for" "(" Expression "
59305929
59315930BoolOrExpression = BoolAndExpression "or" BoolOrExpression | BoolAndExpression
59325931
5933ReturnExpression = option("%") "return" option(Expression)
5932ReturnExpression = "return" option(Expression)
5933
5934TryExpression = "try" Expression
59345935
59355936BreakExpression = "break" option(":" Symbol) option(Expression)
59365937
......@@ -5938,7 +5939,7 @@ Defer(body) = option("%") "defer" body
59385939
59395940IfExpression(body) = "if" "(" Expression ")" body option("else" BlockExpression(body))
59405941
5941TryExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
5942IfErrorExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
59425943
59435944TestExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body option("else" BlockExpression(body))
59445945
......@@ -5988,7 +5989,7 @@ ContainerInitBody = list(StructLiteralField, ",") | list(Expression, ",")
59885989
59895990StructLiteralField = "." Symbol "=" Expression
59905991
5991PrefixOp = "!" | "-" | "~" | "*" | ("&amp;" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%"
5992PrefixOp = "!" | "-" | "~" | "*" | ("&amp;" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%" | "try"
59925993
59935994PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ("error" "." Symbol) | ContainerDecl | ("continue" option(":" Symbol))
59945995
example/cat/main.zig+12-12
......@@ -7,32 +7,32 @@ 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 {
23 var file = io.File.openRead(arg, null) %% |err| {
23 var file = io.File.openRead(arg, null) catch |err| {
2424 warn("Unable to open file: {}\n", @errorName(err));
2525 return err;
2626 };
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
......@@ -45,7 +45,7 @@ fn cat_file(stdout: &io.File, file: &io.File) -> %void {
4545 var buf: [1024 * 4]u8 = undefined;
4646
4747 while (true) {
48 const bytes_read = file.read(buf[0..]) %% |err| {
48 const bytes_read = file.read(buf[0..]) catch |err| {
4949 warn("Unable to read from stream: {}\n", @errorName(err));
5050 return err;
5151 };
......@@ -54,7 +54,7 @@ fn cat_file(stdout: &io.File, file: &io.File) -> %void {
5454 break;
5555 }
5656
57 stdout.write(buf[0..bytes_read]) %% |err| {
57 stdout.write(buf[0..bytes_read]) catch |err| {
5858 warn("Unable to write to stdout: {}\n", @errorName(err));
5959 return err;
6060 };
......@@ -62,7 +62,7 @@ fn cat_file(stdout: &io.File, file: &io.File) -> %void {
6262}
6363
6464fn unwrapArg(arg: %[]u8) -> %[]u8 {
65 return arg %% |err| {
65 return arg catch |err| {
6666 warn("Unable to parse command line: {}\n", err);
6767 return err;
6868 };
example/guess_number/main.zig+11-11
......@@ -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
28 const line_len = stdin_file.read(line_buf[0..]) %% |err| {
29 %return stdout.print("Unable to read from stdin: {}\n", @errorName(err));
28 const line_len = stdin_file.read(line_buf[0..]) catch |err| {
29 try stdout.print("Unable to read from stdin: {}\n", @errorName(err));
3030 return err;
3131 };
3232
33 const guess = fmt.parseUnsigned(u8, line_buf[0..line_len - 1], 10) %% {
34 %return stdout.print("Invalid number.\n");
33 const guess = fmt.parseUnsigned(u8, line_buf[0..line_len - 1], 10) catch {
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+42-42
......@@ -21,7 +21,7 @@ error ZigInstallationNotFound;
2121const default_zig_cache_name = "zig-cache";
2222
2323pub fn main() -> %void {
24 main2() %% |err| {
24 main2() catch |err| {
2525 if (err != error.InvalidCommandLineArguments) {
2626 warn("{}\n", @errorName(err));
2727 }
......@@ -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.
......@@ -571,12 +571,12 @@ fn printZen() -> %void {
571571/// Caller must free result
572572fn resolveZigLibDir(allocator: &mem.Allocator, zig_install_prefix_arg: ?[]const u8) -> %[]u8 {
573573 if (zig_install_prefix_arg) |zig_install_prefix| {
574 return testZigInstallPrefix(allocator, zig_install_prefix) %% |err| {
574 return testZigInstallPrefix(allocator, zig_install_prefix) catch |err| {
575575 warn("No Zig installation found at prefix {}: {}\n", zig_install_prefix_arg, @errorName(err));
576576 return error.ZigInstallationNotFound;
577577 };
578578 } else {
579 return findZigLibDir(allocator) %% |err| {
579 return findZigLibDir(allocator) catch |err| {
580580 warn("Unable to find zig lib directory: {}.\nReinstall Zig or use --zig-install-prefix.\n",
581581 @errorName(err));
582582 return error.ZigLibDirNotFound;
......@@ -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;
......@@ -611,7 +611,7 @@ fn findZigLibDir(allocator: &mem.Allocator) -> %[]u8 {
611611 break;
612612 }
613613
614 return testZigInstallPrefix(allocator, test_dir) %% |err| {
614 return testZigInstallPrefix(allocator, test_dir) catch |err| {
615615 cur_path = test_dir;
616616 continue;
617617 };
src-self-hosted/module.zig+15-15
......@@ -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,21 +200,21 @@ 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);
207207 }
208208
209209 const root_src_path = self.root_src_path ?? @panic("TODO handle null root src path");
210 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);
210 const root_src_real_path = os.path.real(self.allocator, root_src_path) catch |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
216 const source_code = io.readFileAllocExtra(root_src_real_path, self.allocator, 3) %% |err| {
217 %return printError("unable to open '{}': {}", root_src_real_path, err);
216 const source_code = io.readFileAllocExtra(root_src_real_path, self.allocator, 3) catch |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+175-175
......@@ -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 };
......@@ -96,12 +96,12 @@ pub const Parser = struct {
9696 var stack = self.initUtilityArrayList(&ast.Node);
9797 defer self.deinitUtilityArrayList(stack);
9898
99 stack.append(&root_node.base) %% unreachable;
99 stack.append(&root_node.base) catch unreachable;
100100 while (stack.popOrNull()) |node| {
101101 var i: usize = 0;
102102 while (node.iterate(i)) |child| : (i += 1) {
103103 if (child.iterate(0) != null) {
104 stack.append(child) %% unreachable;
104 stack.append(child) catch unreachable;
105105 } else {
106106 child.destroy(self.allocator);
107107 }
......@@ -111,7 +111,7 @@ pub const Parser = struct {
111111 }
112112
113113 pub fn parse(self: &Parser) -> %&ast.NodeRoot {
114 const result = self.parseInner() %% |err| x: {
114 const result = self.parseInner() catch |err| x: {
115115 if (self.cleanup_root_node) |root_node| {
116116 self.freeAst(root_node);
117117 }
......@@ -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);
......@@ -156,14 +156,14 @@ pub const Parser = struct {
156156 const token = self.getNextToken();
157157 switch (token.id) {
158158 Token.Id.Keyword_pub, Token.Id.Keyword_export => {
159 stack.append(State { .TopLevelExtern = token }) %% unreachable;
159 stack.append(State { .TopLevelExtern = token }) catch unreachable;
160160 continue;
161161 },
162162 Token.Id.Eof => return root_node,
163163 else => {
164164 self.putBackToken(token);
165165 // TODO shouldn't need this cast
166 stack.append(State { .TopLevelExtern = null }) %% unreachable;
166 stack.append(State { .TopLevelExtern = null }) catch unreachable;
167167 continue;
168168 },
169169 }
......@@ -176,7 +176,7 @@ pub const Parser = struct {
176176 .visib_token = visib_token,
177177 .extern_token = token,
178178 },
179 }) %% unreachable;
179 }) catch unreachable;
180180 continue;
181181 }
182182 self.putBackToken(token);
......@@ -185,52 +185,52 @@ pub const Parser = struct {
185185 .visib_token = visib_token,
186186 .extern_token = null,
187187 },
188 }) %% unreachable;
188 }) catch unreachable;
189189 continue;
190190 },
191191 State.TopLevelDecl => |ctx| {
192192 const token = self.getNextToken();
193193 switch (token.id) {
194194 Token.Id.Keyword_var, Token.Id.Keyword_const => {
195 stack.append(State.TopLevel) %% unreachable;
195 stack.append(State.TopLevel) catch 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 => {
203 stack.append(State.TopLevel) %% unreachable;
203 stack.append(State.TopLevel) catch 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 => {
212212 @panic("TODO extern with string literal");
213213 },
214214 Token.Id.Keyword_coldcc, Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => {
215 stack.append(State.TopLevel) %% unreachable;
216 const fn_token = %return self.eatToken(Token.Id.Keyword_fn);
215 stack.append(State.TopLevel) catch unreachable;
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);
229 stack.append(State { .VarDeclAlign = var_decl }) %% unreachable;
228 var_decl.name_token = try self.eatToken(Token.Id.Identifier);
229 stack.append(State { .VarDeclAlign = var_decl }) catch 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
......@@ -238,13 +238,13 @@ pub const Parser = struct {
238238 continue;
239239 },
240240 State.VarDeclAlign => |var_decl| {
241 stack.append(State { .VarDeclEq = var_decl }) %% unreachable;
241 stack.append(State { .VarDeclEq = var_decl }) catch unreachable;
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
......@@ -255,8 +255,8 @@ pub const Parser = struct {
255255 const token = self.getNextToken();
256256 if (token.id == Token.Id.Equal) {
257257 var_decl.eq_token = token;
258 stack.append(State { .ExpectToken = Token.Id.Semicolon }) %% unreachable;
259 %return stack.append(State {
258 stack.append(State { .ExpectToken = Token.Id.Semicolon }) catch unreachable;
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
276 stack.append(state) %% unreachable;
277 %return stack.append(State.ExpectOperand);
276 stack.append(state) catch unreachable;
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| {
......@@ -383,21 +383,21 @@ pub const Parser = struct {
383383 var token = self.getNextToken();
384384 switch (token.id) {
385385 Token.Id.Keyword_align => {
386 stack.append(state) %% unreachable;
386 stack.append(state) catch 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 => {
394 stack.append(state) %% unreachable;
394 stack.append(state) catch unreachable;
395395 if (addr_of_info.const_token != null) return self.parseError(token, "duplicate qualifier: const");
396396 addr_of_info.const_token = token;
397397 continue;
398398 },
399399 Token.Id.Keyword_volatile => {
400 stack.append(state) %% unreachable;
400 stack.append(state) catch unreachable;
401401 if (addr_of_info.volatile_token != null) return self.parseError(token, "duplicate qualifier: volatile");
402402 addr_of_info.volatile_token = token;
403403 continue;
......@@ -416,14 +416,14 @@ pub const Parser = struct {
416416 }
417417 self.putBackToken(token);
418418
419 stack.append(State { .Expression = dest_ptr }) %% unreachable;
419 stack.append(State { .Expression = dest_ptr }) catch unreachable;
420420 continue;
421421 },
422422
423423 State.FnProto => |fn_proto| {
424 stack.append(State { .FnProtoAlign = fn_proto }) %% unreachable;
425 %return stack.append(State { .ParamDecl = fn_proto });
426 %return stack.append(State { .ExpectToken = Token.Id.LParen });
424 stack.append(State { .FnProtoAlign = fn_proto }) catch unreachable;
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) {
......@@ -442,7 +442,7 @@ pub const Parser = struct {
442442 if (token.id == Token.Id.Arrow) {
443443 stack.append(State {
444444 .TypeExpr = DestPtr {.NullableField = &fn_proto.return_type},
445 }) %% unreachable;
445 }) catch unreachable;
446446 continue;
447447 } else {
448448 self.putBackToken(token);
......@@ -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();
......@@ -474,15 +474,15 @@ pub const Parser = struct {
474474 }
475475 if (token.id == Token.Id.Ellipsis3) {
476476 param_decl.var_args_token = token;
477 stack.append(State { .ExpectToken = Token.Id.RParen }) %% unreachable;
477 stack.append(State { .ExpectToken = Token.Id.RParen }) catch unreachable;
478478 continue;
479479 } else {
480480 self.putBackToken(token);
481481 }
482482
483 stack.append(State { .ParamDecl = fn_proto }) %% unreachable;
484 %return stack.append(State.ParamDeclComma);
485 %return stack.append(State {
483 stack.append(State { .ParamDecl = fn_proto }) catch unreachable;
484 try stack.append(State.ParamDeclComma);
485 try stack.append(State {
486486 .TypeExpr = DestPtr {.Field = &param_decl.type_node}
487487 });
488488 continue;
......@@ -504,9 +504,9 @@ 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;
509 stack.append(State { .Block = block }) %% unreachable;
509 stack.append(State { .Block = block }) catch unreachable;
510510 continue;
511511 },
512512 Token.Id.Semicolon => continue,
......@@ -523,8 +523,8 @@ pub const Parser = struct {
523523 },
524524 else => {
525525 self.putBackToken(token);
526 stack.append(State { .Block = block }) %% unreachable;
527 %return stack.append(State { .Statement = block });
526 stack.append(State { .Block = block }) catch unreachable;
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
563 stack.append(State { .ExpectToken = Token.Id.Semicolon }) %% unreachable;
564 %return stack.append(State { .Expression = DestPtr{.List = &block.statements} });
563 stack.append(State { .ExpectToken = Token.Id.Semicolon }) catch unreachable;
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
......@@ -1112,7 +1112,7 @@ fn testCanonical(source: []const u8) {
11121112 // Try it once with unlimited memory, make sure it works
11131113 var fixed_allocator = mem.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
11141114 var failing_allocator = std.debug.FailingAllocator.init(&fixed_allocator.allocator, @maxValue(usize));
1115 const result_source = testParse(source, &failing_allocator.allocator) %% @panic("test failed");
1115 const result_source = testParse(source, &failing_allocator.allocator) catch @panic("test failed");
11161116 if (!mem.eql(u8, result_source, source)) {
11171117 warn("\n====== expected this output: =========\n");
11181118 warn("{}", source);
src-self-hosted/target.zig+1-1
......@@ -38,7 +38,7 @@ pub const Target = union(enum) {
3838
3939 pub fn isDarwin(self: &const Target) -> bool {
4040 return switch (self.getOs()) {
41 builtin.Os.darwin, builtin.Os.ios, builtin.Os.macosx => true,
41 builtin.Os.ios, builtin.Os.macosx => true,
4242 else => false,
4343 };
4444 }
src-self-hosted/tokenizer.zig+4-4
......@@ -557,22 +557,22 @@ pub const Tokenizer = struct {
557557 return 0;
558558 } else {
559559 // check utf8-encoded character.
560 const length = std.unicode.utf8ByteSequenceLength(c0) %% return 1;
560 const length = std.unicode.utf8ByteSequenceLength(c0) catch return 1;
561561 // the last 3 bytes in the buffer are guaranteed to be '\n',
562562 // which means we don't need to do any bounds checking here.
563563 const bytes = self.buffer[self.index..self.index + length];
564564 switch (length) {
565565 2 => {
566 const value = std.unicode.utf8Decode2(bytes) %% return length;
566 const value = std.unicode.utf8Decode2(bytes) catch return length;
567567 if (value == 0x85) return length; // U+0085 (NEL)
568568 },
569569 3 => {
570 const value = std.unicode.utf8Decode3(bytes) %% return length;
570 const value = std.unicode.utf8Decode3(bytes) catch return length;
571571 if (value == 0x2028) return length; // U+2028 (LS)
572572 if (value == 0x2029) return length; // U+2029 (PS)
573573 },
574574 4 => {
575 _ = std.unicode.utf8Decode4(bytes) %% return length;
575 _ = std.unicode.utf8Decode4(bytes) catch return length;
576576 },
577577 else => unreachable,
578578 }
src/all_types.hpp+7-12
......@@ -37,13 +37,7 @@ struct ScopeDecls;
3737struct ZigWindowsSDK;
3838struct Tld;
3939struct TldExport;
40
41struct IrGotoItem {
42 AstNode *source_node;
43 IrBasicBlock *bb;
44 size_t instruction_index;
45 Scope *scope;
46};
40struct IrAnalyze;
4741
4842struct IrExecutable {
4943 ZigList<IrBasicBlock *> basic_block_list;
......@@ -53,13 +47,13 @@ struct IrExecutable {
5347 size_t *backward_branch_count;
5448 size_t backward_branch_quota;
5549 bool invalid;
56 ZigList<IrGotoItem> goto_list;
5750 bool is_inline;
5851 FnTableEntry *fn_entry;
5952 Buf *c_import_buf;
6053 AstNode *source_node;
6154 IrExecutable *parent_exec;
6255 IrExecutable *source_exec;
56 IrAnalyze *analysis;
6357 Scope *begin_scope;
6458 ZigList<Tld *> tld_list;
6559};
......@@ -395,7 +389,7 @@ enum NodeType {
395389 NodeTypeArrayType,
396390 NodeTypeErrorType,
397391 NodeTypeVarLiteral,
398 NodeTypeTryExpr,
392 NodeTypeIfErrorExpr,
399393 NodeTypeTestExpr,
400394};
401395
......@@ -552,7 +546,7 @@ struct AstNodeBinOpExpr {
552546 AstNode *op2;
553547};
554548
555struct AstNodeUnwrapErrorExpr {
549struct AstNodeCatchExpr {
556550 AstNode *op1;
557551 AstNode *symbol; // can be null
558552 AstNode *op2;
......@@ -866,7 +860,7 @@ struct AstNode {
866860 AstNodeErrorValueDecl error_value_decl;
867861 AstNodeTestDecl test_decl;
868862 AstNodeBinOpExpr bin_op_expr;
869 AstNodeUnwrapErrorExpr unwrap_err_expr;
863 AstNodeCatchExpr unwrap_err_expr;
870864 AstNodePrefixOpExpr prefix_op_expr;
871865 AstNodeAddrOfExpr addr_of_expr;
872866 AstNodeFnCallExpr fn_call_expr;
......@@ -874,7 +868,7 @@ struct AstNode {
874868 AstNodeSliceExpr slice_expr;
875869 AstNodeUse use;
876870 AstNodeIfBoolExpr if_bool_expr;
877 AstNodeTryExpr try_expr;
871 AstNodeTryExpr if_err_expr;
878872 AstNodeTestExpr test_expr;
879873 AstNodeWhileExpr while_expr;
880874 AstNodeForExpr for_expr;
......@@ -1626,6 +1620,7 @@ struct VariableTableEntry {
16261620 LLVMValueRef param_value_ref;
16271621 bool shadowable;
16281622 size_t mem_slot_index;
1623 IrExecutable *owner_exec;
16291624 size_t ref_count;
16301625 VarLinkage linkage;
16311626 IrInstruction *decl_instruction;
src/analyze.cpp+10-10
......@@ -32,7 +32,7 @@ ErrorMsg *add_node_error(CodeGen *g, AstNode *node, Buf *msg) {
3232 // failed semantic analysis, which isn't supposed to happen
3333 ErrorMsg *err = add_node_error(g, node->owner->c_import_node,
3434 buf_sprintf("compiler bug: @cImport generated invalid zig code"));
35
35
3636 add_error_note(g, err, node, msg);
3737
3838 g->errors.append(err);
......@@ -2425,7 +2425,7 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
24252425 qual_str = "extern";
24262426 break;
24272427 }
2428 AstNode *source_node = (decl_node->data.container_decl.init_arg_expr != nullptr) ?
2428 AstNode *source_node = (decl_node->data.container_decl.init_arg_expr != nullptr) ?
24292429 decl_node->data.container_decl.init_arg_expr : decl_node;
24302430 add_node_error(g, source_node,
24312431 buf_sprintf("%s union does not support enum tag type", qual_str));
......@@ -2599,17 +2599,17 @@ void add_fn_export(CodeGen *g, FnTableEntry *fn_table_entry, Buf *symbol_name, G
25992599 g->windows_subsystem_windows = false;
26002600 g->windows_subsystem_console = true;
26012601 } else if (buf_eql_str(symbol_name, "WinMain") &&
2602 g->zig_target.os == ZigLLVM_Win32)
2602 g->zig_target.os == OsWindows)
26032603 {
26042604 g->have_winmain = true;
26052605 g->windows_subsystem_windows = true;
26062606 g->windows_subsystem_console = false;
26072607 } else if (buf_eql_str(symbol_name, "WinMainCRTStartup") &&
2608 g->zig_target.os == ZigLLVM_Win32)
2608 g->zig_target.os == OsWindows)
26092609 {
26102610 g->have_winmain_crt_startup = true;
26112611 } else if (buf_eql_str(symbol_name, "DllMainCRTStartup") &&
2612 g->zig_target.os == ZigLLVM_Win32)
2612 g->zig_target.os == OsWindows)
26132613 {
26142614 g->have_dllmain_crt_startup = true;
26152615 }
......@@ -2933,7 +2933,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {
29332933 case NodeTypeArrayType:
29342934 case NodeTypeErrorType:
29352935 case NodeTypeVarLiteral:
2936 case NodeTypeTryExpr:
2936 case NodeTypeIfErrorExpr:
29372937 case NodeTypeTestExpr:
29382938 zig_unreachable();
29392939 }
......@@ -3994,7 +3994,7 @@ void find_libc_include_path(CodeGen *g) {
39943994 if (!g->libc_include_dir || buf_len(g->libc_include_dir) == 0) {
39953995 ZigWindowsSDK *sdk = get_windows_sdk(g);
39963996
3997 if (g->zig_target.os == ZigLLVM_Win32) {
3997 if (g->zig_target.os == OsWindows) {
39983998 if (os_get_win32_ucrt_include_path(sdk, g->libc_include_dir)) {
39993999 zig_panic("Unable to determine libc include path.");
40004000 }
......@@ -4010,9 +4010,9 @@ void find_libc_include_path(CodeGen *g) {
40104010void find_libc_lib_path(CodeGen *g) {
40114011 // later we can handle this better by reporting an error via the normal mechanism
40124012 if (!g->libc_lib_dir || buf_len(g->libc_lib_dir) == 0 ||
4013 (g->zig_target.os == ZigLLVM_Win32 && (g->msvc_lib_dir == nullptr || g->kernel32_lib_dir == nullptr)))
4013 (g->zig_target.os == OsWindows && (g->msvc_lib_dir == nullptr || g->kernel32_lib_dir == nullptr)))
40144014 {
4015 if (g->zig_target.os == ZigLLVM_Win32) {
4015 if (g->zig_target.os == OsWindows) {
40164016 ZigWindowsSDK *sdk = get_windows_sdk(g);
40174017
40184018 Buf* vc_lib_dir = buf_alloc();
......@@ -4039,7 +4039,7 @@ void find_libc_lib_path(CodeGen *g) {
40394039 }
40404040
40414041 if (!g->libc_static_lib_dir || buf_len(g->libc_static_lib_dir) == 0) {
4042 if ((g->zig_target.os == ZigLLVM_Win32) && (g->msvc_lib_dir != NULL)) {
4042 if ((g->zig_target.os == OsWindows) && (g->msvc_lib_dir != NULL)) {
40434043 return;
40444044 }
40454045 else {
src/ast_render.cpp+14-14
......@@ -68,7 +68,7 @@ static const char *prefix_op_str(PrefixOp prefix_op) {
6868 case PrefixOpDereference: return "*";
6969 case PrefixOpMaybe: return "?";
7070 case PrefixOpError: return "%";
71 case PrefixOpUnwrapError: return "%%";
71 case PrefixOpUnwrapError: return "catch";
7272 case PrefixOpUnwrapMaybe: return "??";
7373 }
7474 zig_unreachable();
......@@ -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}
......@@ -241,8 +241,8 @@ static const char *node_type_str(NodeType node_type) {
241241 return "ErrorType";
242242 case NodeTypeVarLiteral:
243243 return "VarLiteral";
244 case NodeTypeTryExpr:
245 return "TryExpr";
244 case NodeTypeIfErrorExpr:
245 return "IfErrorExpr";
246246 case NodeTypeTestExpr:
247247 return "TestExpr";
248248 }
......@@ -872,23 +872,23 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
872872 fprintf(ar->f, "null");
873873 break;
874874 }
875 case NodeTypeTryExpr:
875 case NodeTypeIfErrorExpr:
876876 {
877877 fprintf(ar->f, "if (");
878 render_node_grouped(ar, node->data.try_expr.target_node);
878 render_node_grouped(ar, node->data.if_err_expr.target_node);
879879 fprintf(ar->f, ") ");
880 if (node->data.try_expr.var_symbol) {
881 const char *ptr_str = node->data.try_expr.var_is_ptr ? "*" : "";
882 const char *var_name = buf_ptr(node->data.try_expr.var_symbol);
880 if (node->data.if_err_expr.var_symbol) {
881 const char *ptr_str = node->data.if_err_expr.var_is_ptr ? "*" : "";
882 const char *var_name = buf_ptr(node->data.if_err_expr.var_symbol);
883883 fprintf(ar->f, "|%s%s| ", ptr_str, var_name);
884884 }
885 render_node_grouped(ar, node->data.try_expr.then_node);
886 if (node->data.try_expr.else_node) {
885 render_node_grouped(ar, node->data.if_err_expr.then_node);
886 if (node->data.if_err_expr.else_node) {
887887 fprintf(ar->f, " else ");
888 if (node->data.try_expr.err_symbol) {
889 fprintf(ar->f, "|%s| ", buf_ptr(node->data.try_expr.err_symbol));
888 if (node->data.if_err_expr.err_symbol) {
889 fprintf(ar->f, "|%s| ", buf_ptr(node->data.if_err_expr.err_symbol));
890890 }
891 render_node_grouped(ar, node->data.try_expr.else_node);
891 render_node_grouped(ar, node->data.if_err_expr.else_node);
892892 }
893893 break;
894894 }
src/codegen.cpp+13-15
......@@ -42,7 +42,7 @@ static void init_darwin_native(CodeGen *g) {
4242 g->mmacosx_version_min = buf_create_from_str(osx_target);
4343 } else if (ios_target) {
4444 g->mios_version_min = buf_create_from_str(ios_target);
45 } else if (g->zig_target.os != ZigLLVM_IOS) {
45 } else if (g->zig_target.os != OsIOS) {
4646 g->mmacosx_version_min = buf_create_from_str("10.10");
4747 }
4848}
......@@ -136,9 +136,8 @@ CodeGen *codegen_create(Buf *root_src_path, const ZigTarget *target, OutType out
136136 g->each_lib_rpath = true;
137137#endif
138138
139 if (g->zig_target.os == ZigLLVM_Darwin ||
140 g->zig_target.os == ZigLLVM_MacOSX ||
141 g->zig_target.os == ZigLLVM_IOS)
139 if (g->zig_target.os == OsMacOSX ||
140 g->zig_target.os == OsIOS)
142141 {
143142 init_darwin_native(g);
144143 }
......@@ -146,9 +145,8 @@ CodeGen *codegen_create(Buf *root_src_path, const ZigTarget *target, OutType out
146145 }
147146
148147 // On Darwin/MacOS/iOS, we always link libSystem which contains libc.
149 if (g->zig_target.os == ZigLLVM_Darwin ||
150 g->zig_target.os == ZigLLVM_MacOSX ||
151 g->zig_target.os == ZigLLVM_IOS)
148 if (g->zig_target.os == OsMacOSX ||
149 g->zig_target.os == OsIOS)
152150 {
153151 g->libc_link_lib = create_link_lib(buf_create_from_str("c"));
154152 g->link_libs_list.append(g->libc_link_lib);
......@@ -363,7 +361,7 @@ static LLVMCallConv get_llvm_cc(CodeGen *g, CallingConvention cc) {
363361 g->zig_target.arch.arch == ZigLLVM_x86_64)
364362 {
365363 // cold calling convention is not supported on windows
366 if (g->zig_target.os == ZigLLVM_Win32) {
364 if (g->zig_target.os == OsWindows) {
367365 return LLVMCCallConv;
368366 } else {
369367 return LLVMColdCallConv;
......@@ -386,7 +384,7 @@ static LLVMCallConv get_llvm_cc(CodeGen *g, CallingConvention cc) {
386384}
387385
388386static void add_uwtable_attr(CodeGen *g, LLVMValueRef fn_val) {
389 if (g->zig_target.os == ZigLLVM_Win32) {
387 if (g->zig_target.os == OsWindows) {
390388 addLLVMFnAttr(fn_val, "uwtable");
391389 }
392390}
......@@ -559,7 +557,7 @@ static LLVMValueRef fn_llvm_value(CodeGen *g, FnTableEntry *fn_table_entry) {
559557 }
560558 // Note: byval is disabled on windows due to an LLVM bug:
561559 // https://github.com/zig-lang/zig/issues/536
562 if (is_byval && g->zig_target.os != ZigLLVM_Win32) {
560 if (is_byval && g->zig_target.os != OsWindows) {
563561 addLLVMArgAttr(fn_table_entry->llvm_value, (unsigned)gen_index, "byval");
564562 }
565563 }
......@@ -2371,7 +2369,7 @@ static LLVMValueRef ir_render_call(CodeGen *g, IrExecutable *executable, IrInstr
23712369 FnGenParamInfo *gen_info = &fn_type->data.fn.gen_param_info[param_i];
23722370 // Note: byval is disabled on windows due to an LLVM bug:
23732371 // https://github.com/zig-lang/zig/issues/536
2374 if (gen_info->is_byval && g->zig_target.os != ZigLLVM_Win32) {
2372 if (gen_info->is_byval && g->zig_target.os != OsWindows) {
23752373 addLLVMCallsiteAttr(result, (unsigned)gen_info->gen_index, "byval");
23762374 }
23772375 }
......@@ -5094,7 +5092,7 @@ static void define_builtin_compile_vars(CodeGen *g) {
50945092 buf_appendf(contents, "pub const Os = enum {\n");
50955093 uint32_t field_count = (uint32_t)target_os_count();
50965094 for (uint32_t i = 0; i < field_count; i += 1) {
5097 ZigLLVM_OSType os_type = get_target_os(i);
5095 Os os_type = get_target_os(i);
50985096 const char *name = get_target_os_name(os_type);
50995097 buf_appendf(contents, " %s,\n", name);
51005098
......@@ -5304,7 +5302,7 @@ static void init(CodeGen *g) {
53045302 // LLVM creates invalid binaries on Windows sometimes.
53055303 // See https://github.com/zig-lang/zig/issues/508
53065304 // As a workaround we do not use target native features on Windows.
5307 if (g->zig_target.os == ZigLLVM_Win32) {
5305 if (g->zig_target.os == OsWindows) {
53085306 target_specific_cpu_args = "";
53095307 target_specific_features = "";
53105308 } else {
......@@ -5524,13 +5522,13 @@ static void gen_root_source(CodeGen *g) {
55245522 }
55255523 report_errors_and_maybe_exit(g);
55265524
5527 if (!g->is_test_build && g->zig_target.os != ZigLLVM_UnknownOS &&
5525 if (!g->is_test_build && g->zig_target.os != OsFreestanding &&
55285526 !g->have_c_main && !g->have_winmain && !g->have_winmain_crt_startup &&
55295527 ((g->have_pub_main && g->out_type == OutTypeObj) || g->out_type == OutTypeExe))
55305528 {
55315529 g->bootstrap_import = add_special_code(g, create_bootstrap_pkg(g, g->root_package), "bootstrap.zig");
55325530 }
5533 if (g->zig_target.os == ZigLLVM_Win32 && !g->have_dllmain_crt_startup && g->out_type == OutTypeLib) {
5531 if (g->zig_target.os == OsWindows && !g->have_dllmain_crt_startup && g->out_type == OutTypeLib) {
55345532 g->bootstrap_import = add_special_code(g, create_bootstrap_pkg(g, g->root_package), "bootstrap_lib.zig");
55355533 }
55365534
src/ir.cpp+75-53
......@@ -2530,8 +2530,10 @@ static VariableTableEntry *ir_create_var(IrBuilder *irb, AstNode *node, Scope *s
25302530 bool src_is_const, bool gen_is_const, bool is_shadowable, IrInstruction *is_comptime)
25312531{
25322532 VariableTableEntry *var = create_local_var(irb->codegen, node, scope, name, src_is_const, gen_is_const, is_shadowable, is_comptime);
2533 if (is_comptime != nullptr || gen_is_const)
2533 if (is_comptime != nullptr || gen_is_const) {
25342534 var->mem_slot_index = exec_next_mem_slot(irb->exec);
2535 var->owner_exec = irb->exec;
2536 }
25352537 assert(var->child_scope);
25362538 return var;
25372539}
......@@ -3896,22 +3898,21 @@ static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *n
38963898 align_value, bit_offset_start, bit_offset_end);
38973899}
38983900
3899static IrInstruction *ir_gen_err_assert_ok(IrBuilder *irb, Scope *scope, AstNode *node, LVal lval) {
3900 assert(node->type == NodeTypePrefixOpExpr);
3901 AstNode *expr_node = node->data.prefix_op_expr.primary_expr;
3902
3901static IrInstruction *ir_gen_err_assert_ok(IrBuilder *irb, Scope *scope, AstNode *source_node, AstNode *expr_node,
3902 LVal lval)
3903{
39033904 IrInstruction *err_union_ptr = ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR);
39043905 if (err_union_ptr == irb->codegen->invalid_instruction)
39053906 return irb->codegen->invalid_instruction;
39063907
3907 IrInstruction *payload_ptr = ir_build_unwrap_err_payload(irb, scope, node, err_union_ptr, true);
3908 IrInstruction *payload_ptr = ir_build_unwrap_err_payload(irb, scope, source_node, err_union_ptr, true);
39083909 if (payload_ptr == irb->codegen->invalid_instruction)
39093910 return irb->codegen->invalid_instruction;
39103911
39113912 if (lval.is_ptr)
39123913 return payload_ptr;
39133914
3914 return ir_build_load_ptr(irb, scope, node, payload_ptr);
3915 return ir_build_load_ptr(irb, scope, source_node, payload_ptr);
39153916}
39163917
39173918static IrInstruction *ir_gen_maybe_assert_ok(IrBuilder *irb, Scope *scope, AstNode *node, LVal lval) {
......@@ -3963,7 +3964,7 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod
39633964 case PrefixOpError:
39643965 return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpError), lval);
39653966 case PrefixOpUnwrapError:
3966 return ir_gen_err_assert_ok(irb, scope, node, lval);
3967 return ir_gen_err_assert_ok(irb, scope, node, node->data.prefix_op_expr.primary_expr, lval);
39673968 case PrefixOpUnwrapMaybe:
39683969 return ir_gen_maybe_assert_ok(irb, scope, node, lval);
39693970 }
......@@ -4663,16 +4664,16 @@ static IrInstruction *ir_gen_test_expr(IrBuilder *irb, Scope *scope, AstNode *no
46634664 return ir_build_phi(irb, scope, node, 2, incoming_blocks, incoming_values);
46644665}
46654666
4666static IrInstruction *ir_gen_try_expr(IrBuilder *irb, Scope *scope, AstNode *node) {
4667 assert(node->type == NodeTypeTryExpr);
4667static IrInstruction *ir_gen_if_err_expr(IrBuilder *irb, Scope *scope, AstNode *node) {
4668 assert(node->type == NodeTypeIfErrorExpr);
46684669
4669 AstNode *target_node = node->data.try_expr.target_node;
4670 AstNode *then_node = node->data.try_expr.then_node;
4671 AstNode *else_node = node->data.try_expr.else_node;
4672 bool var_is_ptr = node->data.try_expr.var_is_ptr;
4670 AstNode *target_node = node->data.if_err_expr.target_node;
4671 AstNode *then_node = node->data.if_err_expr.then_node;
4672 AstNode *else_node = node->data.if_err_expr.else_node;
4673 bool var_is_ptr = node->data.if_err_expr.var_is_ptr;
46734674 bool var_is_const = true;
4674 Buf *var_symbol = node->data.try_expr.var_symbol;
4675 Buf *err_symbol = node->data.try_expr.err_symbol;
4675 Buf *var_symbol = node->data.if_err_expr.var_symbol;
4676 Buf *err_symbol = node->data.if_err_expr.err_symbol;
46764677
46774678 IrInstruction *err_val_ptr = ir_gen_node_extra(irb, target_node, scope, LVAL_PTR);
46784679 if (err_val_ptr == irb->codegen->invalid_instruction)
......@@ -5179,6 +5180,17 @@ static IrInstruction *ir_gen_err_ok_or(IrBuilder *irb, Scope *parent_scope, AstN
51795180 AstNode *op2_node = node->data.unwrap_err_expr.op2;
51805181 AstNode *var_node = node->data.unwrap_err_expr.symbol;
51815182
5183 if (op2_node->type == NodeTypeUnreachable) {
5184 if (var_node != nullptr) {
5185 assert(var_node->type == NodeTypeSymbol);
5186 Buf *var_name = var_node->data.symbol_expr.symbol;
5187 add_node_error(irb->codegen, var_node, buf_sprintf("unused variable: '%s'", buf_ptr(var_name)));
5188 return irb->codegen->invalid_instruction;
5189 }
5190 return ir_gen_err_assert_ok(irb, parent_scope, node, op1_node, LVAL_NONE);
5191 }
5192
5193
51825194 IrInstruction *err_union_ptr = ir_gen_node_extra(irb, op1_node, parent_scope, LVAL_PTR);
51835195 if (err_union_ptr == irb->codegen->invalid_instruction)
51845196 return irb->codegen->invalid_instruction;
......@@ -5409,8 +5421,8 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
54095421 return ir_lval_wrap(irb, scope, ir_gen_null_literal(irb, scope, node), lval);
54105422 case NodeTypeVarLiteral:
54115423 return ir_lval_wrap(irb, scope, ir_gen_var_literal(irb, scope, node), lval);
5412 case NodeTypeTryExpr:
5413 return ir_lval_wrap(irb, scope, ir_gen_try_expr(irb, scope, node), lval);
5424 case NodeTypeIfErrorExpr:
5425 return ir_lval_wrap(irb, scope, ir_gen_if_err_expr(irb, scope, node), lval);
54145426 case NodeTypeTestExpr:
54155427 return ir_lval_wrap(irb, scope, ir_gen_test_expr(irb, scope, node), lval);
54165428 case NodeTypeSwitchExpr:
......@@ -7037,48 +7049,48 @@ IrInstruction *ir_eval_const_value(CodeGen *codegen, Scope *scope, AstNode *node
70377049 if (expected_type != nullptr && type_is_invalid(expected_type))
70387050 return codegen->invalid_instruction;
70397051
7040 IrExecutable ir_executable = {0};
7041 ir_executable.source_node = source_node;
7042 ir_executable.parent_exec = parent_exec;
7043 ir_executable.name = exec_name;
7044 ir_executable.is_inline = true;
7045 ir_executable.fn_entry = fn_entry;
7046 ir_executable.c_import_buf = c_import_buf;
7047 ir_executable.begin_scope = scope;
7048 ir_gen(codegen, node, scope, &ir_executable);
7049
7050 if (ir_executable.invalid)
7052 IrExecutable *ir_executable = allocate<IrExecutable>(1);
7053 ir_executable->source_node = source_node;
7054 ir_executable->parent_exec = parent_exec;
7055 ir_executable->name = exec_name;
7056 ir_executable->is_inline = true;
7057 ir_executable->fn_entry = fn_entry;
7058 ir_executable->c_import_buf = c_import_buf;
7059 ir_executable->begin_scope = scope;
7060 ir_gen(codegen, node, scope, ir_executable);
7061
7062 if (ir_executable->invalid)
70517063 return codegen->invalid_instruction;
70527064
70537065 if (codegen->verbose_ir) {
70547066 fprintf(stderr, "\nSource: ");
70557067 ast_render(codegen, stderr, node, 4);
70567068 fprintf(stderr, "\n{ // (IR)\n");
7057 ir_print(codegen, stderr, &ir_executable, 4);
7069 ir_print(codegen, stderr, ir_executable, 4);
70587070 fprintf(stderr, "}\n");
70597071 }
7060 IrExecutable analyzed_executable = {0};
7061 analyzed_executable.source_node = source_node;
7062 analyzed_executable.parent_exec = parent_exec;
7063 analyzed_executable.source_exec = &ir_executable;
7064 analyzed_executable.name = exec_name;
7065 analyzed_executable.is_inline = true;
7066 analyzed_executable.fn_entry = fn_entry;
7067 analyzed_executable.c_import_buf = c_import_buf;
7068 analyzed_executable.backward_branch_count = backward_branch_count;
7069 analyzed_executable.backward_branch_quota = backward_branch_quota;
7070 analyzed_executable.begin_scope = scope;
7071 TypeTableEntry *result_type = ir_analyze(codegen, &ir_executable, &analyzed_executable, expected_type, node);
7072 IrExecutable *analyzed_executable = allocate<IrExecutable>(1);
7073 analyzed_executable->source_node = source_node;
7074 analyzed_executable->parent_exec = parent_exec;
7075 analyzed_executable->source_exec = ir_executable;
7076 analyzed_executable->name = exec_name;
7077 analyzed_executable->is_inline = true;
7078 analyzed_executable->fn_entry = fn_entry;
7079 analyzed_executable->c_import_buf = c_import_buf;
7080 analyzed_executable->backward_branch_count = backward_branch_count;
7081 analyzed_executable->backward_branch_quota = backward_branch_quota;
7082 analyzed_executable->begin_scope = scope;
7083 TypeTableEntry *result_type = ir_analyze(codegen, ir_executable, analyzed_executable, expected_type, node);
70727084 if (type_is_invalid(result_type))
70737085 return codegen->invalid_instruction;
70747086
70757087 if (codegen->verbose_ir) {
70767088 fprintf(stderr, "{ // (analyzed)\n");
7077 ir_print(codegen, stderr, &analyzed_executable, 4);
7089 ir_print(codegen, stderr, analyzed_executable, 4);
70787090 fprintf(stderr, "}\n");
70797091 }
70807092
7081 return ir_exec_const_result(codegen, &analyzed_executable);
7093 return ir_exec_const_result(codegen, analyzed_executable);
70827094}
70837095
70847096static TypeTableEntry *ir_resolve_type(IrAnalyze *ira, IrInstruction *type_value) {
......@@ -9334,6 +9346,8 @@ static TypeTableEntry *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstruc
93349346 IrInstruction *casted_init_value = ir_implicit_cast(ira, init_value, explicit_type);
93359347 bool is_comptime_var = ir_get_var_is_comptime(var);
93369348
9349 bool var_class_requires_const = false;
9350
93379351 TypeTableEntry *result_type = casted_init_value->value.type;
93389352 if (type_is_invalid(result_type)) {
93399353 result_type = ira->codegen->builtin_types.entry_invalid;
......@@ -9345,6 +9359,7 @@ static TypeTableEntry *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstruc
93459359 result_type = ira->codegen->builtin_types.entry_invalid;
93469360 break;
93479361 case VarClassRequiredConst:
9362 var_class_requires_const = true;
93489363 if (!var->src_is_const && !is_comptime_var) {
93499364 ir_add_error_node(ira, source_node,
93509365 buf_sprintf("variable of type '%s' must be const or comptime",
......@@ -9366,8 +9381,6 @@ static TypeTableEntry *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstruc
93669381 return ira->codegen->builtin_types.entry_void;
93679382 }
93689383
9369 bool is_comptime = ir_get_var_is_comptime(var);
9370
93719384 if (decl_var_instruction->align_value == nullptr) {
93729385 var->align_bytes = get_abi_alignment(ira->codegen, result_type);
93739386 } else {
......@@ -9382,12 +9395,12 @@ static TypeTableEntry *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstruc
93829395 ConstExprValue *mem_slot = &ira->exec_context.mem_slot_list[var->mem_slot_index];
93839396 *mem_slot = casted_init_value->value;
93849397
9385 if (is_comptime) {
9398 if (is_comptime_var || (var_class_requires_const && var->gen_is_const)) {
93869399 ir_build_const_from(ira, &decl_var_instruction->base);
93879400 return ira->codegen->builtin_types.entry_void;
93889401 }
93899402 }
9390 } else if (is_comptime) {
9403 } else if (is_comptime_var) {
93919404 ir_add_error(ira, &decl_var_instruction->base,
93929405 buf_sprintf("cannot store runtime value in compile time variable"));
93939406 var->value->type = ira->codegen->builtin_types.entry_invalid;
......@@ -9690,6 +9703,10 @@ static VariableTableEntry *get_fn_var_by_index(FnTableEntry *fn_entry, size_t in
96909703static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,
96919704 VariableTableEntry *var, bool is_const_ptr, bool is_volatile_ptr)
96929705{
9706 if (var->mem_slot_index != SIZE_MAX && var->owner_exec->analysis == nullptr) {
9707 assert(ira->codegen->errors.length != 0);
9708 return ira->codegen->invalid_instruction;
9709 }
96939710 assert(var->value->type);
96949711 if (type_is_invalid(var->value->type))
96959712 return ira->codegen->invalid_instruction;
......@@ -9700,9 +9717,14 @@ static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,
97009717 if (var->value->special == ConstValSpecialStatic) {
97019718 mem_slot = var->value;
97029719 } else {
9703 // TODO once the analyze code is fully ported over to IR we won't need this SIZE_MAX thing.
9704 if (var->mem_slot_index != SIZE_MAX && (comptime_var_mem || var->gen_is_const))
9705 mem_slot = &ira->exec_context.mem_slot_list[var->mem_slot_index];
9720 if (var->mem_slot_index != SIZE_MAX && (comptime_var_mem || var->gen_is_const)) {
9721 // find the relevant exec_context
9722 assert(var->owner_exec != nullptr);
9723 assert(var->owner_exec->analysis != nullptr);
9724 IrExecContext *exec_context = &var->owner_exec->analysis->exec_context;
9725 assert(var->mem_slot_index < exec_context->mem_slot_count);
9726 mem_slot = &exec_context->mem_slot_list[var->mem_slot_index];
9727 }
97069728 }
97079729
97089730 bool is_const = (var->value->type->id == TypeTableEntryIdMetaType) ? is_const_ptr : var->src_is_const;
......@@ -15328,8 +15350,8 @@ TypeTableEntry *ir_analyze(CodeGen *codegen, IrExecutable *old_exec, IrExecutabl
1532815350 assert(!old_exec->invalid);
1532915351 assert(expected_type == nullptr || !type_is_invalid(expected_type));
1533015352
15331 IrAnalyze ir_analyze_data = {};
15332 IrAnalyze *ira = &ir_analyze_data;
15353 IrAnalyze *ira = allocate<IrAnalyze>(1);
15354 old_exec->analysis = ira;
1533315355 ira->codegen = codegen;
1533415356 ira->explicit_return_type = expected_type;
1533515357
src/link.cpp+8-1
......@@ -334,6 +334,13 @@ static void construct_linker_job_elf(LinkJob *lj) {
334334 if (!g->is_native_target) {
335335 lj->args.append("--allow-shlib-undefined");
336336 }
337
338 if (g->zig_target.os == OsZen) {
339 lj->args.append("-e");
340 lj->args.append("main");
341
342 lj->args.append("--image-base=0x10000000");
343 }
337344}
338345
339346//static bool is_target_cyg_mingw(const ZigTarget *target) {
......@@ -644,7 +651,7 @@ static void get_darwin_platform(LinkJob *lj, DarwinPlatform *platform) {
644651 platform->kind = MacOS;
645652 } else if (g->mios_version_min) {
646653 platform->kind = IPhoneOS;
647 } else if (g->zig_target.os == ZigLLVM_MacOSX || g->zig_target.os == ZigLLVM_Darwin) {
654 } else if (g->zig_target.os == OsMacOSX) {
648655 platform->kind = MacOS;
649656 g->mmacosx_version_min = buf_create_from_str("10.10");
650657 } else {
src/main.cpp+1-1
......@@ -120,7 +120,7 @@ static int print_target_list(FILE *f) {
120120 fprintf(f, "\nOperating Systems:\n");
121121 size_t os_count = target_os_count();
122122 for (size_t i = 0; i < os_count; i += 1) {
123 ZigLLVM_OSType os_type = get_target_os(i);
123 Os os_type = get_target_os(i);
124124 const char *native_str = (native.os == os_type) ? " (native)" : "";
125125 fprintf(f, " %s%s\n", get_target_os_name(os_type), native_str);
126126 }
src/parser.cpp+50-46
......@@ -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
......@@ -1410,15 +1407,15 @@ static AstNode *ast_parse_if_try_test_expr(ParseContext *pc, size_t *token_index
14101407 }
14111408
14121409 if (err_name_tok != nullptr) {
1413 AstNode *node = ast_create_node(pc, NodeTypeTryExpr, if_token);
1414 node->data.try_expr.target_node = condition;
1415 node->data.try_expr.var_is_ptr = var_is_ptr;
1410 AstNode *node = ast_create_node(pc, NodeTypeIfErrorExpr, if_token);
1411 node->data.if_err_expr.target_node = condition;
1412 node->data.if_err_expr.var_is_ptr = var_is_ptr;
14161413 if (var_name_tok != nullptr) {
1417 node->data.try_expr.var_symbol = token_buf(var_name_tok);
1414 node->data.if_err_expr.var_symbol = token_buf(var_name_tok);
14181415 }
1419 node->data.try_expr.then_node = body_node;
1420 node->data.try_expr.err_symbol = token_buf(err_name_tok);
1421 node->data.try_expr.else_node = else_node;
1416 node->data.if_err_expr.then_node = body_node;
1417 node->data.if_err_expr.err_symbol = token_buf(err_name_tok);
1418 node->data.if_err_expr.else_node = else_node;
14221419 return node;
14231420 } else if (var_name_tok != nullptr) {
14241421 AstNode *node = ast_create_node(pc, NodeTypeTestExpr, if_token);
......@@ -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*/
......@@ -2041,7 +2041,7 @@ static BinOpType ast_parse_ass_op(ParseContext *pc, size_t *token_index, bool ma
20412041/*
20422042UnwrapExpression : BoolOrExpression (UnwrapMaybe | UnwrapError) | BoolOrExpression
20432043UnwrapMaybe : "??" BoolOrExpression
2044UnwrapError : "%%" option("|" "Symbol" "|") BoolOrExpression
2044UnwrapError = "catch" option("|" Symbol "|") Expression
20452045*/
20462046static AstNode *ast_parse_unwrap_expr(ParseContext *pc, size_t *token_index, bool mandatory) {
20472047 AstNode *lhs = ast_parse_bool_or_expr(pc, token_index, mandatory);
......@@ -2061,7 +2061,7 @@ static AstNode *ast_parse_unwrap_expr(ParseContext *pc, size_t *token_index, boo
20612061 node->data.bin_op_expr.op2 = rhs;
20622062
20632063 return node;
2064 } else if (token->id == TokenIdPercentPercent) {
2064 } else if (token->id == TokenIdKeywordCatch) {
20652065 *token_index += 1;
20662066
20672067 AstNode *node = ast_create_node(pc, NodeTypeUnwrapErrorExpr, token);
......@@ -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;
......@@ -2153,10 +2157,10 @@ static bool statement_terminates_without_semicolon(AstNode *node) {
21532157 if (node->data.if_bool_expr.else_node)
21542158 return statement_terminates_without_semicolon(node->data.if_bool_expr.else_node);
21552159 return node->data.if_bool_expr.then_block->type == NodeTypeBlock;
2156 case NodeTypeTryExpr:
2157 if (node->data.try_expr.else_node)
2158 return statement_terminates_without_semicolon(node->data.try_expr.else_node);
2159 return node->data.try_expr.then_node->type == NodeTypeBlock;
2160 case NodeTypeIfErrorExpr:
2161 if (node->data.if_err_expr.else_node)
2162 return statement_terminates_without_semicolon(node->data.if_err_expr.else_node);
2163 return node->data.if_err_expr.then_node->type == NodeTypeBlock;
21602164 case NodeTypeTestExpr:
21612165 if (node->data.test_expr.else_node)
21622166 return statement_terminates_without_semicolon(node->data.test_expr.else_node);
......@@ -2829,10 +2833,10 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont
28292833 visit_field(&node->data.if_bool_expr.then_block, visit, context);
28302834 visit_field(&node->data.if_bool_expr.else_node, visit, context);
28312835 break;
2832 case NodeTypeTryExpr:
2833 visit_field(&node->data.try_expr.target_node, visit, context);
2834 visit_field(&node->data.try_expr.then_node, visit, context);
2835 visit_field(&node->data.try_expr.else_node, visit, context);
2836 case NodeTypeIfErrorExpr:
2837 visit_field(&node->data.if_err_expr.target_node, visit, context);
2838 visit_field(&node->data.if_err_expr.then_node, visit, context);
2839 visit_field(&node->data.if_err_expr.else_node, visit, context);
28362840 break;
28372841 case NodeTypeTestExpr:
28382842 visit_field(&node->data.test_expr.target_node, visit, context);
src/target.cpp+257-81
......@@ -127,39 +127,39 @@ static const ZigLLVM_VendorType vendor_list[] = {
127127 ZigLLVM_SUSE,
128128};
129129
130static const ZigLLVM_OSType os_list[] = {
131 ZigLLVM_UnknownOS,
132 ZigLLVM_Ananas,
133 ZigLLVM_CloudABI,
134 ZigLLVM_Darwin,
135 ZigLLVM_DragonFly,
136 ZigLLVM_FreeBSD,
137 ZigLLVM_Fuchsia,
138 ZigLLVM_IOS,
139 ZigLLVM_KFreeBSD,
140 ZigLLVM_Linux,
141 ZigLLVM_Lv2,
142 ZigLLVM_MacOSX,
143 ZigLLVM_NetBSD,
144 ZigLLVM_OpenBSD,
145 ZigLLVM_Solaris,
146 ZigLLVM_Win32,
147 ZigLLVM_Haiku,
148 ZigLLVM_Minix,
149 ZigLLVM_RTEMS,
150 ZigLLVM_NaCl,
151 ZigLLVM_CNK,
152 ZigLLVM_Bitrig,
153 ZigLLVM_AIX,
154 ZigLLVM_CUDA,
155 ZigLLVM_NVCL,
156 ZigLLVM_AMDHSA,
157 ZigLLVM_PS4,
158 ZigLLVM_ELFIAMCU,
159 ZigLLVM_TvOS,
160 ZigLLVM_WatchOS,
161 ZigLLVM_Mesa3D,
162 ZigLLVM_Contiki,
130static const Os os_list[] = {
131 OsFreestanding,
132 OsAnanas,
133 OsCloudABI,
134 OsDragonFly,
135 OsFreeBSD,
136 OsFuchsia,
137 OsIOS,
138 OsKFreeBSD,
139 OsLinux,
140 OsLv2, // PS3
141 OsMacOSX,
142 OsNetBSD,
143 OsOpenBSD,
144 OsSolaris,
145 OsWindows,
146 OsHaiku,
147 OsMinix,
148 OsRTEMS,
149 OsNaCl, // Native Client
150 OsCNK, // BG/P Compute-Node Kernel
151 OsBitrig,
152 OsAIX,
153 OsCUDA, // NVIDIA CUDA
154 OsNVCL, // NVIDIA OpenCL
155 OsAMDHSA, // AMD HSA Runtime
156 OsPS4,
157 OsELFIAMCU,
158 OsTvOS, // Apple tvOS
159 OsWatchOS, // Apple watchOS
160 OsMesa3D,
161 OsContiki,
162 OsZen,
163163};
164164
165165static const ZigLLVM_EnvironmentType environ_list[] = {
......@@ -233,12 +233,187 @@ ZigLLVM_VendorType get_target_vendor(size_t index) {
233233size_t target_os_count(void) {
234234 return array_length(os_list);
235235}
236ZigLLVM_OSType get_target_os(size_t index) {
236Os get_target_os(size_t index) {
237237 return os_list[index];
238238}
239239
240const char *get_target_os_name(ZigLLVM_OSType os_type) {
241 return (os_type == ZigLLVM_UnknownOS) ? "freestanding" : ZigLLVMGetOSTypeName(os_type);
240static ZigLLVM_OSType get_llvm_os_type(Os os_type) {
241 switch (os_type) {
242 case OsFreestanding:
243 case OsZen:
244 return ZigLLVM_UnknownOS;
245 case OsAnanas:
246 return ZigLLVM_Ananas;
247 case OsCloudABI:
248 return ZigLLVM_CloudABI;
249 case OsDragonFly:
250 return ZigLLVM_DragonFly;
251 case OsFreeBSD:
252 return ZigLLVM_FreeBSD;
253 case OsFuchsia:
254 return ZigLLVM_Fuchsia;
255 case OsIOS:
256 return ZigLLVM_IOS;
257 case OsKFreeBSD:
258 return ZigLLVM_KFreeBSD;
259 case OsLinux:
260 return ZigLLVM_Linux;
261 case OsLv2:
262 return ZigLLVM_Lv2;
263 case OsMacOSX:
264 return ZigLLVM_MacOSX;
265 case OsNetBSD:
266 return ZigLLVM_NetBSD;
267 case OsOpenBSD:
268 return ZigLLVM_OpenBSD;
269 case OsSolaris:
270 return ZigLLVM_Solaris;
271 case OsWindows:
272 return ZigLLVM_Win32;
273 case OsHaiku:
274 return ZigLLVM_Haiku;
275 case OsMinix:
276 return ZigLLVM_Minix;
277 case OsRTEMS:
278 return ZigLLVM_RTEMS;
279 case OsNaCl:
280 return ZigLLVM_NaCl;
281 case OsCNK:
282 return ZigLLVM_CNK;
283 case OsBitrig:
284 return ZigLLVM_Bitrig;
285 case OsAIX:
286 return ZigLLVM_AIX;
287 case OsCUDA:
288 return ZigLLVM_CUDA;
289 case OsNVCL:
290 return ZigLLVM_NVCL;
291 case OsAMDHSA:
292 return ZigLLVM_AMDHSA;
293 case OsPS4:
294 return ZigLLVM_PS4;
295 case OsELFIAMCU:
296 return ZigLLVM_ELFIAMCU;
297 case OsTvOS:
298 return ZigLLVM_TvOS;
299 case OsWatchOS:
300 return ZigLLVM_WatchOS;
301 case OsMesa3D:
302 return ZigLLVM_Mesa3D;
303 case OsContiki:
304 return ZigLLVM_Contiki;
305 }
306 zig_unreachable();
307}
308
309static Os get_zig_os_type(ZigLLVM_OSType os_type) {
310 switch (os_type) {
311 case ZigLLVM_UnknownOS:
312 return OsFreestanding;
313 case ZigLLVM_Ananas:
314 return OsAnanas;
315 case ZigLLVM_CloudABI:
316 return OsCloudABI;
317 case ZigLLVM_DragonFly:
318 return OsDragonFly;
319 case ZigLLVM_FreeBSD:
320 return OsFreeBSD;
321 case ZigLLVM_Fuchsia:
322 return OsFuchsia;
323 case ZigLLVM_IOS:
324 return OsIOS;
325 case ZigLLVM_KFreeBSD:
326 return OsKFreeBSD;
327 case ZigLLVM_Linux:
328 return OsLinux;
329 case ZigLLVM_Lv2:
330 return OsLv2;
331 case ZigLLVM_Darwin:
332 case ZigLLVM_MacOSX:
333 return OsMacOSX;
334 case ZigLLVM_NetBSD:
335 return OsNetBSD;
336 case ZigLLVM_OpenBSD:
337 return OsOpenBSD;
338 case ZigLLVM_Solaris:
339 return OsSolaris;
340 case ZigLLVM_Win32:
341 return OsWindows;
342 case ZigLLVM_Haiku:
343 return OsHaiku;
344 case ZigLLVM_Minix:
345 return OsMinix;
346 case ZigLLVM_RTEMS:
347 return OsRTEMS;
348 case ZigLLVM_NaCl:
349 return OsNaCl;
350 case ZigLLVM_CNK:
351 return OsCNK;
352 case ZigLLVM_Bitrig:
353 return OsBitrig;
354 case ZigLLVM_AIX:
355 return OsAIX;
356 case ZigLLVM_CUDA:
357 return OsCUDA;
358 case ZigLLVM_NVCL:
359 return OsNVCL;
360 case ZigLLVM_AMDHSA:
361 return OsAMDHSA;
362 case ZigLLVM_PS4:
363 return OsPS4;
364 case ZigLLVM_ELFIAMCU:
365 return OsELFIAMCU;
366 case ZigLLVM_TvOS:
367 return OsTvOS;
368 case ZigLLVM_WatchOS:
369 return OsWatchOS;
370 case ZigLLVM_Mesa3D:
371 return OsMesa3D;
372 case ZigLLVM_Contiki:
373 return OsContiki;
374 }
375 zig_unreachable();
376}
377
378const char *get_target_os_name(Os os_type) {
379 switch (os_type) {
380 case OsFreestanding:
381 return "freestanding";
382 case OsZen:
383 return "zen";
384 case OsAnanas:
385 case OsCloudABI:
386 case OsDragonFly:
387 case OsFreeBSD:
388 case OsFuchsia:
389 case OsIOS:
390 case OsKFreeBSD:
391 case OsLinux:
392 case OsLv2: // PS3
393 case OsMacOSX:
394 case OsNetBSD:
395 case OsOpenBSD:
396 case OsSolaris:
397 case OsWindows:
398 case OsHaiku:
399 case OsMinix:
400 case OsRTEMS:
401 case OsNaCl: // Native Client
402 case OsCNK: // BG/P Compute-Node Kernel
403 case OsBitrig:
404 case OsAIX:
405 case OsCUDA: // NVIDIA CUDA
406 case OsNVCL: // NVIDIA OpenCL
407 case OsAMDHSA: // AMD HSA Runtime
408 case OsPS4:
409 case OsELFIAMCU:
410 case OsTvOS: // Apple tvOS
411 case OsWatchOS: // Apple watchOS
412 case OsMesa3D:
413 case OsContiki:
414 return ZigLLVMGetOSTypeName(get_llvm_os_type(os_type));
415 }
416 zig_unreachable();
242417}
243418
244419size_t target_environ_count(void) {
......@@ -249,20 +424,22 @@ ZigLLVM_EnvironmentType get_target_environ(size_t index) {
249424}
250425
251426void get_native_target(ZigTarget *target) {
427 ZigLLVM_OSType os_type;
252428 ZigLLVMGetNativeTarget(
253429 &target->arch.arch,
254430 &target->arch.sub_arch,
255431 &target->vendor,
256 &target->os,
432 &os_type,
257433 &target->env_type,
258434 &target->oformat);
435 target->os = get_zig_os_type(os_type);
259436}
260437
261438void get_unknown_target(ZigTarget *target) {
262439 target->arch.arch = ZigLLVM_UnknownArch;
263440 target->arch.sub_arch = ZigLLVM_NoSubArch;
264441 target->vendor = ZigLLVM_UnknownVendor;
265 target->os = ZigLLVM_UnknownOS;
442 target->os = OsFreestanding;
266443 target->env_type = ZigLLVM_UnknownEnvironment;
267444 target->oformat = ZigLLVM_UnknownObjectFormat;
268445}
......@@ -289,9 +466,9 @@ int parse_target_arch(const char *str, ArchType *out_arch) {
289466 return ErrorFileNotFound;
290467}
291468
292int parse_target_os(const char *str, ZigLLVM_OSType *out_os) {
469int parse_target_os(const char *str, Os *out_os) {
293470 for (size_t i = 0; i < array_length(os_list); i += 1) {
294 ZigLLVM_OSType os = os_list[i];
471 Os os = os_list[i];
295472 const char *os_name = get_target_os_name(os);
296473 if (strcmp(os_name, str) == 0) {
297474 *out_os = os;
......@@ -328,15 +505,14 @@ void get_target_triple(Buf *triple, const ZigTarget *target) {
328505 buf_resize(triple, 0);
329506 buf_appendf(triple, "%s-%s-%s-%s", arch_name,
330507 ZigLLVMGetVendorTypeName(target->vendor),
331 ZigLLVMGetOSTypeName(target->os),
508 ZigLLVMGetOSTypeName(get_llvm_os_type(target->os)),
332509 ZigLLVMGetEnvironmentTypeName(target->env_type));
333510}
334511
335512static bool is_os_darwin(ZigTarget *target) {
336513 switch (target->os) {
337 case ZigLLVM_Darwin:
338 case ZigLLVM_IOS:
339 case ZigLLVM_MacOSX:
514 case OsMacOSX:
515 case OsIOS:
340516 return true;
341517 default:
342518 return false;
......@@ -357,7 +533,7 @@ void resolve_target_object_format(ZigTarget *target) {
357533 case ZigLLVM_x86_64:
358534 if (is_os_darwin(target)) {
359535 target->oformat = ZigLLVM_MachO;
360 } else if (target->os == ZigLLVM_Win32) {
536 } else if (target->os == OsWindows) {
361537 target->oformat = ZigLLVM_COFF;
362538 } else {
363539 target->oformat = ZigLLVM_ELF;
......@@ -489,7 +665,7 @@ static int get_arch_pointer_bit_width(ZigLLVM_ArchType arch) {
489665
490666uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
491667 switch (target->os) {
492 case ZigLLVM_UnknownOS:
668 case OsFreestanding:
493669 switch (id) {
494670 case CIntTypeShort:
495671 case CIntTypeUShort:
......@@ -506,9 +682,9 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
506682 case CIntTypeCount:
507683 zig_unreachable();
508684 }
509 case ZigLLVM_Linux:
510 case ZigLLVM_Darwin:
511 case ZigLLVM_MacOSX:
685 case OsLinux:
686 case OsMacOSX:
687 case OsZen:
512688 switch (id) {
513689 case CIntTypeShort:
514690 case CIntTypeUShort:
......@@ -525,7 +701,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
525701 case CIntTypeCount:
526702 zig_unreachable();
527703 }
528 case ZigLLVM_Win32:
704 case OsWindows:
529705 switch (id) {
530706 case CIntTypeShort:
531707 case CIntTypeUShort:
......@@ -541,40 +717,40 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
541717 case CIntTypeCount:
542718 zig_unreachable();
543719 }
544 case ZigLLVM_Ananas:
545 case ZigLLVM_CloudABI:
546 case ZigLLVM_DragonFly:
547 case ZigLLVM_FreeBSD:
548 case ZigLLVM_IOS:
549 case ZigLLVM_KFreeBSD:
550 case ZigLLVM_Lv2:
551 case ZigLLVM_NetBSD:
552 case ZigLLVM_OpenBSD:
553 case ZigLLVM_Solaris:
554 case ZigLLVM_Haiku:
555 case ZigLLVM_Minix:
556 case ZigLLVM_RTEMS:
557 case ZigLLVM_NaCl:
558 case ZigLLVM_CNK:
559 case ZigLLVM_Bitrig:
560 case ZigLLVM_AIX:
561 case ZigLLVM_CUDA:
562 case ZigLLVM_NVCL:
563 case ZigLLVM_AMDHSA:
564 case ZigLLVM_PS4:
565 case ZigLLVM_ELFIAMCU:
566 case ZigLLVM_TvOS:
567 case ZigLLVM_WatchOS:
568 case ZigLLVM_Mesa3D:
569 case ZigLLVM_Fuchsia:
570 case ZigLLVM_Contiki:
720 case OsAnanas:
721 case OsCloudABI:
722 case OsDragonFly:
723 case OsFreeBSD:
724 case OsIOS:
725 case OsKFreeBSD:
726 case OsLv2:
727 case OsNetBSD:
728 case OsOpenBSD:
729 case OsSolaris:
730 case OsHaiku:
731 case OsMinix:
732 case OsRTEMS:
733 case OsNaCl:
734 case OsCNK:
735 case OsBitrig:
736 case OsAIX:
737 case OsCUDA:
738 case OsNVCL:
739 case OsAMDHSA:
740 case OsPS4:
741 case OsELFIAMCU:
742 case OsTvOS:
743 case OsWatchOS:
744 case OsMesa3D:
745 case OsFuchsia:
746 case OsContiki:
571747 zig_panic("TODO c type size in bits for this target");
572748 }
573749 zig_unreachable();
574750}
575751
576752const char *target_o_file_ext(ZigTarget *target) {
577 if (target->env_type == ZigLLVM_MSVC || target->os == ZigLLVM_Win32) {
753 if (target->env_type == ZigLLVM_MSVC || target->os == OsWindows) {
578754 return ".obj";
579755 } else {
580756 return ".o";
......@@ -590,7 +766,7 @@ const char *target_llvm_ir_file_ext(ZigTarget *target) {
590766}
591767
592768const char *target_exe_file_ext(ZigTarget *target) {
593 if (target->os == ZigLLVM_Win32) {
769 if (target->os == OsWindows) {
594770 return ".exe";
595771 } else {
596772 return "";
......@@ -690,12 +866,12 @@ bool target_can_exec(const ZigTarget *host_target, const ZigTarget *guest_target
690866 return true;
691867 }
692868
693 if (guest_target->os == ZigLLVM_Win32 && host_target->os == ZigLLVM_Win32 &&
869 if (guest_target->os == OsWindows && host_target->os == OsWindows &&
694870 host_target->arch.arch == ZigLLVM_x86_64 && guest_target->arch.arch == ZigLLVM_x86)
695871 {
696872 // 64-bit windows can run 32-bit programs
697873 return true;
698874 }
699
875
700876 return false;
701877}
src/target.hpp+39-4
......@@ -17,10 +17,45 @@ struct ArchType {
1717 ZigLLVM_SubArchType sub_arch;
1818};
1919
20enum Os {
21 OsFreestanding,
22 OsAnanas,
23 OsCloudABI,
24 OsDragonFly,
25 OsFreeBSD,
26 OsFuchsia,
27 OsIOS,
28 OsKFreeBSD,
29 OsLinux,
30 OsLv2, // PS3
31 OsMacOSX,
32 OsNetBSD,
33 OsOpenBSD,
34 OsSolaris,
35 OsWindows,
36 OsHaiku,
37 OsMinix,
38 OsRTEMS,
39 OsNaCl, // Native Client
40 OsCNK, // BG/P Compute-Node Kernel
41 OsBitrig,
42 OsAIX,
43 OsCUDA, // NVIDIA CUDA
44 OsNVCL, // NVIDIA OpenCL
45 OsAMDHSA, // AMD HSA Runtime
46 OsPS4,
47 OsELFIAMCU,
48 OsTvOS, // Apple tvOS
49 OsWatchOS, // Apple watchOS
50 OsMesa3D,
51 OsContiki,
52 OsZen,
53};
54
2055struct ZigTarget {
2156 ArchType arch;
2257 ZigLLVM_VendorType vendor;
23 ZigLLVM_OSType os;
58 Os os;
2459 ZigLLVM_EnvironmentType env_type;
2560 ZigLLVM_ObjectFormatType oformat;
2661};
......@@ -46,8 +81,8 @@ size_t target_vendor_count(void);
4681ZigLLVM_VendorType get_target_vendor(size_t index);
4782
4883size_t target_os_count(void);
49ZigLLVM_OSType get_target_os(size_t index);
50const char *get_target_os_name(ZigLLVM_OSType os_type);
84Os get_target_os(size_t index);
85const char *get_target_os_name(Os os_type);
5186
5287size_t target_environ_count(void);
5388ZigLLVM_EnvironmentType get_target_environ(size_t index);
......@@ -61,7 +96,7 @@ void get_native_target(ZigTarget *target);
6196void get_unknown_target(ZigTarget *target);
6297
6398int parse_target_arch(const char *str, ArchType *arch);
64int parse_target_os(const char *str, ZigLLVM_OSType *os);
99int parse_target_os(const char *str, Os *os);
65100int parse_target_environ(const char *str, ZigLLVM_EnvironmentType *env_type);
66101
67102void init_all_targets(void);
src/tokenizer.cpp+4
......@@ -111,6 +111,7 @@ static const struct ZigKeyword zig_keywords[] = {
111111 {"and", TokenIdKeywordAnd},
112112 {"asm", TokenIdKeywordAsm},
113113 {"break", TokenIdKeywordBreak},
114 {"catch", TokenIdKeywordCatch},
114115 {"coldcc", TokenIdKeywordColdCC},
115116 {"comptime", TokenIdKeywordCompTime},
116117 {"const", TokenIdKeywordConst},
......@@ -141,6 +142,7 @@ static const struct ZigKeyword zig_keywords[] = {
141142 {"test", TokenIdKeywordTest},
142143 {"this", TokenIdKeywordThis},
143144 {"true", TokenIdKeywordTrue},
145 {"try", TokenIdKeywordTry},
144146 {"undefined", TokenIdKeywordUndefined},
145147 {"union", TokenIdKeywordUnion},
146148 {"unreachable", TokenIdKeywordUnreachable},
......@@ -1511,6 +1513,7 @@ const char * token_name(TokenId id) {
15111513 case TokenIdKeywordAnd: return "and";
15121514 case TokenIdKeywordAsm: return "asm";
15131515 case TokenIdKeywordBreak: return "break";
1516 case TokenIdKeywordCatch: return "catch";
15141517 case TokenIdKeywordColdCC: return "coldcc";
15151518 case TokenIdKeywordCompTime: return "comptime";
15161519 case TokenIdKeywordConst: return "const";
......@@ -1541,6 +1544,7 @@ const char * token_name(TokenId id) {
15411544 case TokenIdKeywordTest: return "test";
15421545 case TokenIdKeywordThis: return "this";
15431546 case TokenIdKeywordTrue: return "true";
1547 case TokenIdKeywordTry: return "try";
15441548 case TokenIdKeywordUndefined: return "undefined";
15451549 case TokenIdKeywordUnion: return "union";
15461550 case TokenIdKeywordUnreachable: return "unreachable";
src/tokenizer.hpp+3-1
......@@ -47,10 +47,10 @@ enum TokenId {
4747 TokenIdFloatLiteral,
4848 TokenIdIntLiteral,
4949 TokenIdKeywordAlign,
50 TokenIdKeywordSection,
5150 TokenIdKeywordAnd,
5251 TokenIdKeywordAsm,
5352 TokenIdKeywordBreak,
53 TokenIdKeywordCatch,
5454 TokenIdKeywordColdCC,
5555 TokenIdKeywordCompTime,
5656 TokenIdKeywordConst,
......@@ -74,12 +74,14 @@ enum TokenId {
7474 TokenIdKeywordPacked,
7575 TokenIdKeywordPub,
7676 TokenIdKeywordReturn,
77 TokenIdKeywordSection,
7778 TokenIdKeywordStdcallCC,
7879 TokenIdKeywordStruct,
7980 TokenIdKeywordSwitch,
8081 TokenIdKeywordTest,
8182 TokenIdKeywordThis,
8283 TokenIdKeywordTrue,
84 TokenIdKeywordTry,
8385 TokenIdKeywordUndefined,
8486 TokenIdKeywordUnion,
8587 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+37-37
......@@ -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
......@@ -300,7 +300,7 @@ pub const Builder = struct {
300300 s.loop_flag = true;
301301
302302 for (s.dependencies.toSlice()) |dep| {
303 self.makeOneStep(dep) %% |err| {
303 self.makeOneStep(dep) catch |err| {
304304 if (err == error.DependencyLoopDetected) {
305305 warn(" {}\n", s.name);
306306 }
......@@ -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 {
......@@ -573,7 +573,7 @@ pub const Builder = struct {
573573 child.cwd = cwd;
574574 child.env_map = env_map;
575575
576 const term = child.spawnAndWait() %% |err| {
576 const term = child.spawnAndWait() catch |err| {
577577 warn("Unable to spawn {}: {}\n", argv[0], @errorName(err));
578578 return err;
579579 };
......@@ -596,7 +596,7 @@ pub const Builder = struct {
596596 }
597597
598598 pub fn makePath(self: &Builder, path: []const u8) -> %void {
599 os.makePath(self.allocator, self.pathFromRoot(path)) %% |err| {
599 os.makePath(self.allocator, self.pathFromRoot(path)) catch |err| {
600600 warn("Unable to create path {}: {}\n", path, @errorName(err));
601601 return err;
602602 };
......@@ -641,11 +641,11 @@ pub const Builder = struct {
641641
642642 const dirname = os.path.dirname(dest_path);
643643 const abs_source_path = self.pathFromRoot(source_path);
644 os.makePath(self.allocator, dirname) %% |err| {
644 os.makePath(self.allocator, dirname) catch |err| {
645645 warn("Unable to create path {}: {}\n", dirname, @errorName(err));
646646 return err;
647647 };
648 os.copyFileMode(self.allocator, abs_source_path, dest_path, mode) %% |err| {
648 os.copyFileMode(self.allocator, abs_source_path, dest_path, mode) catch |err| {
649649 warn("Unable to copy {} to {}: {}\n", abs_source_path, dest_path, @errorName(err));
650650 return err;
651651 };
......@@ -663,7 +663,7 @@ pub const Builder = struct {
663663 if (builtin.environ == builtin.Environ.msvc) {
664664 return "cl.exe";
665665 } else {
666 return os.getEnvVarOwned(self.allocator, "CC") %% |err|
666 return os.getEnvVarOwned(self.allocator, "CC") catch |err|
667667 if (err == error.EnvironmentVariableNotFound)
668668 ([]const u8)("cc")
669669 else
......@@ -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 |_| {
......@@ -723,7 +723,7 @@ pub const Builder = struct {
723723
724724 pub fn exec(self: &Builder, argv: []const []const u8) -> []u8 {
725725 const max_output_size = 100 * 1024;
726 const result = os.ChildProcess.exec(self.allocator, argv, null, null, max_output_size) %% |err| {
726 const result = os.ChildProcess.exec(self.allocator, argv, null, null, max_output_size) catch |err| {
727727 std.debug.panic("Unable to spawn {}: {}", argv[0], @errorName(err));
728728 };
729729 switch (result.term) {
......@@ -800,7 +800,7 @@ const Target = union(enum) {
800800
801801 pub fn isDarwin(self: &const Target) -> bool {
802802 return switch (self.getOs()) {
803 builtin.Os.darwin, builtin.Os.ios, builtin.Os.macosx => true,
803 builtin.Os.ios, builtin.Os.macosx => true,
804804 else => false,
805805 };
806806 }
......@@ -1011,7 +1011,7 @@ pub const LibExeObjStep = struct {
10111011 self.out_filename = self.builder.fmt("lib{}.a", self.name);
10121012 } else {
10131013 switch (self.target.getOs()) {
1014 builtin.Os.darwin, builtin.Os.ios, builtin.Os.macosx => {
1014 builtin.Os.ios, builtin.Os.macosx => {
10151015 self.out_filename = self.builder.fmt("lib{}.{d}.{d}.{d}.dylib",
10161016 self.name, self.version.major, self.version.minor, self.version.patch);
10171017 self.major_only_filename = self.builder.fmt("lib{}.{d}.dylib", self.name, self.version.major);
......@@ -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
......@@ -1895,11 +1895,11 @@ pub const WriteFileStep = struct {
18951895 const self = @fieldParentPtr(WriteFileStep, "step", step);
18961896 const full_path = self.builder.pathFromRoot(self.file_path);
18971897 const full_path_dir = os.path.dirname(full_path);
1898 os.makePath(self.builder.allocator, full_path_dir) %% |err| {
1898 os.makePath(self.builder.allocator, full_path_dir) catch |err| {
18991899 warn("unable to make path {}: {}\n", full_path_dir, @errorName(err));
19001900 return err;
19011901 };
1902 io.writeFile(full_path, self.data, self.builder.allocator) %% |err| {
1902 io.writeFile(full_path, self.data, self.builder.allocator) catch |err| {
19031903 warn("unable to write {}: {}\n", full_path, @errorName(err));
19041904 return err;
19051905 };
......@@ -1942,7 +1942,7 @@ pub const RemoveDirStep = struct {
19421942 const self = @fieldParentPtr(RemoveDirStep, "step", step);
19431943
19441944 const full_path = self.builder.pathFromRoot(self.dir_path);
1945 os.deleteTree(self.builder.allocator, full_path) %% |err| {
1945 os.deleteTree(self.builder.allocator, full_path) catch |err| {
19461946 warn("Unable to remove {}: {}\n", full_path, @errorName(err));
19471947 return err;
19481948 };
......@@ -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
......@@ -1991,13 +1991,13 @@ fn doAtomicSymLinks(allocator: &Allocator, output_path: []const u8, filename_maj
19911991 const out_basename = os.path.basename(output_path);
19921992 // sym link for libfoo.so.1 to libfoo.so.1.2.3
19931993 const major_only_path = %%os.path.join(allocator, out_dir, filename_major_only);
1994 os.atomicSymLink(allocator, out_basename, major_only_path) %% |err| {
1994 os.atomicSymLink(allocator, out_basename, major_only_path) catch |err| {
19951995 warn("Unable to symlink {} -> {}\n", major_only_path, out_basename);
19961996 return err;
19971997 };
19981998 // sym link for libfoo.so to libfoo.so.1
19991999 const name_only_path = %%os.path.join(allocator, out_dir, filename_name_only);
2000 os.atomicSymLink(allocator, filename_major_only, name_only_path) %% |err| {
2000 os.atomicSymLink(allocator, filename_major_only, name_only_path) catch |err| {
20012001 warn("Unable to symlink {} -> {}\n", name_only_path, filename_major_only);
20022002 return err;
20032003 };
std/c/index.zig+1-1
......@@ -4,7 +4,7 @@ const Os = builtin.Os;
44pub use switch(builtin.os) {
55 Os.linux => @import("linux.zig"),
66 Os.windows => @import("windows.zig"),
7 Os.darwin, Os.macosx, Os.ios => @import("darwin.zig"),
7 Os.macosx, Os.ios => @import("darwin.zig"),
88 else => empty_import,
99};
1010const empty_import = @import("../empty.zig");
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+133-133
......@@ -22,14 +22,14 @@ var stderr_file: io.File = undefined;
2222var stderr_file_out_stream: io.FileOutStream = undefined;
2323var stderr_stream: ?&io.OutStream = null;
2424pub fn warn(comptime fmt: []const u8, args: ...) {
25 const stderr = getStderrStream() %% return;
26 stderr.print(fmt, args) %% return;
25 const stderr = getStderrStream() catch return;
26 stderr.print(fmt, args) catch return;
2727}
2828fn 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;
......@@ -39,8 +39,8 @@ fn getStderrStream() -> %&io.OutStream {
3939
4040/// Tries to print a stack trace to stderr, unbuffered, and ignores any error returned.
4141pub fn dumpStackTrace() {
42 const stderr = getStderrStream() %% return;
43 writeStackTrace(stderr, global_allocator, stderr_file.isTty(), 1) %% return;
42 const stderr = getStderrStream() catch return;
43 writeStackTrace(stderr, global_allocator, stderr_file.isTty(), 1) catch return;
4444}
4545
4646/// This function invokes undefined behavior when `ok` is `false`.
......@@ -86,9 +86,9 @@ pub fn panic(comptime format: []const u8, args: ...) -> noreturn {
8686 panicking = true;
8787 }
8888
89 const stderr = getStderrStream() %% os.abort();
90 stderr.print(format ++ "\n", args) %% os.abort();
91 writeStackTrace(stderr, global_allocator, stderr_file.isTty(), 1) %% os.abort();
89 const stderr = getStderrStream() catch os.abort();
90 stderr.print(format ++ "\n", args) catch os.abort();
91 writeStackTrace(stderr, global_allocator, stderr_file.isTty(), 1) catch os.abort();
9292
9393 os.abort();
9494}
......@@ -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
......@@ -146,26 +146,26 @@ pub fn writeStackTrace(out_stream: &io.OutStream, allocator: &mem.Allocator, tty
146146 // at compile time. I'll call it issue #313
147147 const ptr_hex = if (@sizeOf(usize) == 4) "0x{x8}" else "0x{x16}";
148148
149 const compile_unit = findCompileUnit(st, return_address) %% {
150 %return out_stream.print("???:?:?: " ++ DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n ???\n\n",
149 const compile_unit = findCompileUnit(st, return_address) catch {
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,
......@@ -757,8 +757,8 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
757757 });
758758 },
759759 else => {
760 const fwd_amt = math.cast(isize, op_size - 1) %% return error.InvalidDebugInfo;
761 %return in_file.seekForward(fwd_amt);
760 const fwd_amt = math.cast(isize, op_size - 1) catch return error.InvalidDebugInfo;
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/endian.zig+1-1
......@@ -16,5 +16,5 @@ pub fn swapIf(endian: builtin.Endian, comptime T: type, x: T) -> T {
1616pub fn swap(comptime T: type, x: T) -> T {
1717 var buf: [@sizeOf(T)]u8 = undefined;
1818 mem.writeInt(buf[0..], x, false);
19 return mem.readInt(buf, T, true);
19 return mem.readInt(buf, T, builtin.Endian.Big);
2020}
std/fmt/index.zig+35-35
......@@ -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
......@@ -533,7 +533,7 @@ fn bufPrintIntToSlice(buf: []u8, value: var, base: u8, uppercase: bool, width: u
533533}
534534
535535test "parse u64 digit too big" {
536 _ = parseUnsigned(u64, "123a", 10) %% |err| {
536 _ = parseUnsigned(u64, "123a", 10) catch |err| {
537537 if (err == error.InvalidChar) return;
538538 unreachable;
539539 };
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+5-5
......@@ -49,7 +49,7 @@ pub const IncrementingAllocator = struct {
4949
5050 fn init(capacity: usize) -> %IncrementingAllocator {
5151 switch (builtin.os) {
52 Os.linux, Os.darwin, Os.macosx, Os.ios => {
52 Os.linux, Os.macosx, Os.ios => {
5353 const p = os.posix;
5454 const addr = p.mmap(null, capacity, p.PROT_READ|p.PROT_WRITE,
5555 p.MAP_PRIVATE|p.MAP_ANONYMOUS|p.MAP_NORESERVE, -1, 0);
......@@ -87,7 +87,7 @@ pub const IncrementingAllocator = struct {
8787
8888 fn deinit(self: &IncrementingAllocator) {
8989 switch (builtin.os) {
90 Os.linux, Os.darwin, Os.macosx, Os.ios => {
90 Os.linux, Os.macosx, Os.ios => {
9191 _ = os.posix.munmap(self.bytes.ptr, self.bytes.len);
9292 },
9393 Os.windows => {
......@@ -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 }
......@@ -137,9 +137,9 @@ pub const IncrementingAllocator = struct {
137137
138138test "c_allocator" {
139139 if (builtin.link_libc) {
140 var slice = c_allocator.alloc(u8, 50) %% return;
140 var slice = c_allocator.alloc(u8, 50) catch return;
141141 defer c_allocator.free(slice);
142 slice = c_allocator.realloc(u8, slice, 100) %% return;
142 slice = c_allocator.realloc(u8, slice, 100) catch return;
143143 }
144144}
145145
std/io.zig+38-38
......@@ -3,7 +3,7 @@ const builtin = @import("builtin");
33const Os = builtin.Os;
44const system = switch(builtin.os) {
55 Os.linux => @import("os/linux.zig"),
6 Os.darwin, Os.macosx, Os.ios => @import("os/darwin.zig"),
6 Os.macosx, Os.ios => @import("os/darwin.zig"),
77 Os.windows => @import("os/windows/index.zig"),
88 else => @compileError("Unsupported OS"),
99};
......@@ -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);
......@@ -190,7 +190,7 @@ pub const File = struct {
190190
191191 pub fn seekForward(self: &File, amount: isize) -> %void {
192192 switch (builtin.os) {
193 Os.linux, Os.darwin => {
193 Os.linux, Os.macosx, Os.ios => {
194194 const result = system.lseek(self.handle, amount, system.SEEK_CUR);
195195 const err = system.getErrno(result);
196196 if (err > 0) {
......@@ -210,7 +210,7 @@ pub const File = struct {
210210
211211 pub fn seekTo(self: &File, pos: usize) -> %void {
212212 switch (builtin.os) {
213 Os.linux, Os.darwin => {
213 Os.linux, Os.macosx, Os.ios => {
214214 const result = system.lseek(self.handle, @bitCast(isize, pos), system.SEEK_SET);
215215 const err = system.getErrno(result);
216216 if (err > 0) {
......@@ -230,7 +230,7 @@ pub const File = struct {
230230
231231 pub fn getPos(self: &File) -> %usize {
232232 switch (builtin.os) {
233 Os.linux, Os.darwin => {
233 Os.linux, Os.macosx, Os.ios => {
234234 const result = system.lseek(self.handle, 0, system.SEEK_CUR);
235235 const err = system.getErrno(result);
236236 if (err > 0) {
......@@ -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+55-55
......@@ -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();
......@@ -383,27 +383,27 @@ pub const ChildProcess = struct {
383383 // we are the child
384384 restore_SIGCHLD();
385385
386 setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) %%
386 setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch
387387 |err| forkChildErrReport(err_pipe[1], err);
388 setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) %%
388 setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch
389389 |err| forkChildErrReport(err_pipe[1], err);
390 setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) %%
390 setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch
391391 |err| forkChildErrReport(err_pipe[1], err);
392392
393393 if (self.cwd) |cwd| {
394 os.changeCurDir(self.allocator, cwd) %%
394 os.changeCurDir(self.allocator, cwd) catch
395395 |err| forkChildErrReport(err_pipe[1], err);
396396 }
397397
398398 if (self.gid) |gid| {
399 os.posix_setregid(gid, gid) %% |err| forkChildErrReport(err_pipe[1], err);
399 os.posix_setregid(gid, gid) catch |err| forkChildErrReport(err_pipe[1], err);
400400 }
401401
402402 if (self.uid) |uid| {
403 os.posix_setreuid(uid, uid) %% |err| forkChildErrReport(err_pipe[1], err);
403 os.posix_setreuid(uid, uid) catch |err| forkChildErrReport(err_pipe[1], err);
404404 }
405405
406 os.posixExecve(self.argv, env_map, self.allocator) %%
406 os.posixExecve(self.argv, env_map, self.allocator) catch
407407 |err| forkChildErrReport(err_pipe[1], err);
408408 }
409409
......@@ -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,27 +563,27 @@ 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);
574574
575575 windowsCreateProcess(app_name.ptr, cmd_line.ptr, envp_ptr, cwd_ptr,
576 &siStartInfo, &piProcInfo) %% |no_path_err|
576 &siStartInfo, &piProcInfo) catch |no_path_err|
577577 {
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}
......@@ -767,12 +767,12 @@ const ErrInt = @IntType(false, @sizeOf(error) * 8);
767767fn writeIntFd(fd: i32, value: ErrInt) -> %void {
768768 var bytes: [@sizeOf(ErrInt)]u8 = undefined;
769769 mem.writeInt(bytes[0..], value, builtin.endian);
770 os.posixWrite(fd, bytes[0..]) %% return error.SystemResources;
770 os.posixWrite(fd, bytes[0..]) catch return error.SystemResources;
771771}
772772
773773fn readIntFd(fd: i32) -> %ErrInt {
774774 var bytes: [@sizeOf(ErrInt)]u8 = undefined;
775 os.posixRead(fd, bytes[0..]) %% return error.SystemResources;
775 os.posixRead(fd, bytes[0..]) catch return error.SystemResources;
776776 return mem.readInt(bytes[0..], ErrInt, builtin.endian);
777777}
778778
std/os/get_user_id.zig+3-3
......@@ -11,7 +11,7 @@ pub const UserInfo = struct {
1111/// POSIX function which gets a uid from username.
1212pub fn getUserInfo(name: []const u8) -> %UserInfo {
1313 return switch (builtin.os) {
14 Os.linux, Os.darwin, Os.macosx, Os.ios => posixGetUserInfo(name),
14 Os.linux, Os.macosx, Os.ios => posixGetUserInfo(name),
1515 else => @compileError("Unsupported OS"),
1616 };
1717}
......@@ -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+81-79
......@@ -7,9 +7,11 @@ const os = this;
77pub const windows = @import("windows/index.zig");
88pub const darwin = @import("darwin.zig");
99pub const linux = @import("linux.zig");
10pub const zen = @import("zen.zig");
1011pub const posix = switch(builtin.os) {
1112 Os.linux => linux,
12 Os.darwin, Os.macosx, Os.ios => darwin,
13 Os.macosx, Os.ios => darwin,
14 Os.zen => zen,
1315 else => @compileError("Unsupported OS"),
1416};
1517
......@@ -89,12 +91,12 @@ pub fn getRandomBytes(buf: []u8) -> %void {
8991 }
9092 return;
9193 },
92 Os.darwin, Os.macosx, Os.ios => {
93 const fd = %return posixOpen("/dev/urandom", posix.O_RDONLY|posix.O_CLOEXEC,
94 Os.macosx, Os.ios => {
95 const fd = try posixOpen("/dev/urandom", posix.O_RDONLY|posix.O_CLOEXEC,
9496 0, null);
9597 defer close(fd);
9698
97 %return posixRead(fd, buf);
99 try posixRead(fd, buf);
98100 },
99101 Os.windows => {
100102 var hCryptProv: windows.HCRYPTPROV = undefined;
......@@ -130,7 +132,7 @@ pub coldcc fn abort() -> noreturn {
130132 c.abort();
131133 }
132134 switch (builtin.os) {
133 Os.linux, Os.darwin, Os.macosx, Os.ios => {
135 Os.linux, Os.macosx, Os.ios => {
134136 _ = posix.raise(posix.SIGABRT);
135137 _ = posix.raise(posix.SIGKILL);
136138 while (true) {}
......@@ -151,7 +153,7 @@ pub coldcc fn exit(status: i32) -> noreturn {
151153 c.exit(status);
152154 }
153155 switch (builtin.os) {
154 Os.linux, Os.darwin, Os.macosx, Os.ios => {
156 Os.linux, Os.macosx, Os.ios => {
155157 posix.exit(status);
156158 },
157159 Os.windows => {
......@@ -254,7 +256,7 @@ pub fn posixOpen(file_path: []const u8, flags: u32, perm: usize, allocator: ?&Al
254256 if (file_path.len < stack_buf.len) {
255257 path0 = stack_buf[0..file_path.len + 1];
256258 } else if (allocator) |a| {
257 path0 = %return a.alloc(u8, file_path.len + 1);
259 path0 = try a.alloc(u8, file_path.len + 1);
258260 need_free = true;
259261 } else {
260262 return error.NameTooLong;
......@@ -312,14 +314,14 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) -> %void {
312314
313315pub fn createNullDelimitedEnvMap(allocator: &Allocator, env_map: &const BufMap) -> %[]?&u8 {
314316 const envp_count = env_map.count();
315 const envp_buf = %return allocator.alloc(?&u8, envp_count + 1);
317 const envp_buf = try allocator.alloc(?&u8, envp_count + 1);
316318 mem.set(?&u8, envp_buf, null);
317319 %defer freeNullDelimitedEnvMap(allocator, envp_buf);
318320 {
319321 var it = env_map.iterator();
320322 var i: usize = 0;
321323 while (it.next()) |pair| : (i += 1) {
322 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);
323325 @memcpy(&env_buf[0], pair.key.ptr, pair.key.len);
324326 env_buf[pair.key.len] = '=';
325327 @memcpy(&env_buf[pair.key.len + 1], pair.value.ptr, pair.value.len);
......@@ -349,7 +351,7 @@ pub fn freeNullDelimitedEnvMap(allocator: &Allocator, envp_buf: []?&u8) {
349351pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap,
350352 allocator: &Allocator) -> %void
351353{
352 const argv_buf = %return allocator.alloc(?&u8, argv.len + 1);
354 const argv_buf = try allocator.alloc(?&u8, argv.len + 1);
353355 mem.set(?&u8, argv_buf, null);
354356 defer {
355357 for (argv_buf) |arg| {
......@@ -359,7 +361,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap,
359361 allocator.free(argv_buf);
360362 }
361363 for (argv) |arg, i| {
362 const arg_buf = %return allocator.alloc(u8, arg.len + 1);
364 const arg_buf = try allocator.alloc(u8, arg.len + 1);
363365 @memcpy(&arg_buf[0], arg.ptr, arg.len);
364366 arg_buf[arg.len] = 0;
365367
......@@ -367,7 +369,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap,
367369 }
368370 argv_buf[argv.len] = null;
369371
370 const envp_buf = %return createNullDelimitedEnvMap(allocator, env_map);
372 const envp_buf = try createNullDelimitedEnvMap(allocator, env_map);
371373 defer freeNullDelimitedEnvMap(allocator, envp_buf);
372374
373375 const exe_path = argv[0];
......@@ -379,7 +381,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap,
379381 // PATH.len because it is >= the largest search_path
380382 // +1 for the / to join the search path and exe_path
381383 // +1 for the null terminating byte
382 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);
383385 defer allocator.free(path_buf);
384386 var it = mem.split(PATH, ":");
385387 var seen_eacces = false;
......@@ -448,7 +450,7 @@ pub fn getEnvMap(allocator: &Allocator) -> %BufMap {
448450
449451 i += 1; // skip over null byte
450452
451 %return result.set(key, value);
453 try result.set(key, value);
452454 }
453455 } else {
454456 for (posix_environ_raw) |ptr| {
......@@ -460,7 +462,7 @@ pub fn getEnvMap(allocator: &Allocator) -> %BufMap {
460462 while (ptr[end_i] != 0) : (end_i += 1) {}
461463 const value = ptr[line_i + 1..end_i];
462464
463 %return result.set(key, value);
465 try result.set(key, value);
464466 }
465467 return result;
466468 }
......@@ -488,14 +490,14 @@ error EnvironmentVariableNotFound;
488490/// Caller must free returned memory.
489491pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) -> %[]u8 {
490492 if (is_windows) {
491 const key_with_null = %return cstr.addNullByte(allocator, key);
493 const key_with_null = try cstr.addNullByte(allocator, key);
492494 defer allocator.free(key_with_null);
493495
494 var buf = %return allocator.alloc(u8, 256);
496 var buf = try allocator.alloc(u8, 256);
495497 %defer allocator.free(buf);
496498
497499 while (true) {
498 const windows_buf_len = %return math.cast(windows.DWORD, buf.len);
500 const windows_buf_len = try math.cast(windows.DWORD, buf.len);
499501 const result = windows.GetEnvironmentVariableA(key_with_null.ptr, buf.ptr, windows_buf_len);
500502
501503 if (result == 0) {
......@@ -507,7 +509,7 @@ pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) -> %[]u8 {
507509 }
508510
509511 if (result > buf.len) {
510 buf = %return allocator.realloc(u8, buf, result);
512 buf = try allocator.realloc(u8, buf, result);
511513 continue;
512514 }
513515
......@@ -523,7 +525,7 @@ pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) -> %[]u8 {
523525pub fn getCwd(allocator: &Allocator) -> %[]u8 {
524526 switch (builtin.os) {
525527 Os.windows => {
526 var buf = %return allocator.alloc(u8, 256);
528 var buf = try allocator.alloc(u8, 256);
527529 %defer allocator.free(buf);
528530
529531 while (true) {
......@@ -537,7 +539,7 @@ pub fn getCwd(allocator: &Allocator) -> %[]u8 {
537539 }
538540
539541 if (result > buf.len) {
540 buf = %return allocator.realloc(u8, buf, result);
542 buf = try allocator.realloc(u8, buf, result);
541543 continue;
542544 }
543545
......@@ -545,12 +547,12 @@ pub fn getCwd(allocator: &Allocator) -> %[]u8 {
545547 }
546548 },
547549 else => {
548 var buf = %return allocator.alloc(u8, 1024);
550 var buf = try allocator.alloc(u8, 1024);
549551 %defer allocator.free(buf);
550552 while (true) {
551553 const err = posix.getErrno(posix.getcwd(buf.ptr, buf.len));
552554 if (err == posix.ERANGE) {
553 buf = %return allocator.realloc(u8, buf, buf.len * 2);
555 buf = try allocator.realloc(u8, buf, buf.len * 2);
554556 continue;
555557 } else if (err > 0) {
556558 return unexpectedErrorPosix(err);
......@@ -576,9 +578,9 @@ pub fn symLink(allocator: &Allocator, existing_path: []const u8, new_path: []con
576578}
577579
578580pub fn symLinkWindows(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) -> %void {
579 const existing_with_null = %return cstr.addNullByte(allocator, existing_path);
581 const existing_with_null = try cstr.addNullByte(allocator, existing_path);
580582 defer allocator.free(existing_with_null);
581 const new_with_null = %return cstr.addNullByte(allocator, new_path);
583 const new_with_null = try cstr.addNullByte(allocator, new_path);
582584 defer allocator.free(new_with_null);
583585
584586 if (windows.CreateSymbolicLinkA(existing_with_null.ptr, new_with_null.ptr, 0) == 0) {
......@@ -590,7 +592,7 @@ pub fn symLinkWindows(allocator: &Allocator, existing_path: []const u8, new_path
590592}
591593
592594pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) -> %void {
593 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);
594596 defer allocator.free(full_buf);
595597
596598 const existing_buf = full_buf;
......@@ -636,11 +638,11 @@ pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path:
636638 }
637639
638640 var rand_buf: [12]u8 = undefined;
639 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));
640642 defer allocator.free(tmp_path);
641643 mem.copy(u8, tmp_path[0..], new_path);
642644 while (true) {
643 %return getRandomBytes(rand_buf[0..]);
645 try getRandomBytes(rand_buf[0..]);
644646 b64_fs_encoder.encode(tmp_path[new_path.len..], rand_buf);
645647 if (symLink(allocator, existing_path, tmp_path)) {
646648 return rename(allocator, tmp_path, new_path);
......@@ -667,7 +669,7 @@ error FileNotFound;
667669error AccessDenied;
668670
669671pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) -> %void {
670 const buf = %return allocator.alloc(u8, file_path.len + 1);
672 const buf = try allocator.alloc(u8, file_path.len + 1);
671673 defer allocator.free(buf);
672674
673675 mem.copy(u8, buf, file_path);
......@@ -685,7 +687,7 @@ pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) -> %void
685687}
686688
687689pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) -> %void {
688 const buf = %return allocator.alloc(u8, file_path.len + 1);
690 const buf = try allocator.alloc(u8, file_path.len + 1);
689691 defer allocator.free(buf);
690692
691693 mem.copy(u8, buf, file_path);
......@@ -719,30 +721,30 @@ pub fn copyFile(allocator: &Allocator, source_path: []const u8, dest_path: []con
719721/// Guaranteed to be atomic.
720722pub fn copyFileMode(allocator: &Allocator, source_path: []const u8, dest_path: []const u8, mode: usize) -> %void {
721723 var rand_buf: [12]u8 = undefined;
722 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));
723725 defer allocator.free(tmp_path);
724726 mem.copy(u8, tmp_path[0..], dest_path);
725 %return getRandomBytes(rand_buf[0..]);
727 try getRandomBytes(rand_buf[0..]);
726728 b64_fs_encoder.encode(tmp_path[dest_path.len..], rand_buf);
727729
728 var out_file = %return io.File.openWriteMode(tmp_path, mode, allocator);
730 var out_file = try io.File.openWriteMode(tmp_path, mode, allocator);
729731 defer out_file.close();
730732 %defer _ = deleteFile(allocator, tmp_path);
731733
732 var in_file = %return io.File.openRead(source_path, allocator);
734 var in_file = try io.File.openRead(source_path, allocator);
733735 defer in_file.close();
734736
735737 var buf: [page_size]u8 = undefined;
736738 while (true) {
737 const amt = %return in_file.read(buf[0..]);
738 %return out_file.write(buf[0..amt]);
739 const amt = try in_file.read(buf[0..]);
740 try out_file.write(buf[0..amt]);
739741 if (amt != buf.len)
740742 return rename(allocator, tmp_path, dest_path);
741743 }
742744}
743745
744746pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) -> %void {
745 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);
746748 defer allocator.free(full_buf);
747749
748750 const old_buf = full_buf;
......@@ -795,7 +797,7 @@ pub fn makeDir(allocator: &Allocator, dir_path: []const u8) -> %void {
795797}
796798
797799pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) -> %void {
798 const path_buf = %return cstr.addNullByte(allocator, dir_path);
800 const path_buf = try cstr.addNullByte(allocator, dir_path);
799801 defer allocator.free(path_buf);
800802
801803 if (windows.CreateDirectoryA(path_buf.ptr, null) == 0) {
......@@ -809,7 +811,7 @@ pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) -> %void {
809811}
810812
811813pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) -> %void {
812 const path_buf = %return cstr.addNullByte(allocator, dir_path);
814 const path_buf = try cstr.addNullByte(allocator, dir_path);
813815 defer allocator.free(path_buf);
814816
815817 const err = posix.getErrno(posix.mkdir(path_buf.ptr, 0o755));
......@@ -835,12 +837,12 @@ pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) -> %void {
835837/// Calls makeDir recursively to make an entire path. Returns success if the path
836838/// already exists and is a directory.
837839pub fn makePath(allocator: &Allocator, full_path: []const u8) -> %void {
838 const resolved_path = %return path.resolve(allocator, full_path);
840 const resolved_path = try path.resolve(allocator, full_path);
839841 defer allocator.free(resolved_path);
840842
841843 var end_index: usize = resolved_path.len;
842844 while (true) {
843 makeDir(allocator, resolved_path[0..end_index]) %% |err| {
845 makeDir(allocator, resolved_path[0..end_index]) catch |err| {
844846 if (err == error.PathAlreadyExists) {
845847 // TODO stat the file and return an error if it's not a directory
846848 // this is important because otherwise a dangling symlink
......@@ -873,7 +875,7 @@ pub fn makePath(allocator: &Allocator, full_path: []const u8) -> %void {
873875/// Returns ::error.DirNotEmpty if the directory is not empty.
874876/// To delete a directory recursively, see ::deleteTree
875877pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) -> %void {
876 const path_buf = %return allocator.alloc(u8, dir_path.len + 1);
878 const path_buf = try allocator.alloc(u8, dir_path.len + 1);
877879 defer allocator.free(path_buf);
878880
879881 mem.copy(u8, path_buf, dir_path);
......@@ -913,7 +915,7 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) -> %void {
913915 return err;
914916 }
915917 {
916 var dir = Dir.open(allocator, full_path) %% |err| {
918 var dir = Dir.open(allocator, full_path) catch |err| {
917919 if (err == error.FileNotFound)
918920 return;
919921 if (err == error.NotDir)
......@@ -925,14 +927,14 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) -> %void {
925927 var full_entry_buf = ArrayList(u8).init(allocator);
926928 defer full_entry_buf.deinit();
927929
928 while (%return dir.next()) |entry| {
929 %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);
930932 const full_entry_path = full_entry_buf.toSlice();
931933 mem.copy(u8, full_entry_path, full_path);
932934 full_entry_path[full_path.len] = '/';
933935 mem.copy(u8, full_entry_path[full_path.len + 1..], entry.name);
934936
935 %return deleteTree(allocator, full_entry_path);
937 try deleteTree(allocator, full_entry_path);
936938 }
937939 }
938940 return deleteDir(allocator, full_path);
......@@ -971,7 +973,7 @@ pub const Dir = struct {
971973 };
972974
973975 pub fn open(allocator: &Allocator, dir_path: []const u8) -> %Dir {
974 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);
975977 return Dir {
976978 .allocator = allocator,
977979 .fd = fd,
......@@ -992,7 +994,7 @@ pub const Dir = struct {
992994 start_over: while (true) {
993995 if (self.index >= self.end_index) {
994996 if (self.buf.len == 0) {
995 self.buf = %return self.allocator.alloc(u8, page_size);
997 self.buf = try self.allocator.alloc(u8, page_size);
996998 }
997999
9981000 while (true) {
......@@ -1002,7 +1004,7 @@ pub const Dir = struct {
10021004 switch (err) {
10031005 posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable,
10041006 posix.EINVAL => {
1005 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);
10061008 continue;
10071009 },
10081010 else => return unexpectedErrorPosix(err),
......@@ -1046,7 +1048,7 @@ pub const Dir = struct {
10461048};
10471049
10481050pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) -> %void {
1049 const path_buf = %return allocator.alloc(u8, dir_path.len + 1);
1051 const path_buf = try allocator.alloc(u8, dir_path.len + 1);
10501052 defer allocator.free(path_buf);
10511053
10521054 mem.copy(u8, path_buf, dir_path);
......@@ -1070,13 +1072,13 @@ pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) -> %void {
10701072
10711073/// Read value of a symbolic link.
10721074pub fn readLink(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
1073 const path_buf = %return allocator.alloc(u8, pathname.len + 1);
1075 const path_buf = try allocator.alloc(u8, pathname.len + 1);
10741076 defer allocator.free(path_buf);
10751077
10761078 mem.copy(u8, path_buf, pathname);
10771079 path_buf[pathname.len] = 0;
10781080
1079 var result_buf = %return allocator.alloc(u8, 1024);
1081 var result_buf = try allocator.alloc(u8, 1024);
10801082 %defer allocator.free(result_buf);
10811083 while (true) {
10821084 const ret_val = posix.readlink(path_buf.ptr, result_buf.ptr, result_buf.len);
......@@ -1095,7 +1097,7 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
10951097 };
10961098 }
10971099 if (ret_val == result_buf.len) {
1098 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);
10991101 continue;
11001102 }
11011103 return allocator.shrink(u8, result_buf, ret_val);
......@@ -1104,7 +1106,7 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
11041106
11051107pub fn sleep(seconds: usize, nanoseconds: usize) {
11061108 switch(builtin.os) {
1107 Os.linux, Os.darwin, Os.macosx, Os.ios => {
1109 Os.linux, Os.macosx, Os.ios => {
11081110 posixSleep(u63(seconds), u63(nanoseconds));
11091111 },
11101112 Os.windows => {
......@@ -1318,7 +1320,7 @@ pub const ArgIteratorWindows = struct {
13181320 }
13191321
13201322 fn internalNext(self: &ArgIteratorWindows, allocator: &Allocator) -> %[]u8 {
1321 var buf = %return Buffer.initSize(allocator, 0);
1323 var buf = try Buffer.initSize(allocator, 0);
13221324 defer buf.deinit();
13231325
13241326 var backslash_count: usize = 0;
......@@ -1328,34 +1330,34 @@ pub const ArgIteratorWindows = struct {
13281330 0 => return buf.toOwnedSlice(),
13291331 '"' => {
13301332 const quote_is_real = backslash_count % 2 == 0;
1331 %return self.emitBackslashes(&buf, backslash_count / 2);
1333 try self.emitBackslashes(&buf, backslash_count / 2);
13321334 backslash_count = 0;
13331335
13341336 if (quote_is_real) {
13351337 self.seen_quote_count += 1;
13361338 if (self.seen_quote_count == self.quote_count and self.seen_quote_count % 2 == 1) {
1337 %return buf.appendByte('"');
1339 try buf.appendByte('"');
13381340 }
13391341 } else {
1340 %return buf.appendByte('"');
1342 try buf.appendByte('"');
13411343 }
13421344 },
13431345 '\\' => {
13441346 backslash_count += 1;
13451347 },
13461348 ' ', '\t' => {
1347 %return self.emitBackslashes(&buf, backslash_count);
1349 try self.emitBackslashes(&buf, backslash_count);
13481350 backslash_count = 0;
13491351 if (self.seen_quote_count % 2 == 1 and self.seen_quote_count != self.quote_count) {
1350 %return buf.appendByte(byte);
1352 try buf.appendByte(byte);
13511353 } else {
13521354 return buf.toOwnedSlice();
13531355 }
13541356 },
13551357 else => {
1356 %return self.emitBackslashes(&buf, backslash_count);
1358 try self.emitBackslashes(&buf, backslash_count);
13571359 backslash_count = 0;
1358 %return buf.appendByte(byte);
1360 try buf.appendByte(byte);
13591361 },
13601362 }
13611363 }
......@@ -1364,7 +1366,7 @@ pub const ArgIteratorWindows = struct {
13641366 fn emitBackslashes(self: &ArgIteratorWindows, buf: &Buffer, emit_count: usize) -> %void {
13651367 var i: usize = 0;
13661368 while (i < emit_count) : (i += 1) {
1367 %return buf.appendByte('\\');
1369 try buf.appendByte('\\');
13681370 }
13691371 }
13701372
......@@ -1428,24 +1430,24 @@ pub fn args() -> ArgIterator {
14281430pub fn argsAlloc(allocator: &mem.Allocator) -> %[]const []u8 {
14291431 // TODO refactor to only make 1 allocation.
14301432 var it = args();
1431 var contents = %return Buffer.initSize(allocator, 0);
1433 var contents = try Buffer.initSize(allocator, 0);
14321434 defer contents.deinit();
14331435
14341436 var slice_list = ArrayList(usize).init(allocator);
14351437 defer slice_list.deinit();
14361438
14371439 while (it.next(allocator)) |arg_or_err| {
1438 const arg = %return arg_or_err;
1440 const arg = try arg_or_err;
14391441 defer allocator.free(arg);
1440 %return contents.append(arg);
1441 %return slice_list.append(arg.len);
1442 try contents.append(arg);
1443 try slice_list.append(arg.len);
14421444 }
14431445
14441446 const contents_slice = contents.toSliceConst();
14451447 const slice_sizes = slice_list.toSliceConst();
1446 const slice_list_bytes = %return math.mul(usize, @sizeOf([]u8), slice_sizes.len);
1447 const total_bytes = %return math.add(usize, slice_list_bytes, contents_slice.len);
1448 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);
14491451 %defer allocator.free(buf);
14501452
14511453 const result_slice_list = ([][]u8)(buf[0..slice_list_bytes]);
......@@ -1537,7 +1539,7 @@ pub fn openSelfExe() -> %io.File {
15371539 Os.linux => {
15381540 return io.File.openRead("/proc/self/exe", null);
15391541 },
1540 Os.darwin => {
1542 Os.macosx, Os.ios => {
15411543 @panic("TODO: openSelfExe on Darwin");
15421544 },
15431545 else => @compileError("Unsupported OS"),
......@@ -1558,10 +1560,10 @@ pub fn selfExePath(allocator: &mem.Allocator) -> %[]u8 {
15581560 return readLink(allocator, "/proc/self/exe");
15591561 },
15601562 Os.windows => {
1561 var out_path = %return Buffer.initSize(allocator, 0xff);
1563 var out_path = try Buffer.initSize(allocator, 0xff);
15621564 %defer out_path.deinit();
15631565 while (true) {
1564 const dword_len = %return math.cast(windows.DWORD, out_path.len());
1566 const dword_len = try math.cast(windows.DWORD, out_path.len());
15651567 const copied_amt = windows.GetModuleFileNameA(null, out_path.ptr(), dword_len);
15661568 if (copied_amt <= 0) {
15671569 const err = windows.GetLastError();
......@@ -1574,14 +1576,14 @@ pub fn selfExePath(allocator: &mem.Allocator) -> %[]u8 {
15741576 return out_path.toOwnedSlice();
15751577 }
15761578 const new_len = (out_path.len() << 1) | 0b1;
1577 %return out_path.resize(new_len);
1579 try out_path.resize(new_len);
15781580 }
15791581 },
1580 Os.darwin, Os.macosx, Os.ios => {
1582 Os.macosx, Os.ios => {
15811583 var u32_len: u32 = 0;
15821584 const ret1 = c._NSGetExecutablePath(undefined, &u32_len);
15831585 assert(ret1 != 0);
1584 const bytes = %return allocator.alloc(u8, u32_len);
1586 const bytes = try allocator.alloc(u8, u32_len);
15851587 %defer allocator.free(bytes);
15861588 const ret2 = c._NSGetExecutablePath(bytes.ptr, &u32_len);
15871589 assert(ret2 == 0);
......@@ -1600,13 +1602,13 @@ pub fn selfExeDirPath(allocator: &mem.Allocator) -> %[]u8 {
16001602 // the file path looks something like `/a/b/c/exe (deleted)`
16011603 // This path cannot be opened, but it's valid for determining the directory
16021604 // the executable was in when it was run.
1603 const full_exe_path = %return readLink(allocator, "/proc/self/exe");
1605 const full_exe_path = try readLink(allocator, "/proc/self/exe");
16041606 %defer allocator.free(full_exe_path);
16051607 const dir = path.dirname(full_exe_path);
16061608 return allocator.shrink(u8, full_exe_path, dir.len);
16071609 },
1608 Os.windows, Os.darwin, Os.macosx, Os.ios => {
1609 const self_exe_path = %return selfExePath(allocator);
1610 Os.windows, Os.macosx, Os.ios => {
1611 const self_exe_path = try selfExePath(allocator);
16101612 %defer allocator.free(self_exe_path);
16111613 const dirname = os.path.dirname(self_exe_path);
16121614 return allocator.shrink(u8, self_exe_path, dirname.len);
std/os/path.zig+23-23
......@@ -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,10 +1099,10 @@ 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) {
1105 const buf_len = math.cast(windows.DWORD, buf.len) %% return error.NameTooLong;
1105 const buf_len = math.cast(windows.DWORD, buf.len) catch return error.NameTooLong;
11061106 const result = windows.GetFinalPathNameByHandleA(h_file, buf.ptr, buf_len, windows.VOLUME_NAME_DOS);
11071107
11081108 if (result == 0) {
......@@ -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
......@@ -1137,13 +1137,13 @@ pub fn real(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
11371137 return allocator.shrink(u8, buf, final_len);
11381138 }
11391139 },
1140 Os.darwin, Os.macosx, Os.ios => {
1140 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+4-4
......@@ -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}
......@@ -166,7 +166,7 @@ pub fn windowsUnloadDll(hModule: windows.HMODULE) {
166166test "InvalidDll" {
167167 const DllName = "asdf.dll";
168168 const allocator = std.debug.global_allocator;
169 const handle = os.windowsLoadDll(allocator, DllName) %% |err| {
169 const handle = os.windowsLoadDll(allocator, DllName) catch |err| {
170170 assert(err == error.DllNotFound);
171171 return;
172172 };
std/os/zen.zig created+94
......@@ -0,0 +1,94 @@
1//////////////////////////////
2//// Reserved mailboxes ////
3//////////////////////////////
4
5pub const MBOX_TERMINAL = 1;
6
7
8///////////////////////////
9//// Syscall numbers ////
10///////////////////////////
11
12pub const SYS_createMailbox = 0;
13pub const SYS_send = 1;
14pub const SYS_receive = 2;
15pub const SYS_map = 3;
16
17
18////////////////////
19//// Syscalls ////
20////////////////////
21
22pub fn createMailbox(id: u16) {
23 _ = syscall1(SYS_createMailbox, id);
24}
25
26pub fn send(mailbox_id: u16, data: usize) {
27 _ = syscall2(SYS_send, mailbox_id, data);
28}
29
30pub fn receive(mailbox_id: u16) -> usize {
31 return syscall1(SYS_receive, mailbox_id);
32}
33
34pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) -> bool {
35 return syscall4(SYS_map, v_addr, p_addr, size, usize(writable)) != 0;
36}
37
38
39/////////////////////////
40//// Syscall stubs ////
41/////////////////////////
42
43pub inline fn syscall0(number: usize) -> usize {
44 return asm volatile ("int $0x80"
45 : [ret] "={eax}" (-> usize)
46 : [number] "{eax}" (number));
47}
48
49pub inline fn syscall1(number: usize, arg1: usize) -> usize {
50 return asm volatile ("int $0x80"
51 : [ret] "={eax}" (-> usize)
52 : [number] "{eax}" (number),
53 [arg1] "{ecx}" (arg1));
54}
55
56pub inline fn syscall2(number: usize, arg1: usize, arg2: usize) -> usize {
57 return asm volatile ("int $0x80"
58 : [ret] "={eax}" (-> usize)
59 : [number] "{eax}" (number),
60 [arg1] "{ecx}" (arg1),
61 [arg2] "{edx}" (arg2));
62}
63
64pub inline fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) -> usize {
65 return asm volatile ("int $0x80"
66 : [ret] "={eax}" (-> usize)
67 : [number] "{eax}" (number),
68 [arg1] "{ecx}" (arg1),
69 [arg2] "{edx}" (arg2),
70 [arg3] "{ebx}" (arg3));
71}
72
73pub inline fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) -> usize {
74 return asm volatile ("int $0x80"
75 : [ret] "={eax}" (-> usize)
76 : [number] "{eax}" (number),
77 [arg1] "{ecx}" (arg1),
78 [arg2] "{edx}" (arg2),
79 [arg3] "{ebx}" (arg3),
80 [arg4] "{esi}" (arg4));
81}
82
83pub inline fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize,
84 arg4: usize, arg5: usize) -> usize
85{
86 return asm volatile ("int $0x80"
87 : [ret] "={eax}" (-> usize)
88 : [number] "{eax}" (number),
89 [arg1] "{ecx}" (arg1),
90 [arg2] "{edx}" (arg2),
91 [arg3] "{ebx}" (arg3),
92 [arg4] "{esi}" (arg4),
93 [arg5] "{edi}" (arg5));
94}
std/rand.zig+1-1
......@@ -43,7 +43,7 @@ pub const Rand = struct {
4343 } else {
4444 var result: [@sizeOf(T)]u8 = undefined;
4545 r.fillBytes(result[0..]);
46 return mem.readInt(result, T, false);
46 return mem.readInt(result, T, builtin.Endian.Little);
4747 }
4848 }
4949
std/special/bootstrap.zig+11-3
......@@ -11,6 +11,8 @@ comptime {
1111 const strong_linkage = builtin.GlobalLinkage.Strong;
1212 if (builtin.link_libc) {
1313 @export("main", main, strong_linkage);
14 } else if (builtin.os == builtin.Os.zen) {
15 @export("main", zenMain, strong_linkage);
1416 } else if (builtin.os == builtin.Os.windows) {
1517 @export("WinMainCRTStartup", WinMainCRTStartup, strong_linkage);
1618 } else {
......@@ -18,6 +20,12 @@ comptime {
1820 }
1921}
2022
23extern fn zenMain() -> noreturn {
24 // TODO: call exit.
25 root.main() catch {};
26 while (true) {}
27}
28
2129nakedcc fn _start() -> noreturn {
2230 switch (builtin.arch) {
2331 builtin.Arch.x86_64 => {
......@@ -36,7 +44,7 @@ nakedcc fn _start() -> noreturn {
3644extern fn WinMainCRTStartup() -> noreturn {
3745 @setAlignStack(16);
3846
39 root.main() %% std.os.windows.ExitProcess(1);
47 root.main() catch std.os.windows.ExitProcess(1);
4048 std.os.windows.ExitProcess(0);
4149}
4250
......@@ -44,7 +52,7 @@ fn posixCallMainAndExit() -> noreturn {
4452 const argc = *argc_ptr;
4553 const argv = @ptrCast(&&u8, &argc_ptr[1]);
4654 const envp = @ptrCast(&?&u8, &argv[argc + 1]);
47 callMain(argc, argv, envp) %% std.os.posix.exit(1);
55 callMain(argc, argv, envp) catch std.os.posix.exit(1);
4856 std.os.posix.exit(0);
4957}
5058
......@@ -59,6 +67,6 @@ fn callMain(argc: usize, argv: &&u8, envp: &?&u8) -> %void {
5967}
6068
6169extern fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) -> i32 {
62 callMain(usize(c_argc), c_argv, c_envp) %% return 1;
70 callMain(usize(c_argc), c_argv, c_envp) catch return 1;
6371 return 0;
6472}
std/special/build_runner.zig+25-25
......@@ -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
120 builder.make(targets.toSliceConst()) %% |err| {
120 builder.make(targets.toSliceConst()) catch |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
......@@ -184,12 +184,12 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: &io.OutStream)
184184}
185185
186186fn usageAndErr(builder: &Builder, already_ran_build: bool, out_stream: &io.OutStream) -> error {
187 usage(builder, already_ran_build, out_stream) %% {};
187 usage(builder, already_ran_build, out_stream) catch {};
188188 return error.InvalidArgs;
189189}
190190
191191fn unwrapArg(arg: %[]u8) -> %[]u8 {
192 return arg %% |err| {
192 return arg catch |err| {
193193 warn("Unable to parse command line: {}\n", err);
194194 return err;
195195 };
std/special/panic.zig+8-4
......@@ -6,9 +6,13 @@
66const builtin = @import("builtin");
77
88pub coldcc fn panic(msg: []const u8) -> noreturn {
9 if (builtin.os == builtin.Os.freestanding) {
10 while (true) {}
11 } else {
12 @import("std").debug.panic("{}", msg);
9 switch (builtin.os) {
10 // TODO: fix panic in zen.
11 builtin.Os.freestanding, builtin.Os.zen => {
12 while (true) {}
13 },
14 else => {
15 @import("std").debug.panic("{}", msg);
16 },
1317 }
1418}
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/defer.zig+1-1
......@@ -18,7 +18,7 @@ test "mixing normal and error defers" {
1818 assert(result[0] == 'c');
1919 assert(result[1] == 'a');
2020
21 const ok = runSomeErrorDefers(false) %% |err| x: {
21 const ok = runSomeErrorDefers(false) catch |err| x: {
2222 assert(err == error.FalseNotAllowed);
2323 break :x true;
2424 };
test/cases/error.zig+5-5
......@@ -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
......@@ -11,7 +11,7 @@ pub fn bar() -> %i32 {
1111}
1212
1313pub fn baz() -> %i32 {
14 const y = foo() %% 1234;
14 const y = foo() catch 1234;
1515 return y + 1;
1616}
1717
......@@ -53,8 +53,8 @@ fn shouldBeNotEqual(a: error, b: error) {
5353
5454
5555test "error binary operator" {
56 const a = errBinaryOperatorG(true) %% 3;
57 const b = errBinaryOperatorG(false) %% 3;
56 const a = errBinaryOperatorG(true) catch 3;
57 const b = errBinaryOperatorG(false) catch 3;
5858 assert(a == 3);
5959 assert(b == 10);
6060}
......@@ -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/misc.zig+31
......@@ -577,3 +577,34 @@ test "implicit comptime while" {
577577 @compileError("bad");
578578 }
579579}
580
581test "struct inside function" {
582 testStructInFn();
583 comptime testStructInFn();
584}
585
586fn testStructInFn() {
587 const BlockKind = u32;
588
589 const Block = struct {
590 kind: BlockKind,
591 };
592
593 var block = Block { .kind = 1234 };
594
595 block.kind += 1;
596
597 assert(block.kind == 1235);
598}
599
600fn fnThatClosesOverLocalConst() -> type {
601 const c = 1;
602 return struct {
603 fn g() -> i32 { return c; }
604 };
605}
606
607test "function closes over local const" {
608 const x = fnThatClosesOverLocalConst().g();
609 assert(x == 1);
610}
test/cases/switch.zig+1-1
......@@ -230,7 +230,7 @@ fn return_a_number() -> %i32 {
230230}
231231
232232test "capture value of switch with all unreachable prongs" {
233 const x = return_a_number() %% |err| switch (err) {
233 const x = return_a_number() catch |err| switch (err) {
234234 else => unreachable,
235235 };
236236 assert(x == 1);
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+10-10
......@@ -395,14 +395,14 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
395395 cases.add("%defer and it fails",
396396 \\const io = @import("std").io;
397397 \\pub fn main() -> %void {
398 \\ do_test() %% return;
398 \\ do_test() catch return;
399399 \\}
400400 \\fn do_test() -> %void {
401401 \\ const stdout = &(io.FileOutStream.init(&%%io.getStdOut()).stream);
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 \\}
......@@ -415,14 +415,14 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
415415 cases.add("%defer and it passes",
416416 \\const io = @import("std").io;
417417 \\pub fn main() -> %void {
418 \\ do_test() %% return;
418 \\ do_test() catch return;
419419 \\}
420420 \\fn do_test() -> %void {
421421 \\ const stdout = &(io.FileOutStream.init(&%%io.getStdOut()).stream);
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+16-4
......@@ -1,6 +1,18 @@
11const tests = @import("tests.zig");
22
33pub fn addCases(cases: &tests.CompileErrorContext) {
4 cases.add("bad identifier in function with struct defined inside function which references local const",
5 \\export fn entry() {
6 \\ const BlockKind = u32;
7 \\
8 \\ const Block = struct {
9 \\ kind: BlockKind,
10 \\ };
11 \\
12 \\ bogus;
13 \\}
14 , ".tmp_source.zig:8:5: error: use of undeclared identifier 'bogus'");
15
416 cases.add("labeled break not found",
517 \\export fn entry() {
618 \\ blah: while (true) {
......@@ -1039,9 +1051,9 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
10391051 \\export fn entry() -> usize { return @sizeOf(@typeOf(f)); }
10401052 , ".tmp_source.zig:3:26: error: expected signed integer type, found 'u32'");
10411053
1042 cases.add("%return in function with non error return type",
1054 cases.add("try in function with non error return type",
10431055 \\export fn f() {
1044 \\ %return something();
1056 \\ try something();
10451057 \\}
10461058 \\fn something() -> %void { }
10471059 ,
......@@ -1276,9 +1288,9 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
12761288
12771289 cases.add("return from defer expression",
12781290 \\pub fn testTrickyDefer() -> %void {
1279 \\ defer canFail() %% {};
1291 \\ defer canFail() catch {};
12801292 \\
1281 \\ defer %return canFail();
1293 \\ defer try canFail();
12821294 \\
12831295 \\ const a = maybeInt() ?? return;
12841296 \\}
test/debug_safety.zig+5-2
......@@ -221,11 +221,14 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
221221
222222 cases.addDebugSafety("unwrap error",
223223 \\pub fn panic(message: []const u8) -> noreturn {
224 \\ @import("std").os.exit(126);
224 \\ if (@import("std").mem.eql(u8, message, "attempt to unwrap error: Whatever")) {
225 \\ @import("std").os.exit(126); // good
226 \\ }
227 \\ @import("std").os.exit(0); // test failed
225228 \\}
226229 \\error Whatever;
227230 \\pub fn main() -> %void {
228 \\ %%bar();
231 \\ bar() catch unreachable;
229232 \\}
230233 \\fn bar() -> %void {
231234 \\ return error.Whatever;
test/tests.zig+8-8
......@@ -33,7 +33,7 @@ const test_targets = []TestTarget {
3333 .environ = builtin.Environ.gnu,
3434 },
3535 TestTarget {
36 .os = builtin.Os.darwin,
36 .os = builtin.Os.macosx,
3737 .arch = builtin.Arch.x86_64,
3838 .environ = builtin.Environ.unknown,
3939 },
......@@ -259,7 +259,7 @@ pub const CompareOutputContext = struct {
259259 child.stderr_behavior = StdIo.Pipe;
260260 child.env_map = &b.env_map;
261261
262 child.spawn() %% |err| debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
262 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
263263
264264 var stdout = Buffer.initNull(b.allocator);
265265 var stderr = Buffer.initNull(b.allocator);
......@@ -270,7 +270,7 @@ pub const CompareOutputContext = struct {
270270 %%stdout_file_in_stream.stream.readAllBuffer(&stdout, max_stdout_size);
271271 %%stderr_file_in_stream.stream.readAllBuffer(&stderr, max_stdout_size);
272272
273 const term = child.wait() %% |err| {
273 const term = child.wait() catch |err| {
274274 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
275275 };
276276 switch (term) {
......@@ -341,7 +341,7 @@ pub const CompareOutputContext = struct {
341341 child.stdout_behavior = StdIo.Ignore;
342342 child.stderr_behavior = StdIo.Ignore;
343343
344 const term = child.spawnAndWait() %% |err| {
344 const term = child.spawnAndWait() catch |err| {
345345 debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
346346 };
347347
......@@ -590,7 +590,7 @@ pub const CompileErrorContext = struct {
590590 child.stdout_behavior = StdIo.Pipe;
591591 child.stderr_behavior = StdIo.Pipe;
592592
593 child.spawn() %% |err| debug.panic("Unable to spawn {}: {}\n", zig_args.items[0], @errorName(err));
593 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", zig_args.items[0], @errorName(err));
594594
595595 var stdout_buf = Buffer.initNull(b.allocator);
596596 var stderr_buf = Buffer.initNull(b.allocator);
......@@ -601,7 +601,7 @@ pub const CompileErrorContext = struct {
601601 %%stdout_file_in_stream.stream.readAllBuffer(&stdout_buf, max_stdout_size);
602602 %%stderr_file_in_stream.stream.readAllBuffer(&stderr_buf, max_stdout_size);
603603
604 const term = child.wait() %% |err| {
604 const term = child.wait() catch |err| {
605605 debug.panic("Unable to spawn {}: {}\n", zig_args.items[0], @errorName(err));
606606 };
607607 switch (term) {
......@@ -862,7 +862,7 @@ pub const TranslateCContext = struct {
862862 child.stdout_behavior = StdIo.Pipe;
863863 child.stderr_behavior = StdIo.Pipe;
864864
865 child.spawn() %% |err| debug.panic("Unable to spawn {}: {}\n", zig_args.toSliceConst()[0], @errorName(err));
865 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", zig_args.toSliceConst()[0], @errorName(err));
866866
867867 var stdout_buf = Buffer.initNull(b.allocator);
868868 var stderr_buf = Buffer.initNull(b.allocator);
......@@ -873,7 +873,7 @@ pub const TranslateCContext = struct {
873873 %%stdout_file_in_stream.stream.readAllBuffer(&stdout_buf, max_stdout_size);
874874 %%stderr_file_in_stream.stream.readAllBuffer(&stderr_buf, max_stdout_size);
875875
876 const term = child.wait() %% |err| {
876 const term = child.wait() catch |err| {
877877 debug.panic("Unable to spawn {}: {}\n", zig_args.toSliceConst()[0], @errorName(err));
878878 };
879879 switch (term) {