authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-06-10 01:13:51-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2018-06-10 01:13:51-04:00
log77678b2cbc7ac9ba2d5d4725241f6a9f7ac64fa4
tree207f75d690aa32ba054c0a4a78ad05ad1ca9902e
parentec1b6f66737f8c3cbc0420715c2c502c7e710081
signature Signed by PGP key 4AEE18F83AFDEB23

breaking syntax change: orelse keyword instead of ?? (#1096)

use the `zig-fmt-optional-default` branch to have zig fmt automatically do the changes. closes #1023

33 files changed, 187 insertions(+), 189 deletions(-)

build.zig+3-3
......@@ -102,11 +102,11 @@ pub fn build(b: *Builder) !void {
102102
103103 b.default_step.dependOn(&exe.step);
104104
105 const skip_self_hosted = b.option(bool, "skip-self-hosted", "Main test suite skips building self hosted compiler") ?? false;
105 const skip_self_hosted = b.option(bool, "skip-self-hosted", "Main test suite skips building self hosted compiler") orelse false;
106106 if (!skip_self_hosted) {
107107 test_step.dependOn(&exe.step);
108108 }
109 const verbose_link_exe = b.option(bool, "verbose-link", "Print link command for self hosted compiler") ?? false;
109 const verbose_link_exe = b.option(bool, "verbose-link", "Print link command for self hosted compiler") orelse false;
110110 exe.setVerboseLink(verbose_link_exe);
111111
112112 b.installArtifact(exe);
......@@ -114,7 +114,7 @@ pub fn build(b: *Builder) !void {
114114 installCHeaders(b, c_header_files);
115115
116116 const test_filter = b.option([]const u8, "test-filter", "Skip tests that do not match filter");
117 const with_lldb = b.option(bool, "with-lldb", "Run tests in LLDB to get a backtrace if one fails") ?? false;
117 const with_lldb = b.option(bool, "with-lldb", "Run tests in LLDB to get a backtrace if one fails") orelse false;
118118
119119 test_step.dependOn(docs_step);
120120
doc/docgen.zig+3-3
......@@ -25,13 +25,13 @@ pub fn main() !void {
2525
2626 if (!args_it.skip()) @panic("expected self arg");
2727
28 const zig_exe = try (args_it.next(allocator) ?? @panic("expected zig exe arg"));
28 const zig_exe = try (args_it.next(allocator) orelse @panic("expected zig exe arg"));
2929 defer allocator.free(zig_exe);
3030
31 const in_file_name = try (args_it.next(allocator) ?? @panic("expected input arg"));
31 const in_file_name = try (args_it.next(allocator) orelse @panic("expected input arg"));
3232 defer allocator.free(in_file_name);
3333
34 const out_file_name = try (args_it.next(allocator) ?? @panic("expected output arg"));
34 const out_file_name = try (args_it.next(allocator) orelse @panic("expected output arg"));
3535 defer allocator.free(out_file_name);
3636
3737 var in_file = try os.File.openRead(allocator, in_file_name);
doc/langref.html.in+8-8
......@@ -985,7 +985,7 @@ a ^= b</code></pre></td>
985985 </td>
986986 </tr>
987987 <tr>
988 <td><pre><code class="zig">a ?? b</code></pre></td>
988 <td><pre><code class="zig">a orelse b</code></pre></td>
989989 <td>
990990 <ul>
991991 <li>{#link|Optionals#}</li>
......@@ -998,7 +998,7 @@ a ^= b</code></pre></td>
998998 </td>
999999 <td>
10001000 <pre><code class="zig">const value: ?u32 = null;
1001const unwrapped = value ?? 1234;
1001const unwrapped = value orelse 1234;
10021002unwrapped == 1234</code></pre>
10031003 </td>
10041004 </tr>
......@@ -1011,7 +1011,7 @@ unwrapped == 1234</code></pre>
10111011 </td>
10121012 <td>
10131013 Equivalent to:
1014 <pre><code class="zig">a ?? unreachable</code></pre>
1014 <pre><code class="zig">a orelse unreachable</code></pre>
10151015 </td>
10161016 <td>
10171017 <pre><code class="zig">const value: ?u32 = 5678;
......@@ -1278,7 +1278,7 @@ x{} x.* x.?
12781278== != &lt; &gt; &lt;= &gt;=
12791279and
12801280or
1281?? catch
1281orelse catch
12821282= *= /= %= += -= &lt;&lt;= &gt;&gt;= &amp;= ^= |=</code></pre>
12831283 {#header_close#}
12841284 {#header_close#}
......@@ -3062,7 +3062,7 @@ fn createFoo(param: i32) !Foo {
30623062 // but we want to return it if the function succeeds.
30633063 errdefer deallocateFoo(foo);
30643064
3065 const tmp_buf = allocateTmpBuffer() ?? return error.OutOfMemory;
3065 const tmp_buf = allocateTmpBuffer() orelse return error.OutOfMemory;
30663066 // tmp_buf is truly a temporary resource, and we for sure want to clean it up
30673067 // before this block leaves scope
30683068 defer deallocateTmpBuffer(tmp_buf);
......@@ -3219,13 +3219,13 @@ struct Foo *do_a_thing(void) {
32193219extern fn malloc(size: size_t) ?*u8;
32203220
32213221fn doAThing() ?*Foo {
3222 const ptr = malloc(1234) ?? return null;
3222 const ptr = malloc(1234) orelse return null;
32233223 // ...
32243224}
32253225 {#code_end#}
32263226 <p>
32273227 Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr"
3228 is <code>*u8</code> <em>not</em> <code>?*u8</code>. The <code>??</code> operator
3228 is <code>*u8</code> <em>not</em> <code>?*u8</code>. The <code>orelse</code> keyword
32293229 unwrapped the optional type and therefore <code>ptr</code> is guaranteed to be non-null everywhere
32303230 it is used in the function.
32313231 </p>
......@@ -5941,7 +5941,7 @@ AsmClobbers= ":" list(String, ",")
59415941
59425942UnwrapExpression = BoolOrExpression (UnwrapOptional | UnwrapError) | BoolOrExpression
59435943
5944UnwrapOptional = "??" Expression
5944UnwrapOptional = "orelse" Expression
59455945
59465946UnwrapError = "catch" option("|" Symbol "|") Expression
59475947
src-self-hosted/main.zig+7-7
......@@ -212,7 +212,7 @@ fn cmdBuild(allocator: *Allocator, args: []const []const u8) !void {
212212 const build_runner_path = try os.path.join(allocator, special_dir, "build_runner.zig");
213213 defer allocator.free(build_runner_path);
214214
215 const build_file = flags.single("build-file") ?? "build.zig";
215 const build_file = flags.single("build-file") orelse "build.zig";
216216 const build_file_abs = try os.path.resolve(allocator, ".", build_file);
217217 defer allocator.free(build_file_abs);
218218
......@@ -516,7 +516,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo
516516
517517 const basename = os.path.basename(in_file.?);
518518 var it = mem.split(basename, ".");
519 const root_name = it.next() ?? {
519 const root_name = it.next() orelse {
520520 try stderr.write("file name cannot be empty\n");
521521 os.exit(1);
522522 };
......@@ -535,7 +535,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo
535535
536536 const zig_root_source_file = in_file;
537537
538 const full_cache_dir = os.path.resolve(allocator, ".", flags.single("cache-dir") ?? "zig-cache"[0..]) catch {
538 const full_cache_dir = os.path.resolve(allocator, ".", flags.single("cache-dir") orelse "zig-cache"[0..]) catch {
539539 os.exit(1);
540540 };
541541 defer allocator.free(full_cache_dir);
......@@ -555,9 +555,9 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo
555555 );
556556 defer module.destroy();
557557
558 module.version_major = try std.fmt.parseUnsigned(u32, flags.single("ver-major") ?? "0", 10);
559 module.version_minor = try std.fmt.parseUnsigned(u32, flags.single("ver-minor") ?? "0", 10);
560 module.version_patch = try std.fmt.parseUnsigned(u32, flags.single("ver-patch") ?? "0", 10);
558 module.version_major = try std.fmt.parseUnsigned(u32, flags.single("ver-major") orelse "0", 10);
559 module.version_minor = try std.fmt.parseUnsigned(u32, flags.single("ver-minor") orelse "0", 10);
560 module.version_patch = try std.fmt.parseUnsigned(u32, flags.single("ver-patch") orelse "0", 10);
561561
562562 module.is_test = false;
563563
......@@ -652,7 +652,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo
652652 }
653653
654654 try module.build();
655 try module.link(flags.single("out-file") ?? null);
655 try module.link(flags.single("out-file") orelse null);
656656
657657 if (flags.present("print-timing-info")) {
658658 // codegen_print_timing_info(g, stderr);
src-self-hosted/module.zig+4-4
......@@ -130,13 +130,13 @@ pub const Module = struct {
130130 var name_buffer = try Buffer.init(allocator, name);
131131 errdefer name_buffer.deinit();
132132
133 const context = c.LLVMContextCreate() ?? return error.OutOfMemory;
133 const context = c.LLVMContextCreate() orelse return error.OutOfMemory;
134134 errdefer c.LLVMContextDispose(context);
135135
136 const module = c.LLVMModuleCreateWithNameInContext(name_buffer.ptr(), context) ?? return error.OutOfMemory;
136 const module = c.LLVMModuleCreateWithNameInContext(name_buffer.ptr(), context) orelse return error.OutOfMemory;
137137 errdefer c.LLVMDisposeModule(module);
138138
139 const builder = c.LLVMCreateBuilderInContext(context) ?? return error.OutOfMemory;
139 const builder = c.LLVMCreateBuilderInContext(context) orelse return error.OutOfMemory;
140140 errdefer c.LLVMDisposeBuilder(builder);
141141
142142 const module_ptr = try allocator.create(Module);
......@@ -223,7 +223,7 @@ pub const Module = struct {
223223 c.ZigLLVMParseCommandLineOptions(self.llvm_argv.len + 1, c_compatible_args.ptr);
224224 }
225225
226 const root_src_path = self.root_src_path ?? @panic("TODO handle null root src path");
226 const root_src_path = self.root_src_path orelse @panic("TODO handle null root src path");
227227 const root_src_real_path = os.path.real(self.allocator, root_src_path) catch |err| {
228228 try printError("unable to get real path '{}': {}", root_src_path, err);
229229 return err;
src/all_types.hpp+6-1
......@@ -387,6 +387,7 @@ enum NodeType {
387387 NodeTypeSliceExpr,
388388 NodeTypeFieldAccessExpr,
389389 NodeTypePtrDeref,
390 NodeTypeUnwrapOptional,
390391 NodeTypeUse,
391392 NodeTypeBoolLiteral,
392393 NodeTypeNullLiteral,
......@@ -575,6 +576,10 @@ struct AstNodeCatchExpr {
575576 AstNode *op2;
576577};
577578
579struct AstNodeUnwrapOptional {
580 AstNode *expr;
581};
582
578583enum CastOp {
579584 CastOpNoCast, // signifies the function call expression is not a cast
580585 CastOpNoop, // fn call expr is a cast, but does nothing
......@@ -624,7 +629,6 @@ enum PrefixOp {
624629 PrefixOpNegation,
625630 PrefixOpNegationWrap,
626631 PrefixOpOptional,
627 PrefixOpUnwrapOptional,
628632 PrefixOpAddrOf,
629633};
630634
......@@ -909,6 +913,7 @@ struct AstNode {
909913 AstNodeTestDecl test_decl;
910914 AstNodeBinOpExpr bin_op_expr;
911915 AstNodeCatchExpr unwrap_err_expr;
916 AstNodeUnwrapOptional unwrap_optional;
912917 AstNodePrefixOpExpr prefix_op_expr;
913918 AstNodePointerType pointer_type;
914919 AstNodeFnCallExpr fn_call_expr;
src/analyze.cpp+1
......@@ -3308,6 +3308,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {
33083308 case NodeTypeAsmExpr:
33093309 case NodeTypeFieldAccessExpr:
33103310 case NodeTypePtrDeref:
3311 case NodeTypeUnwrapOptional:
33113312 case NodeTypeStructField:
33123313 case NodeTypeContainerInitExpr:
33133314 case NodeTypeStructValueField:
src/ast_render.cpp+10-2
......@@ -50,7 +50,7 @@ static const char *bin_op_str(BinOpType bin_op) {
5050 case BinOpTypeAssignBitXor: return "^=";
5151 case BinOpTypeAssignBitOr: return "|=";
5252 case BinOpTypeAssignMergeErrorSets: return "||=";
53 case BinOpTypeUnwrapOptional: return "??";
53 case BinOpTypeUnwrapOptional: return "orelse";
5454 case BinOpTypeArrayCat: return "++";
5555 case BinOpTypeArrayMult: return "**";
5656 case BinOpTypeErrorUnion: return "!";
......@@ -67,7 +67,6 @@ static const char *prefix_op_str(PrefixOp prefix_op) {
6767 case PrefixOpBoolNot: return "!";
6868 case PrefixOpBinNot: return "~";
6969 case PrefixOpOptional: return "?";
70 case PrefixOpUnwrapOptional: return "??";
7170 case PrefixOpAddrOf: return "&";
7271 }
7372 zig_unreachable();
......@@ -222,6 +221,8 @@ static const char *node_type_str(NodeType node_type) {
222221 return "FieldAccessExpr";
223222 case NodeTypePtrDeref:
224223 return "PtrDerefExpr";
224 case NodeTypeUnwrapOptional:
225 return "UnwrapOptional";
225226 case NodeTypeContainerDecl:
226227 return "ContainerDecl";
227228 case NodeTypeStructField:
......@@ -711,6 +712,13 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
711712 fprintf(ar->f, ".*");
712713 break;
713714 }
715 case NodeTypeUnwrapOptional:
716 {
717 AstNode *lhs = node->data.unwrap_optional.expr;
718 render_node_ungrouped(ar, lhs);
719 fprintf(ar->f, ".?");
720 break;
721 }
714722 case NodeTypeUndefinedLiteral:
715723 fprintf(ar->f, "undefined");
716724 break;
src/ir.cpp+13-18
......@@ -4661,21 +4661,6 @@ static IrInstruction *ir_gen_err_assert_ok(IrBuilder *irb, Scope *scope, AstNode
46614661 return ir_build_load_ptr(irb, scope, source_node, payload_ptr);
46624662}
46634663
4664static IrInstruction *ir_gen_maybe_assert_ok(IrBuilder *irb, Scope *scope, AstNode *node, LVal lval) {
4665 assert(node->type == NodeTypePrefixOpExpr);
4666 AstNode *expr_node = node->data.prefix_op_expr.primary_expr;
4667
4668 IrInstruction *maybe_ptr = ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR);
4669 if (maybe_ptr == irb->codegen->invalid_instruction)
4670 return irb->codegen->invalid_instruction;
4671
4672 IrInstruction *unwrapped_ptr = ir_build_unwrap_maybe(irb, scope, node, maybe_ptr, true);
4673 if (lval.is_ptr)
4674 return unwrapped_ptr;
4675
4676 return ir_build_load_ptr(irb, scope, node, unwrapped_ptr);
4677}
4678
46794664static IrInstruction *ir_gen_bool_not(IrBuilder *irb, Scope *scope, AstNode *node) {
46804665 assert(node->type == NodeTypePrefixOpExpr);
46814666 AstNode *expr_node = node->data.prefix_op_expr.primary_expr;
......@@ -4705,8 +4690,6 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod
47054690 return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpNegationWrap), lval);
47064691 case PrefixOpOptional:
47074692 return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpOptional), lval);
4708 case PrefixOpUnwrapOptional:
4709 return ir_gen_maybe_assert_ok(irb, scope, node, lval);
47104693 case PrefixOpAddrOf: {
47114694 AstNode *expr_node = node->data.prefix_op_expr.primary_expr;
47124695 return ir_lval_wrap(irb, scope, ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR), lval);
......@@ -6541,7 +6524,6 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
65416524 return ir_build_load_ptr(irb, scope, node, ptr_instruction);
65426525 }
65436526 case NodeTypePtrDeref: {
6544 assert(node->type == NodeTypePtrDeref);
65456527 AstNode *expr_node = node->data.ptr_deref_expr.target;
65466528 IrInstruction *value = ir_gen_node_extra(irb, expr_node, scope, lval);
65476529 if (value == irb->codegen->invalid_instruction)
......@@ -6549,6 +6531,19 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
65496531
65506532 return ir_build_un_op(irb, scope, node, IrUnOpDereference, value);
65516533 }
6534 case NodeTypeUnwrapOptional: {
6535 AstNode *expr_node = node->data.unwrap_optional.expr;
6536
6537 IrInstruction *maybe_ptr = ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR);
6538 if (maybe_ptr == irb->codegen->invalid_instruction)
6539 return irb->codegen->invalid_instruction;
6540
6541 IrInstruction *unwrapped_ptr = ir_build_unwrap_maybe(irb, scope, node, maybe_ptr, true);
6542 if (lval.is_ptr)
6543 return unwrapped_ptr;
6544
6545 return ir_build_load_ptr(irb, scope, node, unwrapped_ptr);
6546 }
65526547 case NodeTypeThisLiteral:
65536548 return ir_lval_wrap(irb, scope, ir_gen_this_literal(irb, scope, node), lval);
65546549 case NodeTypeBoolLiteral:
src/parser.cpp+7-6
......@@ -1151,9 +1151,8 @@ static AstNode *ast_parse_suffix_op_expr(ParseContext *pc, size_t *token_index,
11511151 } else if (token->id == TokenIdQuestion) {
11521152 *token_index += 1;
11531153
1154 AstNode *node = ast_create_node(pc, NodeTypePrefixOpExpr, first_token);
1155 node->data.prefix_op_expr.prefix_op = PrefixOpUnwrapOptional;
1156 node->data.prefix_op_expr.primary_expr = primary_expr;
1154 AstNode *node = ast_create_node(pc, NodeTypeUnwrapOptional, first_token);
1155 node->data.unwrap_optional.expr = primary_expr;
11571156
11581157 primary_expr = node;
11591158 } else {
......@@ -1173,7 +1172,6 @@ static PrefixOp tok_to_prefix_op(Token *token) {
11731172 case TokenIdMinusPercent: return PrefixOpNegationWrap;
11741173 case TokenIdTilde: return PrefixOpBinNot;
11751174 case TokenIdQuestion: return PrefixOpOptional;
1176 case TokenIdDoubleQuestion: return PrefixOpUnwrapOptional;
11771175 case TokenIdAmpersand: return PrefixOpAddrOf;
11781176 default: return PrefixOpInvalid;
11791177 }
......@@ -2312,7 +2310,7 @@ static BinOpType ast_parse_ass_op(ParseContext *pc, size_t *token_index, bool ma
23122310
23132311/*
23142312UnwrapExpression : BoolOrExpression (UnwrapOptional | UnwrapError) | BoolOrExpression
2315UnwrapOptional : "??" BoolOrExpression
2313UnwrapOptional = "orelse" Expression
23162314UnwrapError = "catch" option("|" Symbol "|") Expression
23172315*/
23182316static AstNode *ast_parse_unwrap_expr(ParseContext *pc, size_t *token_index, bool mandatory) {
......@@ -2322,7 +2320,7 @@ static AstNode *ast_parse_unwrap_expr(ParseContext *pc, size_t *token_index, boo
23222320
23232321 Token *token = &pc->tokens->at(*token_index);
23242322
2325 if (token->id == TokenIdDoubleQuestion) {
2323 if (token->id == TokenIdKeywordOrElse) {
23262324 *token_index += 1;
23272325
23282326 AstNode *rhs = ast_parse_expression(pc, token_index, true);
......@@ -3035,6 +3033,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont
30353033 case NodeTypePtrDeref:
30363034 visit_field(&node->data.ptr_deref_expr.target, visit, context);
30373035 break;
3036 case NodeTypeUnwrapOptional:
3037 visit_field(&node->data.unwrap_optional.expr, visit, context);
3038 break;
30383039 case NodeTypeUse:
30393040 visit_field(&node->data.use.expr, visit, context);
30403041 break;
src/tokenizer.cpp+6-21
......@@ -134,6 +134,7 @@ static const struct ZigKeyword zig_keywords[] = {
134134 {"noalias", TokenIdKeywordNoAlias},
135135 {"null", TokenIdKeywordNull},
136136 {"or", TokenIdKeywordOr},
137 {"orelse", TokenIdKeywordOrElse},
137138 {"packed", TokenIdKeywordPacked},
138139 {"promise", TokenIdKeywordPromise},
139140 {"pub", TokenIdKeywordPub},
......@@ -215,7 +216,6 @@ enum TokenizeState {
215216 TokenizeStateSawGreaterThanGreaterThan,
216217 TokenizeStateSawDot,
217218 TokenizeStateSawDotDot,
218 TokenizeStateSawQuestionMark,
219219 TokenizeStateSawAtSign,
220220 TokenizeStateCharCode,
221221 TokenizeStateError,
......@@ -532,6 +532,10 @@ void tokenize(Buf *buf, Tokenization *out) {
532532 begin_token(&t, TokenIdComma);
533533 end_token(&t);
534534 break;
535 case '?':
536 begin_token(&t, TokenIdQuestion);
537 end_token(&t);
538 break;
535539 case '{':
536540 begin_token(&t, TokenIdLBrace);
537541 end_token(&t);
......@@ -624,28 +628,10 @@ void tokenize(Buf *buf, Tokenization *out) {
624628 begin_token(&t, TokenIdDot);
625629 t.state = TokenizeStateSawDot;
626630 break;
627 case '?':
628 begin_token(&t, TokenIdQuestion);
629 t.state = TokenizeStateSawQuestionMark;
630 break;
631631 default:
632632 invalid_char_error(&t, c);
633633 }
634634 break;
635 case TokenizeStateSawQuestionMark:
636 switch (c) {
637 case '?':
638 set_token_id(&t, t.cur_tok, TokenIdDoubleQuestion);
639 end_token(&t);
640 t.state = TokenizeStateStart;
641 break;
642 default:
643 t.pos -= 1;
644 end_token(&t);
645 t.state = TokenizeStateStart;
646 continue;
647 }
648 break;
649635 case TokenizeStateSawDot:
650636 switch (c) {
651637 case '.':
......@@ -1480,7 +1466,6 @@ void tokenize(Buf *buf, Tokenization *out) {
14801466 case TokenizeStateSawGreaterThan:
14811467 case TokenizeStateSawGreaterThanGreaterThan:
14821468 case TokenizeStateSawDot:
1483 case TokenizeStateSawQuestionMark:
14841469 case TokenizeStateSawAtSign:
14851470 case TokenizeStateSawStarPercent:
14861471 case TokenizeStateSawPlusPercent:
......@@ -1545,7 +1530,6 @@ const char * token_name(TokenId id) {
15451530 case TokenIdDash: return "-";
15461531 case TokenIdDivEq: return "/=";
15471532 case TokenIdDot: return ".";
1548 case TokenIdDoubleQuestion: return "??";
15491533 case TokenIdEllipsis2: return "..";
15501534 case TokenIdEllipsis3: return "...";
15511535 case TokenIdEof: return "EOF";
......@@ -1582,6 +1566,7 @@ const char * token_name(TokenId id) {
15821566 case TokenIdKeywordNoAlias: return "noalias";
15831567 case TokenIdKeywordNull: return "null";
15841568 case TokenIdKeywordOr: return "or";
1569 case TokenIdKeywordOrElse: return "orelse";
15851570 case TokenIdKeywordPacked: return "packed";
15861571 case TokenIdKeywordPromise: return "promise";
15871572 case TokenIdKeywordPub: return "pub";
src/tokenizer.hpp+1-1
......@@ -41,7 +41,6 @@ enum TokenId {
4141 TokenIdDash,
4242 TokenIdDivEq,
4343 TokenIdDot,
44 TokenIdDoubleQuestion,
4544 TokenIdEllipsis2,
4645 TokenIdEllipsis3,
4746 TokenIdEof,
......@@ -76,6 +75,7 @@ enum TokenId {
7675 TokenIdKeywordNoAlias,
7776 TokenIdKeywordNull,
7877 TokenIdKeywordOr,
78 TokenIdKeywordOrElse,
7979 TokenIdKeywordPacked,
8080 TokenIdKeywordPromise,
8181 TokenIdKeywordPub,
src/translate_c.cpp+9-7
......@@ -260,6 +260,12 @@ static AstNode *trans_create_node_prefix_op(Context *c, PrefixOp op, AstNode *ch
260260 return node;
261261}
262262
263static AstNode *trans_create_node_unwrap_null(Context *c, AstNode *child_node) {
264 AstNode *node = trans_create_node(c, NodeTypeUnwrapOptional);
265 node->data.unwrap_optional.expr = child_node;
266 return node;
267}
268
263269static AstNode *trans_create_node_bin_op(Context *c, AstNode *lhs_node, BinOpType op, AstNode *rhs_node) {
264270 AstNode *node = trans_create_node(c, NodeTypeBinOpExpr);
265271 node->data.bin_op_expr.op1 = lhs_node;
......@@ -382,7 +388,7 @@ static AstNode *trans_create_node_inline_fn(Context *c, Buf *fn_name, AstNode *r
382388 fn_def->data.fn_def.fn_proto = fn_proto;
383389 fn_proto->data.fn_proto.fn_def_node = fn_def;
384390
385 AstNode *unwrap_node = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, ref_node);
391 AstNode *unwrap_node = trans_create_node_unwrap_null(c, ref_node);
386392 AstNode *fn_call_node = trans_create_node(c, NodeTypeFnCallExpr);
387393 fn_call_node->data.fn_call_expr.fn_ref_expr = unwrap_node;
388394
......@@ -409,10 +415,6 @@ static AstNode *trans_create_node_inline_fn(Context *c, Buf *fn_name, AstNode *r
409415 return fn_def;
410416}
411417
412static AstNode *trans_create_node_unwrap_null(Context *c, AstNode *child) {
413 return trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, child);
414}
415
416418static AstNode *get_global(Context *c, Buf *name) {
417419 {
418420 auto entry = c->global_table.maybe_get(name);
......@@ -1963,7 +1965,7 @@ static AstNode *trans_unary_operator(Context *c, ResultUsed result_used, TransSc
19631965 bool is_fn_ptr = qual_type_is_fn_ptr(stmt->getSubExpr()->getType());
19641966 if (is_fn_ptr)
19651967 return value_node;
1966 AstNode *unwrapped = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, value_node);
1968 AstNode *unwrapped = trans_create_node_unwrap_null(c, value_node);
19671969 return trans_create_node_ptr_deref(c, unwrapped);
19681970 }
19691971 case UO_Plus:
......@@ -2587,7 +2589,7 @@ static AstNode *trans_call_expr(Context *c, ResultUsed result_used, TransScope *
25872589 }
25882590 }
25892591 if (callee_node == nullptr) {
2590 callee_node = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, callee_raw_node);
2592 callee_node = trans_create_node_unwrap_null(c, callee_raw_node);
25912593 }
25922594 } else {
25932595 callee_node = callee_raw_node;
std/atomic/queue.zig+2-2
......@@ -33,8 +33,8 @@ pub fn Queue(comptime T: type) type {
3333 pub fn get(self: *Self) ?*Node {
3434 var head = @atomicLoad(*Node, &self.head, AtomicOrder.SeqCst);
3535 while (true) {
36 const node = head.next ?? return null;
37 head = @cmpxchgWeak(*Node, &self.head, head, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return node;
36 const node = head.next orelse return null;
37 head = @cmpxchgWeak(*Node, &self.head, head, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse return node;
3838 }
3939 }
4040 };
std/atomic/stack.zig+2-2
......@@ -28,14 +28,14 @@ pub fn Stack(comptime T: type) type {
2828 var root = @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst);
2929 while (true) {
3030 node.next = root;
31 root = @cmpxchgWeak(?*Node, &self.root, root, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? break;
31 root = @cmpxchgWeak(?*Node, &self.root, root, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse break;
3232 }
3333 }
3434
3535 pub fn pop(self: *Self) ?*Node {
3636 var root = @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst);
3737 while (true) {
38 root = @cmpxchgWeak(?*Node, &self.root, root, (root ?? return null).next, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return root;
38 root = @cmpxchgWeak(?*Node, &self.root, root, (root orelse return null).next, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse return root;
3939 }
4040 }
4141
std/buf_map.zig+3-3
......@@ -19,7 +19,7 @@ pub const BufMap = struct {
1919 pub fn deinit(self: *const BufMap) void {
2020 var it = self.hash_map.iterator();
2121 while (true) {
22 const entry = it.next() ?? break;
22 const entry = it.next() orelse break;
2323 self.free(entry.key);
2424 self.free(entry.value);
2525 }
......@@ -37,12 +37,12 @@ pub const BufMap = struct {
3737 }
3838
3939 pub fn get(self: *const BufMap, key: []const u8) ?[]const u8 {
40 const entry = self.hash_map.get(key) ?? return null;
40 const entry = self.hash_map.get(key) orelse return null;
4141 return entry.value;
4242 }
4343
4444 pub fn delete(self: *BufMap, key: []const u8) void {
45 const entry = self.hash_map.remove(key) ?? return;
45 const entry = self.hash_map.remove(key) orelse return;
4646 self.free(entry.key);
4747 self.free(entry.value);
4848 }
std/buf_set.zig+2-2
......@@ -17,7 +17,7 @@ pub const BufSet = struct {
1717 pub fn deinit(self: *const BufSet) void {
1818 var it = self.hash_map.iterator();
1919 while (true) {
20 const entry = it.next() ?? break;
20 const entry = it.next() orelse break;
2121 self.free(entry.key);
2222 }
2323
......@@ -33,7 +33,7 @@ pub const BufSet = struct {
3333 }
3434
3535 pub fn delete(self: *BufSet, key: []const u8) void {
36 const entry = self.hash_map.remove(key) ?? return;
36 const entry = self.hash_map.remove(key) orelse return;
3737 self.free(entry.key);
3838 }
3939
std/build.zig+12-12
......@@ -136,7 +136,7 @@ pub const Builder = struct {
136136 }
137137
138138 pub fn setInstallPrefix(self: *Builder, maybe_prefix: ?[]const u8) void {
139 self.prefix = maybe_prefix ?? "/usr/local"; // TODO better default
139 self.prefix = maybe_prefix orelse "/usr/local"; // TODO better default
140140 self.lib_dir = os.path.join(self.allocator, self.prefix, "lib") catch unreachable;
141141 self.exe_dir = os.path.join(self.allocator, self.prefix, "bin") catch unreachable;
142142 }
......@@ -312,9 +312,9 @@ pub const Builder = struct {
312312 if (os.getEnvVarOwned(self.allocator, "NIX_CFLAGS_COMPILE")) |nix_cflags_compile| {
313313 var it = mem.split(nix_cflags_compile, " ");
314314 while (true) {
315 const word = it.next() ?? break;
315 const word = it.next() orelse break;
316316 if (mem.eql(u8, word, "-isystem")) {
317 const include_path = it.next() ?? {
317 const include_path = it.next() orelse {
318318 warn("Expected argument after -isystem in NIX_CFLAGS_COMPILE\n");
319319 break;
320320 };
......@@ -330,9 +330,9 @@ pub const Builder = struct {
330330 if (os.getEnvVarOwned(self.allocator, "NIX_LDFLAGS")) |nix_ldflags| {
331331 var it = mem.split(nix_ldflags, " ");
332332 while (true) {
333 const word = it.next() ?? break;
333 const word = it.next() orelse break;
334334 if (mem.eql(u8, word, "-rpath")) {
335 const rpath = it.next() ?? {
335 const rpath = it.next() orelse {
336336 warn("Expected argument after -rpath in NIX_LDFLAGS\n");
337337 break;
338338 };
......@@ -362,7 +362,7 @@ pub const Builder = struct {
362362 }
363363 self.available_options_list.append(available_option) catch unreachable;
364364
365 const entry = self.user_input_options.get(name) ?? return null;
365 const entry = self.user_input_options.get(name) orelse return null;
366366 entry.value.used = true;
367367 switch (type_id) {
368368 TypeId.Bool => switch (entry.value.value) {
......@@ -416,9 +416,9 @@ pub const Builder = struct {
416416 pub fn standardReleaseOptions(self: *Builder) builtin.Mode {
417417 if (self.release_mode) |mode| return mode;
418418
419 const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") ?? false;
420 const release_fast = self.option(bool, "release-fast", "optimizations on and safety off") ?? false;
421 const release_small = self.option(bool, "release-small", "size optimizations on and safety off") ?? false;
419 const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") orelse false;
420 const release_fast = self.option(bool, "release-fast", "optimizations on and safety off") orelse false;
421 const release_small = self.option(bool, "release-small", "size optimizations on and safety off") orelse false;
422422
423423 const mode = if (release_safe and !release_fast and !release_small) builtin.Mode.ReleaseSafe else if (release_fast and !release_safe and !release_small) builtin.Mode.ReleaseFast else if (release_small and !release_fast and !release_safe) builtin.Mode.ReleaseSmall else if (!release_fast and !release_safe and !release_small) builtin.Mode.Debug else x: {
424424 warn("Multiple release modes (of -Drelease-safe, -Drelease-fast and -Drelease-small)");
......@@ -518,7 +518,7 @@ pub const Builder = struct {
518518 // make sure all args are used
519519 var it = self.user_input_options.iterator();
520520 while (true) {
521 const entry = it.next() ?? break;
521 const entry = it.next() orelse break;
522522 if (!entry.value.used) {
523523 warn("Invalid option: -D{}\n\n", entry.key);
524524 self.markInvalidUserInput();
......@@ -1246,7 +1246,7 @@ pub const LibExeObjStep = struct {
12461246 {
12471247 var it = self.link_libs.iterator();
12481248 while (true) {
1249 const entry = it.next() ?? break;
1249 const entry = it.next() orelse break;
12501250 zig_args.append("--library") catch unreachable;
12511251 zig_args.append(entry.key) catch unreachable;
12521252 }
......@@ -1696,7 +1696,7 @@ pub const TestStep = struct {
16961696 {
16971697 var it = self.link_libs.iterator();
16981698 while (true) {
1699 const entry = it.next() ?? break;
1699 const entry = it.next() orelse break;
17001700 try zig_args.append("--library");
17011701 try zig_args.append(entry.key);
17021702 }
std/debug/index.zig+10-10
......@@ -208,7 +208,7 @@ fn printSourceAtAddress(debug_info: *ElfStackTrace, out_stream: var, address: us
208208 .name = "???",
209209 .address = address,
210210 };
211 const symbol = debug_info.symbol_table.search(address) ?? &unknown;
211 const symbol = debug_info.symbol_table.search(address) orelse &unknown;
212212 try out_stream.print(WHITE ++ "{}" ++ RESET ++ ": " ++ DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n", symbol.name, address);
213213 },
214214 else => {
......@@ -268,10 +268,10 @@ pub fn openSelfDebugInfo(allocator: *mem.Allocator) !*ElfStackTrace {
268268 try st.elf.openFile(allocator, &st.self_exe_file);
269269 errdefer st.elf.close();
270270
271 st.debug_info = (try st.elf.findSection(".debug_info")) ?? return error.MissingDebugInfo;
272 st.debug_abbrev = (try st.elf.findSection(".debug_abbrev")) ?? return error.MissingDebugInfo;
273 st.debug_str = (try st.elf.findSection(".debug_str")) ?? return error.MissingDebugInfo;
274 st.debug_line = (try st.elf.findSection(".debug_line")) ?? return error.MissingDebugInfo;
271 st.debug_info = (try st.elf.findSection(".debug_info")) orelse return error.MissingDebugInfo;
272 st.debug_abbrev = (try st.elf.findSection(".debug_abbrev")) orelse return error.MissingDebugInfo;
273 st.debug_str = (try st.elf.findSection(".debug_str")) orelse return error.MissingDebugInfo;
274 st.debug_line = (try st.elf.findSection(".debug_line")) orelse return error.MissingDebugInfo;
275275 st.debug_ranges = (try st.elf.findSection(".debug_ranges"));
276276 try scanAllCompileUnits(st);
277277 return st;
......@@ -443,7 +443,7 @@ const Die = struct {
443443 }
444444
445445 fn getAttrAddr(self: *const Die, id: u64) !u64 {
446 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;
446 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
447447 return switch (form_value.*) {
448448 FormValue.Address => |value| value,
449449 else => error.InvalidDebugInfo,
......@@ -451,7 +451,7 @@ const Die = struct {
451451 }
452452
453453 fn getAttrSecOffset(self: *const Die, id: u64) !u64 {
454 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;
454 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
455455 return switch (form_value.*) {
456456 FormValue.Const => |value| value.asUnsignedLe(),
457457 FormValue.SecOffset => |value| value,
......@@ -460,7 +460,7 @@ const Die = struct {
460460 }
461461
462462 fn getAttrUnsignedLe(self: *const Die, id: u64) !u64 {
463 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;
463 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
464464 return switch (form_value.*) {
465465 FormValue.Const => |value| value.asUnsignedLe(),
466466 else => error.InvalidDebugInfo,
......@@ -468,7 +468,7 @@ const Die = struct {
468468 }
469469
470470 fn getAttrString(self: *const Die, st: *ElfStackTrace, id: u64) ![]u8 {
471 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;
471 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
472472 return switch (form_value.*) {
473473 FormValue.String => |value| value,
474474 FormValue.StrPtr => |offset| getString(st, offset),
......@@ -748,7 +748,7 @@ fn parseDie(st: *ElfStackTrace, abbrev_table: *const AbbrevTable, is_64: bool) !
748748 var in_file_stream = io.FileInStream.init(in_file);
749749 const in_stream = &in_file_stream.stream;
750750 const abbrev_code = try readULeb128(in_stream);
751 const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) ?? return error.InvalidDebugInfo;
751 const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) orelse return error.InvalidDebugInfo;
752752
753753 var result = Die{
754754 .tag_id = table_entry.tag_id,
std/heap.zig+5-5
......@@ -97,12 +97,12 @@ pub const DirectAllocator = struct {
9797 },
9898 Os.windows => {
9999 const amt = n + alignment + @sizeOf(usize);
100 const heap_handle = self.heap_handle ?? blk: {
101 const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) ?? return error.OutOfMemory;
100 const heap_handle = self.heap_handle orelse blk: {
101 const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) orelse return error.OutOfMemory;
102102 self.heap_handle = hh;
103103 break :blk hh;
104104 };
105 const ptr = os.windows.HeapAlloc(heap_handle, 0, amt) ?? return error.OutOfMemory;
105 const ptr = os.windows.HeapAlloc(heap_handle, 0, amt) orelse return error.OutOfMemory;
106106 const root_addr = @ptrToInt(ptr);
107107 const rem = @rem(root_addr, alignment);
108108 const march_forward_bytes = if (rem == 0) 0 else (alignment - rem);
......@@ -142,7 +142,7 @@ pub const DirectAllocator = struct {
142142 const root_addr = @intToPtr(*align(1) usize, old_record_addr).*;
143143 const old_ptr = @intToPtr(*c_void, root_addr);
144144 const amt = new_size + alignment + @sizeOf(usize);
145 const new_ptr = os.windows.HeapReAlloc(self.heap_handle.?, 0, old_ptr, amt) ?? blk: {
145 const new_ptr = os.windows.HeapReAlloc(self.heap_handle.?, 0, old_ptr, amt) orelse blk: {
146146 if (new_size > old_mem.len) return error.OutOfMemory;
147147 const new_record_addr = old_record_addr - new_size + old_mem.len;
148148 @intToPtr(*align(1) usize, new_record_addr).* = root_addr;
......@@ -343,7 +343,7 @@ pub const ThreadSafeFixedBufferAllocator = struct {
343343 if (new_end_index > self.buffer.len) {
344344 return error.OutOfMemory;
345345 }
346 end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) ?? return self.buffer[adjusted_index..new_end_index];
346 end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) orelse return self.buffer[adjusted_index..new_end_index];
347347 }
348348 }
349349
std/linked_list.zig+2-2
......@@ -169,7 +169,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
169169 /// Returns:
170170 /// A pointer to the last node in the list.
171171 pub fn pop(list: *Self) ?*Node {
172 const last = list.last ?? return null;
172 const last = list.last orelse return null;
173173 list.remove(last);
174174 return last;
175175 }
......@@ -179,7 +179,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
179179 /// Returns:
180180 /// A pointer to the first node in the list.
181181 pub fn popFirst(list: *Self) ?*Node {
182 const first = list.first ?? return null;
182 const first = list.first orelse return null;
183183 list.remove(first);
184184 return first;
185185 }
std/os/index.zig+7-7
......@@ -425,7 +425,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: *const BufMap, allocator:
425425 return posixExecveErrnoToErr(posix.getErrno(posix.execve(argv_buf[0].?, argv_buf.ptr, envp_buf.ptr)));
426426 }
427427
428 const PATH = getEnvPosix("PATH") ?? "/usr/local/bin:/bin/:/usr/bin";
428 const PATH = getEnvPosix("PATH") orelse "/usr/local/bin:/bin/:/usr/bin";
429429 // PATH.len because it is >= the largest search_path
430430 // +1 for the / to join the search path and exe_path
431431 // +1 for the null terminating byte
......@@ -490,7 +490,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
490490 errdefer result.deinit();
491491
492492 if (is_windows) {
493 const ptr = windows.GetEnvironmentStringsA() ?? return error.OutOfMemory;
493 const ptr = windows.GetEnvironmentStringsA() orelse return error.OutOfMemory;
494494 defer assert(windows.FreeEnvironmentStringsA(ptr) != 0);
495495
496496 var i: usize = 0;
......@@ -573,7 +573,7 @@ pub fn getEnvVarOwned(allocator: *mem.Allocator, key: []const u8) ![]u8 {
573573 return allocator.shrink(u8, buf, result);
574574 }
575575 } else {
576 const result = getEnvPosix(key) ?? return error.EnvironmentVariableNotFound;
576 const result = getEnvPosix(key) orelse return error.EnvironmentVariableNotFound;
577577 return mem.dupe(allocator, u8, result);
578578 }
579579}
......@@ -1641,7 +1641,7 @@ pub const ArgIterator = struct {
16411641 if (builtin.os == Os.windows) {
16421642 return self.inner.next(allocator);
16431643 } else {
1644 return mem.dupe(allocator, u8, self.inner.next() ?? return null);
1644 return mem.dupe(allocator, u8, self.inner.next() orelse return null);
16451645 }
16461646 }
16471647
......@@ -2457,9 +2457,9 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread
24572457 }
24582458 };
24592459
2460 const heap_handle = windows.GetProcessHeap() ?? return SpawnThreadError.OutOfMemory;
2460 const heap_handle = windows.GetProcessHeap() orelse return SpawnThreadError.OutOfMemory;
24612461 const byte_count = @alignOf(WinThread.OuterContext) + @sizeOf(WinThread.OuterContext);
2462 const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) ?? return SpawnThreadError.OutOfMemory;
2462 const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) orelse return SpawnThreadError.OutOfMemory;
24632463 errdefer assert(windows.HeapFree(heap_handle, 0, bytes_ptr) != 0);
24642464 const bytes = @ptrCast([*]u8, bytes_ptr)[0..byte_count];
24652465 const outer_context = std.heap.FixedBufferAllocator.init(bytes).allocator.create(WinThread.OuterContext) catch unreachable;
......@@ -2468,7 +2468,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread
24682468 outer_context.thread.data.alloc_start = bytes_ptr;
24692469
24702470 const parameter = if (@sizeOf(Context) == 0) null else @ptrCast(*c_void, &outer_context.inner);
2471 outer_context.thread.data.handle = windows.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) ?? {
2471 outer_context.thread.data.handle = windows.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) orelse {
24722472 const err = windows.GetLastError();
24732473 return switch (err) {
24742474 else => os.unexpectedErrorWindows(err),
std/os/linux/vdso.zig+4-4
......@@ -28,7 +28,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
2828 }
2929 }
3030 }
31 const dynv = maybe_dynv ?? return 0;
31 const dynv = maybe_dynv orelse return 0;
3232 if (base == @maxValue(usize)) return 0;
3333
3434 var maybe_strings: ?[*]u8 = null;
......@@ -52,9 +52,9 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
5252 }
5353 }
5454
55 const strings = maybe_strings ?? return 0;
56 const syms = maybe_syms ?? return 0;
57 const hashtab = maybe_hashtab ?? return 0;
55 const strings = maybe_strings orelse return 0;
56 const syms = maybe_syms orelse return 0;
57 const hashtab = maybe_hashtab orelse return 0;
5858 if (maybe_verdef == null) maybe_versym = null;
5959
6060 const OK_TYPES = (1 << elf.STT_NOTYPE | 1 << elf.STT_OBJECT | 1 << elf.STT_FUNC | 1 << elf.STT_COMMON);
std/os/path.zig+6-6
......@@ -182,8 +182,8 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {
182182 }
183183
184184 var it = mem.split(path, []u8{this_sep});
185 _ = (it.next() ?? return relative_path);
186 _ = (it.next() ?? return relative_path);
185 _ = (it.next() orelse return relative_path);
186 _ = (it.next() orelse return relative_path);
187187 return WindowsPath{
188188 .is_abs = isAbsoluteWindows(path),
189189 .kind = WindowsPath.Kind.NetworkShare,
......@@ -200,8 +200,8 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {
200200 }
201201
202202 var it = mem.split(path, []u8{this_sep});
203 _ = (it.next() ?? return relative_path);
204 _ = (it.next() ?? return relative_path);
203 _ = (it.next() orelse return relative_path);
204 _ = (it.next() orelse return relative_path);
205205 return WindowsPath{
206206 .is_abs = isAbsoluteWindows(path),
207207 .kind = WindowsPath.Kind.NetworkShare,
......@@ -923,7 +923,7 @@ pub fn relativeWindows(allocator: *Allocator, from: []const u8, to: []const u8)
923923 var from_it = mem.split(resolved_from, "/\\");
924924 var to_it = mem.split(resolved_to, "/\\");
925925 while (true) {
926 const from_component = from_it.next() ?? return mem.dupe(allocator, u8, to_it.rest());
926 const from_component = from_it.next() orelse return mem.dupe(allocator, u8, to_it.rest());
927927 const to_rest = to_it.rest();
928928 if (to_it.next()) |to_component| {
929929 // TODO ASCII is wrong, we actually need full unicode support to compare paths.
......@@ -974,7 +974,7 @@ pub fn relativePosix(allocator: *Allocator, from: []const u8, to: []const u8) ![
974974 var from_it = mem.split(resolved_from, "/");
975975 var to_it = mem.split(resolved_to, "/");
976976 while (true) {
977 const from_component = from_it.next() ?? return mem.dupe(allocator, u8, to_it.rest());
977 const from_component = from_it.next() orelse return mem.dupe(allocator, u8, to_it.rest());
978978 const to_rest = to_it.rest();
979979 if (to_it.next()) |to_component| {
980980 if (mem.eql(u8, from_component, to_component))
std/os/windows/util.zig+1-1
......@@ -153,7 +153,7 @@ pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap)
153153pub fn windowsLoadDll(allocator: *mem.Allocator, dll_path: []const u8) !windows.HMODULE {
154154 const padded_buff = try cstr.addNullByte(allocator, dll_path);
155155 defer allocator.free(padded_buff);
156 return windows.LoadLibraryA(padded_buff.ptr) ?? error.DllNotFound;
156 return windows.LoadLibraryA(padded_buff.ptr) orelse error.DllNotFound;
157157}
158158
159159pub fn windowsUnloadDll(hModule: windows.HMODULE) void {
std/special/build_runner.zig+5-5
......@@ -27,15 +27,15 @@ pub fn main() !void {
2727 // skip my own exe name
2828 _ = arg_it.skip();
2929
30 const zig_exe = try unwrapArg(arg_it.next(allocator) ?? {
30 const zig_exe = try unwrapArg(arg_it.next(allocator) orelse {
3131 warn("Expected first argument to be path to zig compiler\n");
3232 return error.InvalidArgs;
3333 });
34 const build_root = try unwrapArg(arg_it.next(allocator) ?? {
34 const build_root = try unwrapArg(arg_it.next(allocator) orelse {
3535 warn("Expected second argument to be build root directory path\n");
3636 return error.InvalidArgs;
3737 });
38 const cache_root = try unwrapArg(arg_it.next(allocator) ?? {
38 const cache_root = try unwrapArg(arg_it.next(allocator) orelse {
3939 warn("Expected third argument to be cache root directory path\n");
4040 return error.InvalidArgs;
4141 });
......@@ -84,12 +84,12 @@ pub fn main() !void {
8484 } else if (mem.eql(u8, arg, "--help")) {
8585 return usage(&builder, false, try stdout_stream);
8686 } else if (mem.eql(u8, arg, "--prefix")) {
87 prefix = try unwrapArg(arg_it.next(allocator) ?? {
87 prefix = try unwrapArg(arg_it.next(allocator) orelse {
8888 warn("Expected argument after --prefix\n\n");
8989 return usageAndErr(&builder, false, try stderr_stream);
9090 });
9191 } else if (mem.eql(u8, arg, "--search-prefix")) {
92 const search_prefix = try unwrapArg(arg_it.next(allocator) ?? {
92 const search_prefix = try unwrapArg(arg_it.next(allocator) orelse {
9393 warn("Expected argument after --search-prefix\n\n");
9494 return usageAndErr(&builder, false, try stderr_stream);
9595 });
std/unicode.zig+1-1
......@@ -220,7 +220,7 @@ const Utf8Iterator = struct {
220220 }
221221
222222 pub fn nextCodepoint(it: *Utf8Iterator) ?u32 {
223 const slice = it.nextCodepointSlice() ?? return null;
223 const slice = it.nextCodepointSlice() orelse return null;
224224
225225 switch (slice.len) {
226226 1 => return u32(slice[0]),
std/zig/parse.zig+24-23
......@@ -43,7 +43,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
4343
4444 // skip over line comments at the top of the file
4545 while (true) {
46 const next_tok = tok_it.peek() ?? break;
46 const next_tok = tok_it.peek() orelse break;
4747 if (next_tok.id != Token.Id.LineComment) break;
4848 _ = tok_it.next();
4949 }
......@@ -197,7 +197,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
197197 const lib_name_token = nextToken(&tok_it, &tree);
198198 const lib_name_token_index = lib_name_token.index;
199199 const lib_name_token_ptr = lib_name_token.ptr;
200 break :blk (try parseStringLiteral(arena, &tok_it, lib_name_token_ptr, lib_name_token_index, &tree)) ?? {
200 break :blk (try parseStringLiteral(arena, &tok_it, lib_name_token_ptr, lib_name_token_index, &tree)) orelse {
201201 prevToken(&tok_it, &tree);
202202 break :blk null;
203203 };
......@@ -1434,13 +1434,14 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
14341434 try stack.append(State{
14351435 .ExpectTokenSave = ExpectTokenSave{
14361436 .id = Token.Id.AngleBracketRight,
1437 .ptr = &async_node.rangle_bracket.? },
1437 .ptr = &async_node.rangle_bracket.?,
1438 },
14381439 });
14391440 try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &async_node.allocator_type } });
14401441 continue;
14411442 },
14421443 State.AsyncEnd => |ctx| {
1443 const node = ctx.ctx.get() ?? continue;
1444 const node = ctx.ctx.get() orelse continue;
14441445
14451446 switch (node.id) {
14461447 ast.Node.Id.FnProto => {
......@@ -1813,7 +1814,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
18131814 continue;
18141815 },
18151816 State.RangeExpressionEnd => |opt_ctx| {
1816 const lhs = opt_ctx.get() ?? continue;
1817 const lhs = opt_ctx.get() orelse continue;
18171818
18181819 if (eatToken(&tok_it, &tree, Token.Id.Ellipsis3)) |ellipsis3| {
18191820 const node = try arena.construct(ast.Node.InfixOp{
......@@ -1835,7 +1836,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
18351836 },
18361837
18371838 State.AssignmentExpressionEnd => |opt_ctx| {
1838 const lhs = opt_ctx.get() ?? continue;
1839 const lhs = opt_ctx.get() orelse continue;
18391840
18401841 const token = nextToken(&tok_it, &tree);
18411842 const token_index = token.index;
......@@ -1865,7 +1866,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
18651866 },
18661867
18671868 State.UnwrapExpressionEnd => |opt_ctx| {
1868 const lhs = opt_ctx.get() ?? continue;
1869 const lhs = opt_ctx.get() orelse continue;
18691870
18701871 const token = nextToken(&tok_it, &tree);
18711872 const token_index = token.index;
......@@ -1900,7 +1901,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
19001901 },
19011902
19021903 State.BoolOrExpressionEnd => |opt_ctx| {
1903 const lhs = opt_ctx.get() ?? continue;
1904 const lhs = opt_ctx.get() orelse continue;
19041905
19051906 if (eatToken(&tok_it, &tree, Token.Id.Keyword_or)) |or_token| {
19061907 const node = try arena.construct(ast.Node.InfixOp{
......@@ -1924,7 +1925,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
19241925 },
19251926
19261927 State.BoolAndExpressionEnd => |opt_ctx| {
1927 const lhs = opt_ctx.get() ?? continue;
1928 const lhs = opt_ctx.get() orelse continue;
19281929
19291930 if (eatToken(&tok_it, &tree, Token.Id.Keyword_and)) |and_token| {
19301931 const node = try arena.construct(ast.Node.InfixOp{
......@@ -1948,7 +1949,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
19481949 },
19491950
19501951 State.ComparisonExpressionEnd => |opt_ctx| {
1951 const lhs = opt_ctx.get() ?? continue;
1952 const lhs = opt_ctx.get() orelse continue;
19521953
19531954 const token = nextToken(&tok_it, &tree);
19541955 const token_index = token.index;
......@@ -1978,7 +1979,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
19781979 },
19791980
19801981 State.BinaryOrExpressionEnd => |opt_ctx| {
1981 const lhs = opt_ctx.get() ?? continue;
1982 const lhs = opt_ctx.get() orelse continue;
19821983
19831984 if (eatToken(&tok_it, &tree, Token.Id.Pipe)) |pipe| {
19841985 const node = try arena.construct(ast.Node.InfixOp{
......@@ -2002,7 +2003,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
20022003 },
20032004
20042005 State.BinaryXorExpressionEnd => |opt_ctx| {
2005 const lhs = opt_ctx.get() ?? continue;
2006 const lhs = opt_ctx.get() orelse continue;
20062007
20072008 if (eatToken(&tok_it, &tree, Token.Id.Caret)) |caret| {
20082009 const node = try arena.construct(ast.Node.InfixOp{
......@@ -2026,7 +2027,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
20262027 },
20272028
20282029 State.BinaryAndExpressionEnd => |opt_ctx| {
2029 const lhs = opt_ctx.get() ?? continue;
2030 const lhs = opt_ctx.get() orelse continue;
20302031
20312032 if (eatToken(&tok_it, &tree, Token.Id.Ampersand)) |ampersand| {
20322033 const node = try arena.construct(ast.Node.InfixOp{
......@@ -2050,7 +2051,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
20502051 },
20512052
20522053 State.BitShiftExpressionEnd => |opt_ctx| {
2053 const lhs = opt_ctx.get() ?? continue;
2054 const lhs = opt_ctx.get() orelse continue;
20542055
20552056 const token = nextToken(&tok_it, &tree);
20562057 const token_index = token.index;
......@@ -2080,7 +2081,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
20802081 },
20812082
20822083 State.AdditionExpressionEnd => |opt_ctx| {
2083 const lhs = opt_ctx.get() ?? continue;
2084 const lhs = opt_ctx.get() orelse continue;
20842085
20852086 const token = nextToken(&tok_it, &tree);
20862087 const token_index = token.index;
......@@ -2110,7 +2111,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
21102111 },
21112112
21122113 State.MultiplyExpressionEnd => |opt_ctx| {
2113 const lhs = opt_ctx.get() ?? continue;
2114 const lhs = opt_ctx.get() orelse continue;
21142115
21152116 const token = nextToken(&tok_it, &tree);
21162117 const token_index = token.index;
......@@ -2141,7 +2142,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
21412142 },
21422143
21432144 State.CurlySuffixExpressionEnd => |opt_ctx| {
2144 const lhs = opt_ctx.get() ?? continue;
2145 const lhs = opt_ctx.get() orelse continue;
21452146
21462147 if (tok_it.peek().?.id == Token.Id.Period) {
21472148 const node = try arena.construct(ast.Node.SuffixOp{
......@@ -2189,7 +2190,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
21892190 },
21902191
21912192 State.TypeExprEnd => |opt_ctx| {
2192 const lhs = opt_ctx.get() ?? continue;
2193 const lhs = opt_ctx.get() orelse continue;
21932194
21942195 if (eatToken(&tok_it, &tree, Token.Id.Bang)) |bang| {
21952196 const node = try arena.construct(ast.Node.InfixOp{
......@@ -2269,7 +2270,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
22692270 },
22702271
22712272 State.SuffixOpExpressionEnd => |opt_ctx| {
2272 const lhs = opt_ctx.get() ?? continue;
2273 const lhs = opt_ctx.get() orelse continue;
22732274
22742275 const token = nextToken(&tok_it, &tree);
22752276 const token_index = token.index;
......@@ -2418,7 +2419,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
24182419 continue;
24192420 },
24202421 Token.Id.StringLiteral, Token.Id.MultilineStringLiteralLine => {
2421 opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) ?? unreachable);
2422 opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) orelse unreachable);
24222423 continue;
24232424 },
24242425 Token.Id.LParen => {
......@@ -2648,7 +2649,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
26482649 const token = nextToken(&tok_it, &tree);
26492650 const token_index = token.index;
26502651 const token_ptr = token.ptr;
2651 opt_ctx.store((try parseStringLiteral(arena, &tok_it, token_ptr, token_index, &tree)) ?? {
2652 opt_ctx.store((try parseStringLiteral(arena, &tok_it, token_ptr, token_index, &tree)) orelse {
26522653 prevToken(&tok_it, &tree);
26532654 if (opt_ctx != OptionalCtx.Optional) {
26542655 ((try tree.errors.addOne())).* = Error{ .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr{ .token = token_index } };
......@@ -3348,7 +3349,7 @@ fn nextToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) AnnotatedTok
33483349 assert(result.ptr.id != Token.Id.LineComment);
33493350
33503351 while (true) {
3351 const next_tok = tok_it.peek() ?? return result;
3352 const next_tok = tok_it.peek() orelse return result;
33523353 if (next_tok.id != Token.Id.LineComment) return result;
33533354 _ = tok_it.next();
33543355 }
......@@ -3356,7 +3357,7 @@ fn nextToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) AnnotatedTok
33563357
33573358fn prevToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) void {
33583359 while (true) {
3359 const prev_tok = tok_it.prev() ?? return;
3360 const prev_tok = tok_it.prev() orelse return;
33603361 if (prev_tok.id == Token.Id.LineComment) continue;
33613362 return;
33623363 }
std/zig/render.zig+4-4
......@@ -83,7 +83,7 @@ fn renderRoot(
8383 var start_col: usize = 0;
8484 var it = tree.root_node.decls.iterator(0);
8585 while (true) {
86 var decl = (it.next() ?? return).*;
86 var decl = (it.next() orelse return).*;
8787 // look for zig fmt: off comment
8888 var start_token_index = decl.firstToken();
8989 zig_fmt_loop: while (start_token_index != 0) {
......@@ -112,7 +112,7 @@ fn renderRoot(
112112 const start = tree.tokens.at(start_token_index + 1).start;
113113 try stream.print("{}\n", tree.source[start..end_token.end]);
114114 while (tree.tokens.at(decl.firstToken()).start < end_token.end) {
115 decl = (it.next() ?? return).*;
115 decl = (it.next() orelse return).*;
116116 }
117117 break :zig_fmt_loop;
118118 }
......@@ -1993,7 +1993,7 @@ fn renderDocComments(
19931993 indent: usize,
19941994 start_col: *usize,
19951995) (@typeOf(stream).Child.Error || Error)!void {
1996 const comment = node.doc_comments ?? return;
1996 const comment = node.doc_comments orelse return;
19971997 var it = comment.lines.iterator(0);
19981998 const first_token = node.firstToken();
19991999 while (it.next()) |line_token_index| {
......@@ -2021,7 +2021,7 @@ fn nodeIsBlock(base: *const ast.Node) bool {
20212021}
20222022
20232023fn nodeCausesSliceOpSpace(base: *ast.Node) bool {
2024 const infix_op = base.cast(ast.Node.InfixOp) ?? return false;
2024 const infix_op = base.cast(ast.Node.InfixOp) orelse return false;
20252025 return switch (infix_op.op) {
20262026 ast.Node.InfixOp.Op.Period => false,
20272027 else => true,
test/cases/cast.zig+3-3
......@@ -73,7 +73,7 @@ fn Struct(comptime T: type) type {
7373
7474 fn maybePointer(self: ?*const Self) Self {
7575 const none = Self{ .x = if (T == void) void{} else 0 };
76 return (self ?? &none).*;
76 return (self orelse &none).*;
7777 }
7878 };
7979}
......@@ -87,7 +87,7 @@ const Union = union {
8787
8888 fn maybePointer(self: ?*const Union) Union {
8989 const none = Union{ .x = 0 };
90 return (self ?? &none).*;
90 return (self orelse &none).*;
9191 }
9292};
9393
......@@ -100,7 +100,7 @@ const Enum = enum {
100100 }
101101
102102 fn maybePointer(self: ?*const Enum) Enum {
103 return (self ?? &Enum.None).*;
103 return (self orelse &Enum.None).*;
104104 }
105105};
106106
test/cases/null.zig+5-5
......@@ -15,13 +15,13 @@ test "optional type" {
1515
1616 const next_x: ?i32 = null;
1717
18 const z = next_x ?? 1234;
18 const z = next_x orelse 1234;
1919
2020 assert(z == 1234);
2121
2222 const final_x: ?i32 = 13;
2323
24 const num = final_x ?? unreachable;
24 const num = final_x orelse unreachable;
2525
2626 assert(num == 13);
2727}
......@@ -38,7 +38,7 @@ test "test maybe object and get a pointer to the inner value" {
3838
3939test "rhs maybe unwrap return" {
4040 const x: ?bool = true;
41 const y = x ?? return;
41 const y = x orelse return;
4242}
4343
4444test "maybe return" {
......@@ -53,7 +53,7 @@ fn maybeReturnImpl() void {
5353}
5454
5555fn foo(x: ?i32) ?bool {
56 const value = x ?? return null;
56 const value = x orelse return null;
5757 return value > 1234;
5858}
5959
......@@ -140,6 +140,6 @@ test "unwrap optional which is field of global var" {
140140}
141141
142142test "null with default unwrap" {
143 const x: i32 = null ?? 1;
143 const x: i32 = null orelse 1;
144144 assert(x == 1);
145145}
test/compile_errors.zig+1-1
......@@ -2296,7 +2296,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
22962296 \\
22972297 \\ defer try canFail();
22982298 \\
2299 \\ const a = maybeInt() ?? return;
2299 \\ const a = maybeInt() orelse return;
23002300 \\}
23012301 \\
23022302 \\fn canFail() error!void { }
test/translate_c.zig+10-10
......@@ -246,13 +246,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
246246 \\pub extern var fn_ptr: ?extern fn() void;
247247 ,
248248 \\pub inline fn foo() void {
249 \\ return (??fn_ptr)();
249 \\ return fn_ptr.?();
250250 \\}
251251 ,
252252 \\pub extern var fn_ptr2: ?extern fn(c_int, f32) u8;
253253 ,
254254 \\pub inline fn bar(arg0: c_int, arg1: f32) u8 {
255 \\ return (??fn_ptr2)(arg0, arg1);
255 \\ return fn_ptr2.?(arg0, arg1);
256256 \\}
257257 );
258258
......@@ -608,7 +608,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
608608 \\ field: c_int,
609609 \\};
610610 \\pub export fn read_field(foo: ?[*]struct_Foo) c_int {
611 \\ return (??foo).field;
611 \\ return foo.?.field;
612612 \\}
613613 );
614614
......@@ -969,11 +969,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
969969 \\pub export fn bar() void {
970970 \\ var f: ?extern fn() void = foo;
971971 \\ var b: ?extern fn() c_int = baz;
972 \\ (??f)();
973 \\ (??f)();
972 \\ f.?();
973 \\ f.?();
974974 \\ foo();
975 \\ _ = (??b)();
976 \\ _ = (??b)();
975 \\ _ = b.?();
976 \\ _ = b.?();
977977 \\ _ = baz();
978978 \\}
979979 );
......@@ -984,7 +984,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
984984 \\}
985985 ,
986986 \\pub export fn foo(x: ?[*]c_int) void {
987 \\ (??x).* = 1;
987 \\ x.?.* = 1;
988988 \\}
989989 );
990990
......@@ -1012,7 +1012,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
10121012 \\pub fn foo() c_int {
10131013 \\ var x: c_int = 1234;
10141014 \\ var ptr: ?[*]c_int = &x;
1015 \\ return (??ptr).*;
1015 \\ return ptr.?.*;
10161016 \\}
10171017 );
10181018
......@@ -1119,7 +1119,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
11191119 \\pub const glClearPFN = PFNGLCLEARPROC;
11201120 ,
11211121 \\pub inline fn glClearUnion(arg0: GLbitfield) void {
1122 \\ return (??glProcs.gl.Clear)(arg0);
1122 \\ return glProcs.gl.Clear.?(arg0);
11231123 \\}
11241124 ,
11251125 \\pub const OpenGLProcs = union_OpenGLProcs;