Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json: allow stringifying type fields comptime #22149

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Cloudef
Copy link
Contributor

@Cloudef Cloudef commented Dec 5, 2024

This lets one serialize @typeInfo as well.

const std = @import("std");

const Packed = packed struct {
    foo: u1,
    bar: u3,
};

pub fn main() !void {
    @setEvalBranchQuota(100_000);
    comptime var buf: std.BoundedArray(u8, 1024) = .{};
    comptime try std.json.stringify(@typeInfo(Packed), .{.whitespace = .indent_2}, buf.writer());
    std.debug.print("{s}\n", .{comptime buf.constSlice()[0..].*});
}
{
  "struct": {
    "layout": "packed",
    "backing_integer": "u4",
    "fields": [
      {
        "name": "foo",
        "type": "u1",
        "default_value": null,
        "is_comptime": false,
        "alignment": 0
      },
      {
        "name": "bar",
        "type": "u3",
        "default_value": null,
        "is_comptime": false,
        "alignment": 0
      }
    ],
    "decls": [],
    "is_tuple": false
  }
}

@tauoverpi
Copy link
Contributor

Composite types (afaik) do not currently have a format suitable for use outside compile errors thus if you stringify an anon struct the result is then implementation (of the zig compiler) defined and may be broken at any time making this change fragile to changes in type name formatting.

@Cloudef
Copy link
Contributor Author

Cloudef commented Dec 6, 2024

I don't think this has to offer any stability guarantees, especially for anon types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants