Skip to content

Commit 8121949

Browse files
committed
zig fmt: canonicalize nested cast builtin order
1 parent a5f891d commit 8121949

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

lib/std/zig/Ast/Render.zig

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -783,7 +783,48 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void {
783783
=> {
784784
var buf: [2]Ast.Node.Index = undefined;
785785
const params = tree.builtinCallParams(&buf, node).?;
786-
return renderBuiltinCall(r, tree.nodeMainToken(node), params, space);
786+
var builtin_token = tree.nodeMainToken(node);
787+
788+
canonicalize: {
789+
if (params.len != 1) break :canonicalize;
790+
791+
const CastKind = enum {
792+
ptrCast,
793+
alignCast,
794+
addrSpaceCast,
795+
constCast,
796+
volatileCast,
797+
};
798+
const kind = meta.stringToEnum(CastKind, tree.tokenSlice(builtin_token)[1..]) orelse break :canonicalize;
799+
800+
var cast_map = std.EnumMap(CastKind, Ast.TokenIndex).init(.{});
801+
cast_map.put(kind, builtin_token);
802+
803+
var casts_before: usize = 0;
804+
if (builtin_token >= 2) {
805+
var prev_builtin_token = builtin_token - 2;
806+
while (tree.tokenTag(prev_builtin_token) == .builtin) : (prev_builtin_token -= 2) {
807+
const prev_kind = meta.stringToEnum(CastKind, tree.tokenSlice(prev_builtin_token)[1..]) orelse break;
808+
if (cast_map.contains(prev_kind)) break :canonicalize;
809+
cast_map.put(prev_kind, prev_builtin_token);
810+
casts_before += 1;
811+
}
812+
}
813+
814+
var next_builtin_token = builtin_token + 2;
815+
while (tree.tokenTag(next_builtin_token) == .builtin) : (next_builtin_token += 2) {
816+
const next_kind = meta.stringToEnum(CastKind, tree.tokenSlice(next_builtin_token)[1..]) orelse break;
817+
if (cast_map.contains(next_kind)) break :canonicalize;
818+
cast_map.put(next_kind, next_builtin_token);
819+
}
820+
821+
var it = cast_map.iterator();
822+
builtin_token = it.next().?.value.*;
823+
while (casts_before > 0) : (casts_before -= 1) {
824+
builtin_token = it.next().?.value.*;
825+
}
826+
}
827+
return renderBuiltinCall(r, builtin_token, params, space);
787828
},
788829

789830
.fn_proto_simple,

0 commit comments

Comments
 (0)