Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

transCompoundLiteral

Translator.transCompoundLiteral
fn transCompoundLiteral(
    t: *Translator,
    scope: *Scope,
    literal: Node.CompoundLiteral,
    used: ResultUsed,
) TransError!ZigNode

File

lib/compiler/translate-c/Translator.zig:3713

Code

fn transCompoundLiteral(
    t: *Translator,
    scope: *Scope,
    literal: Node.CompoundLiteral,
    used: ResultUsed,
) TransError!ZigNode {
    if (used == .unused) {
        return t.transExpr(scope, literal.initializer, .unused);
    }

    // TODO taking a reference to a compound literal should result in a mutable
    // pointer (unless the literal is const).

    const initializer = try t.transExprCoercing(scope, literal.initializer, .used);
    const ty = try t.transType(scope, literal.qt, literal.l_paren_tok);
    if (!literal.thread_local and literal.storage_class != .static) {
        // In the simple case a compound literal can be translated
        // simply as `@as(type, initializer)`.
        return ZigTag.as.create(t.arena, .{ .lhs = ty, .rhs = initializer });
    }

    // Otherwise static or thread local compound literals are translated as
    // a reference to a variable wrapped in a struct.

    var block_scope = try Scope.Block.init(t, scope, true);
    defer block_scope.deinit();

    const tmp = try block_scope.reserveMangledName("tmp");
    const wrapped_name = "compound_literal";

    // const tmp = struct { var compound_literal = initializer };
    const temp_decl = try ZigTag.var_decl.create(t.arena, .{
        .is_pub = false,
        .is_const = literal.qt.@"const",
        .is_extern = false,
        .is_export = false,
        .is_threadlocal = literal.thread_local,
        .linksection_string = null,
        .alignment = null,
        .name = wrapped_name,
        .type = ty,
        .init = initializer,
    });
    const wrapped = try ZigTag.wrapped_local.create(t.arena, .{ .name = tmp, .init = temp_decl });
    try block_scope.statements.append(t.gpa, wrapped);

    // break :blk tmp.compound_literal
    const static_tmp_ident = try ZigTag.identifier.create(t.arena, tmp);
    const field_access = try ZigTag.field_access.create(t.arena, .{
        .lhs = static_tmp_ident,
        .field_name = wrapped_name,
    });
    const break_node = try ZigTag.break_val.create(t.arena, .{
        .label = block_scope.label,
        .val = field_access,
    });
    try block_scope.statements.append(t.gpa, break_node);

    return block_scope.complete();
}