authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-11-04 15:48:28-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-11-04 15:48:28-07:00
logfc1e7a56441aea4a9394c4e8c0142110891b4a1a
tree8d7fc370a62874bcfe779df04a67fdd8fa17e0a4
parent802c82b0720ff2b7c59ba96effbdd1eed7491df4

zig reduce: rename identifiers when inlining an `@import`


3 files changed, 112 insertions(+), 26 deletions(-)

lib/std/zig/render.zig+17-1
......@@ -26,6 +26,9 @@ pub const Fixups = struct {
2626 omit_nodes: std.AutoHashMapUnmanaged(Ast.Node.Index, void) = .{},
2727 /// These expressions will be replaced with the string value.
2828 replace_nodes: std.AutoHashMapUnmanaged(Ast.Node.Index, []const u8) = .{},
29 /// Change all identifier names matching the key to be value instead.
30 rename_identifiers: std.StringArrayHashMapUnmanaged([]const u8) = .{},
31
2932 /// All `@import` builtin calls which refer to a file path will be prefixed
3033 /// with this path.
3134 rebase_imported_paths: ?[]const u8 = null,
......@@ -34,7 +37,9 @@ pub const Fixups = struct {
3437 return f.unused_var_decls.count() +
3538 f.gut_functions.count() +
3639 f.omit_nodes.count() +
37 f.replace_nodes.count();
40 f.replace_nodes.count() +
41 f.rename_identifiers.count() +
42 @intFromBool(f.rebase_imported_paths != null);
3843 }
3944
4045 pub fn clearRetainingCapacity(f: *Fixups) void {
......@@ -42,6 +47,9 @@ pub const Fixups = struct {
4247 f.gut_functions.clearRetainingCapacity();
4348 f.omit_nodes.clearRetainingCapacity();
4449 f.replace_nodes.clearRetainingCapacity();
50 f.rename_identifiers.clearRetainingCapacity();
51
52 f.rebase_imported_paths = null;
4553 }
4654
4755 pub fn deinit(f: *Fixups, gpa: Allocator) void {
......@@ -49,6 +57,7 @@ pub const Fixups = struct {
4957 f.gut_functions.deinit(gpa);
5058 f.omit_nodes.deinit(gpa);
5159 f.replace_nodes.deinit(gpa);
60 f.rename_identifiers.deinit(gpa);
5261 f.* = undefined;
5362 }
5463};
......@@ -2833,6 +2842,13 @@ fn renderIdentifier(r: *Render, token_index: Ast.TokenIndex, space: Space, quote
28332842 const token_tags = tree.tokens.items(.tag);
28342843 assert(token_tags[token_index] == .identifier);
28352844 const lexeme = tokenSliceForRender(tree, token_index);
2845
2846 if (r.fixups.rename_identifiers.get(lexeme)) |mangled| {
2847 try r.ais.writer().writeAll(mangled);
2848 try renderSpace(r, token_index, lexeme.len, space);
2849 return;
2850 }
2851
28362852 if (lexeme[0] != '@') {
28372853 return renderToken(r, token_index, space);
28382854 }
src/reduce.zig+34-8
......@@ -148,7 +148,7 @@ pub fn main(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
148148
149149 var transformations = std.ArrayList(Walk.Transformation).init(gpa);
150150 defer transformations.deinit();
151 try Walk.findTransformations(&tree, &transformations);
151 try Walk.findTransformations(arena, &tree, &transformations);
152152 sortTransformations(transformations.items, rng.random());
153153
154154 fresh: while (transformations.items.len > 0) {
......@@ -162,12 +162,19 @@ pub fn main(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
162162 subset_size = @max(1, subset_size / 2);
163163
164164 const this_set = transformations.items[start_index..][0..subset_size];
165 std.debug.print("trying {d} random transformations: ", .{subset_size});
166 for (this_set[0..@min(this_set.len, 20)]) |t| {
167 std.debug.print("{s} ", .{@tagName(t)});
168 }
169 std.debug.print("\n", .{});
165170 try transformationsToFixups(gpa, arena, root_source_file_path, this_set, &fixups);
166171
167172 rendered.clearRetainingCapacity();
168173 try tree.renderToArrayList(&rendered, fixups);
169174 try std.fs.cwd().writeFile(root_source_file_path, rendered.items);
170175
176 //std.debug.print("trying this code:\n{s}\n", .{rendered.items});
177
171178 const interestingness = try runCheck(arena, interestingness_argv.items);
172179 std.debug.print("{d} random transformations: {s}. {d} remaining\n", .{
173180 subset_size, @tagName(interestingness), transformations.items.len - start_index,
......@@ -179,7 +186,7 @@ pub fn main(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
179186 tree.deinit(gpa);
180187 tree = new_tree;
181188
182 try Walk.findTransformations(&tree, &transformations);
189 try Walk.findTransformations(arena, &tree, &transformations);
183190 // Resetting based on the seed again means we will get the same
184191 // results if restarting the reduction process from this new point.
185192 rng = std.rand.DefaultPrng.init(seed);
......@@ -263,7 +270,6 @@ fn transformationsToFixups(
263270 try fixups.replace_nodes.put(gpa, node, "undefined");
264271 },
265272 .inline_imported_file => |inline_imported_file| {
266 defer gpa.free(inline_imported_file.imported_string);
267273 const full_imported_path = try std.fs.path.join(gpa, &.{
268274 std.fs.path.dirname(root_source_file_path) orelse ".",
269275 inline_imported_file.imported_string,
......@@ -274,14 +280,34 @@ fn transformationsToFixups(
274280 gpa.free(other_file_ast.source);
275281 other_file_ast.deinit(gpa);
276282 }
277 var other_source = std.ArrayList(u8).init(gpa);
278 defer other_source.deinit();
283
279284 var inlined_fixups: Ast.Fixups = .{};
280285 defer inlined_fixups.deinit(gpa);
286 if (std.fs.path.dirname(inline_imported_file.imported_string)) |dirname| {
287 inlined_fixups.rebase_imported_paths = dirname;
288 }
289 for (inline_imported_file.in_scope_names.keys()) |name| {
290 // This name needs to be mangled in order to not cause an
291 // ambiguous reference error.
292 var i: u32 = 2;
293 const mangled = while (true) : (i += 1) {
294 const mangled = try std.fmt.allocPrint(gpa, "{s}{d}", .{ name, i });
295 if (!inline_imported_file.in_scope_names.contains(mangled))
296 break mangled;
297 gpa.free(mangled);
298 };
299 try inlined_fixups.rename_identifiers.put(gpa, name, mangled);
300 }
301 defer {
302 for (inlined_fixups.rename_identifiers.values()) |v| {
303 gpa.free(v);
304 }
305 }
306
307 var other_source = std.ArrayList(u8).init(gpa);
308 defer other_source.deinit();
281309 try other_source.appendSlice("struct {\n");
282 try other_file_ast.renderToArrayList(&other_source, .{
283 .rebase_imported_paths = std.fs.path.dirname(inline_imported_file.imported_string),
284 });
310 try other_file_ast.renderToArrayList(&other_source, inlined_fixups);
285311 try other_source.appendSlice("}");
286312
287313 try fixups.replace_nodes.put(
src/reduce/Walk.zig+61-17
......@@ -7,7 +7,9 @@ const BuiltinFn = @import("../BuiltinFn.zig");
77ast: *const Ast,
88transformations: *std.ArrayList(Transformation),
99unreferenced_globals: std.StringArrayHashMapUnmanaged(Ast.Node.Index),
10in_scope_names: std.StringArrayHashMapUnmanaged(u32),
1011gpa: std.mem.Allocator,
12arena: std.mem.Allocator,
1113
1214pub const Transformation = union(enum) {
1315 /// Replace the fn decl AST Node with one whose body is only `@trap()` with
......@@ -18,25 +20,39 @@ pub const Transformation = union(enum) {
1820 /// Replace an expression with `undefined`.
1921 replace_with_undef: Ast.Node.Index,
2022 /// Replace an `@import` with the imported file contents wrapped in a struct.
21 inline_imported_file: struct {
23 inline_imported_file: InlineImportedFile,
24
25 pub const InlineImportedFile = struct {
2226 builtin_call_node: Ast.Node.Index,
2327 imported_string: []const u8,
24 },
28 /// Identifier names that must be renamed in the inlined code or else
29 /// will cause ambiguous reference errors.
30 in_scope_names: std.StringArrayHashMapUnmanaged(void),
31 };
2532};
2633
2734pub const Error = error{OutOfMemory};
2835
2936/// The result will be priority shuffled.
30pub fn findTransformations(ast: *const Ast, transformations: *std.ArrayList(Transformation)) !void {
37pub fn findTransformations(
38 arena: std.mem.Allocator,
39 ast: *const Ast,
40 transformations: *std.ArrayList(Transformation),
41) !void {
3142 transformations.clearRetainingCapacity();
3243
3344 var walk: Walk = .{
3445 .ast = ast,
3546 .transformations = transformations,
3647 .gpa = transformations.allocator,
48 .arena = arena,
3749 .unreferenced_globals = .{},
50 .in_scope_names = .{},
3851 };
39 defer walk.unreferenced_globals.deinit(walk.gpa);
52 defer {
53 walk.unreferenced_globals.deinit(walk.gpa);
54 walk.in_scope_names.deinit(walk.gpa);
55 }
4056
4157 try walkMembers(&walk, walk.ast.rootDecls());
4258
......@@ -49,14 +65,18 @@ pub fn findTransformations(ast: *const Ast, transformations: *std.ArrayList(Tran
4965
5066fn walkMembers(w: *Walk, members: []const Ast.Node.Index) Error!void {
5167 // First we scan for globals so that we can delete them while walking.
52 try scanDecls(w, members);
68 try scanDecls(w, members, .add);
5369
5470 for (members) |member| {
5571 try walkMember(w, member);
5672 }
73
74 try scanDecls(w, members, .remove);
5775}
5876
59fn scanDecls(w: *Walk, members: []const Ast.Node.Index) Error!void {
77const ScanDeclsAction = enum { add, remove };
78
79fn scanDecls(w: *Walk, members: []const Ast.Node.Index, action: ScanDeclsAction) Error!void {
6080 const ast = w.ast;
6181 const gpa = w.gpa;
6282 const node_tags = ast.nodes.items(.tag);
......@@ -80,9 +100,27 @@ fn scanDecls(w: *Walk, members: []const Ast.Node.Index) Error!void {
80100
81101 else => continue,
82102 };
103
83104 assert(token_tags[name_token] == .identifier);
84105 const name_bytes = ast.tokenSlice(name_token);
85 try w.unreferenced_globals.put(gpa, name_bytes, member_node);
106
107 switch (action) {
108 .add => {
109 try w.unreferenced_globals.put(gpa, name_bytes, member_node);
110
111 const gop = try w.in_scope_names.getOrPut(gpa, name_bytes);
112 if (!gop.found_existing) gop.value_ptr.* = 0;
113 gop.value_ptr.* += 1;
114 },
115 .remove => {
116 const entry = w.in_scope_names.getEntry(name_bytes).?;
117 if (entry.value_ptr.* <= 1) {
118 assert(w.in_scope_names.swapRemove(name_bytes));
119 } else {
120 entry.value_ptr.* -= 1;
121 }
122 },
123 }
86124 }
87125}
88126
......@@ -567,12 +605,12 @@ fn walkLocalVarDecl(w: *Walk, var_decl: Ast.full.VarDecl) Error!void {
567605 try walkExpression(w, var_decl.ast.section_node);
568606 }
569607
570 assert(var_decl.ast.init_node != 0);
571 if (!isUndefinedIdent(w.ast, var_decl.ast.init_node)) {
572 try w.transformations.append(.{ .replace_with_undef = var_decl.ast.init_node });
608 if (var_decl.ast.init_node != 0) {
609 if (!isUndefinedIdent(w.ast, var_decl.ast.init_node)) {
610 try w.transformations.append(.{ .replace_with_undef = var_decl.ast.init_node });
611 }
612 try walkExpression(w, var_decl.ast.init_node);
573613 }
574
575 return walkExpression(w, var_decl.ast.init_node);
576614}
577615
578616fn walkContainerField(w: *Walk, field: Ast.full.ContainerField) Error!void {
......@@ -582,7 +620,9 @@ fn walkContainerField(w: *Walk, field: Ast.full.ContainerField) Error!void {
582620 if (field.ast.align_expr != 0) {
583621 try walkExpression(w, field.ast.align_expr); // alignment
584622 }
585 try walkExpression(w, field.ast.value_expr); // value
623 if (field.ast.value_expr != 0) {
624 try walkExpression(w, field.ast.value_expr); // value
625 }
586626}
587627
588628fn walkBlock(
......@@ -690,7 +730,6 @@ fn walkBuiltinCall(
690730 params: []const Ast.Node.Index,
691731) Error!void {
692732 const ast = w.ast;
693 const gpa = w.gpa;
694733 const main_tokens = ast.nodes.items(.main_token);
695734 const builtin_token = main_tokens[call_node];
696735 const builtin_name = ast.tokenSlice(builtin_token);
......@@ -700,12 +739,17 @@ fn walkBuiltinCall(
700739 const operand_node = params[0];
701740 const str_lit_token = main_tokens[operand_node];
702741 const token_bytes = ast.tokenSlice(str_lit_token);
703 const imported_string = std.zig.string_literal.parseAlloc(gpa, token_bytes) catch
704 unreachable;
705 if (std.mem.endsWith(u8, imported_string, ".zig")) {
742 if (std.mem.endsWith(u8, token_bytes, ".zig\"")) {
743 const imported_string = std.zig.string_literal.parseAlloc(w.arena, token_bytes) catch
744 unreachable;
706745 try w.transformations.append(.{ .inline_imported_file = .{
707746 .builtin_call_node = call_node,
708747 .imported_string = imported_string,
748 .in_scope_names = try std.StringArrayHashMapUnmanaged(void).init(
749 w.arena,
750 w.in_scope_names.keys(),
751 &.{},
752 ),
709753 } });
710754 }
711755 },