From c18835d71feb5a3d149e77b510718aaa21f26849 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Wed, 16 Oct 2024 18:33:40 +0100 Subject: [PATCH 01/11] std/zig/render: Implement AutoIndentingStream.init --- lib/std/zig/render.zig | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index b71c94e71f..384de4ff0d 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -81,10 +81,7 @@ const Render = struct { pub fn renderTree(buffer: *std.ArrayList(u8), tree: Ast, fixups: Fixups) Error!void { assert(tree.errors.len == 0); // Cannot render an invalid tree. - var auto_indenting_stream = Ais{ - .indent_delta = indent_delta, - .underlying_writer = buffer.writer(), - }; + var auto_indenting_stream = Ais.init(buffer, indent_delta); var r: Render = .{ .gpa = buffer.allocator, .ais = &auto_indenting_stream, @@ -2152,10 +2149,7 @@ fn renderArrayInit( const sub_expr_buffer_starts = try gpa.alloc(usize, section_exprs.len + 1); defer gpa.free(sub_expr_buffer_starts); - var auto_indenting_stream = Ais{ - .indent_delta = indent_delta, - .underlying_writer = sub_expr_buffer.writer(), - }; + var auto_indenting_stream = Ais.init(sub_expr_buffer, indent_delta); var sub_render: Render = .{ .gpa = r.gpa, .ais = &auto_indenting_stream, @@ -3341,6 +3335,13 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { /// not used until the next line indent_next_line: usize = 0, + pub fn init(buffer: *std.ArrayList(u8), indent_delta: usize) Self { + return .{ + .underlying_writer = buffer.writer(), + .indent_delta = indent_delta, + }; + } + pub fn writer(self: *Self) Writer { return .{ .context = self }; } From 8eee2d9d090b5f63e1530237fac6ad12fb188d53 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Wed, 16 Oct 2024 19:15:19 +0100 Subject: [PATCH 02/11] std/zig/render: Initial implementation of indentation --- lib/std/zig/render.zig | 304 ++++++++++++++++------------------------- 1 file changed, 119 insertions(+), 185 deletions(-) diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 384de4ff0d..869d3e5823 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -82,6 +82,7 @@ const Render = struct { pub fn renderTree(buffer: *std.ArrayList(u8), tree: Ast, fixups: Fixups) Error!void { assert(tree.errors.len == 0); // Cannot render an invalid tree. var auto_indenting_stream = Ais.init(buffer, indent_delta); + defer auto_indenting_stream.deinit(); var r: Render = .{ .gpa = buffer.allocator, .ais = &auto_indenting_stream, @@ -195,7 +196,7 @@ fn renderMember( try renderExpression(r, fn_proto, .space); const body_node = datas[decl].rhs; if (r.fixups.gut_functions.contains(decl)) { - ais.pushIndent(); + try ais.pushIndent(.normal); const lbrace = tree.nodes.items(.main_token)[body_node]; try renderToken(r, lbrace, .newline); try discardAllParams(r, fn_proto); @@ -204,7 +205,7 @@ fn renderMember( try ais.insertNewline(); try renderToken(r, tree.lastToken(body_node), space); // rbrace } else if (r.fixups.unused_var_decls.count() != 0) { - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); const lbrace = tree.nodes.items(.main_token)[body_node]; try renderToken(r, lbrace, .newline); @@ -358,13 +359,16 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { => return renderToken(r, main_tokens[node], space), .multiline_string_literal => { - var locked_indents = ais.lockOneShotIndent(); try ais.maybeInsertNewline(); var i = datas[node].lhs; while (i <= datas[node].rhs) : (i += 1) try renderToken(r, i, .newline); - while (locked_indents > 0) : (locked_indents -= 1) ais.popIndent(); + // dedent the next thing that comes after a multiline string literal + if (!ais.indentStackEmpty()) { + ais.popIndent(); + try ais.pushIndent(.normal); + } switch (space) { .none, .space, .newline, .skip => {}, @@ -442,6 +446,7 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { try renderExpression(r, datas[node].lhs, .space); // target + try ais.pushIndent(.normal); if (token_tags[fallback_first - 1] == .pipe) { try renderToken(r, main_token, .space); // catch keyword try renderToken(r, main_token + 1, .none); // pipe @@ -451,38 +456,27 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { assert(token_tags[fallback_first - 1] == .keyword_catch); try renderToken(r, main_token, after_op_space); // catch keyword } - - ais.pushIndentOneShot(); try renderExpression(r, datas[node].rhs, space); // fallback + ais.popIndent(); }, .field_access => { const main_token = main_tokens[node]; const field_access = datas[node]; + try ais.pushIndent(.normal); try renderExpression(r, field_access.lhs, .none); // Allow a line break between the lhs and the dot if the lhs and rhs // are on different lines. const lhs_last_token = tree.lastToken(field_access.lhs); const same_line = tree.tokensOnSameLine(lhs_last_token, main_token + 1); - if (!same_line) { - if (!hasComment(tree, lhs_last_token, main_token)) try ais.insertNewline(); - ais.pushIndentOneShot(); - } + if (!same_line and !hasComment(tree, lhs_last_token, main_token)) try ais.insertNewline(); try renderToken(r, main_token, .none); // . - // This check ensures that zag() is indented in the following example: - // const x = foo - // .bar() - // . // comment - // zag(); - if (!same_line and hasComment(tree, main_token, main_token + 1)) { - ais.pushIndentOneShot(); - } - - return renderIdentifier(r, field_access.rhs, space, .eagerly_unquote); // field + try renderIdentifier(r, field_access.rhs, space, .eagerly_unquote); // field + ais.popIndent(); }, .error_union, @@ -555,15 +549,14 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { const infix = datas[node]; try renderExpression(r, infix.lhs, .space); const op_token = main_tokens[node]; + try ais.pushIndent(.normal); if (tree.tokensOnSameLine(op_token, op_token + 1)) { try renderToken(r, op_token, .space); } else { - ais.pushIndent(); try renderToken(r, op_token, .newline); - ais.popIndent(); } - ais.pushIndentOneShot(); - return renderExpression(r, infix.rhs, space); + try renderExpression(r, infix.rhs, space); + ais.popIndent(); }, .assign_destructure => { @@ -585,15 +578,14 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { else => try renderExpression(r, variable_node, variable_space), } } + try ais.pushIndent(.normal); if (tree.tokensOnSameLine(full.ast.equal_token, full.ast.equal_token + 1)) { try renderToken(r, full.ast.equal_token, .space); } else { - ais.pushIndent(); try renderToken(r, full.ast.equal_token, .newline); - ais.popIndent(); } - ais.pushIndentOneShot(); - return renderExpression(r, full.ast.value_expr, space); + try renderExpression(r, full.ast.value_expr, space); + ais.popIndent(); }, .bit_not, @@ -671,7 +663,7 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { const one_line = tree.tokensOnSameLine(lbracket, rbracket); const inner_space = if (one_line) Space.none else Space.newline; try renderExpression(r, suffix.lhs, .none); - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, lbracket, inner_space); // [ try renderExpression(r, suffix.rhs, inner_space); ais.popIndent(); @@ -723,8 +715,9 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { .grouped_expression => { try renderToken(r, main_tokens[node], .none); // lparen - ais.pushIndentOneShot(); + try ais.pushIndent(.normal); try renderExpression(r, datas[node].lhs, .none); + ais.popIndent(); return renderToken(r, datas[node].rhs, space); // rparen }, @@ -764,7 +757,7 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { return renderToken(r, rbrace, space); } else if (token_tags[rbrace - 1] == .comma) { // There is a trailing comma so render each member on a new line. - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, lbrace, .newline); var i = lbrace + 1; while (i < rbrace) : (i += 1) { @@ -845,7 +838,7 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { try renderExpression(r, full.ast.condition, .none); // condition expression try renderToken(r, rparen, .space); // ) - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); if (full.ast.cases.len == 0) { try renderToken(r, rparen + 1, .none); // { } else { @@ -920,7 +913,7 @@ fn renderArrayType( const rbracket = tree.firstToken(array_type.ast.elem_type) - 1; const one_line = tree.tokensOnSameLine(array_type.ast.lbracket, rbracket); const inner_space = if (one_line) Space.none else Space.newline; - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, array_type.ast.lbracket, inner_space); // lbracket try renderExpression(r, array_type.ast.elem_count, inner_space); if (array_type.ast.sentinel != 0) { @@ -1236,13 +1229,10 @@ fn renderVarDeclWithoutFixups( const eq_token = tree.firstToken(var_decl.ast.init_node) - 1; const eq_space: Space = if (tree.tokensOnSameLine(eq_token, eq_token + 1)) .space else .newline; - { - ais.pushIndent(); - try renderToken(r, eq_token, eq_space); // = - ais.popIndent(); - } - ais.pushIndentOneShot(); - return renderExpression(r, var_decl.ast.init_node, space); // ; + try ais.pushIndent(.normal); + try renderToken(r, eq_token, eq_space); // = + try renderExpression(r, var_decl.ast.init_node, space); // ; + ais.popIndent(); } fn renderIf(r: *Render, if_node: Ast.full.If, space: Space) Error!void { @@ -1342,23 +1332,28 @@ fn renderThenElse( const then_expr_is_block = nodeIsBlock(node_tags[then_expr]); const indent_then_expr = !then_expr_is_block and !tree.tokensOnSameLine(last_prefix_token, tree.firstToken(then_expr)); - if (indent_then_expr or (then_expr_is_block and ais.isLineOverIndented())) { - ais.pushIndentNextLine(); + + if (indent_then_expr) try ais.pushIndent(.normal); + + if (then_expr_is_block and ais.isLineOverIndented()) { + ais.disableIndentCommitting(); + try renderToken(r, last_prefix_token, .newline); + ais.enableIndentCommitting(); + } else if (indent_then_expr) { try renderToken(r, last_prefix_token, .newline); - ais.popIndent(); } else { try renderToken(r, last_prefix_token, .space); } if (else_expr != 0) { if (indent_then_expr) { - ais.pushIndent(); try renderExpression(r, then_expr, .newline); - ais.popIndent(); } else { try renderExpression(r, then_expr, .space); } + if (indent_then_expr) ais.popIndent(); + var last_else_token = else_token; if (maybe_error_token) |error_token| { @@ -1372,20 +1367,17 @@ fn renderThenElse( !nodeIsBlock(node_tags[else_expr]) and !nodeIsIfForWhileSwitch(node_tags[else_expr]); if (indent_else_expr) { - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, last_else_token, .newline); + try renderExpression(r, else_expr, space); ais.popIndent(); - try renderExpressionIndented(r, else_expr, space); } else { try renderToken(r, last_else_token, .space); try renderExpression(r, else_expr, space); } } else { - if (indent_then_expr) { - try renderExpressionIndented(r, then_expr, space); - } else { - try renderExpression(r, then_expr, space); - } + try renderExpression(r, then_expr, space); + if (indent_then_expr) ais.popIndent(); } } @@ -1411,7 +1403,7 @@ fn renderFor(r: *Render, for_node: Ast.full.For, space: Space) Error!void { var cur = for_node.payload_token; const pipe = std.mem.indexOfScalarPos(std.zig.Token.Tag, token_tags, cur, .pipe).?; if (token_tags[pipe - 1] == .comma) { - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, cur - 1, .newline); // | while (true) { if (token_tags[cur] == .asterisk) { @@ -1540,7 +1532,7 @@ fn renderContainerField( const eq_token = tree.firstToken(field.ast.value_expr) - 1; const eq_space: Space = if (tree.tokensOnSameLine(eq_token, eq_token + 1)) .space else .newline; { - ais.pushIndent(); + try ais.pushIndent(.normal); try renderToken(r, eq_token, eq_space); // = ais.popIndent(); } @@ -1552,12 +1544,12 @@ fn renderContainerField( const maybe_comma = tree.lastToken(field.ast.value_expr) + 1; if (token_tags[maybe_comma] == .comma) { - ais.pushIndent(); + try ais.pushIndent(.normal); try renderExpression(r, field.ast.value_expr, .none); // value ais.popIndent(); try renderToken(r, maybe_comma, .newline); } else { - ais.pushIndent(); + try ais.pushIndent(.normal); try renderExpression(r, field.ast.value_expr, space); // value ais.popIndent(); } @@ -1614,9 +1606,12 @@ fn renderBuiltinCall( if (token_tags[first_param_token] == .multiline_string_literal_line or hasSameLineComment(tree, first_param_token - 1)) { - ais.pushIndentOneShot(); + try ais.pushIndent(.normal); + try renderExpression(r, param_node, .none); + ais.popIndent(); + } else { + try renderExpression(r, param_node, .none); } - try renderExpression(r, param_node, .none); if (i + 1 < params.len) { const comma_token = tree.lastToken(param_node) + 1; @@ -1626,7 +1621,7 @@ fn renderBuiltinCall( return renderToken(r, after_last_param_token, space); // ) } else { // Render one param per line. - ais.pushIndent(); + try ais.pushIndent(.normal); try renderToken(r, builtin_token + 1, Space.newline); // ( for (params) |param_node| { @@ -1752,7 +1747,7 @@ fn renderFnProto(r: *Render, fn_proto: Ast.full.FnProto, space: Space) Error!voi } } else { // One param per line. - ais.pushIndent(); + try ais.pushIndent(.normal); try renderToken(r, lparen, .newline); // ( var param_i: usize = 0; @@ -1933,7 +1928,7 @@ fn renderBlock( try renderIdentifier(r, lbrace - 2, .none, .eagerly_unquote); // identifier try renderToken(r, lbrace - 1, .space); // : } - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); if (statements.len == 0) { try renderToken(r, lbrace, .none); ais.popIndent(); @@ -1986,7 +1981,7 @@ fn renderStructInit( try renderExpression(r, struct_init.ast.type_expr, .none); // T } if (struct_init.ast.fields.len == 0) { - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, struct_init.ast.lbrace, .none); // lbrace ais.popIndent(); return renderToken(r, struct_init.ast.lbrace + 1, space); // rbrace @@ -1996,7 +1991,7 @@ fn renderStructInit( const trailing_comma = token_tags[rbrace - 1] == .comma; if (trailing_comma or hasComment(tree, struct_init.ast.lbrace, rbrace)) { // Render one field init per line. - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, struct_init.ast.lbrace, .newline); try renderToken(r, struct_init.ast.lbrace + 1, .none); // . @@ -2054,7 +2049,7 @@ fn renderArrayInit( } if (array_init.ast.elements.len == 0) { - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, array_init.ast.lbrace, .none); // lbrace ais.popIndent(); return renderToken(r, array_init.ast.lbrace + 1, space); // rbrace @@ -2096,7 +2091,7 @@ fn renderArrayInit( return renderToken(r, last_elem_token + 1, space); // rbrace } - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, array_init.ast.lbrace, .newline); var expr_index: usize = 0; @@ -2149,7 +2144,8 @@ fn renderArrayInit( const sub_expr_buffer_starts = try gpa.alloc(usize, section_exprs.len + 1); defer gpa.free(sub_expr_buffer_starts); - var auto_indenting_stream = Ais.init(sub_expr_buffer, indent_delta); + var auto_indenting_stream = Ais.init(&sub_expr_buffer, indent_delta); + defer auto_indenting_stream.deinit(); var sub_render: Render = .{ .gpa = r.gpa, .ais = &auto_indenting_stream, @@ -2312,7 +2308,7 @@ fn renderContainerDecl( const rbrace = tree.lastToken(container_decl_node); if (container_decl.ast.members.len == 0) { - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); if (token_tags[lbrace + 1] == .container_doc_comment) { try renderToken(r, lbrace, .newline); // lbrace try renderContainerDocComments(r, lbrace + 1); @@ -2354,7 +2350,7 @@ fn renderContainerDecl( } // One member per line. - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, lbrace, .newline); // lbrace if (token_tags[lbrace + 1] == .container_doc_comment) { try renderContainerDocComments(r, lbrace + 1); @@ -2395,7 +2391,7 @@ fn renderAsm( } if (asm_node.ast.items.len == 0) { - ais.pushIndent(); + try ais.pushIndent(.normal); if (asm_node.first_clobber) |first_clobber| { // asm ("foo" ::: "a", "b") // asm ("foo" ::: "a", "b",) @@ -2433,7 +2429,7 @@ fn renderAsm( } } - ais.pushIndent(); + try ais.pushIndent(.normal); try renderExpression(r, asm_node.ast.template, .newline); ais.setIndentDelta(asm_indent_delta); const colon1 = tree.lastToken(asm_node.ast.template) + 1; @@ -2444,7 +2440,7 @@ fn renderAsm( } else colon2: { try renderToken(r, colon1, .space); // : - ais.pushIndent(); + try ais.pushIndent(.normal); for (asm_node.outputs, 0..) |asm_output, i| { if (i + 1 < asm_node.outputs.len) { const next_asm_output = asm_node.outputs[i + 1]; @@ -2476,7 +2472,7 @@ fn renderAsm( break :colon3 colon2 + 1; } else colon3: { try renderToken(r, colon2, .space); // : - ais.pushIndent(); + try ais.pushIndent(.normal); for (asm_node.inputs, 0..) |asm_input, i| { if (i + 1 < asm_node.inputs.len) { const next_asm_input = asm_node.inputs[i + 1]; @@ -2558,7 +2554,7 @@ fn renderParamList( const token_tags = tree.tokens.items(.tag); if (params.len == 0) { - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, lparen, .none); ais.popIndent(); return renderToken(r, lparen + 1, space); // ) @@ -2567,22 +2563,15 @@ fn renderParamList( const last_param = params[params.len - 1]; const after_last_param_tok = tree.lastToken(last_param) + 1; if (token_tags[after_last_param_tok] == .comma) { - ais.pushIndentNextLine(); + try ais.pushIndent(.normal); try renderToken(r, lparen, .newline); // ( for (params, 0..) |param_node, i| { if (i + 1 < params.len) { try renderExpression(r, param_node, .none); - // Unindent the comma for multiline string literals. - const is_multiline_string = - token_tags[tree.firstToken(param_node)] == .multiline_string_literal_line; - if (is_multiline_string) ais.popIndent(); - const comma = tree.lastToken(param_node) + 1; try renderToken(r, comma, .newline); // , - if (is_multiline_string) ais.pushIndent(); - try renderExtraNewline(r, params[i + 1]); } else { try renderExpression(r, param_node, .comma); @@ -2599,9 +2588,12 @@ fn renderParamList( if (token_tags[first_param_token] == .multiline_string_literal_line or hasSameLineComment(tree, first_param_token - 1)) { - ais.pushIndentOneShot(); + try ais.pushIndent(.normal); + try renderExpression(r, param_node, .none); + ais.popIndent(); + } else { + try renderExpression(r, param_node, .none); } - try renderExpression(r, param_node, .none); if (i + 1 < params.len) { const comma = tree.lastToken(param_node) + 1; @@ -2615,66 +2607,6 @@ fn renderParamList( return renderToken(r, after_last_param_tok, space); // ) } -/// Renders the given expression indented, popping the indent before rendering -/// any following line comments -fn renderExpressionIndented(r: *Render, node: Ast.Node.Index, space: Space) Error!void { - const tree = r.tree; - const ais = r.ais; - const token_starts = tree.tokens.items(.start); - const token_tags = tree.tokens.items(.tag); - - ais.pushIndent(); - - var last_token = tree.lastToken(node); - const punctuation = switch (space) { - .none, .space, .newline, .skip => false, - .comma => true, - .comma_space => token_tags[last_token + 1] == .comma, - .semicolon => token_tags[last_token + 1] == .semicolon, - }; - - try renderExpression(r, node, if (punctuation) .none else .skip); - - switch (space) { - .none, .space, .newline, .skip => {}, - .comma => { - if (token_tags[last_token + 1] == .comma) { - try renderToken(r, last_token + 1, .skip); - last_token += 1; - } else { - try ais.writer().writeByte(','); - } - }, - .comma_space => if (token_tags[last_token + 1] == .comma) { - try renderToken(r, last_token + 1, .skip); - last_token += 1; - }, - .semicolon => if (token_tags[last_token + 1] == .semicolon) { - try renderToken(r, last_token + 1, .skip); - last_token += 1; - }, - } - - ais.popIndent(); - - if (space == .skip) return; - - const comment_start = token_starts[last_token] + tokenSliceForRender(tree, last_token).len; - const comment = try renderComments(r, comment_start, token_starts[last_token + 1]); - - if (!comment) switch (space) { - .none => {}, - .space, - .comma_space, - => try ais.writer().writeByte(' '), - .newline, - .comma, - .semicolon, - => try ais.insertNewline(), - .skip => unreachable, - }; -} - /// Render an expression, and the comma that follows it, if it is present in the source. /// If a comma is present, and `space` is `Space.comma`, render only a single comma. fn renderExpressionComma(r: *Render, node: Ast.Node.Index, space: Space) Error!void { @@ -3315,6 +3247,14 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { pub const WriteError = UnderlyingWriter.Error; pub const Writer = std.io.Writer(*Self, WriteError, write); + pub const IndentType = enum { + normal, + }; + const StackElem = struct { + indent_type: IndentType, + realized: bool, + }; + underlying_writer: UnderlyingWriter, /// Offset into the source at which formatting has been disabled with @@ -3327,21 +3267,24 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { indent_count: usize = 0, indent_delta: usize, + indent_stack: std.ArrayList(StackElem), + disable_indent_committing: usize = 0, current_line_empty: bool = true, - /// automatically popped when applied - indent_one_shot_count: usize = 0, /// the most recently applied indent applied_indent: usize = 0, - /// not used until the next line - indent_next_line: usize = 0, - pub fn init(buffer: *std.ArrayList(u8), indent_delta: usize) Self { + pub fn init(buffer: *std.ArrayList(u8), indent_delta_: usize) Self { return .{ .underlying_writer = buffer.writer(), - .indent_delta = indent_delta, + .indent_delta = indent_delta_, + .indent_stack = std.ArrayList(StackElem).init(buffer.allocator), }; } + pub fn deinit(self: *Self) void { + self.indent_stack.deinit(); + } + pub fn writer(self: *Self) Writer { return .{ .context = self }; } @@ -3385,7 +3328,23 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { fn resetLine(self: *Self) void { self.current_line_empty = true; - self.indent_next_line = 0; + if (self.disable_indent_committing > 0) return; + if (self.indent_stack.items.len > 0) { + // Only realize last pushed indent + if (!self.indent_stack.items[self.indent_stack.items.len - 1].realized) { + self.indent_stack.items[self.indent_stack.items.len - 1].realized = true; + self.indent_count += 1; + } + } + } + + pub fn disableIndentCommitting(self: *Self) void { + self.disable_indent_committing += 1; + } + + pub fn enableIndentCommitting(self: *Self) void { + assert(self.disable_indent_committing > 0); + self.disable_indent_committing -= 1; } /// Insert a newline unless the current line is blank @@ -3397,36 +3356,19 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { /// Push default indentation /// Doesn't actually write any indentation. /// Just primes the stream to be able to write the correct indentation if it needs to. - pub fn pushIndent(self: *Self) void { - self.indent_count += 1; - } - - /// Push an indent that is automatically popped after being applied - pub fn pushIndentOneShot(self: *Self) void { - self.indent_one_shot_count += 1; - self.pushIndent(); - } - - /// Turns all one-shot indents into regular indents - /// Returns number of indents that must now be manually popped - pub fn lockOneShotIndent(self: *Self) usize { - const locked_count = self.indent_one_shot_count; - self.indent_one_shot_count = 0; - return locked_count; - } - - /// Push an indent that should not take effect until the next line - pub fn pushIndentNextLine(self: *Self) void { - self.indent_next_line += 1; - self.pushIndent(); + pub fn pushIndent(self: *Self, indent_type: IndentType) !void { + try self.indent_stack.append(.{ .indent_type = indent_type, .realized = false }); } pub fn popIndent(self: *Self) void { - assert(self.indent_count != 0); - self.indent_count -= 1; + if (self.indent_stack.pop().realized) { + assert(self.indent_count > 0); + self.indent_count -= 1; + } + } - if (self.indent_next_line > 0) - self.indent_next_line -= 1; + pub fn indentStackEmpty(self: *Self) bool { + return self.indent_stack.items.len == 0; } /// Writes ' ' bytes if the current line is empty @@ -3438,9 +3380,6 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { } self.applied_indent = current_indent; } - - self.indent_count -= self.indent_one_shot_count; - self.indent_one_shot_count = 0; self.current_line_empty = false; } @@ -3451,12 +3390,7 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { } fn currentIndent(self: *Self) usize { - var indent_current: usize = 0; - if (self.indent_count > 0) { - const indent_count = self.indent_count - self.indent_next_line; - indent_current = indent_count * self.indent_delta; - } - return indent_current; + return self.indent_count * self.indent_delta; } }; } From bedc566611b39d990e95738defa2af2bd0cacf44 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Wed, 16 Oct 2024 20:14:46 +0100 Subject: [PATCH 03/11] std/zig/render: Implement space mode to fix comment indentation --- lib/std/zig/render.zig | 96 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 89 insertions(+), 7 deletions(-) diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 869d3e5823..bdfbf7052e 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -295,7 +295,11 @@ fn renderMember( .local_var_decl, .simple_var_decl, .aligned_var_decl, - => return renderVarDecl(r, tree.fullVarDecl(decl).?, false, .semicolon), + => { + try ais.pushSpace(.semicolon); + try renderVarDecl(r, tree.fullVarDecl(decl).?, false, .semicolon); + ais.popSpace(); + }, .test_decl => { const test_token = main_tokens[decl]; @@ -372,8 +376,16 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { switch (space) { .none, .space, .newline, .skip => {}, - .semicolon => if (token_tags[i] == .semicolon) try renderToken(r, i, .newline), - .comma => if (token_tags[i] == .comma) try renderToken(r, i, .newline), + .semicolon => if (token_tags[i] == .semicolon) { + ais.enableSpaceMode(.semicolon); + try renderToken(r, i, .newline); + ais.disableSpaceMode(); + }, + .comma => if (token_tags[i] == .comma) { + ais.enableSpaceMode(.comma); + try renderToken(r, i, .newline); + ais.disableSpaceMode(); + }, .comma_space => if (token_tags[i] == .comma) try renderToken(r, i, .space), } }, @@ -764,7 +776,11 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { if (i > lbrace + 1) try renderExtraNewlineToken(r, i); switch (token_tags[i]) { .doc_comment => try renderToken(r, i, .newline), - .identifier => try renderIdentifier(r, i, .comma, .eagerly_unquote), + .identifier => { + try ais.pushSpace(.comma); + try renderIdentifier(r, i, .comma, .eagerly_unquote); + ais.popSpace(); + }, .comma => {}, else => unreachable, } @@ -843,7 +859,9 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { try renderToken(r, rparen + 1, .none); // { } else { try renderToken(r, rparen + 1, .newline); // { + try ais.pushSpace(.comma); try renderExpressions(r, full.ast.cases, .comma); + ais.popSpace(); } ais.popIndent(); return renderToken(r, tree.lastToken(node), space); // } @@ -1625,7 +1643,9 @@ fn renderBuiltinCall( try renderToken(r, builtin_token + 1, Space.newline); // ( for (params) |param_node| { + try ais.pushSpace(.comma); try renderExpression(r, param_node, .comma); + ais.popSpace(); } ais.popIndent(); @@ -1793,7 +1813,9 @@ fn renderFnProto(r: *Render, fn_proto: Ast.full.FnProto, space: Space) Error!voi } const param = fn_proto.ast.params[param_i]; param_i += 1; + try ais.pushSpace(.comma); try renderExpression(r, param, .comma); + ais.popSpace(); last_param_token = tree.lastToken(param); if (token_tags[last_param_token + 1] == .comma) last_param_token += 1; } @@ -1856,6 +1878,7 @@ fn renderSwitchCase( switch_case: Ast.full.SwitchCase, space: Space, ) Error!void { + const ais = r.ais; const tree = r.tree; const node_tags = tree.nodes.items(.tag); const token_tags = tree.tokens.items(.tag); @@ -1875,7 +1898,9 @@ fn renderSwitchCase( try renderToken(r, switch_case.ast.arrow_token - 1, .space); // else keyword } else if (trailing_comma or has_comment_before_arrow) { // Render each value on a new line + try ais.pushSpace(.comma); try renderExpressions(r, switch_case.ast.values, .comma); + ais.popSpace(); } else { // Render on one line for (switch_case.ast.values) |value_expr| { @@ -1951,6 +1976,7 @@ fn finishRenderBlock( for (statements, 0..) |stmt, i| { if (i != 0) try renderExtraNewline(r, stmt); if (r.fixups.omit_nodes.contains(stmt)) continue; + try ais.pushSpace(.semicolon); switch (node_tags[stmt]) { .global_var_decl, .local_var_decl, @@ -1960,6 +1986,7 @@ fn finishRenderBlock( else => try renderExpression(r, stmt, .semicolon), } + ais.popSpace(); } ais.popIndent(); @@ -2003,7 +2030,10 @@ fn renderStructInit( const expr = nodes[field_node]; var space_after_equal: Space = if (expr == .multiline_string_literal) .none else .space; try renderToken(r, struct_init.ast.lbrace + 3, space_after_equal); // = + + try ais.pushSpace(.comma); try renderExpressionFixup(r, field_node, .comma); + ais.popSpace(); for (struct_init.ast.fields[1..]) |field_init| { const init_token = tree.firstToken(field_init); @@ -2012,7 +2042,10 @@ fn renderStructInit( try renderIdentifier(r, init_token - 2, .space, .eagerly_unquote); // name space_after_equal = if (nodes[field_init] == .multiline_string_literal) .none else .space; try renderToken(r, init_token - 1, space_after_equal); // = + + try ais.pushSpace(.comma); try renderExpressionFixup(r, field_init, .comma); + ais.popSpace(); } ais.popIndent(); @@ -2182,7 +2215,10 @@ fn renderArrayInit( column_counter = 0; } } else { + try ais.pushSpace(.comma); try renderExpression(&sub_render, expr, .comma); + ais.popSpace(); + const width = sub_expr_buffer.items.len - start - 2; const this_contains_newline = mem.indexOfScalar(u8, sub_expr_buffer.items[start .. sub_expr_buffer.items.len - 1], '\n') != null; contains_newline = contains_newline or this_contains_newline; @@ -2362,7 +2398,11 @@ fn renderContainerDecl( .container_field_init, .container_field_align, .container_field, - => try renderMember(r, container, member, .comma), + => { + try ais.pushSpace(.comma); + try renderMember(r, container, member, .comma); + ais.popSpace(); + }, else => try renderMember(r, container, member, .newline), } @@ -2450,13 +2490,17 @@ fn renderAsm( try renderToken(r, comma, .newline); // , try renderExtraNewlineToken(r, tree.firstToken(next_asm_output)); } else if (asm_node.inputs.len == 0 and asm_node.first_clobber == null) { + try ais.pushSpace(.comma); try renderAsmOutput(r, asm_output, .comma); + ais.popSpace(); ais.popIndent(); ais.setIndentDelta(indent_delta); ais.popIndent(); return renderToken(r, asm_node.ast.rparen, space); // rparen } else { + try ais.pushSpace(.comma); try renderAsmOutput(r, asm_output, .comma); + ais.popSpace(); const comma_or_colon = tree.lastToken(asm_output) + 1; ais.popIndent(); break :colon2 switch (token_tags[comma_or_colon]) { @@ -2482,13 +2526,17 @@ fn renderAsm( try renderToken(r, first_token - 1, .newline); // , try renderExtraNewlineToken(r, first_token); } else if (asm_node.first_clobber == null) { + try ais.pushSpace(.comma); try renderAsmInput(r, asm_input, .comma); + ais.popSpace(); ais.popIndent(); ais.setIndentDelta(indent_delta); ais.popIndent(); return renderToken(r, asm_node.ast.rparen, space); // rparen } else { + try ais.pushSpace(.comma); try renderAsmInput(r, asm_input, .comma); + ais.popSpace(); const comma_or_colon = tree.lastToken(asm_input) + 1; ais.popIndent(); break :colon3 switch (token_tags[comma_or_colon]) { @@ -2574,7 +2622,9 @@ fn renderParamList( try renderExtraNewline(r, params[i + 1]); } else { + try ais.pushSpace(.comma); try renderExpression(r, param_node, .comma); + ais.popSpace(); } } ais.popIndent(); @@ -2691,7 +2741,8 @@ fn renderSpace(r: *Render, token_index: Ast.TokenIndex, lexeme_len: usize, space if (space == .comma and token_tags[token_index + 1] != .comma) { try ais.writer().writeByte(','); } - + if (space == .semicolon or space == .comma) ais.enableSpaceMode(space); + defer ais.disableSpaceMode(); const comment = try renderComments(r, token_start + lexeme_len, token_starts[token_index + 1]); switch (space) { .none => {}, @@ -3254,6 +3305,10 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { indent_type: IndentType, realized: bool, }; + const SpaceElem = struct { + space: Space, + indent_count: usize, + }; underlying_writer: UnderlyingWriter, @@ -3268,6 +3323,8 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { indent_count: usize = 0, indent_delta: usize, indent_stack: std.ArrayList(StackElem), + space_stack: std.ArrayList(SpaceElem), + space_mode: ?usize = null, disable_indent_committing: usize = 0, current_line_empty: bool = true, /// the most recently applied indent @@ -3278,11 +3335,13 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { .underlying_writer = buffer.writer(), .indent_delta = indent_delta_, .indent_stack = std.ArrayList(StackElem).init(buffer.allocator), + .space_stack = std.ArrayList(SpaceElem).init(buffer.allocator), }; } pub fn deinit(self: *Self) void { self.indent_stack.deinit(); + self.space_stack.deinit(); } pub fn writer(self: *Self) Writer { @@ -3347,6 +3406,28 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { self.disable_indent_committing -= 1; } + pub fn pushSpace(self: *Self, space: Space) !void { + try self.space_stack.append(.{ .space = space, .indent_count = self.indent_count }); + } + + pub fn popSpace(self: *Self) void { + _ = self.space_stack.pop(); + } + + pub fn enableSpaceMode(self: *Self, space: Space) void { + if (self.space_stack.items.len == 0) return; + const curr = self.space_stack.getLast(); + if (curr.space != space) { + return; + } + assert(curr.space == space); + self.space_mode = curr.indent_count; + } + + pub fn disableSpaceMode(self: *Self) void { + self.space_mode = null; + } + /// Insert a newline unless the current line is blank pub fn maybeInsertNewline(self: *Self) WriteError!void { if (!self.current_line_empty) @@ -3390,7 +3471,8 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { } fn currentIndent(self: *Self) usize { - return self.indent_count * self.indent_delta; + const indent_count = self.space_mode orelse self.indent_count; + return indent_count * self.indent_delta; } }; } From 038b660e31901f521044e43e61379cd3b28c8217 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Wed, 16 Oct 2024 21:24:37 +0100 Subject: [PATCH 04/11] std/zig/render: Collapse one level of indentation in binop after equals sign --- lib/std/zig/render.zig | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index bdfbf7052e..94e74e33e1 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -561,7 +561,7 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { const infix = datas[node]; try renderExpression(r, infix.lhs, .space); const op_token = main_tokens[node]; - try ais.pushIndent(.normal); + try ais.pushIndent(.binop); if (tree.tokensOnSameLine(op_token, op_token + 1)) { try renderToken(r, op_token, .space); } else { @@ -590,7 +590,7 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { else => try renderExpression(r, variable_node, variable_space), } } - try ais.pushIndent(.normal); + try ais.pushIndent(.after_equals); if (tree.tokensOnSameLine(full.ast.equal_token, full.ast.equal_token + 1)) { try renderToken(r, full.ast.equal_token, .space); } else { @@ -1247,7 +1247,7 @@ fn renderVarDeclWithoutFixups( const eq_token = tree.firstToken(var_decl.ast.init_node) - 1; const eq_space: Space = if (tree.tokensOnSameLine(eq_token, eq_token + 1)) .space else .newline; - try ais.pushIndent(.normal); + try ais.pushIndent(.after_equals); try renderToken(r, eq_token, eq_space); // = try renderExpression(r, var_decl.ast.init_node, space); // ; ais.popIndent(); @@ -1549,25 +1549,24 @@ fn renderContainerField( } const eq_token = tree.firstToken(field.ast.value_expr) - 1; const eq_space: Space = if (tree.tokensOnSameLine(eq_token, eq_token + 1)) .space else .newline; - { - try ais.pushIndent(.normal); - try renderToken(r, eq_token, eq_space); // = - ais.popIndent(); - } - if (eq_space == .space) - return renderExpressionComma(r, field.ast.value_expr, space); // value + try ais.pushIndent(.after_equals); + try renderToken(r, eq_token, eq_space); // = + + if (eq_space == .space) { + ais.popIndent(); + try renderExpressionComma(r, field.ast.value_expr, space); // value + return; + } const token_tags = tree.tokens.items(.tag); const maybe_comma = tree.lastToken(field.ast.value_expr) + 1; if (token_tags[maybe_comma] == .comma) { - try ais.pushIndent(.normal); try renderExpression(r, field.ast.value_expr, .none); // value ais.popIndent(); try renderToken(r, maybe_comma, .newline); } else { - try ais.pushIndent(.normal); try renderExpression(r, field.ast.value_expr, space); // value ais.popIndent(); } @@ -3300,6 +3299,8 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { pub const IndentType = enum { normal, + after_equals, + binop, }; const StackElem = struct { indent_type: IndentType, @@ -3391,6 +3392,15 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { if (self.indent_stack.items.len > 0) { // Only realize last pushed indent if (!self.indent_stack.items[self.indent_stack.items.len - 1].realized) { + if (self.indent_stack.items.len >= 2 and + self.indent_stack.items[self.indent_stack.items.len - 2].indent_type == .after_equals and + self.indent_stack.items[self.indent_stack.items.len - 2].realized and + self.indent_stack.items[self.indent_stack.items.len - 1].indent_type == .binop) + { + // collapse one level of indentation in binop after equals sign + return; + } + self.indent_stack.items[self.indent_stack.items.len - 1].realized = true; self.indent_count += 1; } From 79108e9022134de5bea15ca72fe325bb74fa1595 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Wed, 16 Oct 2024 21:18:46 +0100 Subject: [PATCH 05/11] arch/sparc64/CodeGen: Fix indentation in realStackOffset --- src/arch/sparc64/CodeGen.zig | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/arch/sparc64/CodeGen.zig b/src/arch/sparc64/CodeGen.zig index a1bef1f4cd..5cc6407be8 100644 --- a/src/arch/sparc64/CodeGen.zig +++ b/src/arch/sparc64/CodeGen.zig @@ -4411,12 +4411,12 @@ fn processDeath(self: *Self, inst: Air.Inst.Index) void { /// Turns stack_offset MCV into a real SPARCv9 stack offset usable for asm. fn realStackOffset(off: u32) u32 { - return off - // SPARCv9 %sp points away from the stack by some amount. - + abi.stack_bias - // The first couple bytes of each stack frame is reserved - // for ABI and hardware purposes. - + abi.stack_reserved_area; + return off + + // SPARCv9 %sp points away from the stack by some amount. + abi.stack_bias + + // The first couple bytes of each stack frame is reserved + // for ABI and hardware purposes. + abi.stack_reserved_area; // Only after that we have the usable stack frame portion. } From fedb5bbbe992d1911c75c74d518a6377aca639e3 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Wed, 16 Oct 2024 23:15:30 +0100 Subject: [PATCH 06/11] std/zig/render: assigns are .after_equals --- lib/std/zig/render.zig | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 94e74e33e1..e4979fc78e 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -510,11 +510,6 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { } }, - .add, - .add_wrap, - .add_sat, - .array_cat, - .array_mult, .assign, .assign_bit_and, .assign_bit_or, @@ -533,6 +528,25 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { .assign_mul, .assign_mul_wrap, .assign_mul_sat, + => { + const infix = datas[node]; + try renderExpression(r, infix.lhs, .space); + const op_token = main_tokens[node]; + try ais.pushIndent(.after_equals); + if (tree.tokensOnSameLine(op_token, op_token + 1)) { + try renderToken(r, op_token, .space); + } else { + try renderToken(r, op_token, .newline); + } + try renderExpression(r, infix.rhs, space); + ais.popIndent(); + }, + + .add, + .add_wrap, + .add_sat, + .array_cat, + .array_mult, .bang_equal, .bit_and, .bit_or, From 33467d5439a4d2cf08ebc3ab3d96e6bd058ea4c9 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Thu, 17 Oct 2024 01:52:53 +0100 Subject: [PATCH 07/11] std/zig/render: implement fixes for unit tests --- lib/std/zig/parser_test.zig | 40 +++++++------- lib/std/zig/render.zig | 105 ++++++++++++++++++++---------------- 2 files changed, 78 insertions(+), 67 deletions(-) diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index 5261816544..70015fdd3e 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -1776,7 +1776,7 @@ test "zig fmt: if nested" { \\ GE_EQUAL \\ else \\ GE_GREATER - \\ // comment + \\ // comment \\ else if (aInt > bInt) \\ GE_LESS \\ else if (aInt == bInt) @@ -4670,7 +4670,7 @@ test "zig fmt: test comments in field access chain" { \\ .more() // \\ .more().more() // \\ .more() // - \\ // .more() // + \\ // .more() // \\ .more() // \\ .more(); \\ data: Data, @@ -4679,9 +4679,9 @@ test "zig fmt: test comments in field access chain" { \\pub const str = struct { \\ pub const Thing = more.more // \\ .more() // - \\ // .more() // - \\ // .more() // - \\ // .more() // + \\ // .more() // + \\ // .more() // + \\ // .more() // \\ .more() // \\ .more(); \\ data: Data, @@ -4706,7 +4706,7 @@ test "zig fmt: allow line break before field access" { \\ const x = foo \\ .bar() \\ . // comment - \\ // comment + \\ // comment \\ swooop().zippy(zag) \\ .iguessthisisok(); \\ @@ -4716,7 +4716,7 @@ test "zig fmt: allow line break before field access" { \\ .input_manager // \\ .default_seat \\ . // comment - \\ // another comment + \\ // another comment \\ wlr_seat.name; \\} \\ @@ -4955,19 +4955,19 @@ test "zig fmt: use of comments and multiline string literals may force the param \\ \\// This looks like garbage don't do this \\const rparen = tree.prevToken( - \\// the first token for the annotation expressions is the left - \\// parenthesis, hence the need for two prevToken - \\if (fn_proto.getAlignExpr()) |align_expr| - \\ tree.prevToken(tree.prevToken(align_expr.firstToken())) - \\else if (fn_proto.getSectionExpr()) |section_expr| - \\ tree.prevToken(tree.prevToken(section_expr.firstToken())) - \\else if (fn_proto.getCallconvExpr()) |callconv_expr| - \\ tree.prevToken(tree.prevToken(callconv_expr.firstToken())) - \\else switch (fn_proto.return_type) { - \\ .Explicit => |node| node.firstToken(), - \\ .InferErrorSet => |node| tree.prevToken(node.firstToken()), - \\ .Invalid => unreachable, - \\}); + \\ // the first token for the annotation expressions is the left + \\ // parenthesis, hence the need for two prevToken + \\ if (fn_proto.getAlignExpr()) |align_expr| + \\ tree.prevToken(tree.prevToken(align_expr.firstToken())) + \\ else if (fn_proto.getSectionExpr()) |section_expr| + \\ tree.prevToken(tree.prevToken(section_expr.firstToken())) + \\ else if (fn_proto.getCallconvExpr()) |callconv_expr| + \\ tree.prevToken(tree.prevToken(callconv_expr.firstToken())) + \\ else switch (fn_proto.return_type) { + \\ .Explicit => |node| node.firstToken(), + \\ .InferErrorSet => |node| tree.prevToken(node.firstToken()), + \\ .Invalid => unreachable, + \\ }); \\ ); } diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index e4979fc78e..180ec463b5 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -369,23 +369,19 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { while (i <= datas[node].rhs) : (i += 1) try renderToken(r, i, .newline); // dedent the next thing that comes after a multiline string literal - if (!ais.indentStackEmpty()) { + if (!ais.indentStackEmpty() and + token_tags[i] != .colon and + ((token_tags[i] != .semicolon and token_tags[i] != .comma) or + ais.lastSpaceModeIndent() < ais.currentIndent())) + { ais.popIndent(); try ais.pushIndent(.normal); } switch (space) { .none, .space, .newline, .skip => {}, - .semicolon => if (token_tags[i] == .semicolon) { - ais.enableSpaceMode(.semicolon); - try renderToken(r, i, .newline); - ais.disableSpaceMode(); - }, - .comma => if (token_tags[i] == .comma) { - ais.enableSpaceMode(.comma); - try renderToken(r, i, .newline); - ais.disableSpaceMode(); - }, + .semicolon => if (token_tags[i] == .semicolon) try renderTokenOverrideSpaceMode(r, i, .newline, .semicolon), + .comma => if (token_tags[i] == .comma) try renderTokenOverrideSpaceMode(r, i, .newline, .comma), .comma_space => if (token_tags[i] == .comma) try renderToken(r, i, .space), } }, @@ -476,7 +472,7 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { const main_token = main_tokens[node]; const field_access = datas[node]; - try ais.pushIndent(.normal); + try ais.pushIndent(.field_access); try renderExpression(r, field_access.lhs, .none); // Allow a line break between the lhs and the dot if the lhs and rhs @@ -740,8 +736,8 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void { }, .grouped_expression => { - try renderToken(r, main_tokens[node], .none); // lparen try ais.pushIndent(.normal); + try renderToken(r, main_tokens[node], .none); // lparen try renderExpression(r, datas[node].lhs, .none); ais.popIndent(); return renderToken(r, datas[node].rhs, space); // rparen @@ -2444,7 +2440,7 @@ fn renderAsm( } if (asm_node.ast.items.len == 0) { - try ais.pushIndent(.normal); + try ais.forcePushIndent(.normal); if (asm_node.first_clobber) |first_clobber| { // asm ("foo" ::: "a", "b") // asm ("foo" ::: "a", "b",) @@ -2482,7 +2478,7 @@ fn renderAsm( } } - try ais.pushIndent(.normal); + try ais.forcePushIndent(.normal); try renderExpression(r, asm_node.ast.template, .newline); ais.setIndentDelta(asm_indent_delta); const colon1 = tree.lastToken(asm_node.ast.template) + 1; @@ -2493,7 +2489,7 @@ fn renderAsm( } else colon2: { try renderToken(r, colon1, .space); // : - try ais.pushIndent(.normal); + try ais.forcePushIndent(.normal); for (asm_node.outputs, 0..) |asm_output, i| { if (i + 1 < asm_node.outputs.len) { const next_asm_output = asm_node.outputs[i + 1]; @@ -2529,7 +2525,7 @@ fn renderAsm( break :colon3 colon2 + 1; } else colon3: { try renderToken(r, colon2, .space); // : - try ais.pushIndent(.normal); + try ais.forcePushIndent(.normal); for (asm_node.inputs, 0..) |asm_input, i| { if (i + 1 < asm_node.inputs.len) { const next_asm_input = asm_node.inputs[i + 1]; @@ -2568,16 +2564,16 @@ fn renderAsm( switch (token_tags[tok_i + 1]) { .r_paren => { ais.setIndentDelta(indent_delta); - ais.popIndent(); try renderToken(r, tok_i, .newline); + ais.popIndent(); return renderToken(r, tok_i + 1, space); }, .comma => { switch (token_tags[tok_i + 2]) { .r_paren => { ais.setIndentDelta(indent_delta); - ais.popIndent(); try renderToken(r, tok_i, .newline); + ais.popIndent(); return renderToken(r, tok_i + 2, space); }, else => { @@ -2644,19 +2640,10 @@ fn renderParamList( return renderToken(r, after_last_param_tok + 1, space); // ) } + try ais.pushIndent(.normal); try renderToken(r, lparen, .none); // ( - for (params, 0..) |param_node, i| { - const first_param_token = tree.firstToken(param_node); - if (token_tags[first_param_token] == .multiline_string_literal_line or - hasSameLineComment(tree, first_param_token - 1)) - { - try ais.pushIndent(.normal); - try renderExpression(r, param_node, .none); - ais.popIndent(); - } else { - try renderExpression(r, param_node, .none); - } + try renderExpression(r, param_node, .none); if (i + 1 < params.len) { const comma = tree.lastToken(param_node) + 1; @@ -2666,7 +2653,7 @@ fn renderParamList( try renderToken(r, comma, comma_space); } } - + ais.popIndent(); return renderToken(r, after_last_param_tok, space); // ) } @@ -2741,6 +2728,16 @@ fn renderToken(r: *Render, token_index: Ast.TokenIndex, space: Space) Error!void try renderSpace(r, token_index, lexeme.len, space); } +fn renderTokenOverrideSpaceMode(r: *Render, token_index: Ast.TokenIndex, space: Space, override_space: Space) Error!void { + const tree = r.tree; + const ais = r.ais; + const lexeme = tokenSliceForRender(tree, token_index); + try ais.writer().writeAll(lexeme); + ais.enableSpaceMode(override_space); + defer ais.disableSpaceMode(); + try renderSpace(r, token_index, lexeme.len, space); +} + fn renderSpace(r: *Render, token_index: Ast.TokenIndex, lexeme_len: usize, space: Space) Error!void { const tree = r.tree; const ais = r.ais; @@ -3315,6 +3312,7 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { normal, after_equals, binop, + field_access, }; const StackElem = struct { indent_type: IndentType, @@ -3404,20 +3402,26 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { self.current_line_empty = true; if (self.disable_indent_committing > 0) return; if (self.indent_stack.items.len > 0) { - // Only realize last pushed indent - if (!self.indent_stack.items[self.indent_stack.items.len - 1].realized) { - if (self.indent_stack.items.len >= 2 and - self.indent_stack.items[self.indent_stack.items.len - 2].indent_type == .after_equals and - self.indent_stack.items[self.indent_stack.items.len - 2].realized and - self.indent_stack.items[self.indent_stack.items.len - 1].indent_type == .binop) - { - // collapse one level of indentation in binop after equals sign - return; - } + var to_realize = self.indent_stack.items.len - 1; - self.indent_stack.items[self.indent_stack.items.len - 1].realized = true; - self.indent_count += 1; + if (self.indent_stack.items.len >= 2 and + self.indent_stack.items[to_realize - 1].indent_type == .after_equals and + self.indent_stack.items[to_realize - 1].realized and + self.indent_stack.items[to_realize].indent_type == .binop) + { + // collapse one level of indentation in binop after equals sign + return; } + + if (self.indent_stack.items[to_realize].indent_type == .field_access) { + // only realize topmost field_access in a chain + while (to_realize > 0 and self.indent_stack.items[to_realize - 1].indent_type == .field_access) + to_realize -= 1; + } + + if (self.indent_stack.items[to_realize].realized) return; + self.indent_stack.items[to_realize].realized = true; + self.indent_count += 1; } } @@ -3441,10 +3445,7 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { pub fn enableSpaceMode(self: *Self, space: Space) void { if (self.space_stack.items.len == 0) return; const curr = self.space_stack.getLast(); - if (curr.space != space) { - return; - } - assert(curr.space == space); + if (curr.space != space) return; self.space_mode = curr.indent_count; } @@ -3452,6 +3453,11 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { self.space_mode = null; } + pub fn lastSpaceModeIndent(self: *Self) usize { + if (self.space_stack.items.len == 0) return 0; + return self.space_stack.getLast().indent_count * self.indent_delta; + } + /// Insert a newline unless the current line is blank pub fn maybeInsertNewline(self: *Self) WriteError!void { if (!self.current_line_empty) @@ -3465,6 +3471,11 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { try self.indent_stack.append(.{ .indent_type = indent_type, .realized = false }); } + pub fn forcePushIndent(self: *Self, indent_type: IndentType) !void { + try self.indent_stack.append(.{ .indent_type = indent_type, .realized = true }); + self.indent_count += 1; + } + pub fn popIndent(self: *Self) void { if (self.indent_stack.pop().realized) { assert(self.indent_count > 0); From 3404e2ed38ce2551d9b9fc01a238767816216958 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Fri, 18 Oct 2024 09:32:19 +0100 Subject: [PATCH 08/11] std/zig/parser: Add indentation tests --- lib/std/zig/parser_test.zig | 145 ++++++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index 70015fdd3e..8bc639f00a 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -5962,6 +5962,151 @@ test "zig fmt: pointer type syntax to index" { ); } +test "zig fmt: binop indentation in if statement" { + try testCanonical( + \\test { + \\ if (first_param_type.isGenericPoison() or + \\ (first_param_type.zigTypeTag(zcu) == .pointer and + \\ (first_param_type.ptrSize(zcu) == .One or + \\ first_param_type.ptrSize(zcu) == .C) and + \\ first_param_type.childType(zcu).eql(concrete_ty, zcu))) + \\ { + \\ f(x); + \\ } + \\} + \\ + ); +} + +test "zig fmt: test indentation after equals sign" { + try testCanonical( + \\test { + \\ const foo = + \\ if (1 == 2) + \\ 1 + \\ else if (3 > 4) + \\ 2 + \\ else + \\ 0; + \\ + \\ const foo, const bar = + \\ if (1 == 2) + \\ .{ 0, 0 } + \\ else if (3 > 4) + \\ .{ 1, 1 } + \\ else + \\ .{ 2, 2 }; + \\ + \\ while (foo) if (bar) + \\ f(x); + \\ + \\ foobar = + \\ if (true) + \\ 1 + \\ else + \\ 0; + \\ + \\ const foo = if (1 == 2) + \\ 1 + \\ else if (3 > 4) + \\ 2 + \\ else + \\ 0; + \\ + \\ const foo, const bar = if (1 == 2) + \\ .{ 0, 0 } + \\ else if (3 > 4) + \\ .{ 1, 1 } + \\ else + \\ .{ 2, 2 }; + \\ + \\ foobar = if (true) + \\ 1 + \\ else + \\ 0; + \\ + \\ const is_alphanum = + \\ (ch >= 'a' and ch <= 'z') or + \\ (ch >= 'A' and ch <= 'Z') or + \\ (ch >= '0' and ch <= '9'); + \\ + \\ const bar = 100 + calculate( + \\ 200, + \\ 300, + \\ ); + \\ + \\ const gcc_pragma = std.meta.stringToEnum(Directive, pp.expandedSlice(directive_tok)) orelse + \\ return pp.comp.addDiagnostic(.{ + \\ .tag = .unknown_gcc_pragma, + \\ .loc = directive_tok.loc, + \\ }, pp.expansionSlice(start_idx + 1)); + \\ + \\ const vec4s = + \\ [_][4]i32{ + \\ [_]i32{ 0, 1, 0, 0 }, + \\ [_]i32{ 0, -1, 0, 0 }, + \\ [_]i32{ 2, 1, 2, 0 }, + \\ }; + \\} + \\ + ); +} + +test "zig fmt: test indentation of if expressions" { + try testCanonical( + \\test { + \\ const foo = 1 + + \\ if (1 == 2) + \\ 2 + \\ else + \\ 0; + \\ + \\ const foo = 1 + if (1 == 2) + \\ 2 + \\ else + \\ 0; + \\ + \\ errval catch |e| + \\ if (e == error.Meow) + \\ return 0x1F408 + \\ else + \\ unreachable; + \\ + \\ errval catch |e| if (e == error.Meow) + \\ return 0x1F408 + \\ else + \\ unreachable; + \\ + \\ return if (1 == 2) + \\ 1 + \\ else if (3 > 4) + \\ 2 + \\ else + \\ 0; + \\} + \\ + ); +} + +test "zig fmt: indentation of comments within catch, else, orelse" { + try testCanonical( + \\comptime { + \\ _ = foo() catch + \\ // + \\ bar(); + \\ + \\ _ = if (foo) bar() else + \\ // + \\ qux(); + \\ + \\ _ = foo() orelse + \\ // + \\ qux(); + \\} + \\ + ); +} + test "recovery: top level" { try testError( \\test "" {inline} From 73e4efa672d2b820f0c187f47cd3ffe307b98b1f Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Fri, 18 Oct 2024 10:06:02 +0100 Subject: [PATCH 09/11] std/zig/render: Add doc comments to AutoIndentingStream --- lib/std/zig/render.zig | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 180ec463b5..04af44ffb2 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -3302,6 +3302,26 @@ fn rowSize(tree: Ast, exprs: []const Ast.Node.Index, rtoken: Ast.TokenIndex) usi /// Automatically inserts indentation of written data by keeping /// track of the current indentation level +/// +/// We introduce a new indentation scope with pushIndent/popIndent whenever +/// we potentially want to introduce an indent after the next newline. +/// +/// Indentation should only ever increment by one from one line to the next, +/// no matter how many new indentation scopes are introduced. This is done by +/// only realizing the indentation from the most recent scope. As an example: +/// +/// while (foo) if (bar) +/// f(x); +/// +/// The body of `while` introduces a new indentation scope and the body of +/// `if` also introduces a new indentation scope. When the newline is seen, +/// only the indentation scope of the `if` is realized, and the `while` is +/// not. +/// +/// As comments are rendered during space rendering, we need to keep track +/// of the appropriate indentation level for them with pushSpace/popSpace. +/// This should be done whenever a scope that ends in a .semicolon or a +/// .comma is introduced. fn AutoIndentingStream(comptime UnderlyingWriter: type) type { return struct { const Self = @This(); @@ -3400,8 +3420,11 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { fn resetLine(self: *Self) void { self.current_line_empty = true; + if (self.disable_indent_committing > 0) return; + if (self.indent_stack.items.len > 0) { + // By default, we realize the most recent indentation scope. var to_realize = self.indent_stack.items.len - 1; if (self.indent_stack.items.len >= 2 and @@ -3409,12 +3432,18 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { self.indent_stack.items[to_realize - 1].realized and self.indent_stack.items[to_realize].indent_type == .binop) { - // collapse one level of indentation in binop after equals sign + // If we are in a .binop scope and our direct parent is .after_equals, don't indent. + // This ensures correct indentation in the below example: + // + // const foo = + // (x >= 'a' and x <= 'z') or //<-- we are here + // (x >= 'A' and x <= 'Z'); + // return; } if (self.indent_stack.items[to_realize].indent_type == .field_access) { - // only realize topmost field_access in a chain + // Only realize the top-most field_access in a chain. while (to_realize > 0 and self.indent_stack.items[to_realize - 1].indent_type == .field_access) to_realize -= 1; } @@ -3425,6 +3454,7 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { } } + /// Disables indentation level changes during the next newlines until re-enabled. pub fn disableIndentCommitting(self: *Self) void { self.disable_indent_committing += 1; } @@ -3442,6 +3472,7 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { _ = self.space_stack.pop(); } + /// Sets current indentation level to be the same as that of the last pushSpace. pub fn enableSpaceMode(self: *Self, space: Space) void { if (self.space_stack.items.len == 0) return; const curr = self.space_stack.getLast(); @@ -3471,6 +3502,7 @@ fn AutoIndentingStream(comptime UnderlyingWriter: type) type { try self.indent_stack.append(.{ .indent_type = indent_type, .realized = false }); } + /// Forces an indentation level to be realized. pub fn forcePushIndent(self: *Self, indent_type: IndentType) !void { try self.indent_stack.append(.{ .indent_type = indent_type, .realized = true }); self.indent_count += 1; From b7d75a74570c7b92c689bac06d65da3c5a200850 Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Fri, 18 Oct 2024 10:07:33 +0100 Subject: [PATCH 10/11] std/http/Client: Remove TODO comments on indentation --- lib/std/http/Client.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/std/http/Client.zig b/lib/std/http/Client.zig index 9dcf7b5693..3560e69b58 100644 --- a/lib/std/http/Client.zig +++ b/lib/std/http/Client.zig @@ -959,7 +959,7 @@ pub const Request = struct { pub const WaitError = RequestError || SendError || TransferReadError || proto.HeadersParser.CheckCompleteHeadError || Response.ParseError || - error{ // TODO: file zig fmt issue for this bad indentation + error{ TooManyHttpRedirects, RedirectRequiresResend, HttpRedirectLocationMissing, @@ -1539,7 +1539,7 @@ pub fn connect( pub const RequestError = ConnectTcpError || ConnectErrorPartial || Request.SendError || std.fmt.ParseIntError || Connection.WriteError || - error{ // TODO: file a zig fmt issue for this bad indentation + error{ UnsupportedUriScheme, UriMissingHost, From 4a20da167d2eaea39ba7790811922be0e57a734d Mon Sep 17 00:00:00 2001 From: 87flowers <178735591+87flowers@users.noreply.github.com> Date: Tue, 12 Nov 2024 10:26:21 +0000 Subject: [PATCH 11/11] zig fmt --- lib/compiler/aro/aro/Parser.zig | 2 +- lib/compiler/aro/aro/pragmas/gcc.zig | 6 +- lib/compiler/resinator/lang.zig | 2 +- lib/compiler_rt/count0bits.zig | 2 +- lib/compiler_rt/int.zig | 52 +- lib/compiler_rt/popcount.zig | 2 +- lib/docs/wasm/markdown/Parser.zig | 2 +- lib/std/Target.zig | 2 +- lib/std/c.zig | 8 +- lib/std/crypto/tls/Client.zig | 14 +- lib/std/debug/SelfInfo.zig | 18 +- lib/std/http/Client.zig | 24 +- lib/std/posix.zig | 12 +- lib/std/zig/render.zig | 6 +- src/Sema.zig | 24 +- src/Type.zig | 11 +- src/Zcu.zig | 8 +- src/arch/riscv64/CodeGen.zig | 21 +- src/arch/x86_64/CodeGen.zig | 65 +- src/arch/x86_64/Lower.zig | 38 +- src/codegen.zig | 2 +- src/codegen/c.zig | 6 +- src/codegen/c/Type.zig | 69 +- src/codegen/llvm.zig | 109 +- src/link/Elf/relocatable.zig | 22 +- src/link/Elf/synthetic_sections.zig | 2 +- src/link/MachO.zig | 16 +- src/link/MachO/Atom.zig | 8 +- src/link/MachO/ZigObject.zig | 4 +- src/link/MachO/dead_strip.zig | 4 +- src/main.zig | 8 +- src/translate_c.zig | 27 +- test/behavior/export_builtin.zig | 4 +- test/link/elf.zig | 140 +-- test/link/macho.zig | 1624 +++++++++++++------------- tools/doctest.zig | 2 +- tools/update_clang_options.zig | 2 +- 37 files changed, 1182 insertions(+), 1186 deletions(-) diff --git a/lib/compiler/aro/aro/Parser.zig b/lib/compiler/aro/aro/Parser.zig index 85053b7e48..8327469853 100644 --- a/lib/compiler/aro/aro/Parser.zig +++ b/lib/compiler/aro/aro/Parser.zig @@ -979,7 +979,7 @@ fn decl(p: *Parser) Error!bool { _ = try p.expectToken(.semicolon); if (decl_spec.ty.is(.@"enum") or (decl_spec.ty.isRecord() and !decl_spec.ty.isAnonymousRecord(p.comp) and - !decl_spec.ty.isTypeof())) // we follow GCC and clang's behavior here + !decl_spec.ty.isTypeof())) // we follow GCC and clang's behavior here { const specifier = decl_spec.ty.canonicalize(.standard).specifier; const attrs = p.attr_buf.items(.attr)[attr_buf_top..]; diff --git a/lib/compiler/aro/aro/pragmas/gcc.zig b/lib/compiler/aro/aro/pragmas/gcc.zig index a382f4daac..79bd868103 100644 --- a/lib/compiler/aro/aro/pragmas/gcc.zig +++ b/lib/compiler/aro/aro/pragmas/gcc.zig @@ -114,9 +114,9 @@ fn preprocessorHandler(pragma: *Pragma, pp: *Preprocessor, start_idx: TokenIndex const gcc_pragma = std.meta.stringToEnum(Directive, pp.expandedSlice(directive_tok)) orelse return pp.comp.addDiagnostic(.{ - .tag = .unknown_gcc_pragma, - .loc = directive_tok.loc, - }, pp.expansionSlice(start_idx + 1)); + .tag = .unknown_gcc_pragma, + .loc = directive_tok.loc, + }, pp.expansionSlice(start_idx + 1)); switch (gcc_pragma) { .warning, .@"error" => { diff --git a/lib/compiler/resinator/lang.zig b/lib/compiler/resinator/lang.zig index bf36680710..71fcf80149 100644 --- a/lib/compiler/resinator/lang.zig +++ b/lib/compiler/resinator/lang.zig @@ -255,7 +255,7 @@ pub fn parse(lang_tag: []const u8) error{InvalidLanguageTag}!Parsed { // Special case for qps-ploca and qps-plocm else if (std.ascii.eqlIgnoreCase(lang_code, "qps") and (std.ascii.eqlIgnoreCase(part_str, "ploca") or - std.ascii.eqlIgnoreCase(part_str, "plocm"))) + std.ascii.eqlIgnoreCase(part_str, "plocm"))) { parsed.suffix = part_str; } else { diff --git a/lib/compiler_rt/count0bits.zig b/lib/compiler_rt/count0bits.zig index 60da0390da..d9c10adaa9 100644 --- a/lib/compiler_rt/count0bits.zig +++ b/lib/compiler_rt/count0bits.zig @@ -143,7 +143,7 @@ pub const __clzsi2 = switch (builtin.cpu.arch) { .arm, .armeb, .thumb, .thumbeb => impl: { const use_thumb1 = (builtin.cpu.arch.isThumb() or - std.Target.arm.featureSetHas(builtin.cpu.features, .noarm)) and + std.Target.arm.featureSetHas(builtin.cpu.features, .noarm)) and !std.Target.arm.featureSetHas(builtin.cpu.features, .thumb2); if (use_thumb1) { diff --git a/lib/compiler_rt/int.zig b/lib/compiler_rt/int.zig index e71a0c0990..758ca74781 100644 --- a/lib/compiler_rt/int.zig +++ b/lib/compiler_rt/int.zig @@ -81,19 +81,19 @@ fn test_one_divmoddi4(a: i64, b: i64, expected_q: i64, expected_r: i64) !void { const cases__divmoddi4 = [_][4]i64{ - [_]i64{ 0, 1, 0, 0 }, - [_]i64{ 0, -1, 0, 0 }, - [_]i64{ 2, 1, 2, 0 }, - [_]i64{ 2, -1, -2, 0 }, - [_]i64{ -2, 1, -2, 0 }, - [_]i64{ -2, -1, 2, 0 }, - [_]i64{ 7, 5, 1, 2 }, - [_]i64{ -7, 5, -1, -2 }, - [_]i64{ 19, 5, 3, 4 }, - [_]i64{ 19, -5, -3, 4 }, - [_]i64{ @as(i64, @bitCast(@as(u64, 0x8000000000000000))), 8, @as(i64, @bitCast(@as(u64, 0xf000000000000000))), 0 }, - [_]i64{ @as(i64, @bitCast(@as(u64, 0x8000000000000007))), 8, @as(i64, @bitCast(@as(u64, 0xf000000000000001))), -1 }, -}; + [_]i64{ 0, 1, 0, 0 }, + [_]i64{ 0, -1, 0, 0 }, + [_]i64{ 2, 1, 2, 0 }, + [_]i64{ 2, -1, -2, 0 }, + [_]i64{ -2, 1, -2, 0 }, + [_]i64{ -2, -1, 2, 0 }, + [_]i64{ 7, 5, 1, 2 }, + [_]i64{ -7, 5, -1, -2 }, + [_]i64{ 19, 5, 3, 4 }, + [_]i64{ 19, -5, -3, 4 }, + [_]i64{ @as(i64, @bitCast(@as(u64, 0x8000000000000000))), 8, @as(i64, @bitCast(@as(u64, 0xf000000000000000))), 0 }, + [_]i64{ @as(i64, @bitCast(@as(u64, 0x8000000000000007))), 8, @as(i64, @bitCast(@as(u64, 0xf000000000000001))), -1 }, + }; test "test_divmoddi4" { for (cases__divmoddi4) |case| { @@ -215,19 +215,19 @@ pub fn __divmodsi4(a: i32, b: i32, rem: *i32) callconv(.C) i32 { const cases__divmodsi4 = [_][4]i32{ - [_]i32{ 0, 1, 0, 0 }, - [_]i32{ 0, -1, 0, 0 }, - [_]i32{ 2, 1, 2, 0 }, - [_]i32{ 2, -1, -2, 0 }, - [_]i32{ -2, 1, -2, 0 }, - [_]i32{ -2, -1, 2, 0 }, - [_]i32{ 7, 5, 1, 2 }, - [_]i32{ -7, 5, -1, -2 }, - [_]i32{ 19, 5, 3, 4 }, - [_]i32{ 19, -5, -3, 4 }, - [_]i32{ @bitCast(@as(u32, 0x80000000)), 8, @bitCast(@as(u32, 0xf0000000)), 0 }, - [_]i32{ @bitCast(@as(u32, 0x80000007)), 8, @bitCast(@as(u32, 0xf0000001)), -1 }, -}; + [_]i32{ 0, 1, 0, 0 }, + [_]i32{ 0, -1, 0, 0 }, + [_]i32{ 2, 1, 2, 0 }, + [_]i32{ 2, -1, -2, 0 }, + [_]i32{ -2, 1, -2, 0 }, + [_]i32{ -2, -1, 2, 0 }, + [_]i32{ 7, 5, 1, 2 }, + [_]i32{ -7, 5, -1, -2 }, + [_]i32{ 19, 5, 3, 4 }, + [_]i32{ 19, -5, -3, 4 }, + [_]i32{ @bitCast(@as(u32, 0x80000000)), 8, @bitCast(@as(u32, 0xf0000000)), 0 }, + [_]i32{ @bitCast(@as(u32, 0x80000007)), 8, @bitCast(@as(u32, 0xf0000001)), -1 }, + }; fn test_one_divmodsi4(a: i32, b: i32, expected_q: i32, expected_r: i32) !void { var r: i32 = undefined; diff --git a/lib/compiler_rt/popcount.zig b/lib/compiler_rt/popcount.zig index d54a4aab42..492423dda5 100644 --- a/lib/compiler_rt/popcount.zig +++ b/lib/compiler_rt/popcount.zig @@ -40,7 +40,7 @@ inline fn popcountXi2(comptime ST: type, a: ST) i32 { var x: UT = @bitCast(a); x -= (x >> 1) & (~@as(UT, 0) / 3); // 0x55...55, aggregate duos x = ((x >> 2) & (~@as(UT, 0) / 5)) // 0x33...33, aggregate nibbles - + (x & (~@as(UT, 0) / 5)); + + (x & (~@as(UT, 0) / 5)); x += x >> 4; x &= ~@as(UT, 0) / 17; // 0x0F...0F, aggregate bytes // 8 most significant bits of x + (x<<8) + (x<<16) + .. diff --git a/lib/docs/wasm/markdown/Parser.zig b/lib/docs/wasm/markdown/Parser.zig index 32c1729684..1d7ccb2b23 100644 --- a/lib/docs/wasm/markdown/Parser.zig +++ b/lib/docs/wasm/markdown/Parser.zig @@ -374,7 +374,7 @@ fn appendBlockStart(p: *Parser, block_start: BlockStart) !void { // or not of the same marker type. const should_close_list = last_pending_block.tag == .list and (block_start.tag != .list_item or - block_start.data.list_item.marker != last_pending_block.data.list.marker); + block_start.data.list_item.marker != last_pending_block.data.list.marker); // The last block should also be closed if the new block is not a table // row, which is the only allowed child of a table. const should_close_table = last_pending_block.tag == .table and diff --git a/lib/std/Target.zig b/lib/std/Target.zig index 2283004115..6a734d58a8 100644 --- a/lib/std/Target.zig +++ b/lib/std/Target.zig @@ -325,7 +325,7 @@ pub const Os = struct { pub fn parse(str: []const u8) !WindowsVersion { return std.meta.stringToEnum(WindowsVersion, str) orelse @enumFromInt(std.fmt.parseInt(u32, str, 0) catch - return error.InvalidOperatingSystemVersion); + return error.InvalidOperatingSystemVersion); } /// This function is defined to serialize a Zig source code representation of this diff --git a/lib/std/c.zig b/lib/std/c.zig index 81eeba31f6..2ad1e93fc2 100644 --- a/lib/std/c.zig +++ b/lib/std/c.zig @@ -9591,10 +9591,10 @@ pub extern "c" fn setlocale(category: LC, locale: ?[*:0]const u8) ?[*:0]const u8 pub const getcontext = if (builtin.target.isAndroid() or builtin.target.os.tag == .openbsd) {} // android bionic and openbsd libc does not implement getcontext -else if (native_os == .linux and builtin.target.isMusl()) - linux.getcontext -else - private.getcontext; + else if (native_os == .linux and builtin.target.isMusl()) + linux.getcontext + else + private.getcontext; pub const max_align_t = if (native_abi == .msvc or native_abi == .itanium) f64 diff --git a/lib/std/crypto/tls/Client.zig b/lib/std/crypto/tls/Client.zig index 20ea485049..641373685b 100644 --- a/lib/std/crypto/tls/Client.zig +++ b/lib/std/crypto/tls/Client.zig @@ -706,7 +706,7 @@ pub fn init(stream: anytype, options: Options) InitError(@TypeOf(stream))!Client const client_key_exchange_msg = .{@intFromEnum(tls.ContentType.handshake)} ++ int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ array(u16, u8, .{@intFromEnum(tls.HandshakeType.client_key_exchange)} ++ - array(u24, u8, array(u8, u8, key_share.secp256r1_kp.public_key.toUncompressedSec1()))); + array(u24, u8, array(u8, u8, key_share.secp256r1_kp.public_key.toUncompressedSec1()))); const client_change_cipher_spec_msg = .{@intFromEnum(tls.ContentType.change_cipher_spec)} ++ int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ array(u16, tls.ChangeCipherSpecType, .{.change_cipher_spec}); @@ -734,11 +734,11 @@ pub fn init(stream: anytype, options: Options) InitError(@TypeOf(stream))!Client ); const client_verify_cleartext = .{@intFromEnum(tls.HandshakeType.finished)} ++ array(u24, u8, hmacExpandLabel( - P.Hmac, - &master_secret, - &.{ "client finished", &p.transcript_hash.peek() }, - P.verify_data_length, - )); + P.Hmac, + &master_secret, + &.{ "client finished", &p.transcript_hash.peek() }, + P.verify_data_length, + )); p.transcript_hash.update(&client_verify_cleartext); p.version = .{ .tls_1_2 = .{ .expected_server_verify_data = hmacExpandLabel( @@ -766,7 +766,7 @@ pub fn init(stream: anytype, options: Options) InitError(@TypeOf(stream))!Client var client_verify_msg = .{@intFromEnum(tls.ContentType.handshake)} ++ int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ array(u16, u8, nonce[P.fixed_iv_length..].* ++ - @as([client_verify_cleartext.len + P.mac_length]u8, undefined)); + @as([client_verify_cleartext.len + P.mac_length]u8, undefined)); P.AEAD.encrypt( client_verify_msg[client_verify_msg.len - P.mac_length - client_verify_cleartext.len ..][0..client_verify_cleartext.len], diff --git a/lib/std/debug/SelfInfo.zig b/lib/std/debug/SelfInfo.zig index 544cf0ac6f..0b226ae6a0 100644 --- a/lib/std/debug/SelfInfo.zig +++ b/lib/std/debug/SelfInfo.zig @@ -689,15 +689,15 @@ pub const Module = switch (native_os) { const o_file_path = mem.sliceTo(self.strings[symbol.ofile..], 0); const o_file_info = self.ofiles.getPtr(o_file_path) orelse (self.loadOFile(allocator, o_file_path) catch |err| switch (err) { - error.FileNotFound, - error.MissingDebugInfo, - error.InvalidDebugInfo, - => return .{ - .relocated_address = relocated_address, - .symbol = symbol, - }, - else => return err, - }); + error.FileNotFound, + error.MissingDebugInfo, + error.InvalidDebugInfo, + => return .{ + .relocated_address = relocated_address, + .symbol = symbol, + }, + else => return err, + }); return .{ .relocated_address = relocated_address, diff --git a/lib/std/http/Client.zig b/lib/std/http/Client.zig index 3560e69b58..86f29b4a08 100644 --- a/lib/std/http/Client.zig +++ b/lib/std/http/Client.zig @@ -960,13 +960,13 @@ pub const Request = struct { pub const WaitError = RequestError || SendError || TransferReadError || proto.HeadersParser.CheckCompleteHeadError || Response.ParseError || error{ - TooManyHttpRedirects, - RedirectRequiresResend, - HttpRedirectLocationMissing, - HttpRedirectLocationInvalid, - CompressionInitializationFailed, - CompressionUnsupported, - }; + TooManyHttpRedirects, + RedirectRequiresResend, + HttpRedirectLocationMissing, + HttpRedirectLocationInvalid, + CompressionInitializationFailed, + CompressionUnsupported, + }; /// Waits for a response from the server and parses any headers that are sent. /// This function will block until the final response is received. @@ -1540,12 +1540,12 @@ pub fn connect( pub const RequestError = ConnectTcpError || ConnectErrorPartial || Request.SendError || std.fmt.ParseIntError || Connection.WriteError || error{ - UnsupportedUriScheme, - UriMissingHost, + UnsupportedUriScheme, + UriMissingHost, - CertificateBundleLoadFailure, - UnsupportedTransferEncoding, -}; + CertificateBundleLoadFailure, + UnsupportedTransferEncoding, + }; pub const RequestOptions = struct { version: http.Version = .@"HTTP/1.1", diff --git a/lib/std/posix.zig b/lib/std/posix.zig index bb21a79690..fd60011367 100644 --- a/lib/std/posix.zig +++ b/lib/std/posix.zig @@ -2836,12 +2836,12 @@ pub fn renameatW( rc = windows.ntdll.NtSetInformationFile( - src_fd, - &io_status_block, - rename_info, - @intCast(struct_len), // already checked for error.NameTooLong - .FileRenameInformation, - ); + src_fd, + &io_status_block, + rename_info, + @intCast(struct_len), // already checked for error.NameTooLong + .FileRenameInformation, + ); } switch (rc) { diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 04af44ffb2..d0eb421e5b 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -1185,9 +1185,9 @@ fn renderVarDeclWithoutFixups( { const name_space = if (var_decl.ast.type_node == 0 and (var_decl.ast.align_node != 0 or - var_decl.ast.addrspace_node != 0 or - var_decl.ast.section_node != 0 or - var_decl.ast.init_node != 0)) + var_decl.ast.addrspace_node != 0 or + var_decl.ast.section_node != 0 or + var_decl.ast.init_node != 0)) Space.space else Space.none; diff --git a/src/Sema.zig b/src/Sema.zig index b99852fb0a..1160657627 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -23799,7 +23799,7 @@ fn ptrCastFull( errdefer msg.destroy(sema.gpa); if (dest_info.flags.size == .Many and (src_info.flags.size == .Slice or - (src_info.flags.size == .One and Type.fromInterned(src_info.child).zigTypeTag(zcu) == .array))) + (src_info.flags.size == .One and Type.fromInterned(src_info.child).zigTypeTag(zcu) == .array))) { try sema.errNote(src, msg, "use 'ptr' field to convert slice to many pointer", .{}); } else { @@ -28828,9 +28828,9 @@ fn fieldCallBind( const first_param_type = Type.fromInterned(func_type.param_types.get(ip)[0]); if (first_param_type.isGenericPoison() or (first_param_type.zigTypeTag(zcu) == .pointer and - (first_param_type.ptrSize(zcu) == .One or - first_param_type.ptrSize(zcu) == .C) and - first_param_type.childType(zcu).eql(concrete_ty, zcu))) + (first_param_type.ptrSize(zcu) == .One or + first_param_type.ptrSize(zcu) == .C) and + first_param_type.childType(zcu).eql(concrete_ty, zcu))) { // Note that if the param type is generic poison, we know that it must // specifically be `anytype` since it's the first parameter, meaning we @@ -30363,7 +30363,7 @@ fn coerceExtra( if (dest_info.sentinel == .none or inst_info.sentinel == .none or Air.internedToRef(dest_info.sentinel) != - try sema.coerceInMemory(Value.fromInterned(inst_info.sentinel), Type.fromInterned(dest_info.child))) + try sema.coerceInMemory(Value.fromInterned(inst_info.sentinel), Type.fromInterned(dest_info.child))) break :p; const slice_ptr = try sema.analyzeSlicePtr(block, inst_src, inst, inst_ty); @@ -31186,12 +31186,12 @@ pub fn coerceInMemoryAllowed( } const ok_sent = (dest_info.sentinel == null and src_info.sentinel == null) or (src_info.sentinel != null and - dest_info.sentinel != null and - dest_info.sentinel.?.eql( - try pt.getCoerced(src_info.sentinel.?, dest_info.elem_type), - dest_info.elem_type, - zcu, - )); + dest_info.sentinel != null and + dest_info.sentinel.?.eql( + try pt.getCoerced(src_info.sentinel.?, dest_info.elem_type), + dest_info.elem_type, + zcu, + )); if (!ok_sent) { return InMemoryCoercionResult{ .array_sentinel = .{ .actual = src_info.sentinel orelse Value.@"unreachable", @@ -31642,7 +31642,7 @@ fn coerceInMemoryAllowedPtrs( const ok_sent = dest_info.sentinel == .none or src_info.flags.size == .C or (src_info.sentinel != .none and - dest_info.sentinel == try zcu.intern_pool.getCoerced(sema.gpa, pt.tid, src_info.sentinel, dest_info.child)); + dest_info.sentinel == try zcu.intern_pool.getCoerced(sema.gpa, pt.tid, src_info.sentinel, dest_info.child)); if (!ok_sent) { return InMemoryCoercionResult{ .ptr_sentinel = .{ .actual = switch (src_info.sentinel) { diff --git a/src/Type.zig b/src/Type.zig index 9548a4e5ef..45412befdd 100644 --- a/src/Type.zig +++ b/src/Type.zig @@ -607,11 +607,12 @@ pub fn hasRuntimeBitsInner( // in which case we want control flow to continue down below. if (tag_ty != .none and try Type.fromInterned(tag_ty).hasRuntimeBitsInner( - ignore_comptime_only, - strat, - zcu, - tid, - )) { + ignore_comptime_only, + strat, + zcu, + tid, + )) + { return true; } }, diff --git a/src/Zcu.zig b/src/Zcu.zig index d03eb4cc9a..f10cf5f50d 100644 --- a/src/Zcu.zig +++ b/src/Zcu.zig @@ -1195,8 +1195,8 @@ pub const SrcLoc = struct { const case = tree.fullSwitchCase(case_node).?; const is_special = (case.ast.values.len == 0) or (case.ast.values.len == 1 and - node_tags[case.ast.values[0]] == .identifier and - mem.eql(u8, tree.tokenSlice(main_tokens[case.ast.values[0]]), "_")); + node_tags[case.ast.values[0]] == .identifier and + mem.eql(u8, tree.tokenSlice(main_tokens[case.ast.values[0]]), "_")); if (!is_special) continue; return tree.nodeToSpan(case_node); @@ -1215,8 +1215,8 @@ pub const SrcLoc = struct { const case = tree.fullSwitchCase(case_node).?; const is_special = (case.ast.values.len == 0) or (case.ast.values.len == 1 and - node_tags[case.ast.values[0]] == .identifier and - mem.eql(u8, tree.tokenSlice(main_tokens[case.ast.values[0]]), "_")); + node_tags[case.ast.values[0]] == .identifier and + mem.eql(u8, tree.tokenSlice(main_tokens[case.ast.values[0]]), "_")); if (is_special) continue; for (case.ast.values) |item_node| { diff --git a/src/arch/riscv64/CodeGen.zig b/src/arch/riscv64/CodeGen.zig index 24497defa2..23e74fa990 100644 --- a/src/arch/riscv64/CodeGen.zig +++ b/src/arch/riscv64/CodeGen.zig @@ -685,8 +685,7 @@ fn restoreState(func: *Func, state: State, deaths: []const Air.Inst.Index, compt const ExpectedContents = [@typeInfo(RegisterManager.TrackedRegisters).array.len]RegisterLock; var stack align(@max(@alignOf(ExpectedContents), @alignOf(std.heap.StackFallbackAllocator(0)))) = - if (opts.update_tracking) - {} else std.heap.stackFallback(@sizeOf(ExpectedContents), func.gpa); + if (opts.update_tracking) {} else std.heap.stackFallback(@sizeOf(ExpectedContents), func.gpa); var reg_locks = if (opts.update_tracking) {} else try std.ArrayList(RegisterLock).initCapacity( stack.get(), @@ -2303,7 +2302,7 @@ fn airIntCast(func: *Func, inst: Air.Inst.Index) !void { const dst_mcv = if (dst_int_info.bits <= src_storage_bits and math.divCeil(u16, dst_int_info.bits, 64) catch unreachable == - math.divCeil(u32, src_storage_bits, 64) catch unreachable and + math.divCeil(u32, src_storage_bits, 64) catch unreachable and func.reuseOperand(inst, ty_op.operand, 0, src_mcv)) src_mcv else dst: { const dst_mcv = try func.allocRegOrMem(dst_ty, inst, true); try func.genCopy(min_ty, dst_mcv, src_mcv); @@ -2361,9 +2360,9 @@ fn airNot(func: *Func, inst: Air.Inst.Index) !void { const dst_reg: Register = if (func.reuseOperand(inst, ty_op.operand, 0, operand) and operand == .register) - operand.register - else - (try func.allocRegOrMem(func.typeOfIndex(inst), inst, true)).register; + operand.register + else + (try func.allocRegOrMem(func.typeOfIndex(inst), inst, true)).register; switch (ty.zigTypeTag(zcu)) { .bool => { @@ -6271,11 +6270,11 @@ fn airAsm(func: *Func, inst: Air.Inst.Index) !void { const instruction: union(enum) { mnem: Mnemonic, pseudo: Pseudo } = if (std.meta.stringToEnum(Mnemonic, mnem_str)) |mnem| - .{ .mnem = mnem } - else if (std.meta.stringToEnum(Pseudo, mnem_str)) |pseudo| - .{ .pseudo = pseudo } - else - return func.fail("invalid mnem str '{s}'", .{mnem_str}); + .{ .mnem = mnem } + else if (std.meta.stringToEnum(Pseudo, mnem_str)) |pseudo| + .{ .pseudo = pseudo } + else + return func.fail("invalid mnem str '{s}'", .{mnem_str}); const Operand = union(enum) { none, diff --git a/src/arch/x86_64/CodeGen.zig b/src/arch/x86_64/CodeGen.zig index 06ae399f25..866e75ae6e 100644 --- a/src/arch/x86_64/CodeGen.zig +++ b/src/arch/x86_64/CodeGen.zig @@ -2919,8 +2919,7 @@ fn restoreState(self: *Self, state: State, deaths: []const Air.Inst.Index, compt const ExpectedContents = [@typeInfo(RegisterManager.TrackedRegisters).array.len]RegisterLock; var stack align(@max(@alignOf(ExpectedContents), @alignOf(std.heap.StackFallbackAllocator(0)))) = - if (opts.update_tracking) - {} else std.heap.stackFallback(@sizeOf(ExpectedContents), self.gpa); + if (opts.update_tracking) {} else std.heap.stackFallback(@sizeOf(ExpectedContents), self.gpa); var reg_locks = if (opts.update_tracking) {} else try std.ArrayList(RegisterLock).initCapacity( stack.get(), @@ -3487,7 +3486,7 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void { const dst_mcv = if (dst_int_info.bits <= src_storage_bits and math.divCeil(u16, dst_int_info.bits, 64) catch unreachable == - math.divCeil(u32, src_storage_bits, 64) catch unreachable and + math.divCeil(u32, src_storage_bits, 64) catch unreachable and self.reuseOperand(inst, ty_op.operand, 0, src_mcv)) src_mcv else dst: { const dst_mcv = try self.allocRegOrMem(inst, true); try self.genCopy(min_ty, dst_mcv, src_mcv, .{}); @@ -5022,10 +5021,10 @@ fn genIntMulDivOpMir(self: *Self, tag: Mir.Inst.FixedTag, ty: Type, lhs: MCValue ._ => { const hi_reg: Register = switch (bit_size) { - 8 => .ah, - 16, 32, 64 => .edx, - else => unreachable, - }; + 8 => .ah, + 16, 32, 64 => .edx, + else => unreachable, + }; try self.asmRegisterRegister(.{ ._, .xor }, hi_reg, hi_reg); }, .i_ => try self.asmOpOnly(.{ ._, switch (bit_size) { @@ -9349,9 +9348,9 @@ fn genShiftBinOpMir( .size = Memory.Size.fromSize(abi_size), .disp = math.cast(i32, @as(i64, @bitCast(addr))) orelse return self.fail("TODO genShiftBinOpMir between {s} and {s}", .{ - @tagName(lhs_mcv), - @tagName(shift_mcv), - }), + @tagName(lhs_mcv), + @tagName(shift_mcv), + }), } }, }, .indirect => |reg_off| .{ @@ -10081,17 +10080,17 @@ fn genBinOp( const ordered_air: [2]Air.Inst.Ref = if (lhs_ty.isVector(zcu) and switch (lhs_ty.childType(zcu).zigTypeTag(zcu)) { - .bool => false, - .int => switch (air_tag) { - .cmp_lt, .cmp_gte => true, - else => false, - }, - .float => switch (air_tag) { - .cmp_gte, .cmp_gt => true, - else => false, - }, - else => unreachable, - }) .{ rhs_air, lhs_air } else .{ lhs_air, rhs_air }; + .bool => false, + .int => switch (air_tag) { + .cmp_lt, .cmp_gte => true, + else => false, + }, + .float => switch (air_tag) { + .cmp_gte, .cmp_gt => true, + else => false, + }, + else => unreachable, + }) .{ rhs_air, lhs_air } else .{ lhs_air, rhs_air }; if (lhs_ty.isAbiInt(zcu)) for (ordered_air) |op_air| { switch (try self.resolveInst(op_air)) { @@ -12066,13 +12065,13 @@ fn genIntMulComplexOpMir(self: *Self, dst_ty: Type, dst_mcv: MCValue, src_mcv: M .size = Memory.Size.fromSize(abi_size), .disp = math.cast(i32, @as(i64, @bitCast(addr))) orelse return self.asmRegisterRegister( - .{ .i_, .mul }, - dst_alias, - registerAlias( - try self.copyToTmpRegister(dst_ty, resolved_src_mcv), - abi_size, + .{ .i_, .mul }, + dst_alias, + registerAlias( + try self.copyToTmpRegister(dst_ty, resolved_src_mcv), + abi_size, + ), ), - ), } }, }, .indirect => |reg_off| .{ @@ -14165,9 +14164,9 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void { mem.eql(u8, rest, "r,m") or mem.eql(u8, rest, "m,r")) self.register_manager.tryAllocReg(maybe_inst, abi.RegisterClass.gp) orelse if (output != .none) - null - else - return self.fail("ran out of registers lowering inline asm", .{}) + null + else + return self.fail("ran out of registers lowering inline asm", .{}) else if (mem.startsWith(u8, rest, "{") and mem.endsWith(u8, rest, "}")) parseRegName(rest["{".len .. rest.len - "}".len]) orelse return self.fail("invalid register constraint: '{s}'", .{constraint}) @@ -16607,9 +16606,9 @@ fn airAtomicLoad(self: *Self, inst: Air.Inst.Index) !void { const dst_mcv = if (self.reuseOperand(inst, atomic_load.ptr, 0, ptr_mcv)) - ptr_mcv - else - try self.allocRegOrMem(inst, true); + ptr_mcv + else + try self.allocRegOrMem(inst, true); try self.load(dst_mcv, ptr_ty, ptr_mcv); return self.finishAir(inst, dst_mcv, .{ atomic_load.ptr, .none, .none }); diff --git a/src/arch/x86_64/Lower.zig b/src/arch/x86_64/Lower.zig index 058201c2d7..55828c5926 100644 --- a/src/arch/x86_64/Lower.zig +++ b/src/arch/x86_64/Lower.zig @@ -418,17 +418,17 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) _ = lower.reloc(.{ .linker_tlsld = sym_index }, 0); lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .lea, &[_]Operand{ - .{ .reg = .rdi }, - .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }, - }); + .{ .reg = .rdi }, + .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }, + }); lower.result_insts_len += 1; _ = lower.reloc(.{ .linker_extern_fn = try elf_file.getGlobalSymbol("__tls_get_addr", null), }, 0); lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .call, &[_]Operand{ - .{ .imm = Immediate.s(0) }, - }); + .{ .imm = Immediate.s(0) }, + }); lower.result_insts_len += 1; _ = lower.reloc(.{ .linker_dtpoff = sym_index }, 0); emit_mnemonic = .lea; @@ -440,9 +440,9 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) // Since we are linking statically, we emit LE model directly. lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .mov, &[_]Operand{ - .{ .reg = .rax }, - .{ .mem = Memory.initSib(.qword, .{ .base = .{ .reg = .fs } }) }, - }); + .{ .reg = .rax }, + .{ .mem = Memory.initSib(.qword, .{ .base = .{ .reg = .fs } }) }, + }); lower.result_insts_len += 1; _ = lower.reloc(.{ .linker_reloc = sym_index }, 0); emit_mnemonic = .lea; @@ -464,9 +464,9 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) const reg = ops[0].reg; lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .mov, &[_]Operand{ - .{ .reg = reg.to64() }, - .{ .mem = Memory.initRip(.qword, 0) }, - }); + .{ .reg = reg.to64() }, + .{ .mem = Memory.initRip(.qword, 0) }, + }); lower.result_insts_len += 1; break :op .{ .mem = Memory.initSib(mem_op.sib.ptr_size, .{ .base = .{ .reg = reg.to64(), @@ -496,14 +496,14 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) _ = lower.reloc(.{ .linker_reloc = sym_index }, 0); lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .mov, &[_]Operand{ - .{ .reg = .rdi }, - .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }, - }); + .{ .reg = .rdi }, + .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }, + }); lower.result_insts_len += 1; lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .call, &[_]Operand{ - .{ .mem = Memory.initSib(.qword, .{ .base = .{ .reg = .rdi } }) }, - }); + .{ .mem = Memory.initSib(.qword, .{ .base = .{ .reg = .rdi } }) }, + }); lower.result_insts_len += 1; emit_mnemonic = .mov; break :op .{ .reg = .rax }; @@ -520,9 +520,9 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) const reg = ops[0].reg; lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .mov, &[_]Operand{ - .{ .reg = reg.to64() }, - .{ .mem = Memory.initRip(.qword, 0) }, - }); + .{ .reg = reg.to64() }, + .{ .mem = Memory.initRip(.qword, 0) }, + }); lower.result_insts_len += 1; break :op .{ .mem = Memory.initSib(mem_op.sib.ptr_size, .{ .base = .{ .reg = reg.to64(), diff --git a/src/codegen.zig b/src/codegen.zig index 2b179979f0..46d9487141 100644 --- a/src/codegen.zig +++ b/src/codegen.zig @@ -452,7 +452,7 @@ pub fn generateSymbol( const padding = abi_size - (math.cast(usize, Type.fromInterned(vector_type.child).abiSize(zcu) * vector_type.len) orelse - return error.Overflow); + return error.Overflow); if (padding > 0) try code.appendNTimes(0, padding); } }, diff --git a/src/codegen/c.zig b/src/codegen/c.zig index 0410023588..b7fc248a35 100644 --- a/src/codegen/c.zig +++ b/src/codegen/c.zig @@ -1921,7 +1921,7 @@ pub const DeclGen = struct { if (dest_bits <= 64 and src_bits <= 64) { const needs_cast = src_int_info == null or (toCIntBits(dest_int_info.bits) != toCIntBits(src_int_info.?.bits) or - dest_int_info.signedness != src_int_info.?.signedness); + dest_int_info.signedness != src_int_info.?.signedness); return !needs_cast and !src_is_ptr; } else return false; } @@ -1962,7 +1962,7 @@ pub const DeclGen = struct { if (dest_bits <= 64 and src_bits <= 64) { const needs_cast = src_int_info == null or (toCIntBits(dest_int_info.bits) != toCIntBits(src_int_info.?.bits) or - dest_int_info.signedness != src_int_info.?.signedness); + dest_int_info.signedness != src_int_info.?.signedness); if (needs_cast) { try w.writeByte('('); @@ -4278,7 +4278,7 @@ fn airEquality( .aligned, .array, .vector, .fwd_decl, .function => unreachable, .aggregate => |aggregate| if (aggregate.fields.len == 2 and (aggregate.fields.at(0, ctype_pool).name.index == .is_null or - aggregate.fields.at(1, ctype_pool).name.index == .is_null)) + aggregate.fields.at(1, ctype_pool).name.index == .is_null)) { try f.writeCValueMember(writer, lhs, .{ .identifier = "is_null" }); try writer.writeAll(" || "); diff --git a/src/codegen/c/Type.zig b/src/codegen/c/Type.zig index 31daa75a13..6f4d200457 100644 --- a/src/codegen/c/Type.zig +++ b/src/codegen/c/Type.zig @@ -750,12 +750,12 @@ pub const Info = union(enum) { fn tag(pointer_info: Pointer) Pool.Tag { return @enumFromInt(@intFromEnum(Pool.Tag.pointer) + @as(u2, @bitCast(packed struct(u2) { - @"const": bool, - @"volatile": bool, - }{ - .@"const" = pointer_info.@"const", - .@"volatile" = pointer_info.@"volatile", - }))); + @"const": bool, + @"volatile": bool, + }{ + .@"const" = pointer_info.@"const", + .@"volatile" = pointer_info.@"volatile", + }))); } }; @@ -879,24 +879,24 @@ pub const Info = union(enum) { pool_adapter.eql(lhs_vector_info.elem_ctype, rhs_info.vector.elem_ctype), .fwd_decl => |lhs_fwd_decl_info| lhs_fwd_decl_info.tag == rhs_info.fwd_decl.tag and switch (lhs_fwd_decl_info.name) { - .anon => |lhs_anon| rhs_info.fwd_decl.name == .anon and lhs_anon.eqlAdapted( - lhs_pool, - rhs_info.fwd_decl.name.anon, - rhs_pool, - pool_adapter, - ), - .index => |lhs_index| rhs_info.fwd_decl.name == .index and - lhs_index == rhs_info.fwd_decl.name.index, - }, + .anon => |lhs_anon| rhs_info.fwd_decl.name == .anon and lhs_anon.eqlAdapted( + lhs_pool, + rhs_info.fwd_decl.name.anon, + rhs_pool, + pool_adapter, + ), + .index => |lhs_index| rhs_info.fwd_decl.name == .index and + lhs_index == rhs_info.fwd_decl.name.index, + }, .aggregate => |lhs_aggregate_info| lhs_aggregate_info.tag == rhs_info.aggregate.tag and lhs_aggregate_info.@"packed" == rhs_info.aggregate.@"packed" and switch (lhs_aggregate_info.name) { - .anon => |lhs_anon| rhs_info.aggregate.name == .anon and - lhs_anon.index == rhs_info.aggregate.name.anon.index and - lhs_anon.id == rhs_info.aggregate.name.anon.id, - .fwd_decl => |lhs_fwd_decl| rhs_info.aggregate.name == .fwd_decl and - pool_adapter.eql(lhs_fwd_decl, rhs_info.aggregate.name.fwd_decl), - } and lhs_aggregate_info.fields.eqlAdapted( + .anon => |lhs_anon| rhs_info.aggregate.name == .anon and + lhs_anon.index == rhs_info.aggregate.name.anon.index and + lhs_anon.id == rhs_info.aggregate.name.anon.id, + .fwd_decl => |lhs_fwd_decl| rhs_info.aggregate.name == .fwd_decl and + pool_adapter.eql(lhs_fwd_decl, rhs_info.aggregate.name.fwd_decl), + } and lhs_aggregate_info.fields.eqlAdapted( lhs_pool, rhs_info.aggregate.fields, rhs_pool, @@ -905,13 +905,12 @@ pub const Info = union(enum) { .function => |lhs_function_info| lhs_function_info.param_ctypes.len == rhs_info.function.param_ctypes.len and pool_adapter.eql(lhs_function_info.return_ctype, rhs_info.function.return_ctype) and - for (0..lhs_function_info.param_ctypes.len) |param_index| - { - if (!pool_adapter.eql( - lhs_function_info.param_ctypes.at(param_index, lhs_pool), - rhs_info.function.param_ctypes.at(param_index, rhs_pool), - )) break false; - } else true, + for (0..lhs_function_info.param_ctypes.len) |param_index| { + if (!pool_adapter.eql( + lhs_function_info.param_ctypes.at(param_index, lhs_pool), + rhs_info.function.param_ctypes.at(param_index, rhs_pool), + )) break false; + } else true, }; } }; @@ -1947,13 +1946,13 @@ pub const Pool = struct { const return_type = Type.fromInterned(func_info.return_type); const return_ctype: CType = if (!ip.isNoReturn(func_info.return_type)) try pool.fromType( - allocator, - scratch, - return_type, - pt, - mod, - kind.asParameter(), - ) else CType.void; + allocator, + scratch, + return_type, + pt, + mod, + kind.asParameter(), + ) else CType.void; for (0..func_info.param_types.len) |param_index| { const param_type = Type.fromInterned( func_info.param_types.get(ip)[param_index], diff --git a/src/codegen/llvm.zig b/src/codegen/llvm.zig index 3a8fde75da..524f118ace 100644 --- a/src/codegen/llvm.zig +++ b/src/codegen/llvm.zig @@ -486,7 +486,7 @@ const DataLayoutBuilder = struct { self.target.cpu.arch != .riscv64 and self.target.cpu.arch != .loongarch64 and !(self.target.cpu.arch == .aarch64 and - (self.target.os.tag == .uefi or self.target.os.tag == .windows)) and + (self.target.os.tag == .uefi or self.target.os.tag == .windows)) and self.target.cpu.arch != .bpfeb and self.target.cpu.arch != .bpfel) continue; try writer.writeAll("-p"); if (info.llvm != .default) try writer.print("{d}", .{@intFromEnum(info.llvm)}); @@ -957,55 +957,54 @@ pub const Object = struct { builder.data_layout = try builder.fmt("{}", .{DataLayoutBuilder{ .target = target }}); const debug_compile_unit, const debug_enums_fwd_ref, const debug_globals_fwd_ref = - if (!builder.strip) - debug_info: { - // We fully resolve all paths at this point to avoid lack of - // source line info in stack traces or lack of debugging - // information which, if relative paths were used, would be - // very location dependent. - // TODO: the only concern I have with this is WASI as either host or target, should - // we leave the paths as relative then? - // TODO: This is totally wrong. In dwarf, paths are encoded as relative to - // a particular directory, and then the directory path is specified elsewhere. - // In the compiler frontend we have it stored correctly in this - // way already, but here we throw all that sweet information - // into the garbage can by converting into absolute paths. What - // a terrible tragedy. - const compile_unit_dir = blk: { - if (comp.zcu) |zcu| m: { - const d = try zcu.main_mod.root.joinString(arena, ""); - if (d.len == 0) break :m; - if (std.fs.path.isAbsolute(d)) break :blk d; - break :blk std.fs.realpathAlloc(arena, d) catch break :blk d; - } - break :blk try std.process.getCwdAlloc(arena); - }; + if (!builder.strip) debug_info: { + // We fully resolve all paths at this point to avoid lack of + // source line info in stack traces or lack of debugging + // information which, if relative paths were used, would be + // very location dependent. + // TODO: the only concern I have with this is WASI as either host or target, should + // we leave the paths as relative then? + // TODO: This is totally wrong. In dwarf, paths are encoded as relative to + // a particular directory, and then the directory path is specified elsewhere. + // In the compiler frontend we have it stored correctly in this + // way already, but here we throw all that sweet information + // into the garbage can by converting into absolute paths. What + // a terrible tragedy. + const compile_unit_dir = blk: { + if (comp.zcu) |zcu| m: { + const d = try zcu.main_mod.root.joinString(arena, ""); + if (d.len == 0) break :m; + if (std.fs.path.isAbsolute(d)) break :blk d; + break :blk std.fs.realpathAlloc(arena, d) catch break :blk d; + } + break :blk try std.process.getCwdAlloc(arena); + }; - const debug_file = try builder.debugFile( - try builder.metadataString(comp.root_name), - try builder.metadataString(compile_unit_dir), - ); + const debug_file = try builder.debugFile( + try builder.metadataString(comp.root_name), + try builder.metadataString(compile_unit_dir), + ); - const debug_enums_fwd_ref = try builder.debugForwardReference(); - const debug_globals_fwd_ref = try builder.debugForwardReference(); + const debug_enums_fwd_ref = try builder.debugForwardReference(); + const debug_globals_fwd_ref = try builder.debugForwardReference(); - const debug_compile_unit = try builder.debugCompileUnit( - debug_file, - // Don't use the version string here; LLVM misparses it when it - // includes the git revision. - try builder.metadataStringFmt("zig {d}.{d}.{d}", .{ - build_options.semver.major, - build_options.semver.minor, - build_options.semver.patch, - }), - debug_enums_fwd_ref, - debug_globals_fwd_ref, - .{ .optimized = comp.root_mod.optimize_mode != .Debug }, - ); + const debug_compile_unit = try builder.debugCompileUnit( + debug_file, + // Don't use the version string here; LLVM misparses it when it + // includes the git revision. + try builder.metadataStringFmt("zig {d}.{d}.{d}", .{ + build_options.semver.major, + build_options.semver.minor, + build_options.semver.patch, + }), + debug_enums_fwd_ref, + debug_globals_fwd_ref, + .{ .optimized = comp.root_mod.optimize_mode != .Debug }, + ); - try builder.metadataNamed(try builder.metadataString("llvm.dbg.cu"), &.{debug_compile_unit}); - break :debug_info .{ debug_compile_unit, debug_enums_fwd_ref, debug_globals_fwd_ref }; - } else .{.none} ** 3; + try builder.metadataNamed(try builder.metadataString("llvm.dbg.cu"), &.{debug_compile_unit}); + break :debug_info .{ debug_compile_unit, debug_enums_fwd_ref, debug_globals_fwd_ref }; + } else .{.none} ** 3; const obj = try arena.create(Object); obj.* = .{ @@ -2866,9 +2865,9 @@ pub const Object = struct { const full_fields: [2]Builder.Metadata = if (layout.tag_align.compare(.gte, layout.payload_align)) - .{ debug_tag_type, debug_payload_type } - else - .{ debug_payload_type, debug_tag_type }; + .{ debug_tag_type, debug_payload_type } + else + .{ debug_payload_type, debug_tag_type }; const debug_tagged_union_type = try o.builder.debugStructType( try o.builder.metadataString(name), @@ -4673,11 +4672,11 @@ pub const Object = struct { // instruction is followed by a `wrap_optional`, it will return this value // verbatim, and the result should test as non-null. switch (zcu.getTarget().ptrBitWidth()) { - 16 => 0xaaaa, - 32 => 0xaaaaaaaa, - 64 => 0xaaaaaaaa_aaaaaaaa, - else => unreachable, - }; + 16 => 0xaaaa, + 32 => 0xaaaaaaaa, + 64 => 0xaaaaaaaa_aaaaaaaa, + else => unreachable, + }; const llvm_usize = try o.lowerType(Type.usize); const llvm_ptr_ty = try o.lowerType(ptr_ty); return o.builder.castConst(.inttoptr, try o.builder.intConst(llvm_usize, int), llvm_ptr_ty); @@ -9564,7 +9563,7 @@ pub const FuncGen = struct { if (llvm_dest_ty.isStruct(&o.builder) or ((operand_ty.zigTypeTag(zcu) == .vector or inst_ty.zigTypeTag(zcu) == .vector) and - operand_ty.bitSize(zcu) != inst_ty.bitSize(zcu))) + operand_ty.bitSize(zcu) != inst_ty.bitSize(zcu))) { // Both our operand and our result are values, not pointers, // but LLVM won't let us bitcast struct values or vectors with padding bits. diff --git a/src/link/Elf/relocatable.zig b/src/link/Elf/relocatable.zig index 3035c33790..9fe459b217 100644 --- a/src/link/Elf/relocatable.zig +++ b/src/link/Elf/relocatable.zig @@ -217,20 +217,20 @@ fn initSections(elf_file: *Elf) !void { if (elf_file.section_indexes.eh_frame == null) { elf_file.section_indexes.eh_frame = elf_file.sectionByName(".eh_frame") orelse try elf_file.addSection(.{ - .name = try elf_file.insertShString(".eh_frame"), - .type = if (elf_file.getTarget().cpu.arch == .x86_64) - elf.SHT_X86_64_UNWIND - else - elf.SHT_PROGBITS, - .flags = elf.SHF_ALLOC, - .addralign = elf_file.ptrWidthBytes(), - }); + .name = try elf_file.insertShString(".eh_frame"), + .type = if (elf_file.getTarget().cpu.arch == .x86_64) + elf.SHT_X86_64_UNWIND + else + elf.SHT_PROGBITS, + .flags = elf.SHF_ALLOC, + .addralign = elf_file.ptrWidthBytes(), + }); } elf_file.section_indexes.eh_frame_rela = elf_file.sectionByName(".rela.eh_frame") orelse try elf_file.addRelaShdr( - try elf_file.insertShString(".rela.eh_frame"), - elf_file.section_indexes.eh_frame.?, - ); + try elf_file.insertShString(".rela.eh_frame"), + elf_file.section_indexes.eh_frame.?, + ); } try initComdatGroups(elf_file); diff --git a/src/link/Elf/synthetic_sections.zig b/src/link/Elf/synthetic_sections.zig index 6d26ec5d1f..8364846019 100644 --- a/src/link/Elf/synthetic_sections.zig +++ b/src/link/Elf/synthetic_sections.zig @@ -551,7 +551,7 @@ pub const GotSection = struct { switch (entry.tag) { .got => if (symbol.?.flags.import or symbol.?.isIFunc(elf_file) or ((elf_file.isEffectivelyDynLib() or (elf_file.base.isExe() and comp.config.pie)) and - !symbol.?.isAbs(elf_file))) + !symbol.?.isAbs(elf_file))) { num += 1; }, diff --git a/src/link/MachO.zig b/src/link/MachO.zig index 1ffcabb1f5..e3643bdfbd 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -1580,14 +1580,14 @@ fn initOutputSections(self: *MachO) !void { } self.text_sect_index = self.getSectionByName("__TEXT", "__text") orelse try self.addSection("__TEXT", "__text", .{ - .alignment = switch (self.getTarget().cpu.arch) { - .x86_64 => 0, - .aarch64 => 2, - else => unreachable, - }, - .flags = macho.S_REGULAR | - macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS, - }); + .alignment = switch (self.getTarget().cpu.arch) { + .x86_64 => 0, + .aarch64 => 2, + else => unreachable, + }, + .flags = macho.S_REGULAR | + macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS, + }); self.data_sect_index = self.getSectionByName("__DATA", "__data") orelse try self.addSection("__DATA", "__data", .{}); } diff --git a/src/link/MachO/Atom.zig b/src/link/MachO/Atom.zig index f8bf9c37e7..e4506ffa54 100644 --- a/src/link/MachO/Atom.zig +++ b/src/link/MachO/Atom.zig @@ -149,10 +149,10 @@ pub fn initOutputSection(sect: macho.section_64, macho_file: *MachO) !u8 { if (macho_file.base.isRelocatable()) { const osec = macho_file.getSectionByName(sect.segName(), sect.sectName()) orelse try macho_file.addSection( - sect.segName(), - sect.sectName(), - .{ .flags = sect.flags }, - ); + sect.segName(), + sect.sectName(), + .{ .flags = sect.flags }, + ); return osec; } diff --git a/src/link/MachO/ZigObject.zig b/src/link/MachO/ZigObject.zig index 097be1bc70..8182897d4b 100644 --- a/src/link/MachO/ZigObject.zig +++ b/src/link/MachO/ZigObject.zig @@ -1109,8 +1109,8 @@ fn createTlvDescriptor( const sect_index = macho_file.getSectionByName("__DATA", "__thread_vars") orelse try macho_file.addSection("__DATA", "__thread_vars", .{ - .flags = macho.S_THREAD_LOCAL_VARIABLES, - }); + .flags = macho.S_THREAD_LOCAL_VARIABLES, + }); sym.out_n_sect = sect_index; atom.out_n_sect = sect_index; diff --git a/src/link/MachO/dead_strip.zig b/src/link/MachO/dead_strip.zig index 30f53d3744..24d7e18d1a 100644 --- a/src/link/MachO/dead_strip.zig +++ b/src/link/MachO/dead_strip.zig @@ -102,8 +102,8 @@ fn mark(roots: []*Atom, objects: []const File.Index, macho_file: *MachO) void { const isec = atom.getInputSection(macho_file); if (isec.isDontDeadStripIfReferencesLive() and !(mem.eql(u8, isec.sectName(), "__eh_frame") or - mem.eql(u8, isec.sectName(), "__compact_unwind") or - isec.attrs() & macho.S_ATTR_DEBUG != 0) and + mem.eql(u8, isec.sectName(), "__compact_unwind") or + isec.attrs() & macho.S_ATTR_DEBUG != 0) and !atom.isAlive() and refersLive(atom, macho_file)) { markLive(atom, macho_file); diff --git a/src/main.zig b/src/main.zig index 24fc0aa60c..ebd412999d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -5815,8 +5815,8 @@ pub const ClangArgIterator = struct { self.arg_iterator_response_file = initArgIteratorResponseFile(arena, resp_file_path) catch |err| { - fatal("unable to read response file '{s}': {s}", .{ resp_file_path, @errorName(err) }); - }; + fatal("unable to read response file '{s}': {s}", .{ resp_file_path, @errorName(err) }); + }; // NOTE: The ArgIteratorResponseFile returns tokens from next() that are slices of an // internal buffer. This internal buffer is arena allocated, so it is not cleaned up here. @@ -6113,8 +6113,8 @@ fn cmdAstCheck( file.tree.tokens.len * (@sizeOf(std.zig.Token.Tag) + @sizeOf(Ast.ByteOffset)); const tree_bytes = @sizeOf(Ast) + file.tree.nodes.len * (@sizeOf(Ast.Node.Tag) + - @sizeOf(Ast.Node.Data) + - @sizeOf(Ast.TokenIndex)); + @sizeOf(Ast.Node.Data) + + @sizeOf(Ast.TokenIndex)); const instruction_bytes = file.zir.instructions.len * // Here we don't use @sizeOf(Zir.Inst.Data) because it would include // the debug safety tag but we want to measure release size. diff --git a/src/translate_c.zig b/src/translate_c.zig index 6faffde7e2..da224c2828 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -2569,9 +2569,9 @@ fn transInitListExprRecord( // Unions and Structs are both represented as RecordDecl const record_ty = ty.getAsRecordType() orelse blk: { - is_union_type = true; - break :blk ty.getAsUnionType(); - } orelse unreachable; + is_union_type = true; + break :blk ty.getAsUnionType(); + } orelse unreachable; const record_decl = record_ty.getDecl(); const record_def = record_decl.getDefinition() orelse unreachable; @@ -4005,7 +4005,7 @@ fn transCPtrCast( if (!src_ty.isArrayType() and ((src_child_type.isConstQualified() and !child_type.isConstQualified()) or (src_child_type.isVolatileQualified() and - !child_type.isVolatileQualified()))) + !child_type.isVolatileQualified()))) { return removeCVQualifiers(c, dst_type_node, expr); } else { @@ -4091,8 +4091,8 @@ fn transFloatingLiteralQuad(c: *Context, expr: *const clang.FloatingLiteral, use false; break :fmt_decimal if (could_roundtrip) try c.arena.dupe(u8, temp_str) else null; } - // otherwise, fall back to the hexadecimal format - orelse try std.fmt.allocPrint(c.arena, "{x}", .{quad}); + // otherwise, fall back to the hexadecimal format + orelse try std.fmt.allocPrint(c.arena, "{x}", .{quad}); var node = try Tag.float_literal.create(c.arena, str); if (is_negative) node = try Tag.negate.create(c.arena, node); @@ -5079,15 +5079,14 @@ fn finishTransFnProto( const is_noalias = param_qt.isRestrictQualified(); const param_name: ?[]const u8 = - if (fn_decl) |decl| - blk: { - const param = decl.getParamDecl(@as(c_uint, @intCast(i))); - const param_name: []const u8 = try c.str(@as(*const clang.NamedDecl, @ptrCast(param)).getName_bytes_begin()); - if (param_name.len < 1) - break :blk null; + if (fn_decl) |decl| blk: { + const param = decl.getParamDecl(@as(c_uint, @intCast(i))); + const param_name: []const u8 = try c.str(@as(*const clang.NamedDecl, @ptrCast(param)).getName_bytes_begin()); + if (param_name.len < 1) + break :blk null; - break :blk param_name; - } else null; + break :blk param_name; + } else null; const type_node = try transQualType(c, scope, param_qt, source_loc); fn_params.addOneAssumeCapacity().* = .{ diff --git a/test/behavior/export_builtin.zig b/test/behavior/export_builtin.zig index 6ca10376a1..8bb204e0e3 100644 --- a/test/behavior/export_builtin.zig +++ b/test/behavior/export_builtin.zig @@ -50,8 +50,8 @@ test "exporting comptime-known value" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64 and (builtin.target.ofmt != .elf and - builtin.target.ofmt != .macho and - builtin.target.ofmt != .coff)) return error.SkipZigTest; + builtin.target.ofmt != .macho and + builtin.target.ofmt != .coff)) return error.SkipZigTest; if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest; diff --git a/test/link/elf.zig b/test/link/elf.zig index 5014d20c98..85fa41a5a9 100644 --- a/test/link/elf.zig +++ b/test/link/elf.zig @@ -479,7 +479,7 @@ fn testCommentString(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "comment-string", opts); const exe = addExecutable(b, opts, .{ .name = "main", .zig_source_bytes = - \\pub fn main() void {} + \\pub fn main() void {} }); const check = exe.checkObject(); @@ -494,7 +494,7 @@ fn testCommentStringStaticLib(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "comment-string-static-lib", opts); const lib = addStaticLibrary(b, opts, .{ .name = "lib", .zig_source_bytes = - \\export fn foo() void {} + \\export fn foo() void {} }); const check = lib.checkObject(); @@ -865,23 +865,23 @@ fn testEmitRelocatable(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "emit-relocatable", opts); const a_o = addObject(b, opts, .{ .name = "a", .zig_source_bytes = - \\const std = @import("std"); - \\extern var bar: i32; - \\export fn foo() i32 { - \\ return bar; - \\} - \\export fn printFoo() void { - \\ std.debug.print("foo={d}\n", .{foo()}); - \\} + \\const std = @import("std"); + \\extern var bar: i32; + \\export fn foo() i32 { + \\ return bar; + \\} + \\export fn printFoo() void { + \\ std.debug.print("foo={d}\n", .{foo()}); + \\} }); a_o.linkLibC(); const b_o = addObject(b, opts, .{ .name = "b", .c_source_bytes = - \\#include - \\int bar = 42; - \\void printBar() { - \\ fprintf(stderr, "bar=%d\n", bar); - \\} + \\#include + \\int bar = 42; + \\void printBar() { + \\ fprintf(stderr, "bar=%d\n", bar); + \\} }); b_o.linkLibC(); @@ -890,13 +890,13 @@ fn testEmitRelocatable(b: *Build, opts: Options) *Step { c_o.addObject(b_o); const exe = addExecutable(b, opts, .{ .name = "test", .zig_source_bytes = - \\const std = @import("std"); - \\extern fn printFoo() void; - \\extern fn printBar() void; - \\pub fn main() void { - \\ printFoo(); - \\ printBar(); - \\} + \\const std = @import("std"); + \\extern fn printFoo() void; + \\extern fn printBar() void; + \\pub fn main() void { + \\ printFoo(); + \\ printBar(); + \\} }); exe.addObject(c_o); exe.linkLibC(); @@ -1924,8 +1924,8 @@ fn testInitArrayOrder(b: *Build, opts: Options) *Step { g_o.linkLibC(); const h_o = addObject(b, opts, .{ .name = "h", .c_source_bytes = - \\#include - \\__attribute__((destructor)) void fini2() { printf("8"); } + \\#include + \\__attribute__((destructor)) void fini2() { printf("8"); } }); h_o.linkLibC(); @@ -2488,23 +2488,23 @@ fn testMergeStrings2(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "merge-strings2", opts); const obj1 = addObject(b, opts, .{ .name = "a", .zig_source_bytes = - \\const std = @import("std"); - \\export fn foo() void { - \\ var arr: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 }; - \\ const slice = std.mem.sliceTo(&arr, 3); - \\ std.testing.expectEqualSlices(u16, arr[0..2], slice) catch unreachable; - \\} + \\const std = @import("std"); + \\export fn foo() void { + \\ var arr: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 }; + \\ const slice = std.mem.sliceTo(&arr, 3); + \\ std.testing.expectEqualSlices(u16, arr[0..2], slice) catch unreachable; + \\} }); const obj2 = addObject(b, opts, .{ .name = "b", .zig_source_bytes = - \\const std = @import("std"); - \\extern fn foo() void; - \\pub fn main() void { - \\ foo(); - \\ var arr: [5:0]u16 = [_:0]u16{ 5, 4, 3, 2, 1 }; - \\ const slice = std.mem.sliceTo(&arr, 3); - \\ std.testing.expectEqualSlices(u16, arr[0..2], slice) catch unreachable; - \\} + \\const std = @import("std"); + \\extern fn foo() void; + \\pub fn main() void { + \\ foo(); + \\ var arr: [5:0]u16 = [_:0]u16{ 5, 4, 3, 2, 1 }; + \\ const slice = std.mem.sliceTo(&arr, 3); + \\ std.testing.expectEqualSlices(u16, arr[0..2], slice) catch unreachable; + \\} }); { @@ -2745,17 +2745,17 @@ fn testRelocatableEhFrame(b: *Build, opts: Options) *Step { }); obj2.linkLibCpp(); const obj3 = addObject(b, opts, .{ .name = "obj3", .cpp_source_bytes = - \\#include - \\#include - \\extern int try_again(); - \\int main() { - \\ try { - \\ try_again(); - \\ } catch (const std::exception &e) { - \\ std::cout << "exception=" << e.what(); - \\ } - \\ return 0; - \\} + \\#include + \\#include + \\extern int try_again(); + \\int main() { + \\ try { + \\ try_again(); + \\ } catch (const std::exception &e) { + \\ std::cout << "exception=" << e.what(); + \\ } + \\ return 0; + \\} }); obj3.linkLibCpp(); @@ -2857,15 +2857,15 @@ fn testRelocatableMergeStrings(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "relocatable-merge-strings", opts); const obj1 = addObject(b, opts, .{ .name = "a", .asm_source_bytes = - \\.section .rodata.str1.1,"aMS",@progbits,1 - \\val1: - \\.ascii "Hello \0" - \\.section .rodata.str1.1,"aMS",@progbits,1 - \\val5: - \\.ascii "World \0" - \\.section .rodata.str1.1,"aMS",@progbits,1 - \\val7: - \\.ascii "Hello \0" + \\.section .rodata.str1.1,"aMS",@progbits,1 + \\val1: + \\.ascii "Hello \0" + \\.section .rodata.str1.1,"aMS",@progbits,1 + \\val5: + \\.ascii "World \0" + \\.section .rodata.str1.1,"aMS",@progbits,1 + \\val7: + \\.ascii "Hello \0" }); const obj2 = addObject(b, opts, .{ .name = "b" }); @@ -3023,18 +3023,18 @@ fn testThunks(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "thunks", opts); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\void foo(); - \\__attribute__((section(".bar"))) void bar() { - \\ return foo(); - \\} - \\__attribute__((section(".foo"))) void foo() { - \\ return bar(); - \\} - \\int main() { - \\ foo(); - \\ bar(); - \\ return 0; - \\} + \\void foo(); + \\__attribute__((section(".bar"))) void bar() { + \\ return foo(); + \\} + \\__attribute__((section(".foo"))) void foo() { + \\ return bar(); + \\} + \\int main() { + \\ foo(); + \\ bar(); + \\ return 0; + \\} }); const check = exe.checkObject(); diff --git a/test/link/macho.zig b/test/link/macho.zig index 1d790b20c6..87abde2d9d 100644 --- a/test/link/macho.zig +++ b/test/link/macho.zig @@ -108,20 +108,20 @@ fn testDeadStrip(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "dead-strip", opts); const obj = addObject(b, opts, .{ .name = "a", .cpp_source_bytes = - \\#include - \\int two() { return 2; } - \\int live_var1 = 1; - \\int live_var2 = two(); - \\int dead_var1 = 3; - \\int dead_var2 = 4; - \\void live_fn1() {} - \\void live_fn2() { live_fn1(); } - \\void dead_fn1() {} - \\void dead_fn2() { dead_fn1(); } - \\int main() { - \\ printf("%d %d\n", live_var1, live_var2); - \\ live_fn2(); - \\} + \\#include + \\int two() { return 2; } + \\int live_var1 = 1; + \\int live_var2 = two(); + \\int dead_var1 = 3; + \\int dead_var2 = 4; + \\void live_fn1() {} + \\void live_fn2() { live_fn1(); } + \\void dead_fn1() {} + \\void dead_fn2() { dead_fn1(); } + \\int main() { + \\ printf("%d %d\n", live_var1, live_var2); + \\ live_fn2(); + \\} }); { @@ -189,21 +189,21 @@ fn testDuplicateDefinitions(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "duplicate-definitions", opts); const obj = addObject(b, opts, .{ .name = "a", .zig_source_bytes = - \\var x: usize = 1; - \\export fn strong() void { x += 1; } - \\export fn weak() void { x += 1; } + \\var x: usize = 1; + \\export fn strong() void { x += 1; } + \\export fn weak() void { x += 1; } }); const exe = addExecutable(b, opts, .{ .name = "main", .zig_source_bytes = - \\var x: usize = 1; - \\export fn strong() void { x += 1; } - \\comptime { @export(&weakImpl, .{ .name = "weak", .linkage = .weak }); } - \\fn weakImpl() callconv(.C) void { x += 1; } - \\extern fn weak() void; - \\pub fn main() void { - \\ weak(); - \\ strong(); - \\} + \\var x: usize = 1; + \\export fn strong() void { x += 1; } + \\comptime { @export(&weakImpl, .{ .name = "weak", .linkage = .weak }); } + \\fn weakImpl() callconv(.C) void { x += 1; } + \\extern fn weak() void; + \\pub fn main() void { + \\ weak(); + \\ strong(); + \\} }); exe.addObject(obj); @@ -220,16 +220,16 @@ fn testDeadStripDylibs(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "dead-strip-dylibs", opts); const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int main() { - \\ if (objc_getClass("NSObject") == 0) { - \\ return -1; - \\ } - \\ if (objc_getClass("NSApplication") == 0) { - \\ return -2; - \\ } - \\ return 0; - \\} + \\#include + \\int main() { + \\ if (objc_getClass("NSObject") == 0) { + \\ return -1; + \\ } + \\ if (objc_getClass("NSApplication") == 0) { + \\ return -2; + \\ } + \\ return 0; + \\} }); { @@ -269,11 +269,11 @@ fn testDylib(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "dylib", opts); const dylib = addSharedLibrary(b, opts, .{ .name = "a", .c_source_bytes = - \\#include - \\char world[] = "world"; - \\char* hello() { - \\ return "Hello"; - \\} + \\#include + \\char world[] = "world"; + \\char* hello() { + \\ return "Hello"; + \\} }); const check = dylib.checkObject(); @@ -283,13 +283,13 @@ fn testDylib(b: *Build, opts: Options) *Step { test_step.dependOn(&check.step); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\char* hello(); - \\extern char world[]; - \\int main() { - \\ printf("%s %s", hello(), world); - \\ return 0; - \\} + \\#include + \\char* hello(); + \\extern char world[]; + \\int main() { + \\ printf("%s %s", hello(), world); + \\ return 0; + \\} }); exe.root_module.linkSystemLibrary("a", .{}); exe.root_module.addLibraryPath(dylib.getEmittedBinDirectory()); @@ -344,10 +344,10 @@ fn testEmptyObject(b: *Build, opts: Options) *Step { const empty = addObject(b, opts, .{ .name = "empty", .c_source_bytes = "" }); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int main() { - \\ printf("Hello world!"); - \\} + \\#include + \\int main() { + \\ printf("Hello world!"); + \\} }); exe.addObject(empty); @@ -374,11 +374,11 @@ fn testEntryPoint(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "entry-point", opts); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int non_main() { - \\ printf("%d", 42); - \\ return 0; - \\} + \\#include + \\int non_main() { + \\ printf("%d", 42); + \\ return 0; + \\} }); exe.entry = .{ .symbol_name = "_non_main" }; @@ -596,10 +596,10 @@ fn testHeaderWeakFlags(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "header-weak-flags", opts); const obj1 = addObject(b, opts, .{ .name = "a", .asm_source_bytes = - \\.globl _x - \\.weak_definition _x - \\_x: - \\ ret + \\.globl _x + \\.weak_definition _x + \\_x: + \\ ret }); const lib = addSharedLibrary(b, opts, .{ .name = "a" }); @@ -658,11 +658,11 @@ fn testHeaderWeakFlags(b: *Build, opts: Options) *Step { { const exe = addExecutable(b, opts, .{ .name = "main3", .asm_source_bytes = - \\.globl _main, _x - \\_x: - \\ - \\_main: - \\ ret + \\.globl _main, _x + \\_x: + \\ + \\_main: + \\ ret }); exe.linkLibrary(lib); @@ -683,11 +683,11 @@ fn testHelloC(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "hello-c", opts); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int main() { - \\ printf("Hello world!\n"); - \\ return 0; - \\} + \\#include + \\int main() { + \\ printf("Hello world!\n"); + \\ return 0; + \\} }); const run = addRunArtifact(exe); @@ -707,10 +707,10 @@ fn testHelloZig(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "hello-zig", opts); const exe = addExecutable(b, opts, .{ .name = "main", .zig_source_bytes = - \\const std = @import("std"); - \\pub fn main() void { - \\ std.io.getStdOut().writer().print("Hello world!\n", .{}) catch unreachable; - \\} + \\const std = @import("std"); + \\pub fn main() void { + \\ std.io.getStdOut().writer().print("Hello world!\n", .{}) catch unreachable; + \\} }); const run = addRunArtifact(exe); @@ -728,10 +728,10 @@ fn testLargeBss(b: *Build, opts: Options) *Step { // maybe S_GB_ZEROFILL section is an answer to this but it doesn't seem supported by dyld // anymore. When I get some free time I will re-investigate this. const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\char arr[0x1000000]; - \\int main() { - \\ return arr[2000]; - \\} + \\char arr[0x1000000]; + \\int main() { + \\ return arr[2000]; + \\} }); const run = addRunArtifact(exe); @@ -745,11 +745,11 @@ fn testLayout(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "layout", opts); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int main() { - \\ printf("Hello world!"); - \\ return 0; - \\} + \\#include + \\int main() { + \\ printf("Hello world!"); + \\ return 0; + \\} }); const check = exe.checkObject(); @@ -935,11 +935,11 @@ fn testLinksection(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "linksection", opts); const obj = addObject(b, opts, .{ .name = "main", .zig_source_bytes = - \\export var test_global: u32 linksection("__DATA,__TestGlobal") = undefined; - \\export fn testFn() linksection("__TEXT,__TestFn") callconv(.C) void { - \\ testGenericFn("A"); - \\} - \\fn testGenericFn(comptime suffix: []const u8) linksection("__TEXT,__TestGenFn" ++ suffix) void {} + \\export var test_global: u32 linksection("__DATA,__TestGlobal") = undefined; + \\export fn testFn() linksection("__TEXT,__TestFn") callconv(.C) void { + \\ testGenericFn("A"); + \\} + \\fn testGenericFn(comptime suffix: []const u8) linksection("__TEXT,__TestGenFn" ++ suffix) void {} }); const check = obj.checkObject(); @@ -962,71 +962,71 @@ fn testMergeLiteralsX64(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "merge-literals-x64", opts); const a_o = addObject(b, opts, .{ .name = "a", .asm_source_bytes = - \\.globl _q1 - \\.globl _s1 - \\ - \\.align 4 - \\_q1: - \\ lea L._q1(%rip), %rax - \\ mov (%rax), %xmm0 - \\ ret - \\ - \\.section __TEXT,__cstring,cstring_literals - \\l._s1: - \\ .asciz "hello" - \\ - \\.section __TEXT,__literal8,8byte_literals - \\.align 8 - \\L._q1: - \\ .double 1.2345 - \\ - \\.section __DATA,__data - \\.align 8 - \\_s1: - \\ .quad l._s1 + \\.globl _q1 + \\.globl _s1 + \\ + \\.align 4 + \\_q1: + \\ lea L._q1(%rip), %rax + \\ mov (%rax), %xmm0 + \\ ret + \\ + \\.section __TEXT,__cstring,cstring_literals + \\l._s1: + \\ .asciz "hello" + \\ + \\.section __TEXT,__literal8,8byte_literals + \\.align 8 + \\L._q1: + \\ .double 1.2345 + \\ + \\.section __DATA,__data + \\.align 8 + \\_s1: + \\ .quad l._s1 }); const b_o = addObject(b, opts, .{ .name = "b", .asm_source_bytes = - \\.globl _q2 - \\.globl _s2 - \\.globl _s3 - \\ - \\.align 4 - \\_q2: - \\ lea L._q2(%rip), %rax - \\ mov (%rax), %xmm0 - \\ ret - \\ - \\.section __TEXT,__cstring,cstring_literals - \\l._s2: - \\ .asciz "hello" - \\l._s3: - \\ .asciz "world" - \\ - \\.section __TEXT,__literal8,8byte_literals - \\.align 8 - \\L._q2: - \\ .double 1.2345 - \\ - \\.section __DATA,__data - \\.align 8 - \\_s2: - \\ .quad l._s2 - \\_s3: - \\ .quad l._s3 + \\.globl _q2 + \\.globl _s2 + \\.globl _s3 + \\ + \\.align 4 + \\_q2: + \\ lea L._q2(%rip), %rax + \\ mov (%rax), %xmm0 + \\ ret + \\ + \\.section __TEXT,__cstring,cstring_literals + \\l._s2: + \\ .asciz "hello" + \\l._s3: + \\ .asciz "world" + \\ + \\.section __TEXT,__literal8,8byte_literals + \\.align 8 + \\L._q2: + \\ .double 1.2345 + \\ + \\.section __DATA,__data + \\.align 8 + \\_s2: + \\ .quad l._s2 + \\_s3: + \\ .quad l._s3 }); const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\extern double q1(); - \\extern double q2(); - \\extern const char* s1; - \\extern const char* s2; - \\extern const char* s3; - \\int main() { - \\ printf("%s, %s, %s, %f, %f", s1, s2, s3, q1(), q2()); - \\ return 0; - \\} + \\#include + \\extern double q1(); + \\extern double q2(); + \\extern const char* s1; + \\extern const char* s2; + \\extern const char* s3; + \\int main() { + \\ printf("%s, %s, %s, %f, %f", s1, s2, s3, q1(), q2()); + \\ return 0; + \\} }); const runWithChecks = struct { @@ -1078,71 +1078,71 @@ fn testMergeLiteralsArm64(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "merge-literals-arm64", opts); const a_o = addObject(b, opts, .{ .name = "a", .asm_source_bytes = - \\.globl _q1 - \\.globl _s1 - \\ - \\.align 4 - \\_q1: - \\ adrp x8, L._q1@PAGE - \\ ldr d0, [x8, L._q1@PAGEOFF] - \\ ret - \\ - \\.section __TEXT,__cstring,cstring_literals - \\l._s1: - \\ .asciz "hello" - \\ - \\.section __TEXT,__literal8,8byte_literals - \\.align 8 - \\L._q1: - \\ .double 1.2345 - \\ - \\.section __DATA,__data - \\.align 8 - \\_s1: - \\ .quad l._s1 + \\.globl _q1 + \\.globl _s1 + \\ + \\.align 4 + \\_q1: + \\ adrp x8, L._q1@PAGE + \\ ldr d0, [x8, L._q1@PAGEOFF] + \\ ret + \\ + \\.section __TEXT,__cstring,cstring_literals + \\l._s1: + \\ .asciz "hello" + \\ + \\.section __TEXT,__literal8,8byte_literals + \\.align 8 + \\L._q1: + \\ .double 1.2345 + \\ + \\.section __DATA,__data + \\.align 8 + \\_s1: + \\ .quad l._s1 }); const b_o = addObject(b, opts, .{ .name = "b", .asm_source_bytes = - \\.globl _q2 - \\.globl _s2 - \\.globl _s3 - \\ - \\.align 4 - \\_q2: - \\ adrp x8, L._q2@PAGE - \\ ldr d0, [x8, L._q2@PAGEOFF] - \\ ret - \\ - \\.section __TEXT,__cstring,cstring_literals - \\l._s2: - \\ .asciz "hello" - \\l._s3: - \\ .asciz "world" - \\ - \\.section __TEXT,__literal8,8byte_literals - \\.align 8 - \\L._q2: - \\ .double 1.2345 - \\ - \\.section __DATA,__data - \\.align 8 - \\_s2: - \\ .quad l._s2 - \\_s3: - \\ .quad l._s3 + \\.globl _q2 + \\.globl _s2 + \\.globl _s3 + \\ + \\.align 4 + \\_q2: + \\ adrp x8, L._q2@PAGE + \\ ldr d0, [x8, L._q2@PAGEOFF] + \\ ret + \\ + \\.section __TEXT,__cstring,cstring_literals + \\l._s2: + \\ .asciz "hello" + \\l._s3: + \\ .asciz "world" + \\ + \\.section __TEXT,__literal8,8byte_literals + \\.align 8 + \\L._q2: + \\ .double 1.2345 + \\ + \\.section __DATA,__data + \\.align 8 + \\_s2: + \\ .quad l._s2 + \\_s3: + \\ .quad l._s3 }); const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\extern double q1(); - \\extern double q2(); - \\extern const char* s1; - \\extern const char* s2; - \\extern const char* s3; - \\int main() { - \\ printf("%s, %s, %s, %f, %f", s1, s2, s3, q1(), q2()); - \\ return 0; - \\} + \\#include + \\extern double q1(); + \\extern double q2(); + \\extern const char* s1; + \\extern const char* s2; + \\extern const char* s3; + \\int main() { + \\ printf("%s, %s, %s, %f, %f", s1, s2, s3, q1(), q2()); + \\ return 0; + \\} }); const runWithChecks = struct { @@ -1198,59 +1198,59 @@ fn testMergeLiteralsArm642(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "merge-literals-arm64-2", opts); const a_o = addObject(b, opts, .{ .name = "a", .asm_source_bytes = - \\.globl _q1 - \\.globl _s1 - \\ - \\.align 4 - \\_q1: - \\ adrp x0, L._q1@PAGE - \\ ldr x0, [x0, L._q1@PAGEOFF] - \\ ret - \\ - \\.section __TEXT,__cstring,cstring_literals - \\_s1: - \\ .asciz "hello" - \\ - \\.section __TEXT,__literal8,8byte_literals - \\.align 8 - \\L._q1: - \\ .double 1.2345 + \\.globl _q1 + \\.globl _s1 + \\ + \\.align 4 + \\_q1: + \\ adrp x0, L._q1@PAGE + \\ ldr x0, [x0, L._q1@PAGEOFF] + \\ ret + \\ + \\.section __TEXT,__cstring,cstring_literals + \\_s1: + \\ .asciz "hello" + \\ + \\.section __TEXT,__literal8,8byte_literals + \\.align 8 + \\L._q1: + \\ .double 1.2345 }); const b_o = addObject(b, opts, .{ .name = "b", .asm_source_bytes = - \\.globl _q2 - \\.globl _s2 - \\.globl _s3 - \\ - \\.align 4 - \\_q2: - \\ adrp x0, L._q2@PAGE - \\ ldr x0, [x0, L._q2@PAGEOFF] - \\ ret - \\ - \\.section __TEXT,__cstring,cstring_literals - \\_s2: - \\ .asciz "hello" - \\_s3: - \\ .asciz "world" - \\ - \\.section __TEXT,__literal8,8byte_literals - \\.align 8 - \\L._q2: - \\ .double 1.2345 + \\.globl _q2 + \\.globl _s2 + \\.globl _s3 + \\ + \\.align 4 + \\_q2: + \\ adrp x0, L._q2@PAGE + \\ ldr x0, [x0, L._q2@PAGEOFF] + \\ ret + \\ + \\.section __TEXT,__cstring,cstring_literals + \\_s2: + \\ .asciz "hello" + \\_s3: + \\ .asciz "world" + \\ + \\.section __TEXT,__literal8,8byte_literals + \\.align 8 + \\L._q2: + \\ .double 1.2345 }); const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\extern double q1(); - \\extern double q2(); - \\extern const char* s1; - \\extern const char* s2; - \\extern const char* s3; - \\int main() { - \\ printf("%s, %s, %s, %f, %f", s1, s2, s3, q1(), q2()); - \\ return 0; - \\} + \\#include + \\extern double q1(); + \\extern double q2(); + \\extern const char* s1; + \\extern const char* s2; + \\extern const char* s3; + \\int main() { + \\ printf("%s, %s, %s, %f, %f", s1, s2, s3, q1(), q2()); + \\ return 0; + \\} }); const exe = addExecutable(b, opts, .{ .name = "main1" }); @@ -1272,43 +1272,43 @@ fn testMergeLiteralsAlignment(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "merge-literals-alignment", opts); const a_o = addObject(b, opts, .{ .name = "a", .asm_source_bytes = - \\.globl _s1 - \\.globl _s2 - \\ - \\.section __TEXT,__cstring,cstring_literals - \\.align 3 - \\_s1: - \\ .asciz "str1" - \\_s2: - \\ .asciz "str2" + \\.globl _s1 + \\.globl _s2 + \\ + \\.section __TEXT,__cstring,cstring_literals + \\.align 3 + \\_s1: + \\ .asciz "str1" + \\_s2: + \\ .asciz "str2" }); const b_o = addObject(b, opts, .{ .name = "b", .asm_source_bytes = - \\.globl _s3 - \\.globl _s4 - \\ - \\.section __TEXT,__cstring,cstring_literals - \\.align 2 - \\_s3: - \\ .asciz "str1" - \\_s4: - \\ .asciz "str2" + \\.globl _s3 + \\.globl _s4 + \\ + \\.section __TEXT,__cstring,cstring_literals + \\.align 2 + \\_s3: + \\ .asciz "str1" + \\_s4: + \\ .asciz "str2" }); const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\#include - \\#include - \\extern const char* s1; - \\extern const char* s2; - \\extern const char* s3; - \\extern const char* s4; - \\int main() { - \\ assert((uintptr_t)(&s1) % 8 == 0 && s1 == s3); - \\ assert((uintptr_t)(&s2) % 8 == 0 && s2 == s4); - \\ printf("%s%s%s%s", &s1, &s2, &s3, &s4); - \\ return 0; - \\} + \\#include + \\#include + \\#include + \\extern const char* s1; + \\extern const char* s2; + \\extern const char* s3; + \\extern const char* s4; + \\int main() { + \\ assert((uintptr_t)(&s1) % 8 == 0 && s1 == s3); + \\ assert((uintptr_t)(&s2) % 8 == 0 && s2 == s4); + \\ printf("%s%s%s%s", &s1, &s2, &s3, &s4); + \\ return 0; + \\} , .c_source_flags = &.{"-Wno-format"} }); const runWithChecks = struct { @@ -1351,39 +1351,39 @@ fn testMergeLiteralsObjc(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "merge-literals-objc", opts); const main_o = addObject(b, opts, .{ .name = "main", .objc_source_bytes = - \\#import ; - \\ - \\extern void foo(); - \\ - \\int main() { - \\ NSString *thing = @"aaa"; - \\ - \\ SEL sel = @selector(lowercaseString); - \\ NSString *lower = (([thing respondsToSelector:sel]) ? @"YES" : @"NO"); - \\ NSLog (@"Responds to lowercaseString: %@", lower); - \\ if ([thing respondsToSelector:sel]) //(lower == @"YES") - \\ NSLog(@"lowercaseString is: %@", [thing lowercaseString]); - \\ - \\ foo(); - \\} + \\#import ; + \\ + \\extern void foo(); + \\ + \\int main() { + \\ NSString *thing = @"aaa"; + \\ + \\ SEL sel = @selector(lowercaseString); + \\ NSString *lower = (([thing respondsToSelector:sel]) ? @"YES" : @"NO"); + \\ NSLog (@"Responds to lowercaseString: %@", lower); + \\ if ([thing respondsToSelector:sel]) //(lower == @"YES") + \\ NSLog(@"lowercaseString is: %@", [thing lowercaseString]); + \\ + \\ foo(); + \\} }); const a_o = addObject(b, opts, .{ .name = "a", .objc_source_bytes = - \\#import ; - \\ - \\void foo() { - \\ NSString *thing = @"aaa"; - \\ SEL sel = @selector(lowercaseString); - \\ NSString *lower = (([thing respondsToSelector:sel]) ? @"YES" : @"NO"); - \\ NSLog (@"Responds to lowercaseString in foo(): %@", lower); - \\ if ([thing respondsToSelector:sel]) //(lower == @"YES") - \\ NSLog(@"lowercaseString in foo() is: %@", [thing lowercaseString]); - \\ SEL sel2 = @selector(uppercaseString); - \\ NSString *upper = (([thing respondsToSelector:sel2]) ? @"YES" : @"NO"); - \\ NSLog (@"Responds to uppercaseString in foo(): %@", upper); - \\ if ([thing respondsToSelector:sel2]) //(upper == @"YES") - \\ NSLog(@"uppercaseString in foo() is: %@", [thing uppercaseString]); - \\} + \\#import ; + \\ + \\void foo() { + \\ NSString *thing = @"aaa"; + \\ SEL sel = @selector(lowercaseString); + \\ NSString *lower = (([thing respondsToSelector:sel]) ? @"YES" : @"NO"); + \\ NSLog (@"Responds to lowercaseString in foo(): %@", lower); + \\ if ([thing respondsToSelector:sel]) //(lower == @"YES") + \\ NSLog(@"lowercaseString in foo() is: %@", [thing lowercaseString]); + \\ SEL sel2 = @selector(uppercaseString); + \\ NSString *upper = (([thing respondsToSelector:sel2]) ? @"YES" : @"NO"); + \\ NSLog (@"Responds to uppercaseString in foo(): %@", upper); + \\ if ([thing respondsToSelector:sel2]) //(upper == @"YES") + \\ NSLog(@"uppercaseString in foo() is: %@", [thing uppercaseString]); + \\} }); const runWithChecks = struct { @@ -1454,12 +1454,12 @@ fn testNoDeadStrip(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "no-dead-strip", opts); const exe = addExecutable(b, opts, .{ .name = "name", .c_source_bytes = - \\__attribute__((used)) int bogus1 = 0; - \\int bogus2 = 0; - \\int foo = 42; - \\int main() { - \\ return foo - 42; - \\} + \\__attribute__((used)) int bogus1 = 0; + \\int bogus2 = 0; + \\int foo = 42; + \\int main() { + \\ return foo - 42; + \\} }); exe.link_gc_sections = true; @@ -1538,11 +1538,11 @@ fn testObjc(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "objc", opts); const lib = addStaticLibrary(b, opts, .{ .name = "a", .objc_source_bytes = - \\#import - \\@interface Foo : NSObject - \\@end - \\@implementation Foo - \\@end + \\#import + \\@interface Foo : NSObject + \\@end + \\@implementation Foo + \\@end }); { @@ -1595,32 +1595,32 @@ fn testObjcpp(b: *Build, opts: Options) *Step { }; const foo_o = addObject(b, opts, .{ .name = "foo", .objcpp_source_bytes = - \\#import "Foo.h" - \\@implementation Foo - \\- (NSString *)name - \\{ - \\ NSString *str = [[NSString alloc] initWithFormat:@"Zig"]; - \\ return str; - \\} - \\@end + \\#import "Foo.h" + \\@implementation Foo + \\- (NSString *)name + \\{ + \\ NSString *str = [[NSString alloc] initWithFormat:@"Zig"]; + \\ return str; + \\} + \\@end }); foo_o.root_module.addIncludePath(foo_h.dirname()); foo_o.linkLibCpp(); const exe = addExecutable(b, opts, .{ .name = "main", .objcpp_source_bytes = - \\#import "Foo.h" - \\#import - \\#include - \\int main(int argc, char *argv[]) - \\{ - \\ @autoreleasepool { - \\ Foo *foo = [[Foo alloc] init]; - \\ NSString *result = [foo name]; - \\ std::cout << "Hello from C++ and " << [result UTF8String]; - \\ assert([result isEqualToString:@"Zig"]); - \\ return 0; - \\ } - \\} + \\#import "Foo.h" + \\#import + \\#include + \\int main(int argc, char *argv[]) + \\{ + \\ @autoreleasepool { + \\ Foo *foo = [[Foo alloc] init]; + \\ NSString *result = [foo name]; + \\ std::cout << "Hello from C++ and " << [result UTF8String]; + \\ assert([result isEqualToString:@"Zig"]); + \\ return 0; + \\ } + \\} }); exe.root_module.addIncludePath(foo_h.dirname()); exe.addObject(foo_o); @@ -1672,21 +1672,21 @@ fn testReexportsZig(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "reexports-zig", opts); const lib = addStaticLibrary(b, opts, .{ .name = "a", .zig_source_bytes = - \\const x: i32 = 42; - \\export fn foo() i32 { - \\ return x; - \\} - \\comptime { - \\ @export(&foo, .{ .name = "bar", .linkage = .strong }); - \\} + \\const x: i32 = 42; + \\export fn foo() i32 { + \\ return x; + \\} + \\comptime { + \\ @export(&foo, .{ .name = "bar", .linkage = .strong }); + \\} }); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\extern int foo(); - \\extern int bar(); - \\int main() { - \\ return bar() - foo(); - \\} + \\extern int foo(); + \\extern int bar(); + \\int main() { + \\ return bar() - foo(); + \\} }); exe.linkLibrary(lib); @@ -1701,32 +1701,32 @@ fn testRelocatable(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "relocatable", opts); const a_o = addObject(b, opts, .{ .name = "a", .cpp_source_bytes = - \\#include - \\int try_me() { - \\ throw std::runtime_error("Oh no!"); - \\} + \\#include + \\int try_me() { + \\ throw std::runtime_error("Oh no!"); + \\} }); a_o.linkLibCpp(); const b_o = addObject(b, opts, .{ .name = "b", .cpp_source_bytes = - \\extern int try_me(); - \\int try_again() { - \\ return try_me(); - \\} + \\extern int try_me(); + \\int try_again() { + \\ return try_me(); + \\} }); const main_o = addObject(b, opts, .{ .name = "main", .cpp_source_bytes = - \\#include - \\#include - \\extern int try_again(); - \\int main() { - \\ try { - \\ try_again(); - \\ } catch (const std::exception &e) { - \\ std::cout << "exception=" << e.what(); - \\ } - \\ return 0; - \\} + \\#include + \\#include + \\extern int try_again(); + \\int main() { + \\ try { + \\ try_again(); + \\ } catch (const std::exception &e) { + \\ std::cout << "exception=" << e.what(); + \\ } + \\ return 0; + \\} }); main_o.linkLibCpp(); @@ -1769,34 +1769,34 @@ fn testRelocatableZig(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "relocatable-zig", opts); const a_o = addObject(b, opts, .{ .name = "a", .zig_source_bytes = - \\const std = @import("std"); - \\export var foo: i32 = 0; - \\export fn incrFoo() void { - \\ foo += 1; - \\ std.debug.print("incrFoo={d}\n", .{foo}); - \\} + \\const std = @import("std"); + \\export var foo: i32 = 0; + \\export fn incrFoo() void { + \\ foo += 1; + \\ std.debug.print("incrFoo={d}\n", .{foo}); + \\} }); const b_o = addObject(b, opts, .{ .name = "b", .zig_source_bytes = - \\const std = @import("std"); - \\extern var foo: i32; - \\export fn decrFoo() void { - \\ foo -= 1; - \\ std.debug.print("decrFoo={d}\n", .{foo}); - \\} + \\const std = @import("std"); + \\extern var foo: i32; + \\export fn decrFoo() void { + \\ foo -= 1; + \\ std.debug.print("decrFoo={d}\n", .{foo}); + \\} }); const main_o = addObject(b, opts, .{ .name = "main", .zig_source_bytes = - \\const std = @import("std"); - \\extern var foo: i32; - \\extern fn incrFoo() void; - \\extern fn decrFoo() void; - \\pub fn main() void { - \\ const init = foo; - \\ incrFoo(); - \\ decrFoo(); - \\ if (init == foo) @panic("Oh no!"); - \\} + \\const std = @import("std"); + \\extern var foo: i32; + \\extern fn incrFoo() void; + \\extern fn decrFoo() void; + \\pub fn main() void { + \\ const init = foo; + \\ incrFoo(); + \\ decrFoo(); + \\ if (init == foo) @panic("Oh no!"); + \\} }); const c_o = addObject(b, opts, .{ .name = "c" }); @@ -1820,11 +1820,11 @@ fn testSearchStrategy(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "search-strategy", opts); const obj = addObject(b, opts, .{ .name = "a", .c_source_bytes = - \\#include - \\char world[] = "world"; - \\char* hello() { - \\ return "Hello"; - \\} + \\#include + \\char world[] = "world"; + \\char* hello() { + \\ return "Hello"; + \\} }); const liba = addStaticLibrary(b, opts, .{ .name = "a" }); @@ -1834,13 +1834,13 @@ fn testSearchStrategy(b: *Build, opts: Options) *Step { dylib.addObject(obj); const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\char* hello(); - \\extern char world[]; - \\int main() { - \\ printf("%s %s", hello(), world); - \\ return 0; - \\} + \\#include + \\char* hello(); + \\extern char world[]; + \\int main() { + \\ printf("%s %s", hello(), world); + \\ return 0; + \\} }); { @@ -1968,23 +1968,23 @@ fn testSectionBoundarySymbols2(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "section-boundary-symbols-2", opts); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\struct pair { int a; int b; }; - \\struct pair first __attribute__((section("__DATA,__pairs"))) = { 1, 2 }; - \\struct pair second __attribute__((section("__DATA,__pairs"))) = { 3, 4 }; - \\extern struct pair pairs_start __asm("section$start$__DATA$__pairs"); - \\extern struct pair pairs_end __asm("section$end$__DATA$__pairs"); - \\int main() { - \\ printf("%d,%d\n", first.a, first.b); - \\ printf("%d,%d\n", second.a, second.b); - \\ struct pair* p; - \\ for (p = &pairs_start; p < &pairs_end; p++) { - \\ p->a = 0; - \\ } - \\ printf("%d,%d\n", first.a, first.b); - \\ printf("%d,%d\n", second.a, second.b); - \\ return 0; - \\} + \\#include + \\struct pair { int a; int b; }; + \\struct pair first __attribute__((section("__DATA,__pairs"))) = { 1, 2 }; + \\struct pair second __attribute__((section("__DATA,__pairs"))) = { 3, 4 }; + \\extern struct pair pairs_start __asm("section$start$__DATA$__pairs"); + \\extern struct pair pairs_end __asm("section$end$__DATA$__pairs"); + \\int main() { + \\ printf("%d,%d\n", first.a, first.b); + \\ printf("%d,%d\n", second.a, second.b); + \\ struct pair* p; + \\ for (p = &pairs_start; p < &pairs_end; p++) { + \\ p->a = 0; + \\ } + \\ printf("%d,%d\n", first.a, first.b); + \\ printf("%d,%d\n", second.a, second.b); + \\ return 0; + \\} }); const run = b.addRunArtifact(exe); @@ -2005,24 +2005,24 @@ fn testSegmentBoundarySymbols(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "segment-boundary-symbols", opts); const obj1 = addObject(b, opts, .{ .name = "a", .cpp_source_bytes = - \\constexpr const char* MESSAGE __attribute__((used, section("__DATA_CONST_1,__message_ptr"))) = "codebase"; + \\constexpr const char* MESSAGE __attribute__((used, section("__DATA_CONST_1,__message_ptr"))) = "codebase"; }); const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\const char* interop(); - \\int main() { - \\ printf("All your %s are belong to us.\n", interop()); - \\ return 0; - \\} + \\#include + \\const char* interop(); + \\int main() { + \\ printf("All your %s are belong to us.\n", interop()); + \\ return 0; + \\} }); { const obj2 = addObject(b, opts, .{ .name = "b", .cpp_source_bytes = - \\extern const char* message_pointer __asm("segment$start$__DATA_CONST_1"); - \\extern "C" const char* interop() { - \\ return message_pointer; - \\} + \\extern const char* message_pointer __asm("segment$start$__DATA_CONST_1"); + \\extern "C" const char* interop() { + \\ return message_pointer; + \\} }); const exe = addExecutable(b, opts, .{ .name = "main" }); @@ -2042,10 +2042,10 @@ fn testSegmentBoundarySymbols(b: *Build, opts: Options) *Step { { const obj2 = addObject(b, opts, .{ .name = "c", .cpp_source_bytes = - \\extern const char* message_pointer __asm("segment$start$__DATA_1"); - \\extern "C" const char* interop() { - \\ return message_pointer; - \\} + \\extern const char* message_pointer __asm("segment$start$__DATA_1"); + \\extern "C" const char* interop() { + \\ return message_pointer; + \\} }); const exe = addExecutable(b, opts, .{ .name = "main2" }); @@ -2073,27 +2073,27 @@ fn testSymbolStabs(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "symbol-stabs", opts); const a_o = addObject(b, opts, .{ .name = "a", .c_source_bytes = - \\int foo = 42; - \\int getFoo() { - \\ return foo; - \\} + \\int foo = 42; + \\int getFoo() { + \\ return foo; + \\} }); const b_o = addObject(b, opts, .{ .name = "b", .c_source_bytes = - \\int bar = 24; - \\int getBar() { - \\ return bar; - \\} + \\int bar = 24; + \\int getBar() { + \\ return bar; + \\} }); const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\extern int getFoo(); - \\extern int getBar(); - \\int main() { - \\ printf("foo=%d,bar=%d", getFoo(), getBar()); - \\ return 0; - \\} + \\#include + \\extern int getFoo(); + \\extern int getBar(); + \\int main() { + \\ printf("foo=%d,bar=%d", getFoo(), getBar()); + \\ return 0; + \\} }); const exe = addExecutable(b, opts, .{ .name = "main" }); @@ -2157,11 +2157,11 @@ fn testTbdv3(b: *Build, opts: Options) *Step { }; const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int getFoo(); - \\int main() { - \\ return getFoo() - 42; - \\} + \\#include + \\int getFoo(); + \\int main() { + \\ return getFoo() - 42; + \\} }); exe.root_module.linkSystemLibrary("a", .{}); exe.root_module.addLibraryPath(tbd.dirname()); @@ -2204,18 +2204,18 @@ fn testThunks(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "thunks", opts); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\void bar() { - \\ printf("bar"); - \\} - \\void foo() { - \\ fprintf(stdout, "foo"); - \\} - \\int main() { - \\ foo(); - \\ bar(); - \\ return 0; - \\} + \\#include + \\void bar() { + \\ printf("bar"); + \\} + \\void foo() { + \\ fprintf(stdout, "foo"); + \\} + \\int main() { + \\ foo(); + \\ bar(); + \\ return 0; + \\} }); const check = exe.checkObject(); @@ -2236,24 +2236,24 @@ fn testTls(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "tls", opts); const dylib = addSharedLibrary(b, opts, .{ .name = "a", .c_source_bytes = - \\_Thread_local int a; - \\int getA() { - \\ return a; - \\} + \\_Thread_local int a; + \\int getA() { + \\ return a; + \\} }); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\extern _Thread_local int a; - \\extern int getA(); - \\int getA2() { - \\ return a; - \\} - \\int main() { - \\ a = 2; - \\ printf("%d %d %d", a, getA(), getA2()); - \\ return 0; - \\} + \\#include + \\extern _Thread_local int a; + \\extern int getA(); + \\int getA2() { + \\ return a; + \\} + \\int main() { + \\ a = 2; + \\ printf("%d %d %d", a, getA(), getA2()); + \\ return 0; + \\} }); exe.root_module.linkSystemLibrary("a", .{}); exe.root_module.addLibraryPath(dylib.getEmittedBinDirectory()); @@ -2287,33 +2287,33 @@ fn testTlsPointers(b: *Build, opts: Options) *Step { }; const bar_o = addObject(b, opts, .{ .name = "bar", .cpp_source_bytes = - \\#include "foo.h" - \\int bar() { - \\ int v1 = Foo::getVar(); - \\ return v1; - \\} + \\#include "foo.h" + \\int bar() { + \\ int v1 = Foo::getVar(); + \\ return v1; + \\} }); bar_o.root_module.addIncludePath(foo_h.dirname()); bar_o.linkLibCpp(); const baz_o = addObject(b, opts, .{ .name = "baz", .cpp_source_bytes = - \\#include "foo.h" - \\int baz() { - \\ int v1 = Foo::getVar(); - \\ return v1; - \\} + \\#include "foo.h" + \\int baz() { + \\ int v1 = Foo::getVar(); + \\ return v1; + \\} }); baz_o.root_module.addIncludePath(foo_h.dirname()); baz_o.linkLibCpp(); const main_o = addObject(b, opts, .{ .name = "main", .cpp_source_bytes = - \\extern int bar(); - \\extern int baz(); - \\int main() { - \\ int v1 = bar(); - \\ int v2 = baz(); - \\ return v1 != v2; - \\} + \\extern int bar(); + \\extern int baz(); + \\int main() { + \\ int v1 = bar(); + \\ int v2 = baz(); + \\ return v1 != v2; + \\} }); main_o.root_module.addIncludePath(foo_h.dirname()); main_o.linkLibCpp(); @@ -2335,14 +2335,14 @@ fn testTlsLargeTbss(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "tls-large-tbss", opts); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\_Thread_local int x[0x8000]; - \\_Thread_local int y[0x8000]; - \\int main() { - \\ x[0] = 3; - \\ x[0x7fff] = 5; - \\ printf("%d %d %d %d %d %d\n", x[0], x[1], x[0x7fff], y[0], y[1], y[0x7fff]); - \\} + \\#include + \\_Thread_local int x[0x8000]; + \\_Thread_local int y[0x8000]; + \\int main() { + \\ x[0] = 3; + \\ x[0x7fff] = 5; + \\ printf("%d %d %d %d %d %d\n", x[0], x[1], x[0x7fff], y[0], y[1], y[0x7fff]); + \\} }); const run = addRunArtifact(exe); @@ -2356,15 +2356,15 @@ fn testTlsZig(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "tls-zig", opts); const exe = addExecutable(b, opts, .{ .name = "main", .zig_source_bytes = - \\const std = @import("std"); - \\threadlocal var x: i32 = 0; - \\threadlocal var y: i32 = -1; - \\pub fn main() void { - \\ std.io.getStdOut().writer().print("{d} {d}\n", .{x, y}) catch unreachable; - \\ x -= 1; - \\ y += 1; - \\ std.io.getStdOut().writer().print("{d} {d}\n", .{x, y}) catch unreachable; - \\} + \\const std = @import("std"); + \\threadlocal var x: i32 = 0; + \\threadlocal var y: i32 = -1; + \\pub fn main() void { + \\ std.io.getStdOut().writer().print("{d} {d}\n", .{x, y}) catch unreachable; + \\ x -= 1; + \\ y += 1; + \\ std.io.getStdOut().writer().print("{d} {d}\n", .{x, y}) catch unreachable; + \\} }); const run = addRunArtifact(exe); @@ -2382,15 +2382,15 @@ fn testTwoLevelNamespace(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "two-level-namespace", opts); const liba = addSharedLibrary(b, opts, .{ .name = "a", .c_source_bytes = - \\#include - \\int foo = 1; - \\int* ptr_to_foo = &foo; - \\int getFoo() { - \\ return foo; - \\} - \\void printInA() { - \\ printf("liba: getFoo()=%d, ptr_to_foo=%d\n", getFoo(), *ptr_to_foo); - \\} + \\#include + \\int foo = 1; + \\int* ptr_to_foo = &foo; + \\int getFoo() { + \\ return foo; + \\} + \\void printInA() { + \\ printf("liba: getFoo()=%d, ptr_to_foo=%d\n", getFoo(), *ptr_to_foo); + \\} }); { @@ -2403,15 +2403,15 @@ fn testTwoLevelNamespace(b: *Build, opts: Options) *Step { } const libb = addSharedLibrary(b, opts, .{ .name = "b", .c_source_bytes = - \\#include - \\int foo = 2; - \\int* ptr_to_foo = &foo; - \\int getFoo() { - \\ return foo; - \\} - \\void printInB() { - \\ printf("libb: getFoo()=%d, ptr_to_foo=%d\n", getFoo(), *ptr_to_foo); - \\} + \\#include + \\int foo = 2; + \\int* ptr_to_foo = &foo; + \\int getFoo() { + \\ return foo; + \\} + \\void printInB() { + \\ printf("libb: getFoo()=%d, ptr_to_foo=%d\n", getFoo(), *ptr_to_foo); + \\} }); { @@ -2424,17 +2424,17 @@ fn testTwoLevelNamespace(b: *Build, opts: Options) *Step { } const main_o = addObject(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int getFoo(); - \\extern int* ptr_to_foo; - \\void printInA(); - \\void printInB(); - \\int main() { - \\ printf("main: getFoo()=%d, ptr_to_foo=%d\n", getFoo(), *ptr_to_foo); - \\ printInA(); - \\ printInB(); - \\ return 0; - \\} + \\#include + \\int getFoo(); + \\extern int* ptr_to_foo; + \\void printInA(); + \\void printInB(); + \\int main() { + \\ printf("main: getFoo()=%d, ptr_to_foo=%d\n", getFoo(), *ptr_to_foo); + \\ printInA(); + \\ printInB(); + \\ return 0; + \\} }); { @@ -2579,17 +2579,17 @@ fn testUnresolvedError(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "unresolved-error", opts); const obj = addObject(b, opts, .{ .name = "a", .zig_source_bytes = - \\extern fn foo() i32; - \\export fn bar() i32 { return foo() + 1; } + \\extern fn foo() i32; + \\export fn bar() i32 { return foo() + 1; } }); const exe = addExecutable(b, opts, .{ .name = "main", .zig_source_bytes = - \\const std = @import("std"); - \\extern fn foo() i32; - \\extern fn bar() i32; - \\pub fn main() void { - \\ std.debug.print("foo() + bar() = {d}", .{foo() + bar()}); - \\} + \\const std = @import("std"); + \\extern fn foo() i32; + \\extern fn bar() i32; + \\pub fn main() void { + \\ std.debug.print("foo() + bar() = {d}", .{foo() + bar()}); + \\} }); exe.addObject(obj); @@ -2615,17 +2615,17 @@ fn testUnresolvedError2(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "unresolved-error-2", opts); const exe = addExecutable(b, opts, .{ .name = "main", .zig_source_bytes = - \\pub fn main() !void { - \\ const msg_send_fn = @extern( - \\ *const fn () callconv(.C) usize, - \\ .{ .name = "objc_msgSend$initWithContentRect:styleMask:backing:defer:screen:" }, - \\ ); - \\ _ = @call( - \\ .auto, - \\ msg_send_fn, - \\ .{}, - \\ ); - \\} + \\pub fn main() !void { + \\ const msg_send_fn = @extern( + \\ *const fn () callconv(.C) usize, + \\ .{ .name = "objc_msgSend$initWithContentRect:styleMask:backing:defer:screen:" }, + \\ ); + \\ _ = @call( + \\ .auto, + \\ msg_send_fn, + \\ .{}, + \\ ); + \\} }); expectLinkErrors(exe, test_step, .{ .exact = &.{ @@ -2687,82 +2687,82 @@ fn testUnwindInfo(b: *Build, opts: Options) *Step { }; const main_o = addObject(b, opts, .{ .name = "main", .cpp_source_bytes = - \\#include "all.h" - \\#include - \\ - \\void fn_c() { - \\ SimpleStringOwner c{ "cccccccccc" }; - \\} - \\ - \\void fn_b() { - \\ SimpleStringOwner b{ "b" }; - \\ fn_c(); - \\} - \\ - \\int main() { - \\ try { - \\ SimpleStringOwner a{ "a" }; - \\ fn_b(); - \\ SimpleStringOwner d{ "d" }; - \\ } catch (const Error& e) { - \\ printf("Error: %s\n", e.what()); - \\ } catch(const std::exception& e) { - \\ printf("Exception: %s\n", e.what()); - \\ } - \\ return 0; - \\} + \\#include "all.h" + \\#include + \\ + \\void fn_c() { + \\ SimpleStringOwner c{ "cccccccccc" }; + \\} + \\ + \\void fn_b() { + \\ SimpleStringOwner b{ "b" }; + \\ fn_c(); + \\} + \\ + \\int main() { + \\ try { + \\ SimpleStringOwner a{ "a" }; + \\ fn_b(); + \\ SimpleStringOwner d{ "d" }; + \\ } catch (const Error& e) { + \\ printf("Error: %s\n", e.what()); + \\ } catch(const std::exception& e) { + \\ printf("Exception: %s\n", e.what()); + \\ } + \\ return 0; + \\} }); main_o.root_module.addIncludePath(all_h.dirname()); main_o.linkLibCpp(); const simple_string_o = addObject(b, opts, .{ .name = "simple_string", .cpp_source_bytes = - \\#include "all.h" - \\#include - \\#include - \\ - \\SimpleString::SimpleString(size_t max_size) - \\: max_size{ max_size }, length{} { - \\ if (max_size == 0) { - \\ throw Error{ "Max size must be at least 1." }; - \\ } - \\ buffer = new char[max_size]; - \\ buffer[0] = 0; - \\} - \\ - \\SimpleString::~SimpleString() { - \\ delete[] buffer; - \\} - \\ - \\void SimpleString::print(const char* tag) const { - \\ printf("%s: %s", tag, buffer); - \\} - \\ - \\bool SimpleString::append_line(const char* x) { - \\ const auto x_len = strlen(x); - \\ if (x_len + length + 2 > max_size) return false; - \\ std::strncpy(buffer + length, x, max_size - length); - \\ length += x_len; - \\ buffer[length++] = '\n'; - \\ buffer[length] = 0; - \\ return true; - \\} + \\#include "all.h" + \\#include + \\#include + \\ + \\SimpleString::SimpleString(size_t max_size) + \\: max_size{ max_size }, length{} { + \\ if (max_size == 0) { + \\ throw Error{ "Max size must be at least 1." }; + \\ } + \\ buffer = new char[max_size]; + \\ buffer[0] = 0; + \\} + \\ + \\SimpleString::~SimpleString() { + \\ delete[] buffer; + \\} + \\ + \\void SimpleString::print(const char* tag) const { + \\ printf("%s: %s", tag, buffer); + \\} + \\ + \\bool SimpleString::append_line(const char* x) { + \\ const auto x_len = strlen(x); + \\ if (x_len + length + 2 > max_size) return false; + \\ std::strncpy(buffer + length, x, max_size - length); + \\ length += x_len; + \\ buffer[length++] = '\n'; + \\ buffer[length] = 0; + \\ return true; + \\} }); simple_string_o.root_module.addIncludePath(all_h.dirname()); simple_string_o.linkLibCpp(); const simple_string_owner_o = addObject(b, opts, .{ .name = "simple_string_owner", .cpp_source_bytes = - \\#include "all.h" - \\ - \\SimpleStringOwner::SimpleStringOwner(const char* x) : string{ 10 } { - \\ if (!string.append_line(x)) { - \\ throw Error{ "Not enough memory!" }; - \\ } - \\ string.print("Constructed"); - \\} - \\ - \\SimpleStringOwner::~SimpleStringOwner() { - \\ string.print("About to destroy"); - \\} + \\#include "all.h" + \\ + \\SimpleStringOwner::SimpleStringOwner(const char* x) : string{ 10 } { + \\ if (!string.append_line(x)) { + \\ throw Error{ "Not enough memory!" }; + \\ } + \\ string.print("Constructed"); + \\} + \\ + \\SimpleStringOwner::~SimpleStringOwner() { + \\ string.print("About to destroy"); + \\} }); simple_string_owner_o.root_module.addIncludePath(all_h.dirname()); simple_string_owner_o.linkLibCpp(); @@ -2798,52 +2798,52 @@ fn testUnwindInfoNoSubsectionsArm64(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "unwind-info-no-subsections-arm64", opts); const a_o = addObject(b, opts, .{ .name = "a", .asm_source_bytes = - \\.globl _foo - \\.align 4 - \\_foo: - \\ .cfi_startproc - \\ stp x29, x30, [sp, #-32]! - \\ .cfi_def_cfa_offset 32 - \\ .cfi_offset w30, -24 - \\ .cfi_offset w29, -32 - \\ mov x29, sp - \\ .cfi_def_cfa w29, 32 - \\ bl _bar - \\ ldp x29, x30, [sp], #32 - \\ .cfi_restore w29 - \\ .cfi_restore w30 - \\ .cfi_def_cfa_offset 0 - \\ ret - \\ .cfi_endproc - \\ - \\.globl _bar - \\.align 4 - \\_bar: - \\ .cfi_startproc - \\ sub sp, sp, #32 - \\ .cfi_def_cfa_offset -32 - \\ stp x29, x30, [sp, #16] - \\ .cfi_offset w30, -24 - \\ .cfi_offset w29, -32 - \\ mov x29, sp - \\ .cfi_def_cfa w29, 32 - \\ mov w0, #4 - \\ ldp x29, x30, [sp, #16] - \\ .cfi_restore w29 - \\ .cfi_restore w30 - \\ add sp, sp, #32 - \\ .cfi_def_cfa_offset 0 - \\ ret - \\ .cfi_endproc + \\.globl _foo + \\.align 4 + \\_foo: + \\ .cfi_startproc + \\ stp x29, x30, [sp, #-32]! + \\ .cfi_def_cfa_offset 32 + \\ .cfi_offset w30, -24 + \\ .cfi_offset w29, -32 + \\ mov x29, sp + \\ .cfi_def_cfa w29, 32 + \\ bl _bar + \\ ldp x29, x30, [sp], #32 + \\ .cfi_restore w29 + \\ .cfi_restore w30 + \\ .cfi_def_cfa_offset 0 + \\ ret + \\ .cfi_endproc + \\ + \\.globl _bar + \\.align 4 + \\_bar: + \\ .cfi_startproc + \\ sub sp, sp, #32 + \\ .cfi_def_cfa_offset -32 + \\ stp x29, x30, [sp, #16] + \\ .cfi_offset w30, -24 + \\ .cfi_offset w29, -32 + \\ mov x29, sp + \\ .cfi_def_cfa w29, 32 + \\ mov w0, #4 + \\ ldp x29, x30, [sp, #16] + \\ .cfi_restore w29 + \\ .cfi_restore w30 + \\ add sp, sp, #32 + \\ .cfi_def_cfa_offset 0 + \\ ret + \\ .cfi_endproc }); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int foo(); - \\int main() { - \\ printf("%d\n", foo()); - \\ return 0; - \\} + \\#include + \\int foo(); + \\int main() { + \\ printf("%d\n", foo()); + \\ return 0; + \\} }); exe.addObject(a_o); @@ -2858,44 +2858,44 @@ fn testUnwindInfoNoSubsectionsX64(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "unwind-info-no-subsections-x64", opts); const a_o = addObject(b, opts, .{ .name = "a", .asm_source_bytes = - \\.globl _foo - \\_foo: - \\ .cfi_startproc - \\ push %rbp - \\ .cfi_def_cfa_offset 8 - \\ .cfi_offset %rbp, -8 - \\ mov %rsp, %rbp - \\ .cfi_def_cfa_register %rbp - \\ call _bar - \\ pop %rbp - \\ .cfi_restore %rbp - \\ .cfi_def_cfa_offset 0 - \\ ret - \\ .cfi_endproc - \\ - \\.globl _bar - \\_bar: - \\ .cfi_startproc - \\ push %rbp - \\ .cfi_def_cfa_offset 8 - \\ .cfi_offset %rbp, -8 - \\ mov %rsp, %rbp - \\ .cfi_def_cfa_register %rbp - \\ mov $4, %rax - \\ pop %rbp - \\ .cfi_restore %rbp - \\ .cfi_def_cfa_offset 0 - \\ ret - \\ .cfi_endproc + \\.globl _foo + \\_foo: + \\ .cfi_startproc + \\ push %rbp + \\ .cfi_def_cfa_offset 8 + \\ .cfi_offset %rbp, -8 + \\ mov %rsp, %rbp + \\ .cfi_def_cfa_register %rbp + \\ call _bar + \\ pop %rbp + \\ .cfi_restore %rbp + \\ .cfi_def_cfa_offset 0 + \\ ret + \\ .cfi_endproc + \\ + \\.globl _bar + \\_bar: + \\ .cfi_startproc + \\ push %rbp + \\ .cfi_def_cfa_offset 8 + \\ .cfi_offset %rbp, -8 + \\ mov %rsp, %rbp + \\ .cfi_def_cfa_register %rbp + \\ mov $4, %rax + \\ pop %rbp + \\ .cfi_restore %rbp + \\ .cfi_def_cfa_offset 0 + \\ ret + \\ .cfi_endproc }); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\int foo(); - \\int main() { - \\ printf("%d\n", foo()); - \\ return 0; - \\} + \\#include + \\int foo(); + \\int main() { + \\ printf("%d\n", foo()); + \\ return 0; + \\} }); exe.addObject(a_o); @@ -2911,27 +2911,27 @@ fn testWeakBind(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "weak-bind", opts); const lib = addSharedLibrary(b, opts, .{ .name = "foo", .asm_source_bytes = - \\.globl _weak_dysym - \\.weak_definition _weak_dysym - \\_weak_dysym: - \\ .quad 0x1234 - \\ - \\.globl _weak_dysym_for_gotpcrel - \\.weak_definition _weak_dysym_for_gotpcrel - \\_weak_dysym_for_gotpcrel: - \\ .quad 0x1234 - \\ - \\.globl _weak_dysym_fn - \\.weak_definition _weak_dysym_fn - \\_weak_dysym_fn: - \\ ret - \\ - \\.section __DATA,__thread_vars,thread_local_variables - \\ - \\.globl _weak_dysym_tlv - \\.weak_definition _weak_dysym_tlv - \\_weak_dysym_tlv: - \\ .quad 0x1234 + \\.globl _weak_dysym + \\.weak_definition _weak_dysym + \\_weak_dysym: + \\ .quad 0x1234 + \\ + \\.globl _weak_dysym_for_gotpcrel + \\.weak_definition _weak_dysym_for_gotpcrel + \\_weak_dysym_for_gotpcrel: + \\ .quad 0x1234 + \\ + \\.globl _weak_dysym_fn + \\.weak_definition _weak_dysym_fn + \\_weak_dysym_fn: + \\ ret + \\ + \\.section __DATA,__thread_vars,thread_local_variables + \\ + \\.globl _weak_dysym_tlv + \\.weak_definition _weak_dysym_tlv + \\_weak_dysym_tlv: + \\ .quad 0x1234 }); { @@ -2945,61 +2945,61 @@ fn testWeakBind(b: *Build, opts: Options) *Step { } const exe = addExecutable(b, opts, .{ .name = "main", .asm_source_bytes = - \\.globl _main, _weak_external, _weak_external_for_gotpcrel, _weak_external_fn - \\.weak_definition _weak_external, _weak_external_for_gotpcrel, _weak_external_fn, _weak_internal, _weak_internal_for_gotpcrel, _weak_internal_fn - \\ - \\_main: - \\ mov _weak_dysym_for_gotpcrel@GOTPCREL(%rip), %rax - \\ mov _weak_external_for_gotpcrel@GOTPCREL(%rip), %rax - \\ mov _weak_internal_for_gotpcrel@GOTPCREL(%rip), %rax - \\ mov _weak_tlv@TLVP(%rip), %rax - \\ mov _weak_dysym_tlv@TLVP(%rip), %rax - \\ mov _weak_internal_tlv@TLVP(%rip), %rax - \\ callq _weak_dysym_fn - \\ callq _weak_external_fn - \\ callq _weak_internal_fn - \\ mov $0, %rax - \\ ret - \\ - \\_weak_external: - \\ .quad 0x1234 - \\ - \\_weak_external_for_gotpcrel: - \\ .quad 0x1234 - \\ - \\_weak_external_fn: - \\ ret - \\ - \\_weak_internal: - \\ .quad 0x1234 - \\ - \\_weak_internal_for_gotpcrel: - \\ .quad 0x1234 - \\ - \\_weak_internal_fn: - \\ ret - \\ - \\.data - \\ .quad _weak_dysym - \\ .quad _weak_external + 2 - \\ .quad _weak_internal - \\ - \\.tbss _weak_tlv$tlv$init, 4, 2 - \\.tbss _weak_internal_tlv$tlv$init, 4, 2 - \\ - \\.section __DATA,__thread_vars,thread_local_variables - \\.globl _weak_tlv - \\.weak_definition _weak_tlv, _weak_internal_tlv - \\ - \\_weak_tlv: - \\ .quad __tlv_bootstrap - \\ .quad 0 - \\ .quad _weak_tlv$tlv$init - \\ - \\_weak_internal_tlv: - \\ .quad __tlv_bootstrap - \\ .quad 0 - \\ .quad _weak_internal_tlv$tlv$init + \\.globl _main, _weak_external, _weak_external_for_gotpcrel, _weak_external_fn + \\.weak_definition _weak_external, _weak_external_for_gotpcrel, _weak_external_fn, _weak_internal, _weak_internal_for_gotpcrel, _weak_internal_fn + \\ + \\_main: + \\ mov _weak_dysym_for_gotpcrel@GOTPCREL(%rip), %rax + \\ mov _weak_external_for_gotpcrel@GOTPCREL(%rip), %rax + \\ mov _weak_internal_for_gotpcrel@GOTPCREL(%rip), %rax + \\ mov _weak_tlv@TLVP(%rip), %rax + \\ mov _weak_dysym_tlv@TLVP(%rip), %rax + \\ mov _weak_internal_tlv@TLVP(%rip), %rax + \\ callq _weak_dysym_fn + \\ callq _weak_external_fn + \\ callq _weak_internal_fn + \\ mov $0, %rax + \\ ret + \\ + \\_weak_external: + \\ .quad 0x1234 + \\ + \\_weak_external_for_gotpcrel: + \\ .quad 0x1234 + \\ + \\_weak_external_fn: + \\ ret + \\ + \\_weak_internal: + \\ .quad 0x1234 + \\ + \\_weak_internal_for_gotpcrel: + \\ .quad 0x1234 + \\ + \\_weak_internal_fn: + \\ ret + \\ + \\.data + \\ .quad _weak_dysym + \\ .quad _weak_external + 2 + \\ .quad _weak_internal + \\ + \\.tbss _weak_tlv$tlv$init, 4, 2 + \\.tbss _weak_internal_tlv$tlv$init, 4, 2 + \\ + \\.section __DATA,__thread_vars,thread_local_variables + \\.globl _weak_tlv + \\.weak_definition _weak_tlv, _weak_internal_tlv + \\ + \\_weak_tlv: + \\ .quad __tlv_bootstrap + \\ .quad 0 + \\ .quad _weak_tlv$tlv$init + \\ + \\_weak_internal_tlv: + \\ .quad __tlv_bootstrap + \\ .quad 0 + \\ .quad _weak_internal_tlv$tlv$init }); exe.linkLibrary(lib); @@ -3061,23 +3061,23 @@ fn testWeakLibrary(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "weak-library", opts); const dylib = addSharedLibrary(b, opts, .{ .name = "a", .c_source_bytes = - \\#include - \\int a = 42; - \\const char* asStr() { - \\ static char str[3]; - \\ sprintf(str, "%d", 42); - \\ return str; - \\} + \\#include + \\int a = 42; + \\const char* asStr() { + \\ static char str[3]; + \\ sprintf(str, "%d", 42); + \\ return str; + \\} }); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\extern int a; - \\extern const char* asStr(); - \\int main() { - \\ printf("%d %s", a, asStr()); - \\ return 0; - \\} + \\#include + \\extern int a; + \\extern const char* asStr(); + \\int main() { + \\ printf("%d %s", a, asStr()); + \\ return 0; + \\} }); exe.root_module.linkSystemLibrary("a", .{ .weak = true }); exe.root_module.addLibraryPath(dylib.getEmittedBinDirectory()); @@ -3104,11 +3104,11 @@ fn testWeakRef(b: *Build, opts: Options) *Step { const test_step = addTestStep(b, "weak-ref", opts); const exe = addExecutable(b, opts, .{ .name = "main", .c_source_bytes = - \\#include - \\#include - \\int main(int argc, char** argv) { - \\ printf("__darwin_check_fd_set_overflow: %p\n", __darwin_check_fd_set_overflow); - \\} + \\#include + \\#include + \\int main(int argc, char** argv) { + \\ printf("__darwin_check_fd_set_overflow: %p\n", __darwin_check_fd_set_overflow); + \\} }); const check = exe.checkObject(); diff --git a/tools/doctest.zig b/tools/doctest.zig index 070a59ee37..025d59517f 100644 --- a/tools/doctest.zig +++ b/tools/doctest.zig @@ -203,7 +203,7 @@ fn printOutput( if (mem.startsWith(u8, triple, "wasm32") or mem.startsWith(u8, triple, "riscv64-linux") or (mem.startsWith(u8, triple, "x86_64-linux") and - builtin.os.tag != .linux or builtin.cpu.arch != .x86_64)) + builtin.os.tag != .linux or builtin.cpu.arch != .x86_64)) { // skip execution break :code_block; diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index 637c9a5eaf..3dfc192551 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -753,7 +753,7 @@ pub fn main() anyerror!void { if ((std.mem.startsWith(u8, name, "mno-") and llvm_to_zig_cpu_features.contains(name["mno-".len..])) or (std.mem.startsWith(u8, name, "m") and - llvm_to_zig_cpu_features.contains(name["m".len..]))) + llvm_to_zig_cpu_features.contains(name["m".len..]))) { try stdout.print("m(\"{s}\"),\n", .{name}); } else {