authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-12-20 22:55:24-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-12-20 23:00:19-05:00
log8bc523219c66427951e5339550502871547f2138
tree207f1b9335a6bdd2d25a96c206430daf91087e24
parentd686113bd2b2e2207137de6ef81e515bc4a3aa07

add labeled loops, labeled break, labeled continue. remove goto

closes #346 closes #630 regression: translate-c can no longer translate switch statements. after #629 we can ressurect and modify the code to utilize arbitrarily returning from blocks.

15 files changed, 339 insertions(+), 688 deletions(-)

doc/langref.html.in+7-11
......@@ -5847,11 +5847,9 @@ ParamDeclList = "(" list(ParamDecl, ",") ")"
58475847
58485848ParamDecl = option("noalias" | "comptime") option(Symbol ":") (TypeExpr | "...")
58495849
5850Block = "{" many(Statement) option(Expression) "}"
5850Block = option(Symbol ":") "{" many(Statement) option(Expression) "}"
58515851
5852Statement = Label | LocalVarDecl ";" | Defer(Block) | Defer(Expression) ";" | BlockExpression(Block) | Expression ";" | ";"
5853
5854Label = Symbol ":"
5852Statement = LocalVarDecl ";" | Defer(Block) | Defer(Expression) ";" | BlockExpression(Block) | Expression ";" | ";"
58555853
58565854TypeExpr = PrefixOpExpression | "var"
58575855
......@@ -5891,13 +5889,13 @@ SwitchProng = (list(SwitchItem, ",") | "else") "=&gt;" option("|" option("*") Sy
58915889
58925890SwitchItem = Expression | (Expression "..." Expression)
58935891
5894ForExpression(body) = option("inline") "for" "(" Expression ")" option("|" option("*") Symbol option("," Symbol) "|") body option("else" BlockExpression(body))
5892ForExpression(body) = option(Symbol ":") option("inline") "for" "(" Expression ")" option("|" option("*") Symbol option("," Symbol) "|") body option("else" BlockExpression(body))
58955893
58965894BoolOrExpression = BoolAndExpression "or" BoolOrExpression | BoolAndExpression
58975895
58985896ReturnExpression = option("%") "return" option(Expression)
58995897
5900BreakExpression = "break" option(Expression)
5898BreakExpression = "break" option(":" Symbol) option(Expression)
59015899
59025900Defer(body) = option("%") "defer" body
59035901
......@@ -5907,7 +5905,7 @@ TryExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|")
59075905
59085906TestExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body option("else" BlockExpression(body))
59095907
5910WhileExpression(body) = option("inline") "while" "(" Expression ")" option("|" option("*") Symbol "|") option(":" "(" Expression ")") body option("else" option("|" Symbol "|") BlockExpression(body))
5908WhileExpression(body) = option(Symbol ":") option("inline") "while" "(" Expression ")" option("|" option("*") Symbol "|") option(":" "(" Expression ")") body option("else" option("|" Symbol "|") BlockExpression(body))
59115909
59125910BoolAndExpression = ComparisonExpression "and" BoolAndExpression | ComparisonExpression
59135911
......@@ -5955,15 +5953,13 @@ StructLiteralField = "." Symbol "=" Expression
59555953
59565954PrefixOp = "!" | "-" | "~" | "*" | ("&amp;" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "%" | "%%" | "??" | "-%"
59575955
5958PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | GotoExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ("error" "." Symbol) | ContainerDecl
5956PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ("error" "." Symbol) | ContainerDecl | ("continue" option(":" Symbol))
59595957
59605958ArrayType : "[" option(Expression) "]" option("align" "(" Expression option(":" Integer ":" Integer) ")")) option("const") option("volatile") TypeExpr
59615959
5962GotoExpression = "goto" Symbol
5963
59645960GroupedExpression = "(" Expression ")"
59655961
5966KeywordLiteral = "true" | "false" | "null" | "continue" | "undefined" | "error" | "this" | "unreachable"
5962KeywordLiteral = "true" | "false" | "null" | "undefined" | "error" | "this" | "unreachable"
59675963
59685964ContainerDecl = option("extern" | "packed")
59695965 ("struct" option(GroupedExpression) | "union" option("enum" option(GroupedExpression) | GroupedExpression) | ("enum" option(GroupedExpression)))
src/all_types.hpp+7-8
......@@ -386,8 +386,6 @@ enum NodeType {
386386 NodeTypeSwitchExpr,
387387 NodeTypeSwitchProng,
388388 NodeTypeSwitchRange,
389 NodeTypeLabel,
390 NodeTypeGoto,
391389 NodeTypeCompTime,
392390 NodeTypeBreak,
393391 NodeTypeContinue,
......@@ -452,6 +450,7 @@ struct AstNodeParamDecl {
452450};
453451
454452struct AstNodeBlock {
453 Buf *name;
455454 ZigList<AstNode *> statements;
456455 bool last_statement_is_result_expression;
457456};
......@@ -662,6 +661,7 @@ struct AstNodeTestExpr {
662661};
663662
664663struct AstNodeWhileExpr {
664 Buf *name;
665665 AstNode *condition;
666666 Buf *var_symbol;
667667 bool var_is_ptr;
......@@ -673,6 +673,7 @@ struct AstNodeWhileExpr {
673673};
674674
675675struct AstNodeForExpr {
676 Buf *name;
676677 AstNode *array_expr;
677678 AstNode *elem_node; // always a symbol
678679 AstNode *index_node; // always a symbol, might be null
......@@ -704,11 +705,6 @@ struct AstNodeLabel {
704705 Buf *name;
705706};
706707
707struct AstNodeGoto {
708 Buf *name;
709 bool is_inline;
710};
711
712708struct AstNodeCompTime {
713709 AstNode *expr;
714710};
......@@ -836,11 +832,14 @@ struct AstNodeBoolLiteral {
836832};
837833
838834struct AstNodeBreakExpr {
835 Buf *name;
839836 AstNode *expr; // may be null
840837};
841838
842839struct AstNodeContinueExpr {
840 Buf *name;
843841};
842
844843struct AstNodeUnreachableExpr {
845844};
846845
......@@ -886,7 +885,6 @@ struct AstNode {
886885 AstNodeSwitchProng switch_prong;
887886 AstNodeSwitchRange switch_range;
888887 AstNodeLabel label;
889 AstNodeGoto goto_expr;
890888 AstNodeCompTime comptime_expr;
891889 AstNodeAsmExpr asm_expr;
892890 AstNodeFieldAccessExpr field_access_expr;
......@@ -1741,6 +1739,7 @@ struct ScopeCImport {
17411739struct ScopeLoop {
17421740 Scope base;
17431741
1742 Buf *name;
17441743 IrBasicBlock *break_block;
17451744 IrBasicBlock *continue_block;
17461745 IrInstruction *is_comptime;
src/analyze.cpp+7-3
......@@ -144,9 +144,15 @@ ScopeCImport *create_cimport_scope(AstNode *node, Scope *parent) {
144144}
145145
146146ScopeLoop *create_loop_scope(AstNode *node, Scope *parent) {
147 assert(node->type == NodeTypeWhileExpr || node->type == NodeTypeForExpr);
148147 ScopeLoop *scope = allocate<ScopeLoop>(1);
149148 init_scope(&scope->base, ScopeIdLoop, node, parent);
149 if (node->type == NodeTypeWhileExpr) {
150 scope->name = node->data.while_expr.name;
151 } else if (node->type == NodeTypeForExpr) {
152 scope->name = node->data.for_expr.name;
153 } else {
154 zig_unreachable();
155 }
150156 return scope;
151157}
152158
......@@ -2916,8 +2922,6 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {
29162922 case NodeTypeSwitchExpr:
29172923 case NodeTypeSwitchProng:
29182924 case NodeTypeSwitchRange:
2919 case NodeTypeLabel:
2920 case NodeTypeGoto:
29212925 case NodeTypeBreak:
29222926 case NodeTypeContinue:
29232927 case NodeTypeUnreachable:
src/ast_render.cpp+15-17
......@@ -215,10 +215,6 @@ static const char *node_type_str(NodeType node_type) {
215215 return "SwitchProng";
216216 case NodeTypeSwitchRange:
217217 return "SwitchRange";
218 case NodeTypeLabel:
219 return "Label";
220 case NodeTypeGoto:
221 return "Goto";
222218 case NodeTypeCompTime:
223219 return "CompTime";
224220 case NodeTypeBreak:
......@@ -391,7 +387,6 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
391387 switch (node->type) {
392388 case NodeTypeSwitchProng:
393389 case NodeTypeSwitchRange:
394 case NodeTypeLabel:
395390 case NodeTypeStructValueField:
396391 zig_unreachable();
397392 case NodeTypeRoot:
......@@ -470,6 +465,9 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
470465 break;
471466 }
472467 case NodeTypeBlock:
468 if (node->data.block.name != nullptr) {
469 fprintf(ar->f, "%s: ", buf_ptr(node->data.block.name));
470 }
473471 if (node->data.block.statements.length == 0) {
474472 fprintf(ar->f, "{}");
475473 break;
......@@ -478,13 +476,6 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
478476 ar->indent += ar->indent_size;
479477 for (size_t i = 0; i < node->data.block.statements.length; i += 1) {
480478 AstNode *statement = node->data.block.statements.at(i);
481 if (statement->type == NodeTypeLabel) {
482 ar->indent -= ar->indent_size;
483 print_indent(ar);
484 fprintf(ar->f, "%s:\n", buf_ptr(statement->data.label.name));
485 ar->indent += ar->indent_size;
486 continue;
487 }
488479 print_indent(ar);
489480 render_node_grouped(ar, statement);
490481 if (!(i == node->data.block.statements.length - 1 &&
......@@ -515,6 +506,9 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
515506 case NodeTypeBreak:
516507 {
517508 fprintf(ar->f, "break");
509 if (node->data.break_expr.name != nullptr) {
510 fprintf(ar->f, " :%s", buf_ptr(node->data.break_expr.name));
511 }
518512 if (node->data.break_expr.expr) {
519513 fprintf(ar->f, " ");
520514 render_node_grouped(ar, node->data.break_expr.expr);
......@@ -828,6 +822,9 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
828822 }
829823 case NodeTypeWhileExpr:
830824 {
825 if (node->data.while_expr.name != nullptr) {
826 fprintf(ar->f, "%s: ", buf_ptr(node->data.while_expr.name));
827 }
831828 const char *inline_str = node->data.while_expr.is_inline ? "inline " : "";
832829 fprintf(ar->f, "%swhile (", inline_str);
833830 render_node_grouped(ar, node->data.while_expr.condition);
......@@ -957,11 +954,6 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
957954 fprintf(ar->f, "}");
958955 break;
959956 }
960 case NodeTypeGoto:
961 {
962 fprintf(ar->f, "goto %s", buf_ptr(node->data.goto_expr.name));
963 break;
964 }
965957 case NodeTypeCompTime:
966958 {
967959 fprintf(ar->f, "comptime ");
......@@ -970,6 +962,9 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
970962 }
971963 case NodeTypeForExpr:
972964 {
965 if (node->data.for_expr.name != nullptr) {
966 fprintf(ar->f, "%s: ", buf_ptr(node->data.for_expr.name));
967 }
973968 const char *inline_str = node->data.for_expr.is_inline ? "inline " : "";
974969 fprintf(ar->f, "%sfor (", inline_str);
975970 render_node_grouped(ar, node->data.for_expr.array_expr);
......@@ -995,6 +990,9 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
995990 case NodeTypeContinue:
996991 {
997992 fprintf(ar->f, "continue");
993 if (node->data.continue_expr.name != nullptr) {
994 fprintf(ar->f, " :%s", buf_ptr(node->data.continue_expr.name));
995 }
998996 break;
999997 }
1000998 case NodeTypeUnreachable:
src/ir.cpp+32-151
......@@ -3511,29 +3511,6 @@ static VariableTableEntry *ir_create_var(IrBuilder *irb, AstNode *node, Scope *s
35113511 return var;
35123512}
35133513
3514static LabelTableEntry *find_label(IrExecutable *exec, Scope *scope, Buf *name) {
3515 while (scope) {
3516 if (scope->id == ScopeIdBlock) {
3517 ScopeBlock *block_scope = (ScopeBlock *)scope;
3518 auto entry = block_scope->label_table.maybe_get(name);
3519 if (entry)
3520 return entry->value;
3521 }
3522 scope = scope->parent;
3523 }
3524
3525 return nullptr;
3526}
3527
3528static ScopeBlock *find_block_scope(IrExecutable *exec, Scope *scope) {
3529 while (scope) {
3530 if (scope->id == ScopeIdBlock)
3531 return (ScopeBlock *)scope;
3532 scope = scope->parent;
3533 }
3534 return nullptr;
3535}
3536
35373514static IrInstruction *ir_gen_block(IrBuilder *irb, Scope *parent_scope, AstNode *block_node) {
35383515 assert(block_node->type == NodeTypeBlock);
35393516
......@@ -3557,38 +3534,6 @@ static IrInstruction *ir_gen_block(IrBuilder *irb, Scope *parent_scope, AstNode
35573534 for (size_t i = 0; i < block_node->data.block.statements.length; i += 1) {
35583535 AstNode *statement_node = block_node->data.block.statements.at(i);
35593536
3560 if (statement_node->type == NodeTypeLabel) {
3561 Buf *label_name = statement_node->data.label.name;
3562 IrBasicBlock *label_block = ir_build_basic_block(irb, child_scope, buf_ptr(label_name));
3563 LabelTableEntry *label = allocate<LabelTableEntry>(1);
3564 label->decl_node = statement_node;
3565 label->bb = label_block;
3566 irb->exec->all_labels.append(label);
3567
3568 LabelTableEntry *existing_label = find_label(irb->exec, child_scope, label_name);
3569 if (existing_label) {
3570 ErrorMsg *msg = add_node_error(irb->codegen, statement_node,
3571 buf_sprintf("duplicate label name '%s'", buf_ptr(label_name)));
3572 add_error_note(irb->codegen, msg, existing_label->decl_node, buf_sprintf("other label here"));
3573 return irb->codegen->invalid_instruction;
3574 } else {
3575 ScopeBlock *scope_block = find_block_scope(irb->exec, child_scope);
3576 scope_block->label_table.put(label_name, label);
3577 }
3578
3579 if (!is_continuation_unreachable) {
3580 // fall through into new labeled basic block
3581 IrInstruction *is_comptime = ir_mark_gen(ir_build_const_bool(irb, child_scope, statement_node,
3582 ir_should_inline(irb->exec, child_scope)));
3583 ir_mark_gen(ir_build_br(irb, child_scope, statement_node, label_block, is_comptime));
3584 }
3585 ir_set_cursor_at_end(irb, label_block);
3586
3587 // a label is an entry point
3588 is_continuation_unreachable = false;
3589 continue;
3590 }
3591
35923537 IrInstruction *statement_value = ir_gen_node(irb, statement_node, child_scope);
35933538 is_continuation_unreachable = instr_is_unreachable(statement_value);
35943539 if (is_continuation_unreachable) {
......@@ -6000,22 +5945,6 @@ static IrInstruction *ir_gen_switch_expr(IrBuilder *irb, Scope *scope, AstNode *
60005945 return ir_build_phi(irb, scope, node, incoming_blocks.length, incoming_blocks.items, incoming_values.items);
60015946}
60025947
6003static IrInstruction *ir_gen_goto(IrBuilder *irb, Scope *scope, AstNode *node) {
6004 assert(node->type == NodeTypeGoto);
6005
6006 // make a placeholder unreachable statement and a note to come back and
6007 // replace the instruction with a branch instruction
6008 IrGotoItem *goto_item = irb->exec->goto_list.add_one();
6009 goto_item->bb = irb->current_basic_block;
6010 goto_item->instruction_index = irb->current_basic_block->instruction_list.length;
6011 goto_item->source_node = node;
6012 goto_item->scope = scope;
6013
6014 // we don't know if we need to generate defer expressions yet
6015 // we do that later when we find out which label we're jumping to.
6016 return ir_build_unreachable(irb, scope, node);
6017}
6018
60195948static IrInstruction *ir_gen_comptime(IrBuilder *irb, Scope *parent_scope, AstNode *node, LVal lval) {
60205949 assert(node->type == NodeTypeCompTime);
60215950
......@@ -6033,16 +5962,28 @@ static IrInstruction *ir_gen_break(IrBuilder *irb, Scope *break_scope, AstNode *
60335962
60345963 Scope *search_scope = break_scope;
60355964 ScopeLoop *loop_scope;
5965 bool saw_any_loop_scope = false;
60365966 for (;;) {
60375967 if (search_scope == nullptr || search_scope->id == ScopeIdFnDef) {
6038 add_node_error(irb->codegen, node, buf_sprintf("break expression outside loop"));
6039 return irb->codegen->invalid_instruction;
5968 if (saw_any_loop_scope) {
5969 add_node_error(irb->codegen, node, buf_sprintf("labeled loop not found: '%s'", buf_ptr(node->data.break_expr.name)));
5970 return irb->codegen->invalid_instruction;
5971 } else {
5972 add_node_error(irb->codegen, node, buf_sprintf("break expression outside loop"));
5973 return irb->codegen->invalid_instruction;
5974 }
60405975 } else if (search_scope->id == ScopeIdDeferExpr) {
60415976 add_node_error(irb->codegen, node, buf_sprintf("cannot break out of defer expression"));
60425977 return irb->codegen->invalid_instruction;
60435978 } else if (search_scope->id == ScopeIdLoop) {
6044 loop_scope = (ScopeLoop *)search_scope;
6045 break;
5979 ScopeLoop *this_loop_scope = (ScopeLoop *)search_scope;
5980 saw_any_loop_scope = true;
5981 if (node->data.break_expr.name == nullptr ||
5982 (this_loop_scope->name != nullptr && buf_eql_buf(node->data.break_expr.name, this_loop_scope->name)))
5983 {
5984 loop_scope = this_loop_scope;
5985 break;
5986 }
60465987 }
60475988 search_scope = search_scope->parent;
60485989 }
......@@ -6081,16 +6022,28 @@ static IrInstruction *ir_gen_continue(IrBuilder *irb, Scope *continue_scope, Ast
60816022
60826023 Scope *search_scope = continue_scope;
60836024 ScopeLoop *loop_scope;
6025 bool saw_any_loop_scope = false;
60846026 for (;;) {
60856027 if (search_scope == nullptr || search_scope->id == ScopeIdFnDef) {
6086 add_node_error(irb->codegen, node, buf_sprintf("continue expression outside loop"));
6087 return irb->codegen->invalid_instruction;
6028 if (saw_any_loop_scope) {
6029 add_node_error(irb->codegen, node, buf_sprintf("labeled loop not found: '%s'", buf_ptr(node->data.continue_expr.name)));
6030 return irb->codegen->invalid_instruction;
6031 } else {
6032 add_node_error(irb->codegen, node, buf_sprintf("continue expression outside loop"));
6033 return irb->codegen->invalid_instruction;
6034 }
60886035 } else if (search_scope->id == ScopeIdDeferExpr) {
60896036 add_node_error(irb->codegen, node, buf_sprintf("cannot continue out of defer expression"));
60906037 return irb->codegen->invalid_instruction;
60916038 } else if (search_scope->id == ScopeIdLoop) {
6092 loop_scope = (ScopeLoop *)search_scope;
6093 break;
6039 ScopeLoop *this_loop_scope = (ScopeLoop *)search_scope;
6040 saw_any_loop_scope = true;
6041 if (node->data.continue_expr.name == nullptr ||
6042 (this_loop_scope->name != nullptr && buf_eql_buf(node->data.continue_expr.name, this_loop_scope->name)))
6043 {
6044 loop_scope = this_loop_scope;
6045 break;
6046 }
60946047 }
60956048 search_scope = search_scope->parent;
60966049 }
......@@ -6332,7 +6285,6 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
63326285 case NodeTypeSwitchProng:
63336286 case NodeTypeSwitchRange:
63346287 case NodeTypeStructField:
6335 case NodeTypeLabel:
63366288 case NodeTypeFnDef:
63376289 case NodeTypeFnDecl:
63386290 case NodeTypeErrorValueDecl:
......@@ -6396,8 +6348,6 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
63966348 return ir_lval_wrap(irb, scope, ir_gen_test_expr(irb, scope, node), lval);
63976349 case NodeTypeSwitchExpr:
63986350 return ir_lval_wrap(irb, scope, ir_gen_switch_expr(irb, scope, node), lval);
6399 case NodeTypeGoto:
6400 return ir_lval_wrap(irb, scope, ir_gen_goto(irb, scope, node), lval);
64016351 case NodeTypeCompTime:
64026352 return ir_gen_comptime(irb, scope, node, lval);
64036353 case NodeTypeErrorType:
......@@ -6432,70 +6382,6 @@ static IrInstruction *ir_gen_node(IrBuilder *irb, AstNode *node, Scope *scope) {
64326382 return ir_gen_node_extra(irb, node, scope, LVAL_NONE);
64336383}
64346384
6435static bool ir_goto_pass2(IrBuilder *irb) {
6436 for (size_t i = 0; i < irb->exec->goto_list.length; i += 1) {
6437 IrGotoItem *goto_item = &irb->exec->goto_list.at(i);
6438 AstNode *source_node = goto_item->source_node;
6439
6440 // Since a goto will always end a basic block, we move the "current instruction"
6441 // index back to over the placeholder unreachable instruction and begin overwriting
6442 irb->current_basic_block = goto_item->bb;
6443 irb->current_basic_block->instruction_list.resize(goto_item->instruction_index);
6444
6445 Buf *label_name = source_node->data.goto_expr.name;
6446
6447 // Search up the scope until we find one of these things:
6448 // * A block scope with the label in it => OK
6449 // * A defer expression scope => error, error, cannot leave defer expression
6450 // * Top level scope => error, didn't find label
6451
6452 LabelTableEntry *label;
6453 Scope *search_scope = goto_item->scope;
6454 for (;;) {
6455 if (search_scope == nullptr) {
6456 add_node_error(irb->codegen, source_node,
6457 buf_sprintf("no label in scope named '%s'", buf_ptr(label_name)));
6458 return false;
6459 } else if (search_scope->id == ScopeIdBlock) {
6460 ScopeBlock *block_scope = (ScopeBlock *)search_scope;
6461 auto entry = block_scope->label_table.maybe_get(label_name);
6462 if (entry) {
6463 label = entry->value;
6464 break;
6465 }
6466 } else if (search_scope->id == ScopeIdDeferExpr) {
6467 add_node_error(irb->codegen, source_node,
6468 buf_sprintf("cannot goto out of defer expression"));
6469 return false;
6470 }
6471 search_scope = search_scope->parent;
6472 }
6473
6474 label->used = true;
6475
6476 IrInstruction *is_comptime = ir_build_const_bool(irb, goto_item->scope, source_node,
6477 ir_should_inline(irb->exec, goto_item->scope) || source_node->data.goto_expr.is_inline);
6478 if (!ir_gen_defers_for_block(irb, goto_item->scope, label->bb->scope, false)) {
6479 add_node_error(irb->codegen, source_node,
6480 buf_sprintf("no label in scope named '%s'", buf_ptr(label_name)));
6481 return false;
6482 }
6483 ir_build_br(irb, goto_item->scope, source_node, label->bb, is_comptime);
6484 }
6485
6486 for (size_t i = 0; i < irb->exec->all_labels.length; i += 1) {
6487 LabelTableEntry *label = irb->exec->all_labels.at(i);
6488 if (!label->used) {
6489 add_node_error(irb->codegen, label->decl_node,
6490 buf_sprintf("label '%s' defined but not used",
6491 buf_ptr(label->decl_node->data.label.name)));
6492 return false;
6493 }
6494 }
6495
6496 return true;
6497}
6498
64996385static void invalidate_exec(IrExecutable *exec) {
65006386 if (exec->invalid)
65016387 return;
......@@ -6532,11 +6418,6 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec
65326418 ir_mark_gen(ir_build_return(irb, scope, result->source_node, result));
65336419 }
65346420
6535 if (!ir_goto_pass2(irb)) {
6536 invalidate_exec(ir_executable);
6537 return false;
6538 }
6539
65406421 return true;
65416422}
65426423
src/parser.cpp+106-97
......@@ -632,27 +632,6 @@ static AstNode *ast_parse_asm_expr(ParseContext *pc, size_t *token_index, bool m
632632 return node;
633633}
634634
635/*
636GotoExpression = "goto" Symbol
637*/
638static AstNode *ast_parse_goto_expr(ParseContext *pc, size_t *token_index, bool mandatory) {
639 Token *goto_token = &pc->tokens->at(*token_index);
640 if (goto_token->id == TokenIdKeywordGoto) {
641 *token_index += 1;
642 } else if (mandatory) {
643 ast_expect_token(pc, goto_token, TokenIdKeywordGoto);
644 zig_unreachable();
645 } else {
646 return nullptr;
647 }
648
649 AstNode *node = ast_create_node(pc, NodeTypeGoto, goto_token);
650
651 Token *dest_symbol = ast_eat_token(pc, token_index, TokenIdSymbol);
652 node->data.goto_expr.name = token_buf(dest_symbol);
653 return node;
654}
655
656635/*
657636CompTimeExpression(body) = "comptime" body
658637*/
......@@ -676,8 +655,8 @@ static AstNode *ast_parse_comptime_expr(ParseContext *pc, size_t *token_index, b
676655}
677656
678657/*
679PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | GotoExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ("error" "." Symbol) | ContainerDecl
680KeywordLiteral = "true" | "false" | "null" | "continue" | "undefined" | "error" | "this" | "unreachable"
658PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ("error" "." Symbol) | ContainerDecl | ("continue" option(":" Symbol))
659KeywordLiteral = "true" | "false" | "null" | "undefined" | "error" | "this" | "unreachable"
681660*/
682661static AstNode *ast_parse_primary_expr(ParseContext *pc, size_t *token_index, bool mandatory) {
683662 Token *token = &pc->tokens->at(*token_index);
......@@ -721,6 +700,12 @@ static AstNode *ast_parse_primary_expr(ParseContext *pc, size_t *token_index, bo
721700 } else if (token->id == TokenIdKeywordContinue) {
722701 AstNode *node = ast_create_node(pc, NodeTypeContinue, token);
723702 *token_index += 1;
703 Token *maybe_colon_token = &pc->tokens->at(*token_index);
704 if (maybe_colon_token->id == TokenIdColon) {
705 *token_index += 1;
706 Token *name = ast_eat_token(pc, token_index, TokenIdSymbol);
707 node->data.continue_expr.name = token_buf(name);
708 }
724709 return node;
725710 } else if (token->id == TokenIdKeywordUndefined) {
726711 AstNode *node = ast_create_node(pc, NodeTypeUndefinedLiteral, token);
......@@ -770,10 +755,6 @@ static AstNode *ast_parse_primary_expr(ParseContext *pc, size_t *token_index, bo
770755 return node;
771756 }
772757
773 AstNode *goto_node = ast_parse_goto_expr(pc, token_index, false);
774 if (goto_node)
775 return goto_node;
776
777758 AstNode *grouped_expr_node = ast_parse_grouped_expr(pc, token_index, false);
778759 if (grouped_expr_node) {
779760 return grouped_expr_node;
......@@ -1488,7 +1469,7 @@ static AstNode *ast_parse_return_expr(ParseContext *pc, size_t *token_index) {
14881469}
14891470
14901471/*
1491BreakExpression : "break" option(Expression)
1472BreakExpression = "break" option(":" Symbol) option(Expression)
14921473*/
14931474static AstNode *ast_parse_break_expr(ParseContext *pc, size_t *token_index) {
14941475 Token *token = &pc->tokens->at(*token_index);
......@@ -1498,8 +1479,15 @@ static AstNode *ast_parse_break_expr(ParseContext *pc, size_t *token_index) {
14981479 } else {
14991480 return nullptr;
15001481 }
1501
15021482 AstNode *node = ast_create_node(pc, NodeTypeBreak, token);
1483
1484 Token *maybe_colon_token = &pc->tokens->at(*token_index);
1485 if (maybe_colon_token->id == TokenIdColon) {
1486 *token_index += 1;
1487 Token *name = ast_eat_token(pc, token_index, TokenIdSymbol);
1488 node->data.break_expr.name = token_buf(name);
1489 }
1490
15031491 node->data.break_expr.expr = ast_parse_expression(pc, token_index, false);
15041492
15051493 return node;
......@@ -1678,35 +1666,53 @@ static AstNode *ast_parse_bool_or_expr(ParseContext *pc, size_t *token_index, bo
16781666}
16791667
16801668/*
1681WhileExpression(body) = option("inline") "while" "(" Expression ")" option("|" option("*") Symbol "|") option(":" "(" Expression ")") body option("else" option("|" Symbol "|") BlockExpression(body))
1669WhileExpression(body) = option(Symbol ":") option("inline") "while" "(" Expression ")" option("|" option("*") Symbol "|") option(":" "(" Expression ")") body option("else" option("|" Symbol "|") BlockExpression(body))
16821670*/
16831671static AstNode *ast_parse_while_expr(ParseContext *pc, size_t *token_index, bool mandatory) {
1684 Token *first_token = &pc->tokens->at(*token_index);
1685 Token *while_token;
1672 size_t orig_token_index = *token_index;
16861673
1687 bool is_inline;
1688 if (first_token->id == TokenIdKeywordInline) {
1689 while_token = &pc->tokens->at(*token_index + 1);
1690 if (while_token->id == TokenIdKeywordWhile) {
1691 is_inline = true;
1692 *token_index += 2;
1674 Token *name_token = nullptr;
1675 Token *token = &pc->tokens->at(*token_index);
1676
1677 if (token->id == TokenIdSymbol) {
1678 *token_index += 1;
1679 Token *colon_token = &pc->tokens->at(*token_index);
1680 if (colon_token->id == TokenIdColon) {
1681 *token_index += 1;
1682 name_token = token;
1683 token = &pc->tokens->at(*token_index);
16931684 } else if (mandatory) {
1694 ast_expect_token(pc, while_token, TokenIdKeywordWhile);
1685 ast_expect_token(pc, colon_token, TokenIdColon);
16951686 zig_unreachable();
16961687 } else {
1688 *token_index = orig_token_index;
16971689 return nullptr;
16981690 }
1699 } else if (first_token->id == TokenIdKeywordWhile) {
1700 while_token = first_token;
1701 is_inline = false;
1691 }
1692
1693 bool is_inline = false;
1694 if (token->id == TokenIdKeywordInline) {
1695 is_inline = true;
1696 *token_index += 1;
1697 token = &pc->tokens->at(*token_index);
1698 }
1699
1700 Token *while_token;
1701 if (token->id == TokenIdKeywordWhile) {
1702 while_token = token;
17021703 *token_index += 1;
17031704 } else if (mandatory) {
1704 ast_expect_token(pc, first_token, TokenIdKeywordWhile);
1705 ast_expect_token(pc, token, TokenIdKeywordWhile);
17051706 zig_unreachable();
17061707 } else {
1708 *token_index = orig_token_index;
17071709 return nullptr;
17081710 }
1711
17091712 AstNode *node = ast_create_node(pc, NodeTypeWhileExpr, while_token);
1713 if (name_token != nullptr) {
1714 node->data.while_expr.name = token_buf(name_token);
1715 }
17101716 node->data.while_expr.is_inline = is_inline;
17111717
17121718 ast_eat_token(pc, token_index, TokenIdLParen);
......@@ -1766,36 +1772,53 @@ static AstNode *ast_parse_symbol(ParseContext *pc, size_t *token_index) {
17661772}
17671773
17681774/*
1769ForExpression(body) = option("inline") "for" "(" Expression ")" option("|" option("*") Symbol option("," Symbol) "|") body option("else" BlockExpression(body))
1775ForExpression(body) = option(Symbol ":") option("inline") "for" "(" Expression ")" option("|" option("*") Symbol option("," Symbol) "|") body option("else" BlockExpression(body))
17701776*/
17711777static AstNode *ast_parse_for_expr(ParseContext *pc, size_t *token_index, bool mandatory) {
1772 Token *first_token = &pc->tokens->at(*token_index);
1773 Token *for_token;
1778 size_t orig_token_index = *token_index;
17741779
1775 bool is_inline;
1776 if (first_token->id == TokenIdKeywordInline) {
1777 is_inline = true;
1778 for_token = &pc->tokens->at(*token_index + 1);
1779 if (for_token->id == TokenIdKeywordFor) {
1780 *token_index += 2;
1780 Token *name_token = nullptr;
1781 Token *token = &pc->tokens->at(*token_index);
1782
1783 if (token->id == TokenIdSymbol) {
1784 *token_index += 1;
1785 Token *colon_token = &pc->tokens->at(*token_index);
1786 if (colon_token->id == TokenIdColon) {
1787 *token_index += 1;
1788 name_token = token;
1789 token = &pc->tokens->at(*token_index);
17811790 } else if (mandatory) {
1782 ast_expect_token(pc, first_token, TokenIdKeywordFor);
1791 ast_expect_token(pc, colon_token, TokenIdColon);
17831792 zig_unreachable();
17841793 } else {
1794 *token_index = orig_token_index;
17851795 return nullptr;
17861796 }
1787 } else if (first_token->id == TokenIdKeywordFor) {
1788 for_token = first_token;
1789 is_inline = false;
1797 }
1798
1799 bool is_inline = false;
1800 if (token->id == TokenIdKeywordInline) {
1801 is_inline = true;
1802 *token_index += 1;
1803 token = &pc->tokens->at(*token_index);
1804 }
1805
1806 Token *for_token;
1807 if (token->id == TokenIdKeywordFor) {
1808 for_token = token;
17901809 *token_index += 1;
17911810 } else if (mandatory) {
1792 ast_expect_token(pc, first_token, TokenIdKeywordFor);
1811 ast_expect_token(pc, token, TokenIdKeywordFor);
17931812 zig_unreachable();
17941813 } else {
1814 *token_index = orig_token_index;
17951815 return nullptr;
17961816 }
17971817
17981818 AstNode *node = ast_create_node(pc, NodeTypeForExpr, for_token);
1819 if (name_token != nullptr) {
1820 node->data.for_expr.name = token_buf(name_token);
1821 }
17991822 node->data.for_expr.is_inline = is_inline;
18001823
18011824 ast_eat_token(pc, token_index, TokenIdLParen);
......@@ -2125,32 +2148,6 @@ static AstNode *ast_parse_expression(ParseContext *pc, size_t *token_index, bool
21252148/*
21262149Label: token(Symbol) token(Colon)
21272150*/
2128static AstNode *ast_parse_label(ParseContext *pc, size_t *token_index, bool mandatory) {
2129 Token *symbol_token = &pc->tokens->at(*token_index);
2130 if (symbol_token->id != TokenIdSymbol) {
2131 if (mandatory) {
2132 ast_expect_token(pc, symbol_token, TokenIdSymbol);
2133 } else {
2134 return nullptr;
2135 }
2136 }
2137
2138 Token *colon_token = &pc->tokens->at(*token_index + 1);
2139 if (colon_token->id != TokenIdColon) {
2140 if (mandatory) {
2141 ast_expect_token(pc, colon_token, TokenIdColon);
2142 } else {
2143 return nullptr;
2144 }
2145 }
2146
2147 *token_index += 2;
2148
2149 AstNode *node = ast_create_node(pc, NodeTypeLabel, symbol_token);
2150 node->data.label.name = token_buf(symbol_token);
2151 return node;
2152}
2153
21542151static bool statement_terminates_without_semicolon(AstNode *node) {
21552152 switch (node->type) {
21562153 case NodeTypeIfBoolExpr:
......@@ -2175,7 +2172,6 @@ static bool statement_terminates_without_semicolon(AstNode *node) {
21752172 return node->data.defer.expr->type == NodeTypeBlock;
21762173 case NodeTypeSwitchExpr:
21772174 case NodeTypeBlock:
2178 case NodeTypeLabel:
21792175 return true;
21802176 default:
21812177 return false;
......@@ -2183,27 +2179,48 @@ static bool statement_terminates_without_semicolon(AstNode *node) {
21832179}
21842180
21852181/*
2186Block = "{" many(Statement) option(Expression) "}"
2182Block = option(Symbol ":") "{" many(Statement) option(Expression) "}"
21872183Statement = Label | VariableDeclaration ";" | Defer(Block) | Defer(Expression) ";" | BlockExpression(Block) | Expression ";" | ";" | ExportDecl
21882184*/
21892185static AstNode *ast_parse_block(ParseContext *pc, size_t *token_index, bool mandatory) {
2186 size_t orig_token_index = *token_index;
2187
2188 Token *name_token = nullptr;
21902189 Token *last_token = &pc->tokens->at(*token_index);
21912190
2191 if (last_token->id == TokenIdSymbol) {
2192 *token_index += 1;
2193 Token *colon_token = &pc->tokens->at(*token_index);
2194 if (colon_token->id == TokenIdColon) {
2195 *token_index += 1;
2196 name_token = last_token;
2197 last_token = &pc->tokens->at(*token_index);
2198 } else if (mandatory) {
2199 ast_expect_token(pc, colon_token, TokenIdColon);
2200 zig_unreachable();
2201 } else {
2202 *token_index = orig_token_index;
2203 return nullptr;
2204 }
2205 }
2206
21922207 if (last_token->id != TokenIdLBrace) {
21932208 if (mandatory) {
21942209 ast_expect_token(pc, last_token, TokenIdLBrace);
21952210 } else {
2211 *token_index = orig_token_index;
21962212 return nullptr;
21972213 }
21982214 }
21992215 *token_index += 1;
22002216
22012217 AstNode *node = ast_create_node(pc, NodeTypeBlock, last_token);
2218 if (name_token != nullptr) {
2219 node->data.block.name = token_buf(name_token);
2220 }
22022221
22032222 for (;;) {
2204 AstNode *statement_node = ast_parse_label(pc, token_index, false);
2205 if (!statement_node)
2206 statement_node = ast_parse_local_var_decl(pc, token_index);
2223 AstNode *statement_node = ast_parse_local_var_decl(pc, token_index);
22072224 if (!statement_node)
22082225 statement_node = ast_parse_defer_expr(pc, token_index);
22092226 if (!statement_node)
......@@ -2225,9 +2242,7 @@ static AstNode *ast_parse_block(ParseContext *pc, size_t *token_index, bool mand
22252242 }
22262243 }
22272244
2228 node->data.block.last_statement_is_result_expression = statement_node && !(
2229 statement_node->type == NodeTypeLabel ||
2230 statement_node->type == NodeTypeDefer);
2245 node->data.block.last_statement_is_result_expression = statement_node && statement_node->type != NodeTypeDefer;
22312246
22322247 last_token = &pc->tokens->at(*token_index);
22332248 if (last_token->id == TokenIdRBrace) {
......@@ -2860,12 +2875,6 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont
28602875 visit_field(&node->data.switch_range.start, visit, context);
28612876 visit_field(&node->data.switch_range.end, visit, context);
28622877 break;
2863 case NodeTypeLabel:
2864 // none
2865 break;
2866 case NodeTypeGoto:
2867 // none
2868 break;
28692878 case NodeTypeCompTime:
28702879 visit_field(&node->data.comptime_expr.expr, visit, context);
28712880 break;
src/translate_c.cpp+7-177
......@@ -104,10 +104,8 @@ static TransScopeRoot *trans_scope_root_create(Context *c);
104104static TransScopeWhile *trans_scope_while_create(Context *c, TransScope *parent_scope);
105105static TransScopeBlock *trans_scope_block_create(Context *c, TransScope *parent_scope);
106106static TransScopeVar *trans_scope_var_create(Context *c, TransScope *parent_scope, Buf *wanted_name);
107static TransScopeSwitch *trans_scope_switch_create(Context *c, TransScope *parent_scope);
108107
109108static TransScopeBlock *trans_scope_block_find(TransScope *scope);
110static TransScopeSwitch *trans_scope_switch_find(TransScope *scope);
111109
112110static AstNode *resolve_record_decl(Context *c, const RecordDecl *record_decl);
113111static AstNode *resolve_enum_decl(Context *c, const EnumDecl *enum_decl);
......@@ -265,18 +263,6 @@ static AstNode *trans_create_node_addr_of(Context *c, bool is_const, bool is_vol
265263 return node;
266264}
267265
268static AstNode *trans_create_node_goto(Context *c, Buf *label_name) {
269 AstNode *goto_node = trans_create_node(c, NodeTypeGoto);
270 goto_node->data.goto_expr.name = label_name;
271 return goto_node;
272}
273
274static AstNode *trans_create_node_label(Context *c, Buf *label_name) {
275 AstNode *label_node = trans_create_node(c, NodeTypeLabel);
276 label_node->data.label.name = label_name;
277 return label_node;
278}
279
280266static AstNode *trans_create_node_bool(Context *c, bool value) {
281267 AstNode *bool_node = trans_create_node(c, NodeTypeBoolLiteral);
282268 bool_node->data.bool_literal.value = value;
......@@ -2379,145 +2365,6 @@ static AstNode *trans_do_loop(Context *c, TransScope *parent_scope, const DoStmt
23792365 return while_scope->node;
23802366}
23812367
2382static AstNode *trans_switch_stmt(Context *c, TransScope *parent_scope, const SwitchStmt *stmt) {
2383 TransScopeBlock *block_scope = trans_scope_block_create(c, parent_scope);
2384
2385 TransScopeSwitch *switch_scope;
2386
2387 const DeclStmt *var_decl_stmt = stmt->getConditionVariableDeclStmt();
2388 if (var_decl_stmt == nullptr) {
2389 switch_scope = trans_scope_switch_create(c, &block_scope->base);
2390 } else {
2391 AstNode *vars_node;
2392 TransScope *var_scope = trans_stmt(c, &block_scope->base, var_decl_stmt, &vars_node);
2393 if (var_scope == nullptr)
2394 return nullptr;
2395 if (vars_node != nullptr)
2396 block_scope->node->data.block.statements.append(vars_node);
2397 switch_scope = trans_scope_switch_create(c, var_scope);
2398 }
2399 block_scope->node->data.block.statements.append(switch_scope->switch_node);
2400
2401 // TODO avoid name collisions
2402 Buf *end_label_name = buf_create_from_str("end");
2403 switch_scope->end_label_name = end_label_name;
2404
2405 const Expr *cond_expr = stmt->getCond();
2406 assert(cond_expr != nullptr);
2407
2408 AstNode *expr_node = trans_expr(c, ResultUsedYes, &block_scope->base, cond_expr, TransRValue);
2409 if (expr_node == nullptr)
2410 return nullptr;
2411 switch_scope->switch_node->data.switch_expr.expr = expr_node;
2412
2413 AstNode *body_node;
2414 const Stmt *body_stmt = stmt->getBody();
2415 if (body_stmt->getStmtClass() == Stmt::CompoundStmtClass) {
2416 if (trans_compound_stmt_inline(c, &switch_scope->base, (const CompoundStmt *)body_stmt,
2417 block_scope->node, nullptr))
2418 {
2419 return nullptr;
2420 }
2421 } else {
2422 TransScope *body_scope = trans_stmt(c, &switch_scope->base, body_stmt, &body_node);
2423 if (body_scope == nullptr)
2424 return nullptr;
2425 if (body_node != nullptr)
2426 block_scope->node->data.block.statements.append(body_node);
2427 }
2428
2429 if (!switch_scope->found_default && !stmt->isAllEnumCasesCovered()) {
2430 AstNode *prong_node = trans_create_node(c, NodeTypeSwitchProng);
2431 prong_node->data.switch_prong.expr = trans_create_node_goto(c, end_label_name);
2432 switch_scope->switch_node->data.switch_expr.prongs.append(prong_node);
2433 }
2434
2435 // This is necessary if the last switch case "falls through" the end of the switch block
2436 block_scope->node->data.block.statements.append(trans_create_node_goto(c, end_label_name));
2437
2438 block_scope->node->data.block.statements.append(trans_create_node_label(c, end_label_name));
2439
2440 return block_scope->node;
2441}
2442
2443static int trans_switch_case(Context *c, TransScope *parent_scope, const CaseStmt *stmt, AstNode **out_node,
2444 TransScope **out_scope)
2445{
2446 *out_node = nullptr;
2447
2448 if (stmt->getRHS() != nullptr) {
2449 emit_warning(c, stmt->getLocStart(), "TODO support GNU switch case a ... b extension");
2450 return ErrorUnexpected;
2451 }
2452
2453 TransScopeSwitch *switch_scope = trans_scope_switch_find(parent_scope);
2454 assert(switch_scope != nullptr);
2455
2456 Buf *label_name = buf_sprintf("case_%" PRIu32, switch_scope->case_index);
2457 switch_scope->case_index += 1;
2458
2459 {
2460 // Add the prong
2461 AstNode *prong_node = trans_create_node(c, NodeTypeSwitchProng);
2462 AstNode *item_node = trans_expr(c, ResultUsedYes, &switch_scope->base, stmt->getLHS(), TransRValue);
2463 if (item_node == nullptr)
2464 return ErrorUnexpected;
2465 prong_node->data.switch_prong.items.append(item_node);
2466
2467 prong_node->data.switch_prong.expr = trans_create_node_goto(c, label_name);
2468
2469 switch_scope->switch_node->data.switch_expr.prongs.append(prong_node);
2470 }
2471
2472 TransScopeBlock *scope_block = trans_scope_block_find(parent_scope);
2473 scope_block->node->data.block.statements.append(trans_create_node_label(c, label_name));
2474
2475 AstNode *sub_stmt_node;
2476 TransScope *new_scope = trans_stmt(c, parent_scope, stmt->getSubStmt(), &sub_stmt_node);
2477 if (new_scope == nullptr)
2478 return ErrorUnexpected;
2479 if (sub_stmt_node != nullptr)
2480 scope_block->node->data.block.statements.append(sub_stmt_node);
2481
2482 *out_scope = new_scope;
2483 return ErrorNone;
2484}
2485
2486static int trans_switch_default(Context *c, TransScope *parent_scope, const DefaultStmt *stmt, AstNode **out_node,
2487 TransScope **out_scope)
2488{
2489 *out_node = nullptr;
2490
2491 TransScopeSwitch *switch_scope = trans_scope_switch_find(parent_scope);
2492 assert(switch_scope != nullptr);
2493
2494 Buf *label_name = buf_sprintf("default");
2495
2496 {
2497 // Add the prong
2498 AstNode *prong_node = trans_create_node(c, NodeTypeSwitchProng);
2499
2500 prong_node->data.switch_prong.expr = trans_create_node_goto(c, label_name);
2501
2502 switch_scope->switch_node->data.switch_expr.prongs.append(prong_node);
2503 switch_scope->found_default = true;
2504 }
2505
2506 TransScopeBlock *scope_block = trans_scope_block_find(parent_scope);
2507 scope_block->node->data.block.statements.append(trans_create_node_label(c, label_name));
2508
2509
2510 AstNode *sub_stmt_node;
2511 TransScope *new_scope = trans_stmt(c, parent_scope, stmt->getSubStmt(), &sub_stmt_node);
2512 if (new_scope == nullptr)
2513 return ErrorUnexpected;
2514 if (sub_stmt_node != nullptr)
2515 scope_block->node->data.block.statements.append(sub_stmt_node);
2516
2517 *out_scope = new_scope;
2518 return ErrorNone;
2519}
2520
25212368static AstNode *trans_for_loop(Context *c, TransScope *parent_scope, const ForStmt *stmt) {
25222369 AstNode *loop_block_node;
25232370 TransScopeWhile *while_scope;
......@@ -2595,8 +2442,7 @@ static AstNode *trans_break_stmt(Context *c, TransScope *scope, const BreakStmt
25952442 if (cur_scope->id == TransScopeIdWhile) {
25962443 return trans_create_node(c, NodeTypeBreak);
25972444 } else if (cur_scope->id == TransScopeIdSwitch) {
2598 TransScopeSwitch *switch_scope = (TransScopeSwitch *)cur_scope;
2599 return trans_create_node_goto(c, switch_scope->end_label_name);
2445 zig_panic("TODO");
26002446 }
26012447 cur_scope = cur_scope->parent;
26022448 }
......@@ -2696,12 +2542,14 @@ static int trans_stmt_extra(Context *c, TransScope *scope, const Stmt *stmt,
26962542 return wrap_stmt(out_node, out_child_scope, scope,
26972543 trans_expr(c, result_used, scope, ((const ParenExpr*)stmt)->getSubExpr(), lrvalue));
26982544 case Stmt::SwitchStmtClass:
2699 return wrap_stmt(out_node, out_child_scope, scope,
2700 trans_switch_stmt(c, scope, (const SwitchStmt *)stmt));
2545 emit_warning(c, stmt->getLocStart(), "TODO handle C SwitchStmtClass");
2546 return ErrorUnexpected;
27012547 case Stmt::CaseStmtClass:
2702 return trans_switch_case(c, scope, (const CaseStmt *)stmt, out_node, out_child_scope);
2548 emit_warning(c, stmt->getLocStart(), "TODO handle C CaseStmtClass");
2549 return ErrorUnexpected;
27032550 case Stmt::DefaultStmtClass:
2704 return trans_switch_default(c, scope, (const DefaultStmt *)stmt, out_node, out_child_scope);
2551 emit_warning(c, stmt->getLocStart(), "TODO handle C DefaultStmtClass");
2552 return ErrorUnexpected;
27052553 case Stmt::NoStmtClass:
27062554 emit_warning(c, stmt->getLocStart(), "TODO handle C NoStmtClass");
27072555 return ErrorUnexpected;
......@@ -3871,14 +3719,6 @@ static TransScopeVar *trans_scope_var_create(Context *c, TransScope *parent_scop
38713719 return result;
38723720}
38733721
3874static TransScopeSwitch *trans_scope_switch_create(Context *c, TransScope *parent_scope) {
3875 TransScopeSwitch *result = allocate<TransScopeSwitch>(1);
3876 result->base.id = TransScopeIdSwitch;
3877 result->base.parent = parent_scope;
3878 result->switch_node = trans_create_node(c, NodeTypeSwitchExpr);
3879 return result;
3880}
3881
38823722static TransScopeBlock *trans_scope_block_find(TransScope *scope) {
38833723 while (scope != nullptr) {
38843724 if (scope->id == TransScopeIdBlock) {
......@@ -3889,16 +3729,6 @@ static TransScopeBlock *trans_scope_block_find(TransScope *scope) {
38893729 return nullptr;
38903730}
38913731
3892static TransScopeSwitch *trans_scope_switch_find(TransScope *scope) {
3893 while (scope != nullptr) {
3894 if (scope->id == TransScopeIdSwitch) {
3895 return (TransScopeSwitch *)scope;
3896 }
3897 scope = scope->parent;
3898 }
3899 return nullptr;
3900}
3901
39023732static void render_aliases(Context *c) {
39033733 for (size_t i = 0; i < c->aliases.length; i += 1) {
39043734 Alias *alias = &c->aliases.at(i);
std/elf.zig+2-4
......@@ -243,7 +243,7 @@ pub const Elf = struct {
243243 var file_stream = io.FileInStream.init(elf.in_file);
244244 const in = &file_stream.stream;
245245
246 for (elf.section_headers) |*elf_section| {
246 section_loop: for (elf.section_headers) |*elf_section| {
247247 if (elf_section.sh_type == SHT_NULL) continue;
248248
249249 const name_offset = elf.string_section.offset + elf_section.name;
......@@ -251,15 +251,13 @@ pub const Elf = struct {
251251
252252 for (name) |expected_c| {
253253 const target_c = %return in.readByte();
254 if (target_c == 0 or expected_c != target_c) goto next_section;
254 if (target_c == 0 or expected_c != target_c) continue :section_loop;
255255 }
256256
257257 {
258258 const null_byte = %return in.readByte();
259259 if (null_byte == 0) return elf_section;
260260 }
261
262 next_section:
263261 }
264262
265263 return null;
std/os/index.zig+74-72
......@@ -902,40 +902,41 @@ pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) -> %void {
902902/// this function recursively removes its entries and then tries again.
903903// TODO non-recursive implementation
904904pub fn deleteTree(allocator: &Allocator, full_path: []const u8) -> %void {
905start_over:
906 // First, try deleting the item as a file. This way we don't follow sym links.
907 if (deleteFile(allocator, full_path)) {
908 return;
909 } else |err| {
910 if (err == error.FileNotFound)
905 start_over: while (true) {
906 // First, try deleting the item as a file. This way we don't follow sym links.
907 if (deleteFile(allocator, full_path)) {
911908 return;
912 if (err != error.IsDir)
913 return err;
914 }
915 {
916 var dir = Dir.open(allocator, full_path) %% |err| {
909 } else |err| {
917910 if (err == error.FileNotFound)
918911 return;
919 if (err == error.NotDir)
920 goto start_over;
921 return err;
922 };
923 defer dir.close();
912 if (err != error.IsDir)
913 return err;
914 }
915 {
916 var dir = Dir.open(allocator, full_path) %% |err| {
917 if (err == error.FileNotFound)
918 return;
919 if (err == error.NotDir)
920 continue :start_over;
921 return err;
922 };
923 defer dir.close();
924924
925 var full_entry_buf = ArrayList(u8).init(allocator);
926 defer full_entry_buf.deinit();
925 var full_entry_buf = ArrayList(u8).init(allocator);
926 defer full_entry_buf.deinit();
927927
928 while (%return dir.next()) |entry| {
929 %return full_entry_buf.resize(full_path.len + entry.name.len + 1);
930 const full_entry_path = full_entry_buf.toSlice();
931 mem.copy(u8, full_entry_path, full_path);
932 full_entry_path[full_path.len] = '/';
933 mem.copy(u8, full_entry_path[full_path.len + 1..], entry.name);
928 while (%return dir.next()) |entry| {
929 %return full_entry_buf.resize(full_path.len + entry.name.len + 1);
930 const full_entry_path = full_entry_buf.toSlice();
931 mem.copy(u8, full_entry_path, full_path);
932 full_entry_path[full_path.len] = '/';
933 mem.copy(u8, full_entry_path[full_path.len + 1..], entry.name);
934934
935 %return deleteTree(allocator, full_entry_path);
935 %return deleteTree(allocator, full_entry_path);
936 }
936937 }
938 return deleteDir(allocator, full_path);
937939 }
938 return deleteDir(allocator, full_path);
939940}
940941
941942pub const Dir = struct {
......@@ -988,58 +989,59 @@ pub const Dir = struct {
988989 /// Memory such as file names referenced in this returned entry becomes invalid
989990 /// with subsequent calls to next, as well as when this ::Dir is deinitialized.
990991 pub fn next(self: &Dir) -> %?Entry {
991 start_over:
992 if (self.index >= self.end_index) {
993 if (self.buf.len == 0) {
994 self.buf = %return self.allocator.alloc(u8, page_size);
995 }
992 start_over: while (true) {
993 if (self.index >= self.end_index) {
994 if (self.buf.len == 0) {
995 self.buf = %return self.allocator.alloc(u8, page_size);
996 }
996997
997 while (true) {
998 const result = posix.getdents(self.fd, self.buf.ptr, self.buf.len);
999 const err = linux.getErrno(result);
1000 if (err > 0) {
1001 switch (err) {
1002 posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable,
1003 posix.EINVAL => {
1004 self.buf = %return self.allocator.realloc(u8, self.buf, self.buf.len * 2);
1005 continue;
1006 },
1007 else => return unexpectedErrorPosix(err),
1008 };
998 while (true) {
999 const result = posix.getdents(self.fd, self.buf.ptr, self.buf.len);
1000 const err = linux.getErrno(result);
1001 if (err > 0) {
1002 switch (err) {
1003 posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable,
1004 posix.EINVAL => {
1005 self.buf = %return self.allocator.realloc(u8, self.buf, self.buf.len * 2);
1006 continue;
1007 },
1008 else => return unexpectedErrorPosix(err),
1009 };
1010 }
1011 if (result == 0)
1012 return null;
1013 self.index = 0;
1014 self.end_index = result;
1015 break;
10091016 }
1010 if (result == 0)
1011 return null;
1012 self.index = 0;
1013 self.end_index = result;
1014 break;
10151017 }
1016 }
1017 const linux_entry = @ptrCast(& align(1) LinuxEntry, &self.buf[self.index]);
1018 const next_index = self.index + linux_entry.d_reclen;
1019 self.index = next_index;
1018 const linux_entry = @ptrCast(& align(1) LinuxEntry, &self.buf[self.index]);
1019 const next_index = self.index + linux_entry.d_reclen;
1020 self.index = next_index;
10201021
1021 const name = cstr.toSlice(&linux_entry.d_name);
1022 const name = cstr.toSlice(&linux_entry.d_name);
10221023
1023 // skip . and .. entries
1024 if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) {
1025 goto start_over;
1026 }
1024 // skip . and .. entries
1025 if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) {
1026 continue :start_over;
1027 }
10271028
1028 const type_char = self.buf[next_index - 1];
1029 const entry_kind = switch (type_char) {
1030 posix.DT_BLK => Entry.Kind.BlockDevice,
1031 posix.DT_CHR => Entry.Kind.CharacterDevice,
1032 posix.DT_DIR => Entry.Kind.Directory,
1033 posix.DT_FIFO => Entry.Kind.NamedPipe,
1034 posix.DT_LNK => Entry.Kind.SymLink,
1035 posix.DT_REG => Entry.Kind.File,
1036 posix.DT_SOCK => Entry.Kind.UnixDomainSocket,
1037 else => Entry.Kind.Unknown,
1038 };
1039 return Entry {
1040 .name = name,
1041 .kind = entry_kind,
1042 };
1029 const type_char = self.buf[next_index - 1];
1030 const entry_kind = switch (type_char) {
1031 posix.DT_BLK => Entry.Kind.BlockDevice,
1032 posix.DT_CHR => Entry.Kind.CharacterDevice,
1033 posix.DT_DIR => Entry.Kind.Directory,
1034 posix.DT_FIFO => Entry.Kind.NamedPipe,
1035 posix.DT_LNK => Entry.Kind.SymLink,
1036 posix.DT_REG => Entry.Kind.File,
1037 posix.DT_SOCK => Entry.Kind.UnixDomainSocket,
1038 else => Entry.Kind.Unknown,
1039 };
1040 return Entry {
1041 .name = name,
1042 .kind = entry_kind,
1043 };
1044 }
10431045 }
10441046};
10451047
test/behavior.zig-1
......@@ -20,7 +20,6 @@ comptime {
2020 _ = @import("cases/fn.zig");
2121 _ = @import("cases/for.zig");
2222 _ = @import("cases/generics.zig");
23 _ = @import("cases/goto.zig");
2423 _ = @import("cases/if.zig");
2524 _ = @import("cases/import.zig");
2625 _ = @import("cases/incomplete_struct_param_tld.zig");
test/cases/for.zig+34
......@@ -55,3 +55,37 @@ test "basic for loop" {
5555
5656 assert(mem.eql(u8, buffer[0..buf_index], expected_result));
5757}
58
59test "break from outer for loop" {
60 testBreakOuter();
61 comptime testBreakOuter();
62}
63
64fn testBreakOuter() {
65 var array = "aoeu";
66 var count: usize = 0;
67 outer: for (array) |_| {
68 for (array) |_2| { // TODO shouldn't get error for redeclaring "_"
69 count += 1;
70 break :outer;
71 }
72 }
73 assert(count == 1);
74}
75
76test "continue outer for loop" {
77 testContinueOuter();
78 comptime testContinueOuter();
79}
80
81fn testContinueOuter() {
82 var array = "aoeu";
83 var counter: usize = 0;
84 outer: for (array) |_| {
85 for (array) |_2| { // TODO shouldn't get error for redeclaring "_"
86 counter += 1;
87 continue :outer;
88 }
89 }
90 assert(counter == array.len);
91}
test/cases/goto.zig deleted-37
......@@ -1,37 +0,0 @@
1const assert = @import("std").debug.assert;
2
3test "goto and labels" {
4 gotoLoop();
5 assert(goto_counter == 10);
6}
7fn gotoLoop() {
8 var i: i32 = 0;
9 goto cond;
10loop:
11 i += 1;
12cond:
13 if (!(i < 10)) goto end;
14 goto_counter += 1;
15 goto loop;
16end:
17}
18var goto_counter: i32 = 0;
19
20
21
22test "goto leave defer scope" {
23 testGotoLeaveDeferScope(true);
24}
25fn testGotoLeaveDeferScope(b: bool) {
26 var it_worked = false;
27
28 goto entry;
29exit:
30 if (it_worked) {
31 return;
32 }
33 unreachable;
34entry:
35 defer it_worked = true;
36 if (b) goto exit;
37}
test/cases/while.zig+27
......@@ -188,6 +188,33 @@ test "while on bool with else result follow break prong" {
188188 assert(result == 10);
189189}
190190
191test "break from outer while loop" {
192 testBreakOuter();
193 comptime testBreakOuter();
194}
195
196fn testBreakOuter() {
197 outer: while (true) {
198 while (true) {
199 break :outer;
200 }
201 }
202}
203
204test "continue outer while loop" {
205 testContinueOuter();
206 comptime testContinueOuter();
207}
208
209fn testContinueOuter() {
210 var i: usize = 0;
211 outer: while (i < 10) : (i += 1) {
212 while (true) {
213 continue :outer;
214 }
215 }
216}
217
191218fn returnNull() -> ?i32 { null }
192219fn returnMaybe(x: i32) -> ?i32 { x }
193220error YouWantedAnError;
test/compile_errors.zig+21-30
......@@ -1,6 +1,27 @@
11const tests = @import("tests.zig");
22
33pub fn addCases(cases: &tests.CompileErrorContext) {
4 cases.add("labeled break not found",
5 \\export fn entry() {
6 \\ blah: while (true) {
7 \\ while (true) {
8 \\ break :outer;
9 \\ }
10 \\ }
11 \\}
12 , ".tmp_source.zig:4:13: error: labeled loop not found: 'outer'");
13
14 cases.add("labeled continue not found",
15 \\export fn entry() {
16 \\ var i: usize = 0;
17 \\ blah: while (i < 10) : (i += 1) {
18 \\ while (true) {
19 \\ continue :outer;
20 \\ }
21 \\ }
22 \\}
23 , ".tmp_source.zig:5:13: error: labeled loop not found: 'outer'");
24
425 cases.add("attempt to use 0 bit type in extern fn",
526 \\extern fn foo(ptr: extern fn(&void));
627 \\
......@@ -833,26 +854,6 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
833854 \\export fn entry() -> usize { @sizeOf(@typeOf(test1)) }
834855 , ".tmp_source.zig:3:16: error: unable to evaluate constant expression");
835856
836 cases.add("goto jumping into block",
837 \\export fn f() {
838 \\ {
839 \\a_label:
840 \\ }
841 \\ goto a_label;
842 \\}
843 , ".tmp_source.zig:5:5: error: no label in scope named 'a_label'");
844
845 cases.add("goto jumping past a defer",
846 \\fn f(b: bool) {
847 \\ if (b) goto label;
848 \\ defer derp();
849 \\label:
850 \\}
851 \\fn derp(){}
852 \\
853 \\export fn entry() -> usize { @sizeOf(@typeOf(f)) }
854 , ".tmp_source.zig:2:12: error: no label in scope named 'label'");
855
856857 cases.add("assign null to non-nullable pointer",
857858 \\const a: &u8 = null;
858859 \\
......@@ -1854,16 +1855,6 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
18541855 ,
18551856 ".tmp_source.zig:4:13: error: cannot continue out of defer expression");
18561857
1857 cases.add("cannot goto out of defer expression",
1858 \\export fn foo() {
1859 \\ defer {
1860 \\ goto label;
1861 \\ };
1862 \\label:
1863 \\}
1864 ,
1865 ".tmp_source.zig:3:9: error: cannot goto out of defer expression");
1866
18671858 cases.add("calling a var args function only known at runtime",
18681859 \\var foos = []fn(...) { foo1, foo2 };
18691860 \\
test/translate_c.zig-80
......@@ -1005,48 +1005,6 @@ pub fn addCases(cases: &tests.TranslateCContext) {
10051005 \\}
10061006 );
10071007
1008 cases.add("switch statement",
1009 \\int foo(int x) {
1010 \\ switch (x) {
1011 \\ case 1:
1012 \\ x += 1;
1013 \\ case 2:
1014 \\ break;
1015 \\ case 3:
1016 \\ case 4:
1017 \\ return x + 1;
1018 \\ default:
1019 \\ return 10;
1020 \\ }
1021 \\ return x + 13;
1022 \\}
1023 ,
1024 \\fn foo(_arg_x: c_int) -> c_int {
1025 \\ var x = _arg_x;
1026 \\ {
1027 \\ switch (x) {
1028 \\ 1 => goto case_0,
1029 \\ 2 => goto case_1,
1030 \\ 3 => goto case_2,
1031 \\ 4 => goto case_3,
1032 \\ else => goto default,
1033 \\ };
1034 \\ case_0:
1035 \\ x += 1;
1036 \\ case_1:
1037 \\ goto end;
1038 \\ case_2:
1039 \\ case_3:
1040 \\ return x + 1;
1041 \\ default:
1042 \\ return 10;
1043 \\ goto end;
1044 \\ end:
1045 \\ };
1046 \\ return x + 13;
1047 \\}
1048 );
1049
10501008 cases.add("macros with field targets",
10511009 \\typedef unsigned int GLbitfield;
10521010 \\typedef void (*PFNGLCLEARPROC) (GLbitfield mask);
......@@ -1085,44 +1043,6 @@ pub fn addCases(cases: &tests.TranslateCContext) {
10851043 \\pub const OpenGLProcs = union_OpenGLProcs;
10861044 );
10871045
1088 cases.add("switch statement with no default",
1089 \\int foo(int x) {
1090 \\ switch (x) {
1091 \\ case 1:
1092 \\ x += 1;
1093 \\ case 2:
1094 \\ break;
1095 \\ case 3:
1096 \\ case 4:
1097 \\ return x + 1;
1098 \\ }
1099 \\ return x + 13;
1100 \\}
1101 ,
1102 \\fn foo(_arg_x: c_int) -> c_int {
1103 \\ var x = _arg_x;
1104 \\ {
1105 \\ switch (x) {
1106 \\ 1 => goto case_0,
1107 \\ 2 => goto case_1,
1108 \\ 3 => goto case_2,
1109 \\ 4 => goto case_3,
1110 \\ else => goto end,
1111 \\ };
1112 \\ case_0:
1113 \\ x += 1;
1114 \\ case_1:
1115 \\ goto end;
1116 \\ case_2:
1117 \\ case_3:
1118 \\ return x + 1;
1119 \\ goto end;
1120 \\ end:
1121 \\ };
1122 \\ return x + 13;
1123 \\}
1124 );
1125
11261046 cases.add("variable name shadowing",
11271047 \\int foo(void) {
11281048 \\ int x = 1;