From 8db9852a28bd59bed7101af5db1945f86a5622bc Mon Sep 17 00:00:00 2001 From: Jeff Hodges Date: Sun, 15 Nov 2026 21:13:35 -0800 Subject: [PATCH 1/2] feat: add --allow-inline-imports to accept @import outside the import block Platform-selecting switch arms (.windows => @import("win.zig")), test-local imports and type expressions are reported as banned with no way to opt out. The flag skips that check; --ban-prefix still applies to those imports. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++++++ README.md | 3 +++ src/zsort.zig | 18 +++++++++++++--- src/zsort_test.zig | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 78 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e5dbb6..478d32b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `--allow-inline-imports`: accept `@import` calls outside the top-level + import block (switch arms selecting a platform file, test bodies, type + expressions) instead of reporting them as banned; `--ban-prefix` still + applies to them + ## [0.9.0] - 2026-10-21 ### Added diff --git a/README.md b/README.md index 2171c14..0d7f708 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,8 @@ Options: --ban-prefix

Reject imports starting with

(repeatable) --bottom Place the import block at the end of the file --remove-unused Drop imports and aliases no code references (opt-in) + --allow-inline-imports + Accept @import outside the import block (opt-in) -h, --help Show help --version Print version ``` @@ -88,6 +90,7 @@ zsort check src/ build.zig # mixed targets zsort check . --ban-prefix ./ --ban-prefix src/ # ban relative paths zsort fix . --bottom # imports at the end of the file zsort fix . --remove-unused # also prune dead imports +zsort check . --allow-inline-imports # allow switch-arm / test-local imports ``` - `check` prints unified diffs for files that need changes. diff --git a/src/zsort.zig b/src/zsort.zig index 8c45e75..c6800b3 100644 --- a/src/zsort.zig +++ b/src/zsort.zig @@ -89,11 +89,12 @@ fn scanBannedPatterns( allocator: std.mem.Allocator, analysis: *const ast_scan.Analysis, banned_prefixes: []const []const u8, + allow_inline_imports: bool, source: []const u8, ) !?[]const u8 { for (analysis.calls.items) |call| { const line = std.mem.count(u8, source[0..call.offset], "\n") + 1; - if (std.mem.indexOfScalar(usize, analysis.allowed.items, call.offset) == null) { + if (!allow_inline_imports and std.mem.indexOfScalar(usize, analysis.allowed.items, call.offset) == null) { return try allocFmt(allocator, "inline @import inside a type expression (line {d})", .{line}); } if (call.path) |path| { @@ -116,7 +117,7 @@ pub fn hasBannedPatterns( defer allocator.free(dup); var analysis = try ast_scan.analyze(allocator, dup); defer analysis.deinit(allocator); - return scanBannedPatterns(allocator, &analysis, banned_prefixes, source); + return scanBannedPatterns(allocator, &analysis, banned_prefixes, false, source); } fn detectNewline(source: []const u8) []const u8 { @@ -637,6 +638,9 @@ pub const ProcessOptions = struct { banned_prefixes: []const []const u8 = &.{}, bottom: bool = false, remove_unused: bool = false, + /// Accept `@import` calls outside the top-level import block (switch + /// arms, test bodies, type expressions); `--ban-prefix` still applies. + allow_inline_imports: bool = false, }; pub fn processSource( @@ -694,7 +698,7 @@ pub fn processSource( const kept_imports = kept_imports_buf.items; const kept_aliases = kept_aliases_buf.items; - const banned_msg = try scanBannedPatterns(allocator, &analysis, banned_prefixes, source); + const banned_msg = try scanBannedPatterns(allocator, &analysis, banned_prefixes, options.allow_inline_imports, source); errdefer if (banned_msg) |msg| allocator.free(msg); if (imports.len == 0) { @@ -874,6 +878,7 @@ pub const Args = struct { banned_prefixes: std.ArrayListUnmanaged([]const u8), bottom: bool = false, remove_unused: bool = false, + allow_inline_imports: bool = false, help: bool = false, version: bool = false, @@ -895,6 +900,7 @@ pub fn parseArgs( var show_version = false; var bottom = false; var remove_unused = false; + var allow_inline_imports = false; var targets: std.ArrayListUnmanaged([]const u8) = .empty; errdefer targets.deinit(allocator); @@ -920,6 +926,8 @@ pub fn parseArgs( bottom = true; } else if (std.mem.eql(u8, arg, "--remove-unused")) { remove_unused = true; + } else if (std.mem.eql(u8, arg, "--allow-inline-imports")) { + allow_inline_imports = true; } else if (arg.len > 0 and arg[0] == '-') { err_msg.* = try allocFmt(allocator, "Unknown option '{s}'", .{arg}); return error.UnexpectedArg; @@ -944,6 +952,7 @@ pub fn parseArgs( .banned_prefixes = banned_prefixes, .bottom = bottom, .remove_unused = remove_unused, + .allow_inline_imports = allow_inline_imports, .help = help, .version = show_version, }; @@ -962,6 +971,7 @@ pub fn parseArgs( .banned_prefixes = banned_prefixes, .bottom = bottom, .remove_unused = remove_unused, + .allow_inline_imports = allow_inline_imports, }; } @@ -1028,6 +1038,7 @@ fn printHelp(io: compat.Io, use_color: bool) void { \\ {[2]s}--ban-prefix

{[1]s} Reject import paths starting with this prefix (repeatable) \\ {[2]s}--bottom{[1]s} Place the import block at the end of the file \\ {[2]s}--remove-unused{[1]s} Drop imports and aliases no code references + \\ {[2]s}--allow-inline-imports{[1]s} Accept @import outside the import block \\ {[2]s}-h, --help{[1]s} Show this help message \\ {[2]s}--version{[1]s} Print version and exit \\ @@ -1182,6 +1193,7 @@ fn runMain(allocator: std.mem.Allocator, args: []const []const u8, io: compat.Io .banned_prefixes = parsed.banned_prefixes.items, .bottom = parsed.bottom, .remove_unused = parsed.remove_unused, + .allow_inline_imports = parsed.allow_inline_imports, }, }; initialized += 1; diff --git a/src/zsort_test.zig b/src/zsort_test.zig index c4dfbef..488936f 100644 --- a/src/zsort_test.zig +++ b/src/zsort_test.zig @@ -2015,3 +2015,54 @@ test "processSource: --remove-unused keeps a trailing comment without a leading try std.testing.expect(result.changed); try std.testing.expectEqualStrings("// Explains the body.\npub fn main() void {}\n", result.new_text); } + +test "processSource: --allow-inline-imports accepts inline @import" { + const source = + \\const std = @import("std"); + \\ + \\const impl = switch (@import("builtin").os.tag) { + \\ .windows => @import("ipc_windows.zig"), + \\ else => @import("ipc_posix.zig"), + \\}; + \\ + ; + const strict = try zsort.processSource(std.testing.allocator, source, .{}); + defer std.testing.allocator.free(strict.new_text); + defer std.testing.allocator.free(strict.new_block); + defer if (strict.banned_msg) |msg| std.testing.allocator.free(msg); + try std.testing.expect(strict.banned); + + const relaxed = try zsort.processSource(std.testing.allocator, source, .{ .allow_inline_imports = true }); + defer std.testing.allocator.free(relaxed.new_text); + defer std.testing.allocator.free(relaxed.new_block); + try std.testing.expect(!relaxed.banned); + try std.testing.expect(!relaxed.changed); +} + +test "processSource: --allow-inline-imports still enforces --ban-prefix" { + const source = + \\const std = @import("std"); + \\ + \\fn get() type { + \\ return @import("./impl.zig").Impl; + \\} + \\ + ; + const result = try zsort.processSource(std.testing.allocator, source, .{ + .banned_prefixes = &.{"./"}, + .allow_inline_imports = true, + }); + defer std.testing.allocator.free(result.new_text); + defer std.testing.allocator.free(result.new_block); + const msg = result.banned_msg orelse return error.TestFailed; + defer std.testing.allocator.free(msg); + try std.testing.expect(std.mem.indexOf(u8, msg, "./") != null); +} + +test "parseArgs: --allow-inline-imports" { + const args = [_][]const u8{ "zsort", "check", "src", "--allow-inline-imports" }; + var msg: ?[]const u8 = null; + var parsed = try zsort.parseArgs(std.testing.allocator, &args, &msg); + defer parsed.deinit(std.testing.allocator); + try std.testing.expect(parsed.allow_inline_imports); +} From 616561ad44ebe1ed316494dbef0a5a27840e0aad Mon Sep 17 00:00:00 2001 From: Jeff Hodges Date: Sun, 15 Nov 2026 21:13:35 -0800 Subject: [PATCH 2/2] fix: keep a decl's doc comment attached when fix hoists an import lineBlockEnd counted a /// doc comment directly above the first body decl as part of the import block, so the separating blank line split the comment from its decl. The block now ends before that doc-comment run. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++++ src/ast_scan.zig | 15 +++++++++++++-- src/zsort_test.zig | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 478d32b..d0d4ec4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,12 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). expressions) instead of reporting them as banned; `--ban-prefix` still applies to them +### Fixed + +- A `///` doc comment on the first decl after the import block stays attached + to that decl when `fix` hoists a stray import, instead of being split from + it by the separating blank line + ## [0.9.0] - 2026-10-21 ### Added diff --git a/src/ast_scan.zig b/src/ast_scan.zig index a082f7e..15482f2 100644 --- a/src/ast_scan.zig +++ b/src/ast_scan.zig @@ -358,10 +358,20 @@ fn importHeadOffset(tree: Ast, init: Ast.Node.Index) ?usize { /// instead of being swallowed by the rebuilt block. fn lineBlockEnd(source: []const u8, imports: []const Import, aliases: []const Import) usize { var pos: usize = 0; + // Start of the comment run that opens with a `///` doc comment: it + // documents the next decl, so a block that ends at that decl ends here. + var doc_run_start: ?usize = null; while (pos < source.len) { const le = findLineEnd(source, pos); const trimmed = std.mem.trimStart(u8, source[pos..le], " \t\n\r"); - if (trimmed.len == 0 or std.mem.startsWith(u8, trimmed, "//")) { + if (trimmed.len == 0) { + doc_run_start = null; + pos = le; + continue; + } + if (std.mem.startsWith(u8, trimmed, "//")) { + const is_doc = std.mem.startsWith(u8, trimmed, "///") and !std.mem.startsWith(u8, trimmed, "////"); + if (is_doc and doc_run_start == null) doc_run_start = pos; pos = le; continue; } @@ -378,7 +388,8 @@ fn lineBlockEnd(source: []const u8, imports: []const Import, aliases: []const Im break; } }; - if (!covered) return pos; + if (!covered) return doc_run_start orelse pos; + doc_run_start = null; pos = le; } return pos; diff --git a/src/zsort_test.zig b/src/zsort_test.zig index 488936f..d05e6ee 100644 --- a/src/zsort_test.zig +++ b/src/zsort_test.zig @@ -2066,3 +2066,38 @@ test "parseArgs: --allow-inline-imports" { defer parsed.deinit(std.testing.allocator); try std.testing.expect(parsed.allow_inline_imports); } + +test "processSource: hoisting a stray keeps the next decl's doc comment attached" { + const source = + \\const std = @import("std"); + \\const Module = std.Build.Module; + \\ + \\/// Docs for Manifest. + \\const Manifest = struct { + \\ id: []const u8, + \\}; + \\const manifest: Manifest = @import("app.zon"); + \\ + \\pub fn main() void {} + \\ + ; + const result = try zsort.processSource(std.testing.allocator, source, .{}); + defer std.testing.allocator.free(result.new_text); + defer std.testing.allocator.free(result.new_block); + try std.testing.expect(result.changed); + try std.testing.expectEqualStrings( + \\const std = @import("std"); + \\ + \\const manifest: Manifest = @import("app.zon"); + \\ + \\const Module = std.Build.Module; + \\ + \\/// Docs for Manifest. + \\const Manifest = struct { + \\ id: []const u8, + \\}; + \\ + \\pub fn main() void {} + \\ + , result.new_text); +}