From 19421e0f3eb97324186165b21b4293ef351764c4 Mon Sep 17 00:00:00 2001 From: Techatrix Date: Wed, 1 Jan 2025 01:24:30 +0100 Subject: [PATCH] refactor: embrace RLS, anonymous struct literals and decl literals (#2128) --- build.zig | 18 +-- src/DiagnosticsCollection.zig | 16 +-- src/DocumentScope.zig | 33 +++-- src/DocumentStore.zig | 58 ++++---- src/Server.zig | 36 ++--- src/analyser/InternPool.zig | 180 ++++++++++++++----------- src/analyser/completions.zig | 14 +- src/analyser/degibberish.zig | 20 +-- src/analyser/string_pool.zig | 31 ++--- src/analysis.zig | 105 +++++++-------- src/ast.zig | 24 ++-- src/binned_allocator.zig | 60 +++++---- src/configuration.zig | 6 +- src/debug.zig | 4 +- src/diff.zig | 8 +- src/features/code_actions.zig | 18 +-- src/features/completions.zig | 30 ++--- src/features/diagnostics.zig | 16 +-- src/features/document_symbol.zig | 14 +- src/features/folding_range.zig | 6 +- src/features/goto.zig | 13 +- src/features/hover.zig | 14 +- src/features/inlay_hints.zig | 8 +- src/features/references.zig | 23 ++-- src/features/selection_range.zig | 4 +- src/features/semantic_tokens.zig | 2 +- src/features/signature_help.zig | 6 +- src/main.zig | 14 +- src/tools/config_gen.zig | 22 +-- src/tools/publish_http_form.zig | 8 +- src/translate_c.zig | 8 +- src/uri.zig | 2 +- tests/ErrorBuilder.zig | 12 +- tests/build_runner_check.zig | 2 +- tests/context.zig | 6 +- tests/helper.zig | 8 +- tests/language_features/cimport.zig | 4 +- tests/lifecycle.zig | 2 +- tests/lsp_features/code_actions.zig | 4 +- tests/lsp_features/completion.zig | 32 ++--- tests/lsp_features/definition.zig | 10 +- tests/lsp_features/document_symbol.zig | 8 +- tests/lsp_features/folding_range.zig | 4 +- tests/lsp_features/hover.zig | 4 +- tests/lsp_features/inlay_hints.zig | 10 +- tests/lsp_features/references.zig | 12 +- tests/lsp_features/selection_range.zig | 10 +- tests/lsp_features/semantic_tokens.zig | 8 +- tests/lsp_features/signature_help.zig | 4 +- tests/utility/ast.zig | 2 +- tests/utility/diff.zig | 2 +- tests/utility/position_context.zig | 2 +- 52 files changed, 494 insertions(+), 473 deletions(-) diff --git a/build.zig b/build.zig index 50df0b281..0733f1d2d 100644 --- a/build.zig +++ b/build.zig @@ -3,7 +3,7 @@ const builtin = @import("builtin"); /// Must match the `version` in `build.zig.zon`. /// Remove `.pre` when tagging a new ZLS release and add it back on the next development cycle. -const zls_version = std.SemanticVersion{ .major = 0, .minor = 14, .patch = 0, .pre = "dev" }; +const zls_version: std.SemanticVersion = .{ .major = 0, .minor = 14, .patch = 0, .pre = "dev" }; /// Specify the minimum Zig version that is required to compile and test ZLS: /// std.Build: add new functions to create artifacts/Step.Compile from existing module @@ -313,7 +313,7 @@ fn getVersion(b: *Build) std.SemanticVersion { std.debug.assert(zls_version.order(ancestor_ver) == .gt); // ZLS version must be greater than its previous version std.debug.assert(std.mem.startsWith(u8, commit_id, "g")); // commit hash is prefixed with a 'g' - return std.SemanticVersion{ + return .{ .major = zls_version.major, .minor = zls_version.minor, .patch = zls_version.patch, @@ -436,7 +436,7 @@ fn release(b: *Build, target_queries: []const std.Target.Query, release_artifact "--form", b.fmt("minimum-runtime-zig-version={s}", .{minimum_runtime_zig_version}), }); - var compressed_artifacts = std.StringArrayHashMap(std.Build.LazyPath).init(b.allocator); + var compressed_artifacts: std.StringArrayHashMapUnmanaged(std.Build.LazyPath) = .empty; for (target_queries, release_artifacts) |target_query, exe| { const resolved_target = exe.root_module.resolved_target.?.result; @@ -462,7 +462,7 @@ fn release(b: *Build, target_queries: []const std.Target.Query, release_artifact switch (extension) { .zip => { compress_cmd.addArgs(&.{ "7z", "a", "-mx=9" }); - compressed_artifacts.putNoClobber(file_name, compress_cmd.addOutputFileArg(file_name)) catch @panic("OOM"); + compressed_artifacts.putNoClobber(b.allocator, file_name, compress_cmd.addOutputFileArg(file_name)) catch @panic("OOM"); compress_cmd.addArtifactArg(exe); compress_cmd.addFileArg(exe.getEmittedPdb()); compress_cmd.addFileArg(b.path("LICENSE")); @@ -473,7 +473,7 @@ fn release(b: *Build, target_queries: []const std.Target.Query, release_artifact => { compress_cmd.setEnvironmentVariable("XZ_OPT", "-9"); compress_cmd.addArgs(&.{ "tar", "caf" }); - compressed_artifacts.putNoClobber(file_name, compress_cmd.addOutputFileArg(file_name)) catch @panic("OOM"); + compressed_artifacts.putNoClobber(b.allocator, file_name, compress_cmd.addOutputFileArg(file_name)) catch @panic("OOM"); compress_cmd.addPrefixedDirectoryArg("-C", exe.getEmittedBinDirectory()); compress_cmd.addArg(exe_name); @@ -554,8 +554,8 @@ const Build = blk: { @compileError(message); } } else { - const min_build_zig_simple = std.SemanticVersion{ .major = min_build_zig.major, .minor = min_build_zig.minor, .patch = 0 }; - const zls_version_simple = std.SemanticVersion{ .major = zls_version.major, .minor = zls_version.minor, .patch = 0 }; + const min_build_zig_simple: std.SemanticVersion = .{ .major = min_build_zig.major, .minor = min_build_zig.minor, .patch = 0 }; + const zls_version_simple: std.SemanticVersion = .{ .major = zls_version.major, .minor = zls_version.minor, .patch = 0 }; const min_zig_is_tagged = min_build_zig.build == null and min_build_zig.pre == null; if (!min_zig_is_tagged and zls_version_simple.order(min_build_zig_simple) != .eq) { const message = std.fmt.comptimePrint( @@ -574,8 +574,8 @@ const Build = blk: { // check minimum build version const is_current_zig_tagged_release = builtin.zig_version.pre == null and builtin.zig_version.build == null; const is_min_build_zig_tagged_release = min_build_zig.pre == null and min_build_zig.build == null; - const min_build_zig_simple = std.SemanticVersion{ .major = min_build_zig.major, .minor = min_build_zig.minor, .patch = 0 }; - const current_zig_simple = std.SemanticVersion{ .major = builtin.zig_version.major, .minor = builtin.zig_version.minor, .patch = 0 }; + const min_build_zig_simple: std.SemanticVersion = .{ .major = min_build_zig.major, .minor = min_build_zig.minor, .patch = 0 }; + const current_zig_simple: std.SemanticVersion = .{ .major = builtin.zig_version.major, .minor = builtin.zig_version.minor, .patch = 0 }; if (switch (builtin.zig_version.order(min_build_zig)) { .lt => true, .eq => false, diff --git a/src/DiagnosticsCollection.zig b/src/DiagnosticsCollection.zig index b23c2b690..9d5ec8fe3 100644 --- a/src/DiagnosticsCollection.zig +++ b/src/DiagnosticsCollection.zig @@ -226,7 +226,7 @@ fn pathToUri(allocator: std.mem.Allocator, base_path: ?[]const u8, src_path: []c pub fn publishDiagnostics(collection: *DiagnosticsCollection) (std.mem.Allocator.Error || lsp.AnyTransport.WriteError)!void { const transport = collection.transport orelse return; - var arena_allocator = std.heap.ArenaAllocator.init(collection.allocator); + var arena_allocator: std.heap.ArenaAllocator = .init(collection.allocator); defer arena_allocator.deinit(); while (true) { @@ -240,7 +240,7 @@ pub fn publishDiagnostics(collection: *DiagnosticsCollection) (std.mem.Allocator _ = arena_allocator.reset(.retain_capacity); - var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .{}; + var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .empty; try collection.collectLspDiagnosticsForDocument(document_uri, collection.offset_encoding, arena_allocator.allocator(), &diagnostics); const params: lsp.types.PublishDiagnosticsParams = .{ @@ -429,7 +429,7 @@ test errorBundleSourceLocationToRange { } test DiagnosticsCollection { - var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator); + var arena_allocator: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); @@ -454,7 +454,7 @@ test DiagnosticsCollection { try std.testing.expectEqual(1, collection.outdated_files.count()); try std.testing.expectEqualStrings(uri, collection.outdated_files.keys()[0]); - var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .{}; + var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .empty; try collection.collectLspDiagnosticsForDocument(uri, .@"utf-8", arena, &diagnostics); try std.testing.expectEqual(1, diagnostics.items.len); @@ -466,7 +466,7 @@ test DiagnosticsCollection { { try collection.pushErrorBundle(.parse, 0, null, eb2); - var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .{}; + var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .empty; try collection.collectLspDiagnosticsForDocument(uri, .@"utf-8", arena, &diagnostics); try std.testing.expectEqual(1, diagnostics.items.len); @@ -476,7 +476,7 @@ test DiagnosticsCollection { { try collection.pushErrorBundle(.parse, 2, null, eb2); - var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .{}; + var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .empty; try collection.collectLspDiagnosticsForDocument(uri, .@"utf-8", arena, &diagnostics); try std.testing.expectEqual(1, diagnostics.items.len); @@ -486,7 +486,7 @@ test DiagnosticsCollection { { try collection.pushErrorBundle(.parse, 3, null, .empty); - var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .{}; + var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .empty; try collection.collectLspDiagnosticsForDocument(uri, .@"utf-8", arena, &diagnostics); try std.testing.expectEqual(0, diagnostics.items.len); @@ -496,7 +496,7 @@ test DiagnosticsCollection { try collection.pushErrorBundle(@enumFromInt(16), 4, null, eb2); try collection.pushErrorBundle(@enumFromInt(17), 4, null, eb3); - var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .{}; + var diagnostics: std.ArrayListUnmanaged(lsp.types.Diagnostic) = .empty; try collection.collectLspDiagnosticsForDocument(uri, .@"utf-8", arena, &diagnostics); try std.testing.expectEqual(2, diagnostics.items.len); diff --git a/src/DocumentScope.zig b/src/DocumentScope.zig index 43a70443d..a17604ef9 100644 --- a/src/DocumentScope.zig +++ b/src/DocumentScope.zig @@ -8,21 +8,21 @@ const offsets = @import("offsets.zig"); const DocumentScope = @This(); -scopes: std.MultiArrayList(Scope) = .{}, -declarations: std.MultiArrayList(Declaration) = .{}, +scopes: std.MultiArrayList(Scope), +declarations: std.MultiArrayList(Declaration), /// used for looking up a child declaration in a given scope -declaration_lookup_map: DeclarationLookupMap = .{}, -extra: std.ArrayListUnmanaged(u32) = .{}, +declaration_lookup_map: DeclarationLookupMap, +extra: std.ArrayListUnmanaged(u32), /// All identifier token that are in error sets. /// When there are multiple error sets that contain the same error, only one of them is stored. /// A token that has a doc comment takes priority. /// This means that if there a multiple error sets with the same name, only one of them is included. -global_error_set: IdentifierSet = .{}, +global_error_set: IdentifierSet, /// All identifier token that are in enums. /// When there are multiple enums that contain the field name, only one of them is stored. /// A token that has a doc comment takes priority. /// This means that if there a multiple enums with the same name, only one of them is included. -global_enum_set: IdentifierSet = .{}, +global_enum_set: IdentifierSet, /// Stores a set of identifier tokens with unique names pub const IdentifierSet = std.ArrayHashMapUnmanaged(Ast.TokenIndex, void, IdentifierTokenContext, true); @@ -63,7 +63,7 @@ pub const DeclarationLookup = struct { pub const DeclarationLookupContext = struct { pub fn hash(self: @This(), s: DeclarationLookup) u32 { _ = self; - var hasher = std.hash.Wyhash.init(0); + var hasher: std.hash.Wyhash = .init(0); std.hash.autoHash(&hasher, s.scope); hasher.update(s.name); std.hash.autoHash(&hasher, s.kind); @@ -372,8 +372,8 @@ const ScopeContext = struct { doc_scope: *DocumentScope, current_scope: Scope.OptionalIndex = .none, - child_scopes_scratch: std.ArrayListUnmanaged(Scope.Index) = .{}, - child_declarations_scratch: std.ArrayListUnmanaged(Declaration.Index) = .{}, + child_scopes_scratch: std.ArrayListUnmanaged(Scope.Index) = .empty, + child_declarations_scratch: std.ArrayListUnmanaged(Declaration.Index) = .empty, fn deinit(context: *ScopeContext) void { context.child_scopes_scratch.deinit(context.allocator); @@ -548,10 +548,17 @@ pub fn init(allocator: std.mem.Allocator, tree: Ast) error{OutOfMemory}!Document const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var document_scope = DocumentScope{}; + var document_scope: DocumentScope = .{ + .scopes = .empty, + .declarations = .empty, + .declaration_lookup_map = .empty, + .extra = .empty, + .global_error_set = .empty, + .global_enum_set = .empty, + }; errdefer document_scope.deinit(allocator); - var context = ScopeContext{ + var context: ScopeContext = .{ .allocator = allocator, .tree = tree, .doc_scope = &document_scope, @@ -855,7 +862,7 @@ noinline fn walkContainerDecl( locToSmallLoc(offsets.nodeToLoc(tree, node_idx)), ); - var uses = std.ArrayListUnmanaged(Ast.Node.Index){}; + var uses: std.ArrayListUnmanaged(Ast.Node.Index) = .empty; defer uses.deinit(allocator); for (container_decl.ast.members) |decl| { @@ -949,7 +956,7 @@ noinline fn walkErrorSetNode( locToSmallLoc(offsets.nodeToLoc(tree, node_idx)), ); - var it = ast.ErrorSetIterator.init(tree, node_idx); + var it: ast.ErrorSetIterator = .init(tree, node_idx); while (it.next()) |identifier_token| { try scope.pushDeclaration(identifier_token, .{ .error_token = identifier_token }, .other); diff --git a/src/DocumentStore.zig b/src/DocumentStore.zig index d2d972fe8..c812142f4 100644 --- a/src/DocumentStore.zig +++ b/src/DocumentStore.zig @@ -21,9 +21,9 @@ allocator: std.mem.Allocator, config: Config, lock: std.Thread.RwLock = .{}, thread_pool: if (builtin.single_threaded) void else *std.Thread.Pool, -handles: std.StringArrayHashMapUnmanaged(*Handle) = .{}, -build_files: std.StringArrayHashMapUnmanaged(*BuildFile) = .{}, -cimports: std.AutoArrayHashMapUnmanaged(Hash, translate_c.Result) = .{}, +handles: std.StringArrayHashMapUnmanaged(*Handle) = .empty, +build_files: std.StringArrayHashMapUnmanaged(*BuildFile) = .empty, +cimports: std.AutoArrayHashMapUnmanaged(Hash, translate_c.Result) = .empty, diagnostics_collection: *DiagnosticsCollection, pub const Uri = []const u8; @@ -34,7 +34,7 @@ pub const Hash = [Hasher.mac_length]u8; pub const max_document_size = std.math.maxInt(u32); pub fn computeHash(bytes: []const u8) Hash { - var hasher: Hasher = Hasher.init(&[_]u8{0} ** Hasher.key_length); + var hasher: Hasher = .init(&@splat(0)); hasher.update(bytes); var hash: Hash = undefined; hasher.final(&hash); @@ -89,7 +89,7 @@ pub const BuildFile = struct { /// Usage example: /// ```zig - /// const package_uris = std.ArrayListUnmanaged([]const u8){}; + /// const package_uris: std.ArrayListUnmanaged([]const u8) = .empty; /// defer { /// for (package_uris) |uri| allocator.free(uri); /// package_uris.deinit(allocator); @@ -116,7 +116,7 @@ pub const BuildFile = struct { /// Usage example: /// ```zig - /// const include_paths = std.ArrayListUnmanaged([]u8){}; + /// const include_paths: std.ArrayListUnmanaged([]u8) = .empty; /// defer { /// for (include_paths) |path| allocator.free(path); /// include_paths.deinit(allocator); @@ -177,14 +177,14 @@ pub const Handle = struct { version: u32 = 0, tree: Ast, /// Contains one entry for every import in the document - import_uris: std.ArrayListUnmanaged(Uri) = .{}, + import_uris: std.ArrayListUnmanaged(Uri) = .empty, /// Contains one entry for every cimport in the document - cimports: std.MultiArrayList(CImportHandle) = .{}, + cimports: std.MultiArrayList(CImportHandle) = .empty, /// private field impl: struct { /// @bitCast from/to `Status` - status: std.atomic.Value(u32) = std.atomic.Value(u32).init(@bitCast(Status{})), + status: std.atomic.Value(u32) = .init(@bitCast(Status{})), /// TODO can we avoid storing one allocator per Handle? allocator: std.mem.Allocator, @@ -417,7 +417,7 @@ pub const Handle = struct { defer self.impl.condition.broadcast(); self.impl.document_scope = blk: { - var document_scope = try DocumentScope.init(self.impl.allocator, self.tree); + var document_scope: DocumentScope = try .init(self.impl.allocator, self.tree); errdefer document_scope.deinit(self.impl.allocator); // remove unused capacity @@ -536,7 +536,7 @@ pub const Handle = struct { const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - const new_status = Handle.Status{ + const new_status: Handle.Status = .{ .open = self.getStatus().open, }; @@ -554,8 +554,8 @@ pub const Handle = struct { var old_zir = if (old_status.has_zir) self.impl.zir else null; self.tree = new_tree; - self.import_uris = .{}; - self.cimports = .{}; + self.import_uris = .empty; + self.cimports = .empty; self.impl.document_scope = undefined; self.impl.zir = undefined; @@ -853,12 +853,12 @@ fn garbageCollectionImports(self: *DocumentStore) error{OutOfMemory}!void { const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var arena = std.heap.ArenaAllocator.init(self.allocator); + var arena: std.heap.ArenaAllocator = .init(self.allocator); defer arena.deinit(); - var reachable = try std.DynamicBitSetUnmanaged.initEmpty(arena.allocator(), self.handles.count()); + var reachable: std.DynamicBitSetUnmanaged = try .initEmpty(arena.allocator(), self.handles.count()); - var queue = std.ArrayListUnmanaged(Uri){}; + var queue: std.ArrayListUnmanaged(Uri) = .empty; for (self.handles.values(), 0..) |handle, handle_index| { if (!handle.getStatus().open) continue; @@ -899,7 +899,7 @@ fn garbageCollectionCImports(self: *DocumentStore) error{OutOfMemory}!void { if (self.cimports.count() == 0) return; - var reachable = try std.DynamicBitSetUnmanaged.initEmpty(self.allocator, self.cimports.count()); + var reachable: std.DynamicBitSetUnmanaged = try .initEmpty(self.allocator, self.cimports.count()); defer reachable.deinit(self.allocator); for (self.handles.values()) |handle| { @@ -934,7 +934,7 @@ fn garbageCollectionBuildFiles(self: *DocumentStore) error{OutOfMemory}!void { if (self.build_files.count() == 0) return; - var reachable = try std.DynamicBitSetUnmanaged.initEmpty(self.allocator, self.build_files.count()); + var reachable: std.DynamicBitSetUnmanaged = try .initEmpty(self.allocator, self.build_files.count()); defer reachable.deinit(self.allocator); for (self.handles.values()) |handle| { @@ -1004,7 +1004,7 @@ fn prepareBuildRunnerArgs(self: *DocumentStore, build_file_uri: []const u8) ![][ self.config.zig_exe_path.?, "build", "--build-runner", self.config.build_runner_path.?, }; - var args = try std.ArrayListUnmanaged([]const u8).initCapacity(self.allocator, base_args.len); + var args: std.ArrayListUnmanaged([]const u8) = try .initCapacity(self.allocator, base_args.len); errdefer { for (args.items) |arg| self.allocator.free(arg); args.deinit(self.allocator); @@ -1073,7 +1073,7 @@ fn loadBuildConfiguration(self: *DocumentStore, build_file_uri: Uri) !std.json.P else => return error.RunFailed, } - const parse_options = std.json.ParseOptions{ + const parse_options: std.json.ParseOptions = .{ // We ignore unknown fields so people can roll // their own build runners in libraries with // the only requirement being general adherence @@ -1110,7 +1110,7 @@ fn buildDotZigExists(dir_path: []const u8) bool { /// See `Handle.getAssociatedBuildFileUri`. /// Caller owns returned memory. fn collectPotentialBuildFiles(self: *DocumentStore, uri: Uri) ![]Uri { - var potential_build_files = std.ArrayListUnmanaged(Uri){}; + var potential_build_files: std.ArrayListUnmanaged(Uri) = .empty; errdefer { for (potential_build_files.items) |build_file_uri| self.allocator.free(build_file_uri); potential_build_files.deinit(self.allocator); @@ -1190,10 +1190,10 @@ fn uriAssociatedWithBuild( const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var checked_uris = std.StringHashMapUnmanaged(void){}; + var checked_uris: std.StringHashMapUnmanaged(void) = .empty; defer checked_uris.deinit(self.allocator); - var package_uris = std.ArrayListUnmanaged(Uri){}; + var package_uris: std.ArrayListUnmanaged(Uri) = .empty; defer { for (package_uris.items) |package_uri| self.allocator.free(package_uri); package_uris.deinit(self.allocator); @@ -1250,7 +1250,7 @@ fn createDocument(self: *DocumentStore, uri: Uri, text: [:0]const u8, open: bool const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var handle = try Handle.init(self.allocator, uri, text); + var handle: Handle = try .init(self.allocator, uri, text); errdefer handle.deinit(); _ = handle.setOpen(open); @@ -1267,7 +1267,7 @@ fn createDocument(self: *DocumentStore, uri: Uri, text: [:0]const u8, open: bool self.allocator.free(potential_build_files); } - var has_been_checked = try std.DynamicBitSetUnmanaged.initEmpty(self.allocator, potential_build_files.len); + var has_been_checked: std.DynamicBitSetUnmanaged = try .initEmpty(self.allocator, potential_build_files.len); errdefer has_been_checked.deinit(self.allocator); handle.impl.associated_build_file = .{ .unresolved = .{ @@ -1361,7 +1361,7 @@ fn collectCIncludes(allocator: std.mem.Allocator, tree: Ast) error{OutOfMemory}! const cimport_nodes = try analysis.collectCImportNodes(allocator, tree); defer allocator.free(cimport_nodes); - var sources = std.MultiArrayList(CImportHandle){}; + var sources: std.MultiArrayList(CImportHandle) = .empty; try sources.ensureTotalCapacity(allocator, cimport_nodes.len); errdefer { for (sources.items(.source)) |source| { @@ -1450,7 +1450,7 @@ pub fn collectIncludeDirs( handle: *Handle, include_dirs: *std.ArrayListUnmanaged([]const u8), ) !bool { - var arena_allocator = std.heap.ArenaAllocator.init(allocator); + var arena_allocator: std.heap.ArenaAllocator = .init(allocator); defer arena_allocator.deinit(); const target_info: std.Target = .{ @@ -1464,7 +1464,7 @@ pub fn collectIncludeDirs( .ofmt = comptime std.Target.ObjectFormat.default(builtin.os.tag, builtin.cpu.arch), .dynamic_linker = std.Target.DynamicLinker.none, }; - const native_paths = try std.zig.system.NativePaths.detect(arena_allocator.allocator(), target_info); + const native_paths: std.zig.system.NativePaths = try .detect(arena_allocator.allocator(), target_info); try include_dirs.ensureUnusedCapacity(allocator, native_paths.include_dirs.items.len); for (native_paths.include_dirs.items) |native_include_dir| { @@ -1514,7 +1514,7 @@ pub fn resolveCImport(self: *DocumentStore, handle: *Handle, node: Ast.Node.Inde } } - var include_dirs: std.ArrayListUnmanaged([]const u8) = .{}; + var include_dirs: std.ArrayListUnmanaged([]const u8) = .empty; defer { for (include_dirs.items) |path| { self.allocator.free(path); diff --git a/src/Server.zig b/src/Server.zig index f4d9c2a52..8996da0b3 100644 --- a/src/Server.zig +++ b/src/Server.zig @@ -55,7 +55,7 @@ thread_pool: if (zig_builtin.single_threaded) void else std.Thread.Pool, wait_group: if (zig_builtin.single_threaded) void else std.Thread.WaitGroup, job_queue: std.fifo.LinearFifo(Job, .Dynamic), job_queue_lock: std.Thread.Mutex = .{}, -ip: InternPool = .{}, +ip: InternPool = undefined, /// avoid Zig deadlocking when spawning multiple `zig ast-check` processes at the same time. /// See https://github.com/ziglang/zig/issues/16369 zig_ast_check_lock: std.Thread.Mutex = .{}, @@ -65,7 +65,7 @@ zig_ast_check_lock: std.Thread.Mutex = .{}, config_arena: std.heap.ArenaAllocator.State = .{}, client_capabilities: ClientCapabilities = .{}, diagnostics_collection: DiagnosticsCollection, -workspaces: std.ArrayListUnmanaged(Workspace) = .{}, +workspaces: std.ArrayListUnmanaged(Workspace) = .empty, // Code was based off of https://github.com/andersfr/zig-lsp/blob/master/server.zig @@ -227,7 +227,7 @@ fn sendToClientInternal( extra_name: []const u8, extra: anytype, ) error{OutOfMemory}![]u8 { - var buffer = std.ArrayListUnmanaged(u8){}; + var buffer: std.ArrayListUnmanaged(u8) = .empty; errdefer buffer.deinit(server.allocator); var writer = buffer.writer(server.allocator); try writer.writeAll( @@ -313,8 +313,8 @@ fn showMessage( } } -fn initAnalyser(server: *Server, handle: ?*DocumentStore.Handle) Analyser { - return Analyser.init( +pub fn initAnalyser(server: *Server, handle: ?*DocumentStore.Handle) Analyser { + return .init( server.allocator, &server.document_store, &server.ip, @@ -344,12 +344,12 @@ pub fn getAutofixMode(server: *Server) enum { /// caller owns returned memory. fn autofix(server: *Server, arena: std.mem.Allocator, handle: *DocumentStore.Handle) error{OutOfMemory}!std.ArrayListUnmanaged(types.TextEdit) { - if (handle.tree.errors.len != 0) return .{}; - if (handle.tree.mode == .zon) return .{}; + if (handle.tree.errors.len != 0) return .empty; + if (handle.tree.mode == .zon) return .empty; var error_bundle = try diagnostics_gen.getAstCheckDiagnostics(server, handle); defer error_bundle.deinit(server.allocator); - if (error_bundle.errorMessageCount() == 0) return .{}; + if (error_bundle.errorMessageCount() == 0) return .empty; var analyser = server.initAnalyser(handle); defer analyser.deinit(); @@ -359,15 +359,15 @@ fn autofix(server: *Server, arena: std.mem.Allocator, handle: *DocumentStore.Han .analyser = &analyser, .handle = handle, .offset_encoding = server.offset_encoding, - .only_kinds = std.EnumSet(std.meta.Tag(types.CodeActionKind)).init(.{ + .only_kinds = .init(.{ .@"source.fixAll" = true, }), }; - var actions: std.ArrayListUnmanaged(types.CodeAction) = .{}; + var actions: std.ArrayListUnmanaged(types.CodeAction) = .empty; try builder.generateCodeAction(error_bundle, &actions); - var text_edits: std.ArrayListUnmanaged(types.TextEdit) = .{}; + var text_edits: std.ArrayListUnmanaged(types.TextEdit) = .empty; for (actions.items) |action| { std.debug.assert(action.kind != null); std.debug.assert(action.kind.? == .@"source.fixAll"); @@ -737,7 +737,7 @@ fn handleConfiguration(server: *Server, json: std.json.Value) error{OutOfMemory} }, }; - var arena_allocator = std.heap.ArenaAllocator.init(server.allocator); + var arena_allocator: std.heap.ArenaAllocator = .init(server.allocator); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); @@ -1343,7 +1343,7 @@ fn resolveConfiguration( const build_runner_hash = get_hash: { const Hasher = std.crypto.auth.siphash.SipHash128(1, 3); - var hasher: Hasher = Hasher.init(&[_]u8{0} ** Hasher.key_length); + var hasher: Hasher = .init(&@splat(0)); hasher.update(build_runner_source); hasher.update(build_runner_config_source); break :get_hash hasher.finalResult(); @@ -1753,7 +1753,7 @@ fn codeActionHandler(server: *Server, arena: std.mem.Allocator, request: types.C defer analyser.deinit(); const only_kinds = if (request.context.only) |kinds| blk: { - var set = std.EnumSet(std.meta.Tag(types.CodeActionKind)).initEmpty(); + var set: std.EnumSet(std.meta.Tag(types.CodeActionKind)) = .initEmpty(); for (kinds) |kind| { set.setPresent(kind, true); } @@ -1768,7 +1768,7 @@ fn codeActionHandler(server: *Server, arena: std.mem.Allocator, request: types.C .only_kinds = only_kinds, }; - var actions: std.ArrayListUnmanaged(types.CodeAction) = .{}; + var actions: std.ArrayListUnmanaged(types.CodeAction) = .empty; try builder.generateCodeAction(error_bundle, &actions); try builder.generateCodeActionsInRange(request.range, &actions); @@ -1890,11 +1890,11 @@ pub fn create(allocator: std.mem.Allocator) !*Server { .config = .{}, .document_store = .{ .allocator = allocator, - .config = DocumentStore.Config.fromMainConfig(Config{}), + .config = .fromMainConfig(Config{}), .thread_pool = if (zig_builtin.single_threaded) {} else undefined, // set below .diagnostics_collection = &server.diagnostics_collection, }, - .job_queue = std.fifo.LinearFifo(Job, .Dynamic).init(allocator), + .job_queue = .init(allocator), .thread_pool = undefined, // set below .wait_group = if (zig_builtin.single_threaded) {} else .{}, .diagnostics_collection = .{ .allocator = allocator }, @@ -2086,7 +2086,7 @@ fn processMessage(server: *Server, message: Message) Error!?[]u8 { try server.validateMessage(message); - var arena_allocator = std.heap.ArenaAllocator.init(server.allocator); + var arena_allocator: std.heap.ArenaAllocator = .init(server.allocator); defer arena_allocator.deinit(); switch (message) { diff --git a/src/analyser/InternPool.zig b/src/analyser/InternPool.zig index 147f67b24..0ad5047df 100644 --- a/src/analyser/InternPool.zig +++ b/src/analyser/InternPool.zig @@ -1,18 +1,18 @@ //! Based on src/InternPool.zig from the zig codebase //! https://github.com/ziglang/zig/blob/master/src/InternPool.zig -map: std.AutoArrayHashMapUnmanaged(void, void) = .{}, -items: std.MultiArrayList(Item) = .{}, -extra: std.ArrayListUnmanaged(u32) = .{}, -string_pool: StringPool = .{}, -lock: RwLock = .{}, +map: std.AutoArrayHashMapUnmanaged(void, void), +items: std.MultiArrayList(Item), +extra: std.ArrayListUnmanaged(u32), +string_pool: StringPool, +lock: RwLock, -limbs: std.ArrayListUnmanaged(usize) = .{}, +limbs: std.ArrayListUnmanaged(usize), -decls: std.SegmentedList(InternPool.Decl, 0) = .{}, -structs: std.SegmentedList(InternPool.Struct, 0) = .{}, -enums: std.SegmentedList(InternPool.Enum, 0) = .{}, -unions: std.SegmentedList(InternPool.Union, 0) = .{}, +decls: std.SegmentedList(InternPool.Decl, 0), +structs: std.SegmentedList(InternPool.Struct, 0), +enums: std.SegmentedList(InternPool.Enum, 0), +unions: std.SegmentedList(InternPool.Union, 0), const InternPool = @This(); const std = @import("std"); @@ -116,11 +116,11 @@ pub const Key = union(enum) { pub const Function = struct { args: Index.Slice, /// zig only lets the first 32 arguments be `comptime` - args_is_comptime: std.StaticBitSet(32) = std.StaticBitSet(32).initEmpty(), + args_is_comptime: std.StaticBitSet(32) = .initEmpty(), /// zig only lets the first 32 arguments be generic - args_is_generic: std.StaticBitSet(32) = std.StaticBitSet(32).initEmpty(), + args_is_generic: std.StaticBitSet(32) = .initEmpty(), /// zig only lets the first 32 arguments be `noalias` - args_is_noalias: std.StaticBitSet(32) = std.StaticBitSet(32).initEmpty(), + args_is_noalias: std.StaticBitSet(32) = .initEmpty(), return_type: Index, flags: Flags = .{}, @@ -292,7 +292,7 @@ pub const Key = union(enum) { } pub fn hash64(key: Key, ip: *InternPool) u64 { - var hasher = std.hash.Wyhash.init(0); + var hasher: std.hash.Wyhash = .init(0); key.hashWithHasher(&hasher, ip); return hasher.final(); } @@ -1034,7 +1034,18 @@ pub const Union = struct { }; pub fn init(gpa: Allocator) Allocator.Error!InternPool { - var ip: InternPool = .{}; + var ip: InternPool = .{ + .map = .empty, + .items = .empty, + .extra = .empty, + .string_pool = .empty, + .lock = .{}, + .limbs = .empty, + .decls = .{}, + .structs = .{}, + .enums = .{}, + .unions = .{}, + }; errdefer ip.deinit(gpa); const items = [_]struct { index: Index, key: Key }{ @@ -1142,7 +1153,7 @@ pub fn init(gpa: Allocator) Allocator.Error!InternPool { for (items, 0..) |item, i| { assert(@intFromEnum(item.index) == i); if (builtin.is_test or builtin.mode == .Debug) { - var failing_allocator = std.testing.FailingAllocator.init(undefined, .{ + var failing_allocator: std.testing.FailingAllocator = .init(undefined, .{ .fail_index = 0, .resize_fail_index = 0, }); @@ -1854,7 +1865,7 @@ fn intFitsInType( .undefined_value, .unknown_value => return true, inline .int_i64_value, .int_u64_value => |value| { var buffer: [std.math.big.int.calcTwosCompLimbCount(64)]std.math.big.Limb = undefined; - var big_int = std.math.big.int.Mutable.init(&buffer, value.int); + var big_int: std.math.big.int.Mutable = .init(&buffer, value.int); return big_int.toConst().fitsInTwosComp(info.signedness, info.bits); }, .int_big_value => |int| return int.getConst(ip).fitsInTwosComp(info.signedness, info.bits), @@ -1901,7 +1912,7 @@ pub fn resolvePeerTypes(ip: *InternPool, gpa: Allocator, types: []const Index, t else => {}, } - var arena_allocator = std.heap.ArenaAllocator.init(gpa); + var arena_allocator: std.heap.ArenaAllocator = .init(gpa); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); @@ -2668,7 +2679,7 @@ fn coerceInMemoryAllowedErrorSets( const src_set_names = try ip.indexToKey(src_ty).error_set_type.names.dupe(gpa, ip); defer gpa.free(src_set_names); - var missing_error_buf = std.ArrayListUnmanaged(String){}; + var missing_error_buf: std.ArrayListUnmanaged(String) = .empty; defer missing_error_buf.deinit(gpa); for (src_set_names) |name| { @@ -3129,13 +3140,18 @@ pub fn isUnknown(ip: *InternPool, index: Index) bool { } pub fn isUnknownDeep(ip: *InternPool, gpa: Allocator, index: Index) Allocator.Error!bool { - var set = std.AutoHashMap(Index, void).init(gpa); - defer set.deinit(); - return try ip.isUnknownDeepInternal(index, &set); + var set: std.AutoHashMapUnmanaged(Index, void) = .empty; + defer set.deinit(gpa); + return try ip.isUnknownDeepInternal(index, gpa, &set); } -fn isUnknownDeepInternal(ip: *InternPool, index: Index, set: *std.AutoHashMap(Index, void)) Allocator.Error!bool { - const gop = try set.getOrPut(index); +fn isUnknownDeepInternal( + ip: *InternPool, + index: Index, + gpa: Allocator, + set: *std.AutoHashMapUnmanaged(Index, void), +) Allocator.Error!bool { + const gop = try set.getOrPut(gpa, index); if (gop.found_existing) return false; return switch (ip.indexToKey(index)) { .simple_type => |simple| switch (simple) { @@ -3146,31 +3162,31 @@ fn isUnknownDeepInternal(ip: *InternPool, index: Index, set: *std.AutoHashMap(In .int_type => false, .pointer_type => |pointer_info| { - if (try ip.isUnknownDeepInternal(pointer_info.elem_type, set)) return true; - if (pointer_info.sentinel != .none and try ip.isUnknownDeepInternal(pointer_info.sentinel, set)) return true; + if (try ip.isUnknownDeepInternal(pointer_info.elem_type, gpa, set)) return true; + if (pointer_info.sentinel != .none and try ip.isUnknownDeepInternal(pointer_info.sentinel, gpa, set)) return true; return false; }, .array_type => |array_info| { - if (try ip.isUnknownDeepInternal(array_info.child, set)) return true; - if (array_info.sentinel != .none and try ip.isUnknownDeepInternal(array_info.sentinel, set)) return true; + if (try ip.isUnknownDeepInternal(array_info.child, gpa, set)) return true; + if (array_info.sentinel != .none and try ip.isUnknownDeepInternal(array_info.sentinel, gpa, set)) return true; return false; }, .struct_type => |struct_index| { const struct_info = ip.getStruct(struct_index); for (struct_info.fields.values()) |field| { - if (try ip.isUnknownDeepInternal(field.ty, set)) return true; - if (field.default_value != .none and try ip.isUnknownDeepInternal(field.default_value, set)) return true; + if (try ip.isUnknownDeepInternal(field.ty, gpa, set)) return true; + if (field.default_value != .none and try ip.isUnknownDeepInternal(field.default_value, gpa, set)) return true; } // TODO namespace return false; }, - .optional_type => |optional_info| try ip.isUnknownDeepInternal(optional_info.payload_type, set), - .error_union_type => |error_union_info| try ip.isUnknownDeepInternal(error_union_info.payload_type, set), + .optional_type => |optional_info| try ip.isUnknownDeepInternal(optional_info.payload_type, gpa, set), + .error_union_type => |error_union_info| try ip.isUnknownDeepInternal(error_union_info.payload_type, gpa, set), .error_set_type => false, .enum_type => |enum_index| { const enum_info = ip.getEnum(enum_index); for (enum_info.values.keys()) |val| { - if (try ip.isUnknownDeepInternal(val, set)) return true; + if (try ip.isUnknownDeepInternal(val, gpa, set)) return true; } // TODO namespace return false; @@ -3178,15 +3194,15 @@ fn isUnknownDeepInternal(ip: *InternPool, index: Index, set: *std.AutoHashMap(In .function_type => |function_info| { for (0..function_info.args.len) |i| { const arg_ty = function_info.args.at(@intCast(i), ip); - if (try ip.isUnknownDeepInternal(arg_ty, set)) return true; + if (try ip.isUnknownDeepInternal(arg_ty, gpa, set)) return true; } - if (try ip.isUnknownDeepInternal(function_info.return_type, set)) return true; + if (try ip.isUnknownDeepInternal(function_info.return_type, gpa, set)) return true; return false; }, .union_type => |union_index| { const union_info = ip.getUnion(union_index); for (union_info.fields.values()) |field| { - if (try ip.isUnknownDeepInternal(field.ty, set)) return true; + if (try ip.isUnknownDeepInternal(field.ty, gpa, set)) return true; } // TODO namespace return false; @@ -3197,13 +3213,13 @@ fn isUnknownDeepInternal(ip: *InternPool, index: Index, set: *std.AutoHashMap(In for (0..tuple_info.types.len) |i| { const ty = tuple_info.types.at(@intCast(i), ip); const val = tuple_info.values.at(@intCast(i), ip); - if (try ip.isUnknownDeepInternal(ty, set)) return true; - if (try ip.isUnknownDeepInternal(val, set)) return true; + if (try ip.isUnknownDeepInternal(ty, gpa, set)) return true; + if (try ip.isUnknownDeepInternal(val, gpa, set)) return true; } return false; }, - .vector_type => |vector_info| try ip.isUnknownDeepInternal(vector_info.child, set), - .anyframe_type => |anyframe_info| try ip.isUnknownDeepInternal(anyframe_info.child, set), + .vector_type => |vector_info| try ip.isUnknownDeepInternal(vector_info.child, gpa, set), + .anyframe_type => |anyframe_info| try ip.isUnknownDeepInternal(anyframe_info.child, gpa, set), .int_u64_value, .int_i64_value, @@ -3223,7 +3239,7 @@ fn isUnknownDeepInternal(ip: *InternPool, index: Index, set: *std.AutoHashMap(In .error_value, .null_value, .undefined_value, - => try ip.isUnknownDeepInternal(ip.typeOf(index), set), + => try ip.isUnknownDeepInternal(ip.typeOf(index), gpa, set), .unknown_value => true, }; } @@ -3449,7 +3465,7 @@ pub fn errorSetMerge(ip: *InternPool, gpa: Allocator, a_ty: Index, b_ty: Index) const b_names = try ip.indexToKey(b_ty).error_set_type.names.dupe(gpa, ip); defer gpa.free(b_names); - var set = std.AutoArrayHashMapUnmanaged(String, void){}; + var set: std.AutoArrayHashMapUnmanaged(String, void) = .empty; defer set.deinit(gpa); try set.ensureTotalCapacity(gpa, a_names.len + b_names.len); @@ -4091,7 +4107,7 @@ pub fn fmtId(ip: *InternPool, string: String) std.fmt.Formatter(formatId) { test "simple types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const null_type = try ip.get(gpa, .{ .simple_type = .null_type }); @@ -4120,7 +4136,7 @@ test "simple types" { test "int type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const i32_type = try ip.get(gpa, .{ .int_type = .{ .signedness = .signed, .bits = 32 } }); @@ -4142,7 +4158,7 @@ test "int type" { test "int value" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const unsigned_zero_value = try ip.get(gpa, .{ .int_u64_value = .{ .ty = .u64_type, .int = 0 } }); @@ -4175,12 +4191,12 @@ test "int value" { test "big int value" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); - var result = try std.math.big.int.Managed.init(gpa); + var result: std.math.big.int.Managed = try .init(gpa); defer result.deinit(); - var a = try std.math.big.int.Managed.initSet(gpa, 2); + var a: std.math.big.int.Managed = try .initSet(gpa, 2); defer a.deinit(); try result.pow(&a, 128); @@ -4204,7 +4220,7 @@ test "big int value" { test "float type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const f16_type = try ip.get(gpa, .{ .simple_type = .f16 }); @@ -4234,7 +4250,7 @@ test "float type" { test "float value" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const f16_value = try ip.get(gpa, .{ .float_16_value = 0.25 }); @@ -4380,7 +4396,7 @@ test "pointer type" { test "optional type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const i32_optional_type = try ip.get(gpa, .{ .optional_type = .{ .payload_type = .i32_type } }); @@ -4395,7 +4411,7 @@ test "optional type" { test "optional value" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const u32_optional_type = try ip.get(gpa, .{ .optional_type = .{ .payload_type = .u32_type } }); @@ -4409,7 +4425,7 @@ test "optional value" { test "error set type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const foo_name = try ip.string_pool.getOrPutString(gpa, "foo"); @@ -4442,7 +4458,7 @@ test "error set type" { test "error union type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const empty_error_set = try ip.get(gpa, .{ .error_set_type = .{ @@ -4462,7 +4478,7 @@ test "error union type" { test "array type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const i32_3_array_type = try ip.get(gpa, .{ .array_type = .{ @@ -4484,14 +4500,14 @@ test "array type" { test "struct value" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const foo_name_index = try ip.string_pool.getOrPutString(gpa, "foo"); const bar_name_index = try ip.string_pool.getOrPutString(gpa, "bar"); const struct_index = try ip.createStruct(gpa, .{ - .fields = .{}, + .fields = .empty, .owner_decl = .none, .namespace = .none, .layout = .auto, @@ -4514,7 +4530,7 @@ test "struct value" { test "function type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"fn(i32) bool" = try ip.get(gpa, .{ .function_type = .{ @@ -4522,9 +4538,9 @@ test "function type" { .return_type = .bool_type, } }); - var args_is_comptime = std.StaticBitSet(32).initEmpty(); + var args_is_comptime: std.StaticBitSet(32) = .initEmpty(); args_is_comptime.set(0); - var args_is_noalias = std.StaticBitSet(32).initEmpty(); + var args_is_noalias: std.StaticBitSet(32) = .initEmpty(); args_is_noalias.set(1); const @"fn(comptime type, noalias i32) type" = try ip.get(gpa, .{ .function_type = .{ @@ -4543,7 +4559,7 @@ test "function type" { } }); const @"fn() align(4) callconv(.c) type" = try ip.get(gpa, .{ .function_type = .{ - .args = Index.Slice.empty, + .args = .empty, .return_type = .type_type, .flags = .{ .calling_convention = std.builtin.CallingConvention.c, @@ -4560,7 +4576,7 @@ test "function type" { test "union value" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const int_name_index = try ip.string_pool.getOrPutString(gpa, "int"); @@ -4570,7 +4586,7 @@ test "union value" { const union_index = try ip.createUnion(gpa, .{ .tag_type = .none, - .fields = .{}, + .fields = .empty, .namespace = .none, .layout = .auto, .status = .none, @@ -4598,7 +4614,7 @@ test "union value" { test "anyframe type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"anyframe->i32" = try ip.get(gpa, .{ .anyframe_type = .{ .child = .i32_type } }); @@ -4613,7 +4629,7 @@ test "anyframe type" { test "vector type" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"@Vector(2,u32)" = try ip.get(gpa, .{ .vector_type = .{ @@ -4634,7 +4650,7 @@ test "vector type" { test "Index.Slice" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); _ = try ip.getIndexSlice(gpa, &.{ .none, .c_ulonglong_type, .call_modifier_type }); @@ -4660,7 +4676,7 @@ test "Index.Slice" { test StringSlice { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const str1 = try ip.string_pool.getOrPutString(gpa, "aaa"); @@ -4692,10 +4708,10 @@ test "test thread safety of InternPool" { const gpa = std.testing.allocator; var pool: std.Thread.Pool = undefined; - try std.Thread.Pool.init(&pool, .{ .allocator = gpa }); + try pool.init(.{ .allocator = gpa }); defer pool.deinit(); - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const index_start = ip.map.count(); @@ -4721,7 +4737,7 @@ test "test thread safety of InternPool" { } }; - var wait_group = std.Thread.WaitGroup{}; + var wait_group: std.Thread.WaitGroup = .{}; for (0..pool.threads.len) |_| { wait_group.start(); try pool.spawn(funcs.do, .{ &ip, &wait_group, gpa, size }); @@ -4730,7 +4746,7 @@ test "test thread safety of InternPool" { try std.testing.expectEqual(index_start + size, ip.map.count()); - var found = try std.DynamicBitSetUnmanaged.initEmpty(gpa, size); + var found: std.DynamicBitSetUnmanaged = try .initEmpty(gpa, size); defer found.deinit(gpa); // test that every value is in the InternPool @@ -4754,11 +4770,11 @@ test "test thread safety of InternPool" { test "coerceInMemoryAllowed integers and floats" { const gpa = std.testing.allocator; - var arena_allocator = std.heap.ArenaAllocator.init(gpa); + var arena_allocator: std.heap.ArenaAllocator = .init(gpa); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); try expect(try ip.coerceInMemoryAllowed(gpa, arena, .u32_type, .u32_type, true, builtin.target) == .ok); @@ -4778,11 +4794,11 @@ test "coerceInMemoryAllowed integers and floats" { test "coerceInMemoryAllowed error set" { const gpa = std.testing.allocator; - var arena_allocator = std.heap.ArenaAllocator.init(gpa); + var arena_allocator: std.heap.ArenaAllocator = .init(gpa); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const foo_name = try ip.string_pool.getOrPutString(gpa, "foo"); @@ -4836,7 +4852,7 @@ test "coerceInMemoryAllowed error set" { test "resolvePeerTypes" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); try expect(.noreturn_type == try ip.resolvePeerTypes(gpa, &.{}, builtin.target)); @@ -4852,7 +4868,7 @@ test "resolvePeerTypes" { test "resolvePeerTypes integers and floats" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); try ip.testResolvePeerTypes(.i16_type, .i16_type, .i16_type); @@ -4937,7 +4953,7 @@ test "resolvePeerTypes integers and floats" { test "resolvePeerTypes optionals" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"?u32" = try ip.get(gpa, .{ .optional_type = .{ .payload_type = .u32_type } }); @@ -4950,7 +4966,7 @@ test "resolvePeerTypes optionals" { test "resolvePeerTypes pointers" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"*u32" = try ip.get(gpa, .{ .pointer_type = .{ .elem_type = .u32_type, .flags = .{ .size = .One } } }); @@ -5043,7 +5059,7 @@ test "resolvePeerTypes pointers" { test "resolvePeerTypes function pointers" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"*u32" = try ip.get(gpa, .{ .pointer_type = .{ @@ -5087,7 +5103,7 @@ fn testResolvePeerTypesInOrder(ip: *InternPool, lhs: Index, rhs: Index, expected test "coerce int" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"as(comptime_int, 1)" = try ip.get(gpa, .{ .int_u64_value = .{ .ty = .comptime_int_type, .int = 1 } }); @@ -5104,7 +5120,7 @@ fn testCoerce(ip: *InternPool, dest_ty: Index, inst: Index, expected: Index) !vo assert(ip.isType(dest_ty)); const gpa = std.testing.allocator; - var arena_allocator = std.heap.ArenaAllocator.init(gpa); + var arena_allocator: std.heap.ArenaAllocator = .init(gpa); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); diff --git a/src/analyser/completions.zig b/src/analyser/completions.zig index 541303cb2..8ce704cde 100644 --- a/src/analyser/completions.zig +++ b/src/analyser/completions.zig @@ -214,7 +214,7 @@ pub fn fmtFieldDetail(ip: *InternPool, field: InternPool.Struct.Field) std.fmt.F test "dotCompletions - primitives" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); try testCompletion(&ip, .bool_type, &.{}); @@ -226,7 +226,7 @@ test "dotCompletions - primitives" { test "dotCompletions - optional types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"?u32" = try ip.get(gpa, .{ .optional_type = .{ .payload_type = .u32_type } }); @@ -241,7 +241,7 @@ test "dotCompletions - optional types" { test "dotCompletions - array types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"[3]u32" = try ip.get(gpa, .{ .array_type = .{ .child = .u32_type, .len = 3 } }); @@ -265,7 +265,7 @@ test "dotCompletions - array types" { test "dotCompletions - pointer types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"*u32" = try ip.get(gpa, .{ .pointer_type = .{ @@ -317,7 +317,7 @@ test "dotCompletions - pointer types" { test "dotCompletions - single pointer indirection" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"[1]u32" = try ip.get(gpa, .{ .array_type = .{ .child = .u32_type, .len = 1 } }); @@ -357,11 +357,11 @@ fn testCompletion( expected: []const types.CompletionItem, ) !void { const gpa = std.testing.allocator; - var arena_allocator = std.heap.ArenaAllocator.init(gpa); + var arena_allocator: std.heap.ArenaAllocator = .init(gpa); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); - var completions = std.ArrayListUnmanaged(types.CompletionItem){}; + var completions: std.ArrayListUnmanaged(types.CompletionItem) = .empty; try dotCompletions(arena, &completions, ip, index); diff --git a/src/analyser/degibberish.zig b/src/analyser/degibberish.zig index 1409dc4dd..549a8bb66 100644 --- a/src/analyser/degibberish.zig +++ b/src/analyser/degibberish.zig @@ -153,7 +153,7 @@ fn formatDegibberish(data: FormatDegibberishData, comptime fmt: []const u8, opti test "degibberish - simple types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); try std.testing.expectFmt("u32", "{}", .{fmtDegibberish(&ip, .u32_type)}); @@ -162,7 +162,7 @@ test "degibberish - simple types" { test "degibberish - pointer types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); try std.testing.expectFmt("many-item pointer to u8", "{}", .{fmtDegibberish(&ip, .manyptr_u8_type)}); @@ -175,7 +175,7 @@ test "degibberish - pointer types" { test "degibberish - array types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"[3:0]u8" = try ip.get(gpa, .{ .array_type = .{ .len = 3, .child = .u8_type, .sentinel = .zero_u8 } }); @@ -187,7 +187,7 @@ test "degibberish - array types" { test "degibberish - optional types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"?u32" = try ip.get(gpa, .{ .optional_type = .{ .payload_type = .u32_type } }); @@ -197,7 +197,7 @@ test "degibberish - optional types" { test "degibberish - error union types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const foo_string = try ip.string_pool.getOrPutString(gpa, "foo"); @@ -219,7 +219,7 @@ test "degibberish - error union types" { test "degibberish - error set types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const foo_string = try ip.string_pool.getOrPutString(gpa, "foo"); @@ -236,7 +236,7 @@ test "degibberish - error set types" { test "degibberish - function types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"fn(u32, void) type" = try ip.get(gpa, .{ .function_type = .{ @@ -251,7 +251,7 @@ test "degibberish - function types" { test "degibberish - tuple types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"struct{u32, comptime_float, c_int}" = try ip.get(gpa, .{ .tuple_type = .{ @@ -264,7 +264,7 @@ test "degibberish - tuple types" { test "degibberish - vector types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"@Vector(3, u8)" = try ip.get(gpa, .{ .vector_type = .{ .len = 3, .child = .u8_type } }); @@ -276,7 +276,7 @@ test "degibberish - vector types" { test "degibberish - anyframe types" { const gpa = std.testing.allocator; - var ip = try InternPool.init(gpa); + var ip: InternPool = try .init(gpa); defer ip.deinit(gpa); const @"anyframe->u32" = try ip.get(gpa, .{ .anyframe_type = .{ .child = .u32_type } }); diff --git a/src/analyser/string_pool.zig b/src/analyser/string_pool.zig index 62390de31..6ef6e38ea 100644 --- a/src/analyser/string_pool.zig +++ b/src/analyser/string_pool.zig @@ -62,7 +62,7 @@ pub fn StringPool(comptime config: Config) type { pool.mutex.lock(); defer pool.mutex.unlock(); - const adapter = PrecomputedStringIndexAdapter{ + const adapter: PrecomputedStringIndexAdapter = .{ .bytes = &pool.bytes, .adapted_key = str, .precomputed_key_hash = precomputed_key_hash, @@ -85,7 +85,7 @@ pub fn StringPool(comptime config: Config) type { pool.mutex.lock(); defer pool.mutex.unlock(); - const adapter = PrecomputedStringIndexAdapter{ + const adapter: PrecomputedStringIndexAdapter = .{ .bytes = &pool.bytes, .adapted_key = str, .precomputed_key_hash = precomputed_key_hash, @@ -169,9 +169,15 @@ pub fn StringPool(comptime config: Config) type { return std.mem.sliceTo(string_bytes + start, 0); } - mutex: @TypeOf(mutex_init) = mutex_init, - bytes: std.ArrayListUnmanaged(u8) = .{}, - map: std.HashMapUnmanaged(u32, void, std.hash_map.StringIndexContext, std.hash_map.default_max_load_percentage) = .{}, + mutex: MutexType, + bytes: std.ArrayListUnmanaged(u8), + map: std.HashMapUnmanaged(u32, void, std.hash_map.StringIndexContext, std.hash_map.default_max_load_percentage), + + pub const empty: Pool = .{ + .mutex = .{}, + .bytes = .empty, + .map = .empty, + }; pub fn deinit(pool: *Pool, allocator: Allocator) void { pool.bytes.deinit(allocator); @@ -184,12 +190,7 @@ pub fn StringPool(comptime config: Config) type { pool.* = undefined; } - const mutex_init = if (config.MutexType) |T| - T{} - else if (config.thread_safe) - std.Thread.Mutex{} - else - DummyMutex{}; + pub const MutexType = config.MutexType orelse if (config.thread_safe) std.Thread.Mutex else DummyMutex; const DummyMutex = struct { pub fn lock(_: *@This()) void {} @@ -229,7 +230,7 @@ const PrecomputedStringIndexAdapter = struct { test StringPool { const gpa = std.testing.allocator; - var pool = StringPool(.{}){}; + var pool: StringPool(.{}) = .empty; defer pool.deinit(gpa); const str = "All Your Codebase Are Belong To Us"; @@ -246,7 +247,7 @@ test StringPool { test "StringPool - check interning" { const gpa = std.testing.allocator; - var pool = StringPool(.{ .thread_safe = false }){}; + var pool: StringPool(.{ .thread_safe = false }) = .empty; defer pool.deinit(gpa); const str = "All Your Codebase Are Belong To Us"; @@ -266,9 +267,9 @@ test "StringPool - check interning" { test "StringPool - getOrPut on existing string without allocation" { const gpa = std.testing.allocator; - var failing_gpa = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + var failing_gpa: std.testing.FailingAllocator = .init(gpa, .{ .fail_index = 0 }); - var pool = StringPool(.{}){}; + var pool: StringPool(.{}) = .empty; defer pool.deinit(gpa); const hello_string = try pool.getOrPutString(gpa, "hello"); diff --git a/src/analysis.zig b/src/analysis.zig index d27deda12..55d372bde 100644 --- a/src/analysis.zig +++ b/src/analysis.zig @@ -28,11 +28,11 @@ gpa: std.mem.Allocator, arena: std.heap.ArenaAllocator, store: *DocumentStore, ip: *InternPool, -bound_type_params: std.AutoHashMapUnmanaged(Declaration.Param, Type) = .{}, -resolved_callsites: std.AutoHashMapUnmanaged(Declaration.Param, ?Type) = .{}, -resolved_nodes: std.HashMapUnmanaged(NodeWithUri, ?Type, NodeWithUri.Context, std.hash_map.default_max_load_percentage) = .{}, +bound_type_params: std.AutoHashMapUnmanaged(Declaration.Param, Type) = .empty, +resolved_callsites: std.AutoHashMapUnmanaged(Declaration.Param, ?Type) = .empty, +resolved_nodes: std.HashMapUnmanaged(NodeWithUri, ?Type, NodeWithUri.Context, std.hash_map.default_max_load_percentage) = .empty, /// used to detect recursion -use_trail: NodeSet = .{}, +use_trail: NodeSet = .empty, collect_callsite_references: bool, /// avoid unnecessarily parsing number literals resolve_number_literal_values: bool, @@ -49,7 +49,7 @@ pub fn init( ) Analyser { return .{ .gpa = gpa, - .arena = std.heap.ArenaAllocator.init(gpa), + .arena = .init(gpa), .store = store, .ip = ip, .collect_callsite_references = true, @@ -121,15 +121,15 @@ pub fn getDocCommentTokenIndex(tokens: []const std.zig.Token.Tag, base_token: As } pub fn collectDocComments(allocator: std.mem.Allocator, tree: Ast, doc_comments: Ast.TokenIndex, container_doc: bool) error{OutOfMemory}![]const u8 { - var lines = std.ArrayList([]const u8).init(allocator); - defer lines.deinit(); + var lines: std.ArrayListUnmanaged([]const u8) = .empty; + defer lines.deinit(allocator); const tokens = tree.tokens.items(.tag); var curr_line_tok = doc_comments; while (true) : (curr_line_tok += 1) { const comm = tokens[curr_line_tok]; if ((container_doc and comm == .container_doc_comment) or (!container_doc and comm == .doc_comment)) { - try lines.append(tree.tokenSlice(curr_line_tok)[3..]); + try lines.append(allocator, tree.tokenSlice(curr_line_tok)[3..]); } else break; } @@ -329,7 +329,7 @@ pub fn isInstanceCall( std.debug.assert(!func_ty.is_type_val); if (call_handle.tree.nodes.items(.tag)[call.ast.fn_expr] != .field_access) return false; - const container_node = NodeWithHandle{ .node = call_handle.tree.nodes.items(.data)[call.ast.fn_expr].lhs, .handle = call_handle }; + const container_node: NodeWithHandle = .{ .node = call_handle.tree.nodes.items(.data)[call.ast.fn_expr].lhs, .handle = call_handle }; const container_ty = if (try analyser.resolveTypeOfNodeInternal(container_node)) |container_instance| container_instance.typeOf(analyser) @@ -464,7 +464,7 @@ pub fn getVariableSignature( break :end_token ast.lastToken(tree, init_node); } - var members_source = std.ArrayList(u8).init(arena); + var members_source: std.ArrayListUnmanaged(u8) = .empty; for (container_decl.ast.members) |member| { const member_line_start = offsets.lineLocUntilIndex(tree.source, offsets.tokenToIndex(tree, tree.firstToken(member))).start; @@ -476,9 +476,9 @@ pub fn getVariableSignature( => tree.source[member_line_start..offsets.tokenToLoc(tree, ast.lastToken(tree, member)).end], else => continue, }; - try members_source.append('\n'); - try members_source.appendSlice(try trimCommonIndentation(arena, member_source_indented, 4)); - try members_source.append(','); + try members_source.append(arena, '\n'); + try members_source.appendSlice(arena, try trimCommonIndentation(arena, member_source_indented, 4)); + try members_source.append(arena, ','); } if (members_source.items.len == 0) break :end_token token + offset; @@ -515,7 +515,7 @@ fn trimCommonIndentation(allocator: std.mem.Allocator, str: []const u8, preserve if (common_indent == 0) return try allocator.dupe(u8, str); const capacity = str.len - non_empty_lines * common_indent; - var output = try std.ArrayListUnmanaged(u8).initCapacity(allocator, capacity); + var output: std.ArrayListUnmanaged(u8) = try .initCapacity(allocator, capacity); std.debug.assert(capacity == output.capacity); errdefer @compileError("error would leak here"); @@ -692,7 +692,7 @@ pub fn resolveVarDeclAlias(analyser: *Analyser, node_handle: NodeWithHandle) err const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var node_trail: NodeSet = .{}; + var node_trail: NodeSet = .empty; defer node_trail.deinit(analyser.gpa); return try analyser.resolveVarDeclAliasInternal(node_handle, &node_trail); } @@ -1268,7 +1268,7 @@ fn resolveIntegerLiteral(analyser: *Analyser, comptime T: type, node_handle: Nod return analyser.ip.toInt(ip_index, T); } -const primitives = std.StaticStringMap(InternPool.Index).initComptime(.{ +const primitives: std.StaticStringMap(InternPool.Index) = .initComptime(.{ .{ "anyerror", .anyerror_type }, .{ "anyframe", .anyframe_type }, .{ "anyopaque", .anyopaque_type }, @@ -1374,7 +1374,7 @@ const FindBreaks = struct { label: ?[]const u8, allow_unlabeled: bool, allocator: std.mem.Allocator, - break_operands: std.ArrayListUnmanaged(Ast.Node.Index) = .{}, + break_operands: std.ArrayListUnmanaged(Ast.Node.Index) = .empty, fn deinit(context: *FindBreaks) void { context.break_operands.deinit(context.allocator); @@ -1428,7 +1428,7 @@ pub fn resolveTypeOfNode(analyser: *Analyser, node_handle: NodeWithHandle) error } fn resolveTypeOfNodeInternal(analyser: *Analyser, node_handle: NodeWithHandle) error{OutOfMemory}!?Type { - const node_with_uri = NodeWithUri{ + const node_with_uri: NodeWithUri = .{ .node = node_handle.node, .uri = node_handle.handle.uri, }; @@ -1525,7 +1525,7 @@ fn resolveTypeOfNodeUncached(analyser: *Analyser, node_handle: NodeWithHandle) e var buf: [1]Ast.Node.Index = undefined; const fn_proto = func_tree.fullFnProto(&buf, func_node).?; - var params = try std.ArrayListUnmanaged(Ast.full.FnProto.Param).initCapacity(analyser.arena.allocator(), fn_proto.ast.params.len); + var params: std.ArrayListUnmanaged(Ast.full.FnProto.Param) = try .initCapacity(analyser.arena.allocator(), fn_proto.ast.params.len); defer params.deinit(analyser.arena.allocator()); var it = fn_proto.iterate(&func_handle.tree); @@ -1789,7 +1789,7 @@ fn resolveTypeOfNodeUncached(analyser: *Analyser, node_handle: NodeWithHandle) e return try innermostContainer(handle, starts[tree.firstToken(node)]); } - const cast_map = std.StaticStringMap(void).initComptime(.{ + const cast_map: std.StaticStringMap(void) = .initComptime(.{ .{"@as"}, .{"@atomicLoad"}, .{"@atomicRmw"}, @@ -1844,7 +1844,7 @@ fn resolveTypeOfNodeUncached(analyser: *Analyser, node_handle: NodeWithHandle) e .data = .{ .container = .{ .handle = new_handle, - .scope = Scope.Index.root, + .scope = .root, }, }, .is_type_val = true, @@ -1860,7 +1860,7 @@ fn resolveTypeOfNodeUncached(analyser: *Analyser, node_handle: NodeWithHandle) e .data = .{ .container = .{ .handle = new_handle, - .scope = Scope.Index.root, + .scope = .root, }, }, .is_type_val = true, @@ -1978,11 +1978,11 @@ fn resolveTypeOfNodeUncached(analyser: *Analyser, node_handle: NodeWithHandle) e const extra = tree.extraData(datas[node].rhs, Ast.Node.SubRange); const cases = tree.extra_data[extra.start..extra.end]; - var either = std.ArrayListUnmanaged(Type.TypeWithDescriptor){}; + var either: std.ArrayListUnmanaged(Type.TypeWithDescriptor) = .empty; for (cases) |case| { const switch_case = tree.fullSwitchCase(case).?; - var descriptor = std.ArrayListUnmanaged(u8){}; + var descriptor: std.ArrayListUnmanaged(u8) = .empty; for (switch_case.ast.values, 0..) |values, index| { try descriptor.appendSlice(analyser.arena.allocator(), offsets.nodeToSlice(tree, values)); @@ -2210,7 +2210,7 @@ fn resolveTypeOfNodeUncached(analyser: *Analyser, node_handle: NodeWithHandle) e ); }, .big_int => |base| blk: { - var big_int = try std.math.big.int.Managed.init(analyser.gpa); + var big_int: std.math.big.int.Managed = try .init(analyser.gpa); defer big_int.deinit(); const prefix_length: usize = if (base != .decimal) 2 else 0; big_int.setString(@intFromEnum(base), bytes[prefix_length..]) catch |err| switch (err) { @@ -2403,7 +2403,7 @@ pub const Type = struct { } pub fn hash64(self: Type) u64 { - var hasher = std.hash.Wyhash.init(0); + var hasher: std.hash.Wyhash = .init(0); self.hashWithHasher(&hasher); return hasher.final(); } @@ -2559,7 +2559,7 @@ pub const Type = struct { }; const Deduplicator = std.ArrayHashMapUnmanaged(Type.Data.EitherEntry, void, DeduplicatorContext, true); - var deduplicator = Deduplicator{}; + var deduplicator: Deduplicator = .empty; defer deduplicator.deinit(arena); var has_type_val: bool = false; @@ -2587,7 +2587,7 @@ pub const Type = struct { /// Resolves possible types of a type (single for all except either) /// Drops duplicates pub fn getAllTypesWithHandles(ty: Type, arena: std.mem.Allocator) ![]const Type { - var all_types = std.ArrayListUnmanaged(Type){}; + var all_types: std.ArrayListUnmanaged(Type) = .empty; try ty.getAllTypesWithHandlesArrayList(arena, &all_types); return try all_types.toOwnedSlice(arena); } @@ -2974,7 +2974,7 @@ pub const Type = struct { return; } - var it = ast.ErrorSetIterator.init(tree, node); + var it: ast.ErrorSetIterator = .init(tree, node); var i: usize = 0; try writer.writeAll("error{"); @@ -3067,7 +3067,7 @@ pub fn instanceStdBuiltinType(analyser: *Analyser, type_name: []const u8) error{ const builtin_handle = analyser.store.getOrLoadHandle(builtin_uri) orelse return null; const builtin_root_struct_type: Type = .{ - .data = .{ .container = .{ .handle = builtin_handle, .scope = Scope.Index.root } }, + .data = .{ .container = .{ .handle = builtin_handle, .scope = .root } }, .is_type_val = true, }; @@ -3106,7 +3106,7 @@ pub fn collectCImportNodes(allocator: std.mem.Allocator, tree: Ast) error{OutOfM const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var import_nodes = std.ArrayListUnmanaged(Ast.Node.Index){}; + var import_nodes: std.ArrayListUnmanaged(Ast.Node.Index) = .empty; errdefer import_nodes.deinit(allocator); const node_tags = tree.nodes.items(.tag); @@ -3136,7 +3136,7 @@ pub const NodeWithUri = struct { const Context = struct { pub fn hash(self: @This(), item: NodeWithUri) u64 { _ = self; - var hasher = std.hash.Wyhash.init(0); + var hasher: std.hash.Wyhash = .init(0); std.hash.autoHash(&hasher, item.node); hasher.update(item.uri); return hasher.final(); @@ -3169,7 +3169,7 @@ pub fn getFieldAccessType( analyser.bound_type_params.clearRetainingCapacity(); const held_range = try analyser.arena.allocator().dupeZ(u8, offsets.locToSlice(handle.tree.source, loc)); - var tokenizer = std.zig.Tokenizer.init(held_range); + var tokenizer: std.zig.Tokenizer = .init(held_range); var current_type: ?Type = null; var do_unwrap_error_payload = false; // .keyword_try seen, ie `(try foo())` @@ -3505,7 +3505,7 @@ pub fn getPositionContext( break; } - var stack = try std.ArrayListUnmanaged(StackState).initCapacity(allocator, 8); + var stack: std.ArrayListUnmanaged(StackState) = try .initCapacity(allocator, 8); defer stack.deinit(allocator); var should_do_lookahead = lookahead; @@ -3927,7 +3927,7 @@ pub const DeclWithHandle = struct { // TODO: Set `workspace` to true; current problems // - we gather dependencies, not dependents - var possible = std.ArrayListUnmanaged(Type.TypeWithDescriptor){}; + var possible: std.ArrayListUnmanaged(Type.TypeWithDescriptor) = .empty; for (refs.items) |ref| { const handle = analyser.store.getOrLoadHandle(ref.uri).?; @@ -4858,7 +4858,7 @@ pub fn getSymbolFieldAccesses( const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var decls_with_handles = std.ArrayListUnmanaged(DeclWithHandle){}; + var decls_with_handles: std.ArrayListUnmanaged(DeclWithHandle) = .empty; if (try analyser.getFieldAccessType(handle, source_index, held_loc)) |ty| { const container_handle = try analyser.resolveDerefType(ty) orelse ty; @@ -4881,17 +4881,14 @@ pub const ReferencedType = struct { pub const Collector = struct { type_str: ?[]const u8 = null, referenced_types: *Set, - pub fn init(referenced_types: *Set) Collector { - return .{ .referenced_types = referenced_types }; - } }; - pub const Set = std.ArrayHashMap(ReferencedType, void, SetContext, true); + pub const Set = std.ArrayHashMapUnmanaged(ReferencedType, void, SetContext, true); const SetContext = struct { pub fn hash(self: @This(), item: ReferencedType) u32 { _ = self; - var hasher = std.hash.Wyhash.init(0); + var hasher: std.hash.Wyhash = .init(0); hasher.update(item.str); hasher.update(item.handle.uri); hasher.update(&std.mem.toBytes(item.token)); @@ -4934,7 +4931,7 @@ fn referencedTypesFromNodeInternal( node = call.ast.fn_expr; if (try analyser.resolveVarDeclAlias(.{ .node = node, .handle = handle })) |decl_handle| { - try collector.referenced_types.put(.{ + try collector.referenced_types.put(analyser.arena.allocator(), .{ .str = offsets.nodeToSlice(tree, node), .handle = decl_handle.handle, .token = decl_handle.nameToken(), @@ -4969,7 +4966,7 @@ fn addReferencedTypesFromNode( if (analyser.resolved_nodes.contains(.{ .node = node_handle.node, .uri = node_handle.handle.uri })) return; const ty = try analyser.resolveTypeOfNodeInternal(node_handle) orelse return; if (!ty.is_type_val) return; - var collector = ReferencedType.Collector.init(referenced_types); + var collector: ReferencedType.Collector = .{ .referenced_types = referenced_types }; try analyser.referencedTypesFromNodeInternal(node_handle, &collector); try analyser.addReferencedTypes(ty, collector); } @@ -4981,19 +4978,19 @@ fn addReferencedTypes( ) error{OutOfMemory}!void { const type_str = collector.type_str; const referenced_types = collector.referenced_types; - const allocator = referenced_types.allocator; + const arena = analyser.arena.allocator(); switch (ty.data) { - .pointer => |info| try analyser.addReferencedTypes(info.elem_ty.*, ReferencedType.Collector.init(referenced_types)), - .array => |info| try analyser.addReferencedTypes(info.elem_ty.*, ReferencedType.Collector.init(referenced_types)), - .optional => |child_ty| try analyser.addReferencedTypes(child_ty.*, ReferencedType.Collector.init(referenced_types)), + .pointer => |info| try analyser.addReferencedTypes(info.elem_ty.*, .{ .referenced_types = referenced_types }), + .array => |info| try analyser.addReferencedTypes(info.elem_ty.*, .{ .referenced_types = referenced_types }), + .optional => |child_ty| try analyser.addReferencedTypes(child_ty.*, .{ .referenced_types = referenced_types }), .error_union => |info| { if (info.error_set) |error_set| { - try analyser.addReferencedTypes(error_set.*, ReferencedType.Collector.init(referenced_types)); + try analyser.addReferencedTypes(error_set.*, .{ .referenced_types = referenced_types }); } - try analyser.addReferencedTypes(info.payload.*, ReferencedType.Collector.init(referenced_types)); + try analyser.addReferencedTypes(info.payload.*, .{ .referenced_types = referenced_types }); }, - .union_tag => |t| try analyser.addReferencedTypes(t.*, ReferencedType.Collector.init(referenced_types)), + .union_tag => |t| try analyser.addReferencedTypes(t.*, .{ .referenced_types = referenced_types }), .container => |scope_handle| { const handle = scope_handle.handle; @@ -5004,12 +5001,12 @@ fn addReferencedTypes( switch (tree.nodes.items(.tag)[node]) { .root => { - const path = URI.parse(allocator, handle.uri) catch |err| switch (err) { + const path = URI.parse(arena, handle.uri) catch |err| switch (err) { error.OutOfMemory => |e| return e, else => return, }; const str = std.fs.path.stem(path); - try referenced_types.put(.{ + try referenced_types.put(arena, .{ .str = type_str orelse str, .handle = handle, .token = tree.firstToken(node), @@ -5036,7 +5033,7 @@ fn addReferencedTypes( const token = tree.firstToken(node); if (token >= 2 and token_tags[token - 2] == .identifier and token_tags[token - 1] == .equal) { const str = tree.tokenSlice(token - 2); - try referenced_types.put(.{ + try referenced_types.put(arena, .{ .str = type_str orelse str, .handle = handle, .token = token - 2, @@ -5049,7 +5046,7 @@ fn addReferencedTypes( const func = tree.fullFnProto(&buf, function_node).?; const func_name_token = func.name_token orelse break :blk; const func_name = offsets.tokenToSlice(tree, func_name_token); - try referenced_types.put(.{ + try referenced_types.put(arena, .{ .str = type_str orelse func_name, .handle = handle, .token = func_name_token, diff --git a/src/ast.zig b/src/ast.zig index 972a26496..78c193591 100644 --- a/src/ast.zig +++ b/src/ast.zig @@ -1852,17 +1852,18 @@ pub fn iterateChildrenRecursive( /// caller owns the returned memory pub fn nodeChildrenAlloc(allocator: std.mem.Allocator, tree: Ast, node: Ast.Node.Index) error{OutOfMemory}![]Ast.Node.Index { const Context = struct { - children: *std.ArrayList(Ast.Node.Index), + allocator: std.mem.Allocator, + children: *std.ArrayListUnmanaged(Ast.Node.Index), fn callback(self: @This(), ast: Ast, child_node: Ast.Node.Index) error{OutOfMemory}!void { _ = ast; if (child_node == 0) return; - try self.children.append(child_node); + try self.children.append(self.allocator, child_node); } }; - var children = std.ArrayList(Ast.Node.Index).init(allocator); + var children: std.ArrayListUnmanaged(Ast.Node.Index) = .empty; errdefer children.deinit(); - try iterateChildren(tree, node, Context{ .children = &children }, error{OutOfMemory}, Context.callback); + try iterateChildren(tree, node, Context{ .allocator = allocator, .children = &children }, error{OutOfMemory}, Context.callback); return children.toOwnedSlice(); } @@ -1871,17 +1872,18 @@ pub fn nodeChildrenAlloc(allocator: std.mem.Allocator, tree: Ast, node: Ast.Node /// caller owns the returned memory pub fn nodeChildrenRecursiveAlloc(allocator: std.mem.Allocator, tree: Ast, node: Ast.Node.Index) error{OutOfMemory}![]Ast.Node.Index { const Context = struct { - children: *std.ArrayList(Ast.Node.Index), + allocator: std.mem.Allocator, + children: *std.ArrayListUnmanaged(Ast.Node.Index), fn callback(self: @This(), ast: Ast, child_node: Ast.Node.Index) error{OutOfMemory}!void { _ = ast; if (child_node == 0) return; - try self.children.append(child_node); + try self.children.append(self.allocator, child_node); } }; - var children = std.ArrayList(Ast.Node.Index).init(allocator); + var children: std.ArrayListUnmanaged(Ast.Node.Index) = .empty; errdefer children.deinit(); - try iterateChildrenRecursive(tree, node, .{ .children = &children }, Context.callback); + try iterateChildrenRecursive(tree, node, .{ .allocator = allocator, .children = &children }, Context.callback); return children.toOwnedSlice(allocator); } @@ -1894,7 +1896,7 @@ pub fn nodesOverlappingIndex(allocator: std.mem.Allocator, tree: Ast, index: usi const Context = struct { index: usize, allocator: std.mem.Allocator, - nodes: std.ArrayListUnmanaged(Ast.Node.Index) = .{}, + nodes: std.ArrayListUnmanaged(Ast.Node.Index) = .empty, pub fn append(self: *@This(), ast: Ast, node: Ast.Node.Index) error{OutOfMemory}!void { if (node == 0) return; @@ -1919,8 +1921,8 @@ pub fn nodesAtLoc(allocator: std.mem.Allocator, tree: Ast, loc: offsets.Loc) err const Context = struct { allocator: std.mem.Allocator, - nodes: std.ArrayListUnmanaged(Ast.Node.Index) = .{}, - locs: std.ArrayListUnmanaged(offsets.Loc) = .{}, + nodes: std.ArrayListUnmanaged(Ast.Node.Index) = .empty, + locs: std.ArrayListUnmanaged(offsets.Loc) = .empty, pub fn append(self: *@This(), ast: Ast, node: Ast.Node.Index) !void { if (node == 0) return; diff --git a/src/binned_allocator.zig b/src/binned_allocator.zig index 77996c4bf..92ccf3e03 100644 --- a/src/binned_allocator.zig +++ b/src/binned_allocator.zig @@ -35,6 +35,12 @@ pub fn BinnedAllocator(comptime config: Config) type { const Self = @This(); + pub const init: Self = .{ + .backing_allocator = std.heap.page_allocator, + .bins = .{ .{}, .{}, .{}, .{}, .{} }, + .large_count = if (config.report_leaks) Counter.init(), + }; + pub fn deinit(self: *Self) void { const log = std.log.scoped(.binned_allocator); @@ -227,17 +233,18 @@ pub fn BinnedAllocator(comptime config: Config) type { } test "small allocations - free in same order" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); - var list = std.ArrayList(*u64).init(std.testing.allocator); - defer list.deinit(); + const gpa = std.testing.allocator; + var list: std.ArrayListUnmanaged(*u64) = .empty; + defer list.deinit(gpa); var i: usize = 0; while (i < 513) : (i += 1) { const ptr = try allocator.create(u64); - try list.append(ptr); + try list.append(gpa, ptr); } for (list.items) |ptr| { @@ -246,17 +253,18 @@ test "small allocations - free in same order" { } test "small allocations - free in reverse order" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); - var list = std.ArrayList(*u64).init(std.testing.allocator); - defer list.deinit(); + const gpa = std.testing.allocator; + var list: std.ArrayListUnmanaged(*u64) = .empty; + defer list.deinit(gpa); var i: usize = 0; while (i < 513) : (i += 1) { const ptr = try allocator.create(u64); - try list.append(ptr); + try list.append(gpa, ptr); } while (list.popOrNull()) |ptr| { @@ -265,7 +273,7 @@ test "small allocations - free in reverse order" { } test "small allocations - alloc free alloc" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -276,7 +284,7 @@ test "small allocations - alloc free alloc" { } test "large allocations" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -289,7 +297,7 @@ test "large allocations" { } test "very large allocation" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -297,7 +305,7 @@ test "very large allocation" { } test "realloc" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -320,7 +328,7 @@ test "realloc" { } test "shrink" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -344,7 +352,7 @@ test "shrink" { } test "large object - grow" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -362,7 +370,7 @@ test "large object - grow" { } test "realloc small object to large object" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -379,7 +387,7 @@ test "realloc small object to large object" { } test "shrink large object to large object" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -404,7 +412,7 @@ test "shrink large object to large object" { } test "shrink large object to large object with larger alignment" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -423,9 +431,9 @@ test "shrink large object to large object with larger alignment" { // This loop allocates until we find a page that is not aligned to the big // alignment. Then we shrink the allocation after the loop, but increase the // alignment to the higher one, that we know will force it to realloc. - var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator); + var stuff_to_free: std.ArrayListUnmanaged([]align(16) u8) = .empty; while (std.mem.isAligned(@intFromPtr(slice.ptr), big_alignment)) { - try stuff_to_free.append(slice); + try stuff_to_free.append(debug_allocator, slice); slice = try allocator.alignedAlloc(u8, 16, alloc_size); } while (stuff_to_free.popOrNull()) |item| { @@ -440,7 +448,7 @@ test "shrink large object to large object with larger alignment" { } test "realloc large object to small object" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -455,7 +463,7 @@ test "realloc large object to small object" { } test "non-page-allocator backing allocator" { - var binned = BinnedAllocator(.{}){ .backing_allocator = std.testing.allocator }; + var binned: BinnedAllocator(.{}) = .{ .backing_allocator = std.testing.allocator }; defer binned.deinit(); const allocator = binned.allocator(); @@ -464,7 +472,7 @@ test "non-page-allocator backing allocator" { } test "realloc large object to larger alignment" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -480,9 +488,9 @@ test "realloc large object to larger alignment" { else => 8192, }; // This loop allocates until we find a page that is not aligned to the big alignment. - var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator); + var stuff_to_free: std.ArrayListUnmanaged([]align(16) u8) = .{}; while (std.mem.isAligned(@intFromPtr(slice.ptr), big_alignment)) { - try stuff_to_free.append(slice); + try stuff_to_free.append(debug_allocator, slice); slice = try allocator.alignedAlloc(u8, 16, 8192 + 50); } while (stuff_to_free.popOrNull()) |item| { @@ -505,7 +513,7 @@ test "realloc large object to larger alignment" { } test "large object does not shrink to small" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); @@ -516,7 +524,7 @@ test "large object does not shrink to small" { } test "objects of size 1024 and 2048" { - var binned = BinnedAllocator(.{}){}; + var binned: BinnedAllocator(.{}) = .{}; defer binned.deinit(); const allocator = binned.allocator(); diff --git a/src/configuration.zig b/src/configuration.zig index 2e2d4986d..6c08af9ee 100644 --- a/src/configuration.zig +++ b/src/configuration.zig @@ -58,7 +58,7 @@ pub const LoadConfigResult = union(enum) { pub fn toMessage(self: @This(), allocator: std.mem.Allocator) error{OutOfMemory}!?[]u8 { const error_bundle = self.error_bundle orelse return null; - var msg: std.ArrayListUnmanaged(u8) = .{}; + var msg: std.ArrayListUnmanaged(u8) = .empty; errdefer msg.deinit(allocator); error_bundle.renderToWriter(.{ .ttyconf = .no_color }, msg.writer(allocator)) catch |err| switch (err) { error.OutOfMemory => |e| return e, @@ -97,13 +97,13 @@ pub fn loadFromFile(allocator: std.mem.Allocator, file_path: []const u8) error{O }; defer allocator.free(file_buf); - const parse_options = std.json.ParseOptions{ + const parse_options: std.json.ParseOptions = .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }; var parse_diagnostics: std.json.Diagnostics = .{}; - var scanner = std.json.Scanner.initCompleteInput(allocator, file_buf); + var scanner: std.json.Scanner = .initCompleteInput(allocator, file_buf); defer scanner.deinit(); scanner.enableDiagnostics(&parse_diagnostics); diff --git a/src/debug.zig b/src/debug.zig index ecc7f9e96..5b6794521 100644 --- a/src/debug.zig +++ b/src/debug.zig @@ -84,9 +84,9 @@ pub const FailingAllocator = struct { /// `likelihood == 0` means that every allocation will fail /// `likelihood == std.math.intMax(u32)` means that no allocation will be forced to fail pub fn init(internal_allocator: std.mem.Allocator, likelihood: u32) FailingAllocator { - return FailingAllocator{ + return .{ .internal_allocator = internal_allocator, - .random = std.Random.DefaultPrng.init(std.crypto.random.int(u64)), + .random = .init(std.crypto.random.int(u64)), .likelihood = likelihood, }; } diff --git a/src/diff.zig b/src/diff.zig index 66a44800b..f9f95bd34 100644 --- a/src/diff.zig +++ b/src/diff.zig @@ -21,7 +21,7 @@ pub fn edits( const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var arena = std.heap.ArenaAllocator.init(allocator); + var arena: std.heap.ArenaAllocator = .init(allocator); defer arena.deinit(); const diffs = try dmp.diff(arena.allocator(), before, after, true); @@ -34,7 +34,7 @@ pub fn edits( } } - var eds = std.ArrayListUnmanaged(types.TextEdit){}; + var eds: std.ArrayListUnmanaged(types.TextEdit) = .empty; try eds.ensureTotalCapacity(allocator, edit_count); errdefer { for (eds.items) |edit| allocator.free(edit.newText); @@ -88,7 +88,7 @@ pub fn applyContentChanges( break :blk .{ null, text }; }; - var text_array = std.ArrayListUnmanaged(u8){}; + var text_array: std.ArrayListUnmanaged(u8) = .empty; errdefer text_array.deinit(allocator); try text_array.appendSlice(allocator, last_full_text); @@ -127,7 +127,7 @@ pub fn applyTextEdits( std.mem.sort(types.TextEdit, text_edits_sortable, {}, textEditLessThan); - var final_text = std.ArrayListUnmanaged(u8){}; + var final_text: std.ArrayListUnmanaged(u8) = .empty; errdefer final_text.deinit(allocator); var last: usize = 0; diff --git a/src/features/code_actions.zig b/src/features/code_actions.zig index c5c494a10..09f9fb8ca 100644 --- a/src/features/code_actions.zig +++ b/src/features/code_actions.zig @@ -27,7 +27,7 @@ pub const Builder = struct { const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var remove_capture_actions: std.AutoHashMapUnmanaged(types.Range, void) = .{}; + var remove_capture_actions: std.AutoHashMapUnmanaged(types.Range, void) = .empty; try handleUnorganizedImport(builder, actions); @@ -155,7 +155,7 @@ pub fn generateStringLiteralCodeActions( if (!std.unicode.utf8ValidateSlice(parsed)) return; const with_slashes = try std.mem.replaceOwned(u8, builder.arena, parsed, "\n", "\n \\\\"); // Hardcoded 4 spaces - var result = try std.ArrayListUnmanaged(u8).initCapacity(builder.arena, with_slashes.len + 3); + var result: std.ArrayListUnmanaged(u8) = try .initCapacity(builder.arena, with_slashes.len + 3); result.appendSliceAssumeCapacity("\\\\"); result.appendSliceAssumeCapacity(with_slashes); result.appendAssumeCapacity('\n'); @@ -187,7 +187,7 @@ pub fn generateMultilineStringCodeActions( // collect the text in the literal const loc = offsets.tokensToLoc(builder.handle.tree, @intCast(start), @intCast(end)); - var str_escaped = try std.ArrayListUnmanaged(u8).initCapacity(builder.arena, 2 * (loc.end - loc.start)); + var str_escaped: std.ArrayListUnmanaged(u8) = try .initCapacity(builder.arena, 2 * (loc.end - loc.start)); str_escaped.appendAssumeCapacity('"'); for (start..end) |i| { std.debug.assert(token_tags[i] == .multiline_string_literal_line); @@ -586,11 +586,11 @@ fn handleUnorganizedImport(builder: *Builder, actions: *std.ArrayListUnmanaged(t const sorted_imports = try builder.arena.dupe(ImportDecl, imports); std.mem.sort(ImportDecl, sorted_imports, tree, ImportDecl.lessThan); - var edits = std.ArrayListUnmanaged(types.TextEdit){}; + var edits: std.ArrayListUnmanaged(types.TextEdit) = .empty; // add sorted imports { - var new_text = std.ArrayListUnmanaged(u8){}; + var new_text: std.ArrayListUnmanaged(u8) = .empty; var writer = new_text.writer(builder.arena); for (sorted_imports, 0..) |import_decl, i| { @@ -788,10 +788,10 @@ pub fn getImportsDecls(builder: *Builder, allocator: std.mem.Allocator) error{Ou const root_decls = tree.rootDecls(); - var skip_set = try std.DynamicBitSetUnmanaged.initEmpty(allocator, root_decls.len); + var skip_set: std.DynamicBitSetUnmanaged = try .initEmpty(allocator, root_decls.len); defer skip_set.deinit(allocator); - var imports: std.ArrayHashMapUnmanaged(ImportDecl, void, void, true) = .{}; + var imports: std.ArrayHashMapUnmanaged(ImportDecl, void, void, true) = .empty; defer imports.deinit(allocator); // iterate until no more imports are found @@ -920,7 +920,7 @@ fn createCamelcaseText(allocator: std.mem.Allocator, identifier: []const u8) ![] const num_separators = std.mem.count(u8, trimmed_identifier, "_"); const new_text_len = trimmed_identifier.len - num_separators; - var new_text = try std.ArrayListUnmanaged(u8).initCapacity(allocator, new_text_len); + var new_text: std.ArrayListUnmanaged(u8) = try .initCapacity(allocator, new_text_len); errdefer new_text.deinit(allocator); var idx: usize = 0; @@ -984,7 +984,7 @@ fn createDiscardText( identifier_name.len + "; // autofix".len + if (add_suffix_newline) 1 + indent.len else 0; - var new_text = try std.ArrayListUnmanaged(u8).initCapacity(builder.arena, new_text_len); + var new_text: std.ArrayListUnmanaged(u8) = try .initCapacity(builder.arena, new_text_len); new_text.appendAssumeCapacity('\n'); new_text.appendSliceAssumeCapacity(indent); diff --git a/src/features/completions.zig b/src/features/completions.zig index c2bcbf0ae..72e547f6f 100644 --- a/src/features/completions.zig +++ b/src/features/completions.zig @@ -103,7 +103,7 @@ fn typeToCompletion(builder: *Builder, ty: Analyser.Type) error{OutOfMemory}!voi }); }, .container => |scope_handle| { - var decls: std.ArrayListUnmanaged(Analyser.DeclWithHandle) = .{}; + var decls: std.ArrayListUnmanaged(Analyser.DeclWithHandle) = .empty; try builder.analyser.collectDeclarationsOfContainer(scope_handle, builder.orig_handle, !ty.is_type_val, &decls); for (decls.items) |decl_with_handle| { @@ -155,7 +155,7 @@ fn declToCompletion(builder: *Builder, decl_handle: Analyser.DeclWithHandle, opt if (std.mem.startsWith(u8, name, "_")) return; // TODO figuring out which declarations should be excluded could be made more complete and accurate // by translating an empty file to acquire all exclusions - const exclusions = std.StaticStringMap(void).initComptime(.{ + const exclusions: std.StaticStringMap(void) = .initComptime(.{ .{ "linux", {} }, .{ "unix", {} }, .{ "WIN32", {} }, @@ -488,8 +488,8 @@ fn prepareFunctionCompletion(builder: *Builder) PrepareFunctionCompletionResult end_index += 1; } - var insert_loc = offsets.Loc{ .start = start_index, .end = builder.source_index }; - var replace_loc = offsets.Loc{ .start = start_index, .end = end_index }; + var insert_loc: offsets.Loc = .{ .start = start_index, .end = builder.source_index }; + var replace_loc: offsets.Loc = .{ .start = start_index, .end = end_index }; var format: FunctionCompletionFormat = .only_name; @@ -558,7 +558,7 @@ fn completeGlobal(builder: *Builder) error{OutOfMemory}!void { const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var decls: std.ArrayListUnmanaged(Analyser.DeclWithHandle) = .{}; + var decls: std.ArrayListUnmanaged(Analyser.DeclWithHandle) = .empty; try builder.analyser.collectAllSymbolsAtSourceIndex(builder.orig_handle, builder.source_index, &decls); for (decls.items) |decl_with_handle| { try declToCompletion(builder, decl_with_handle, .{}); @@ -604,12 +604,12 @@ fn collectUsedMembersSet(builder: *Builder, likely: EnumLiteralContext.Likely, d switch (likely) { .struct_field, .switch_case => {}, - else => return std.BufSet.init(builder.arena), + else => return .init(builder.arena), } const tree = builder.orig_handle.tree; const token_tags = tree.tokens.items(.tag); - var used_members_set = std.BufSet.init(builder.arena); + var used_members_set: std.BufSet = .init(builder.arena); var depth: usize = 0; var i: Ast.Node.Index = @max(dot_token_index, 2); @@ -698,7 +698,7 @@ fn completeDot(builder: *Builder, loc: offsets.Loc) error{OutOfMemory}!void { /// - `.embedfile_string_literal` /// - `.string_literal` fn completeFileSystemStringLiteral(builder: *Builder, pos_context: Analyser.PositionContext) !void { - var completions: CompletionSet = .{}; + var completions: CompletionSet = .empty; const store = &builder.server.document_store; const source = builder.orig_handle.tree.source; @@ -724,7 +724,7 @@ fn completeFileSystemStringLiteral(builder: *Builder, pos_context: Analyser.Posi const completing = offsets.locToSlice(source, .{ .start = string_content_loc.start, .end = previous_separator_index orelse string_content_loc.start }); - var search_paths: std.ArrayListUnmanaged([]const u8) = .{}; + var search_paths: std.ArrayListUnmanaged([]const u8) = .empty; if (std.fs.path.isAbsolute(completing) and pos_context != .import_string_literal) { try search_paths.append(builder.arena, completing); } else if (pos_context == .cinclude_string_literal) { @@ -863,7 +863,7 @@ pub fn completionAtIndex( .arena = arena, .orig_handle = handle, .source_index = source_index, - .completions = .{}, + .completions = .empty, }; const source = handle.tree.source; @@ -974,12 +974,12 @@ fn globalSetCompletions(builder: *Builder, kind: enum { error_set, enum_set }) e const store = &builder.server.document_store; - var dependencies = std.ArrayListUnmanaged(DocumentStore.Uri){}; + var dependencies: std.ArrayListUnmanaged(DocumentStore.Uri) = .empty; try dependencies.append(builder.arena, builder.orig_handle.uri); try store.collectDependencies(builder.arena, builder.orig_handle, &dependencies); // TODO Better solution for deciding what tags to include - var result_set = CompletionSet{}; + var result_set: CompletionSet = .empty; for (dependencies.items) |uri| { // not every dependency is loaded which results in incomplete completion @@ -1073,7 +1073,7 @@ fn getEnumLiteralContext( (dot_token_index - 1); if (token_index == 0) return null; - var dot_context = EnumLiteralContext{ .likely = .enum_literal }; + var dot_context: EnumLiteralContext = .{ .likely = .enum_literal }; switch (token_tags[token_index]) { .equal => { @@ -1364,7 +1364,7 @@ fn collectContainerNodes( const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var types_with_handles = std.ArrayListUnmanaged(Analyser.Type){}; + var types_with_handles: std.ArrayListUnmanaged(Analyser.Type) = .empty; const position_context = try Analyser.getPositionContext(builder.arena, handle.tree, source_index, false); switch (position_context) { .var_access => |loc| try collectVarAccessContainerNodes(builder, handle, loc, dot_context, &types_with_handles), @@ -1528,7 +1528,7 @@ fn collectVarAccessContainerNodes( .func = func_node_handle.node, .param_index = @intCast(dot_context.fn_arg_index), } }; - const fn_param_decl_with_handle = Analyser.DeclWithHandle{ .decl = fn_param_decl, .handle = func_node_handle.handle }; + const fn_param_decl_with_handle: Analyser.DeclWithHandle = .{ .decl = fn_param_decl, .handle = func_node_handle.handle }; const param_type = try fn_param_decl_with_handle.resolveType(analyser) orelse return; try types_with_handles.append(arena, param_type); } diff --git a/src/features/diagnostics.zig b/src/features/diagnostics.zig index c375e92e3..e8b9ecadc 100644 --- a/src/features/diagnostics.zig +++ b/src/features/diagnostics.zig @@ -55,11 +55,11 @@ pub fn generateDiagnostics( } { - var arena_allocator = std.heap.ArenaAllocator.init(server.diagnostics_collection.allocator); + var arena_allocator: std.heap.ArenaAllocator = .init(server.diagnostics_collection.allocator); errdefer arena_allocator.deinit(); const arena = arena_allocator.allocator(); - var diagnostics: std.ArrayListUnmanaged(types.Diagnostic) = .{}; + var diagnostics: std.ArrayListUnmanaged(types.Diagnostic) = .empty; if (server.getAutofixMode() != .none and handle.tree.mode == .zig) { try code_actions.collectAutoDiscardDiagnostics(handle.tree, arena, &diagnostics, server.offset_encoding); @@ -322,7 +322,7 @@ fn getErrorBundleFromAstCheck( zig_ast_check_lock.lock(); defer zig_ast_check_lock.unlock(); - var process = std.process.Child.init(&.{ zig_exe_path, "ast-check", "--color", "off" }, allocator); + var process: std.process.Child = .init(&.{ zig_exe_path, "ast-check", "--color", "off" }, allocator); process.stdin_behavior = .Pipe; process.stdout_behavior = .Ignore; process.stderr_behavior = .Pipe; @@ -349,7 +349,7 @@ fn getErrorBundleFromAstCheck( if (stderr_bytes.len == 0) return .empty; var last_error_message: ?std.zig.ErrorBundle.ErrorMessage = null; - var notes: std.ArrayListUnmanaged(std.zig.ErrorBundle.MessageIndex) = .{}; + var notes: std.ArrayListUnmanaged(std.zig.ErrorBundle.MessageIndex) = .empty; defer notes.deinit(allocator); var error_bundle: std.zig.ErrorBundle.Wip = undefined; @@ -464,7 +464,7 @@ pub const BuildOnSave = struct { options.zig_lib_path, "--watch", }; - var argv = try std.ArrayListUnmanaged([]const u8).initCapacity( + var argv: std.ArrayListUnmanaged([]const u8) = try .initCapacity( options.allocator, base_args.len + options.build_on_save_args.len + @intFromBool(options.check_step_only), ); @@ -474,7 +474,7 @@ pub const BuildOnSave = struct { if (options.check_step_only) argv.appendAssumeCapacity("--check-only"); argv.appendSliceAssumeCapacity(options.build_on_save_args); - var child_process = std.process.Child.init(argv.items, options.allocator); + var child_process: std.process.Child = .init(argv.items, options.allocator); child_process.stdin_behavior = .Pipe; child_process.stdout_behavior = .Pipe; child_process.stderr_behavior = .Pipe; @@ -544,7 +544,7 @@ pub const BuildOnSave = struct { ) void { defer self.allocator.free(workspace_path); - var transport = Transport.init(.{ + var transport: Transport = .init(.{ .gpa = self.allocator, .in = self.child_process.stdout.?, .out = self.child_process.stdin.?, @@ -606,7 +606,7 @@ pub const BuildOnSave = struct { const error_bundle: std.zig.ErrorBundle = .{ .string_bytes = string_bytes, .extra = extra }; - var hasher = std.hash.Wyhash.init(0); + var hasher: std.hash.Wyhash = .init(0); hasher.update(workspace_path); std.hash.autoHash(&hasher, header.step_id); diff --git a/src/features/document_symbol.zig b/src/features/document_symbol.zig index df691921f..4d3adb9dd 100644 --- a/src/features/document_symbol.zig +++ b/src/features/document_symbol.zig @@ -61,7 +61,7 @@ fn callback(ctx: *Context, tree: Ast, node: Ast.Node.Index) error{OutOfMemory}!v .kind = kind, .loc = offsets.nodeToLoc(tree, node), .selection_loc = offsets.tokenToLoc(tree, var_decl_name_token), - .children = .{}, + .children = .empty, }; }, @@ -73,7 +73,7 @@ fn callback(ctx: *Context, tree: Ast, node: Ast.Node.Index) error{OutOfMemory}!v .kind = .Method, // there is no SymbolKind that represents a tests .loc = offsets.nodeToLoc(tree, node), .selection_loc = offsets.tokenToLoc(tree, test_name_token), - .children = .{}, + .children = .empty, }; }, @@ -88,7 +88,7 @@ fn callback(ctx: *Context, tree: Ast, node: Ast.Node.Index) error{OutOfMemory}!v .kind = .Function, .loc = offsets.nodeToLoc(tree, node), .selection_loc = offsets.tokenToLoc(tree, name_token), - .children = .{}, + .children = .empty, }; }, @@ -136,7 +136,7 @@ fn callback(ctx: *Context, tree: Ast, node: Ast.Node.Index) error{OutOfMemory}!v .kind = kind, .loc = offsets.nodeToLoc(tree, node), .selection_loc = offsets.tokenToLoc(tree, decl_name_token), - .children = .{}, + .children = .empty, }; }, .container_decl, @@ -180,13 +180,13 @@ fn convertSymbols( const tracy_zone = tracy.trace(@src()); defer tracy_zone.end(); - var symbol_buffer = std.ArrayListUnmanaged(types.DocumentSymbol){}; + var symbol_buffer: std.ArrayListUnmanaged(types.DocumentSymbol) = .empty; try symbol_buffer.ensureTotalCapacityPrecise(arena, total_symbol_count); // instead of converting every `offsets.Loc` to `types.Range` by calling `offsets.locToRange` // we instead store a mapping from source indices to their desired position, sort them by their source index // and then iterate through them which avoids having to re-iterate through the source file to find out the line number - var mappings = std.ArrayListUnmanaged(offsets.multiple.IndexToPositionMapping){}; + var mappings: std.ArrayListUnmanaged(offsets.multiple.IndexToPositionMapping) = .empty; try mappings.ensureTotalCapacityPrecise(arena, total_symbol_count * 4); const result = convertSymbolsInternal(from, &symbol_buffer, &mappings); @@ -232,7 +232,7 @@ pub fn getDocumentSymbols( tree: Ast, encoding: offsets.Encoding, ) error{OutOfMemory}![]types.DocumentSymbol { - var root_symbols = std.ArrayListUnmanaged(Symbol){}; + var root_symbols: std.ArrayListUnmanaged(Symbol) = .empty; var total_symbol_count: usize = 0; var ctx = Context{ diff --git a/src/features/folding_range.zig b/src/features/folding_range.zig index f56651310..2e21e489e 100644 --- a/src/features/folding_range.zig +++ b/src/features/folding_range.zig @@ -106,9 +106,9 @@ const Builder = struct { }; pub fn generateFoldingRanges(allocator: std.mem.Allocator, tree: Ast, encoding: offsets.Encoding) error{OutOfMemory}![]types.FoldingRange { - var builder = Builder{ + var builder: Builder = .{ .allocator = allocator, - .locations = .{}, + .locations = .empty, .tree = tree, .encoding = encoding, }; @@ -295,7 +295,7 @@ pub fn generateFoldingRanges(allocator: std.mem.Allocator, tree: Ast, encoding: } // We add opened folding regions to a stack as we go and pop one off when we find a closing brace. - var stack = std.ArrayListUnmanaged(usize){}; + var stack: std.ArrayListUnmanaged(usize) = .empty; defer stack.deinit(allocator); var i: usize = 0; diff --git a/src/features/goto.zig b/src/features/goto.zig index 9a91e2252..307c545db 100644 --- a/src/features/goto.zig +++ b/src/features/goto.zig @@ -164,7 +164,7 @@ fn gotoDefinitionFieldAccess( const name = offsets.locToSlice(handle.tree.source, name_loc); const held_loc = offsets.locMerge(loc, name_loc); const accesses = (try analyser.getSymbolFieldAccesses(arena, handle, source_index, held_loc, name)) orelse return null; - var locs = std.ArrayListUnmanaged(types.DefinitionLink){}; + var locs: std.ArrayListUnmanaged(types.DefinitionLink) = .empty; for (accesses) |access| { if (try gotoDefinitionSymbol(analyser, offsets.locToRange(handle.tree.source, name_loc, offset_encoding), access, kind, offset_encoding)) |l| @@ -199,7 +199,7 @@ fn gotoDefinitionString( arena, blk: { if (std.fs.path.isAbsolute(import_str)) break :blk import_str; - var include_dirs: std.ArrayListUnmanaged([]const u8) = .{}; + var include_dirs: std.ArrayListUnmanaged([]const u8) = .empty; _ = document_store.collectIncludeDirs(arena, handle, &include_dirs) catch |err| { log.err("failed to resolve include paths: {}", .{err}); return null; @@ -215,7 +215,7 @@ fn gotoDefinitionString( else => unreachable, }; - const target_range = types.Range{ + const target_range: types.Range = .{ .start = .{ .line = 0, .character = 0 }, .end = .{ .line = 0, .character = 0 }, }; @@ -238,12 +238,7 @@ pub fn gotoHandler( const handle = server.document_store.getHandle(request.textDocument.uri) orelse return null; if (handle.tree.mode == .zon) return null; - var analyser = Analyser.init( - server.allocator, - &server.document_store, - &server.ip, - handle, - ); + var analyser = server.initAnalyser(handle); defer analyser.deinit(); const source_index = offsets.positionToIndex(handle.tree.source, request.position, server.offset_encoding); diff --git a/src/features/hover.zig b/src/features/hover.zig index 8e6f1ae49..0a5ba46b4 100644 --- a/src/features/hover.zig +++ b/src/features/hover.zig @@ -19,7 +19,7 @@ fn hoverSymbol( decl_handle: Analyser.DeclWithHandle, markup_kind: types.MarkupKind, ) error{OutOfMemory}!?[]const u8 { - var doc_strings = std.ArrayListUnmanaged([]const u8){}; + var doc_strings: std.ArrayListUnmanaged([]const u8) = .empty; return hoverSymbolRecursive(analyser, arena, decl_handle, markup_kind, &doc_strings); } @@ -36,8 +36,8 @@ fn hoverSymbolRecursive( const handle = decl_handle.handle; const tree = handle.tree; - var type_references = Analyser.ReferencedType.Set.init(arena); - var reference_collector = Analyser.ReferencedType.Collector.init(&type_references); + var type_references: Analyser.ReferencedType.Set = .empty; + var reference_collector: Analyser.ReferencedType.Collector = .{ .referenced_types = &type_references }; if (try decl_handle.docComments(arena)) |doc| try doc_strings.append(arena, doc); @@ -144,8 +144,8 @@ fn hoverSymbolRecursive( } const referenced_types: []const Analyser.ReferencedType = type_references.keys(); - var hover_text = std.ArrayList(u8).init(arena); - const writer = hover_text.writer(); + var hover_text: std.ArrayListUnmanaged(u8) = .empty; + const writer = hover_text.writer(arena); if (markup_kind == .markdown) { for (doc_strings.items) |doc| try writer.print("{s}\n\n", .{doc}); @@ -217,7 +217,7 @@ fn hoverDefinitionBuiltin( const name = offsets.locToSlice(handle.tree.source, name_loc); - var contents: std.ArrayListUnmanaged(u8) = .{}; + var contents: std.ArrayListUnmanaged(u8) = .empty; var writer = contents.writer(arena); if (std.mem.eql(u8, name, "@cImport")) blk: { @@ -346,7 +346,7 @@ fn hoverDefinitionFieldAccess( const held_loc = offsets.locMerge(loc, name_loc); const decls = (try analyser.getSymbolFieldAccesses(arena, handle, source_index, held_loc, name)) orelse return null; - var content = try std.ArrayListUnmanaged([]const u8).initCapacity(arena, decls.len); + var content: std.ArrayListUnmanaged([]const u8) = try .initCapacity(arena, decls.len); for (decls) |decl| { content.appendAssumeCapacity(try hoverSymbol(analyser, arena, decl, markup_kind) orelse continue); diff --git a/src/features/inlay_hints.zig b/src/features/inlay_hints.zig index 09269fccb..f188e9613 100644 --- a/src/features/inlay_hints.zig +++ b/src/features/inlay_hints.zig @@ -16,9 +16,9 @@ const data = @import("version_data"); /// don't show inlay hints for builtin functions whose parameter names carry no /// meaningful information or are trivial deductible based on the builtin name. -const excluded_builtins_set = blk: { +const excluded_builtins_set: std.StaticStringMap(void) = blk: { @setEvalBranchQuota(2000); - break :blk std.StaticStringMap(void).initComptime(.{ + break :blk .initComptime(.{ .{"addrSpaceCast"}, .{"addWithOverflow"}, .{"alignCast"}, @@ -154,7 +154,7 @@ const Builder = struct { analyser: *Analyser, config: *const Config, handle: *DocumentStore.Handle, - hints: std.ArrayListUnmanaged(InlayHint) = .{}, + hints: std.ArrayListUnmanaged(InlayHint) = .empty, hover_kind: types.MarkupKind, fn appendParameterHint(self: *Builder, token_index: Ast.TokenIndex, label: []const u8, tooltip: []const u8, tooltip_noalias: bool, tooltip_comptime: bool) !void { @@ -232,7 +232,7 @@ fn writeCallHint( var buffer: [1]Ast.Node.Index = undefined; const fn_proto = fn_node.handle.tree.fullFnProto(&buffer, fn_node.node).?; - var params = try std.ArrayListUnmanaged(Ast.full.FnProto.Param).initCapacity(builder.arena, fn_proto.ast.params.len); + var params: std.ArrayListUnmanaged(Ast.full.FnProto.Param) = try .initCapacity(builder.arena, fn_proto.ast.params.len); defer params.deinit(builder.arena); var it = fn_proto.iterate(&fn_node.handle.tree); diff --git a/src/features/references.zig b/src/features/references.zig index d9108d418..eb09b7453 100644 --- a/src/features/references.zig +++ b/src/features/references.zig @@ -31,7 +31,7 @@ fn labelReferences( const first_tok = decl.decl.label.identifier; const last_tok = ast.lastToken(tree, decl.decl.label.block); - var locations = std.ArrayListUnmanaged(types.Location){}; + var locations: std.ArrayListUnmanaged(types.Location) = .empty; errdefer locations.deinit(allocator); if (include_decl) { @@ -63,7 +63,7 @@ fn labelReferences( const Builder = struct { allocator: std.mem.Allocator, - locations: std.ArrayListUnmanaged(types.Location) = .{}, + locations: std.ArrayListUnmanaged(types.Location) = .empty, /// this is the declaration we are searching for decl_handle: Analyser.DeclWithHandle, /// Whether the `decl_handle` has been added @@ -182,7 +182,7 @@ fn gatherReferences( builder: anytype, handle_behavior: enum { get, get_or_load }, ) !void { - var dependencies = std.StringArrayHashMapUnmanaged(void){}; + var dependencies: std.StringArrayHashMapUnmanaged(void) = .empty; defer { for (dependencies.keys()) |uri| { allocator.free(uri); @@ -196,7 +196,7 @@ fn gatherReferences( continue; } - var handle_dependencies = std.ArrayListUnmanaged([]const u8){}; + var handle_dependencies: std.ArrayListUnmanaged([]const u8) = .empty; defer handle_dependencies.deinit(allocator); try analyser.store.collectDependencies(allocator, handle, &handle_dependencies); @@ -290,7 +290,7 @@ pub const Callsite = struct { const CallBuilder = struct { allocator: std.mem.Allocator, - callsites: std.ArrayListUnmanaged(Callsite) = .{}, + callsites: std.ArrayListUnmanaged(Callsite) = .empty, /// this is the declaration we are searching for decl_handle: Analyser.DeclWithHandle, analyser: *Analyser, @@ -452,12 +452,7 @@ pub fn referencesHandler(server: *Server, arena: std.mem.Allocator, request: Gen const name = offsets.locToSlice(handle.tree.source, name_loc); const pos_context = try Analyser.getPositionContext(server.allocator, handle.tree, source_index, true); - var analyser = Analyser.init( - server.allocator, - &server.document_store, - &server.ip, - handle, - ); + var analyser = server.initAnalyser(handle); defer analyser.deinit(); // TODO: Make this work with branching types @@ -498,10 +493,10 @@ pub fn referencesHandler(server: *Server, arena: std.mem.Allocator, request: Gen switch (request) { .rename => |rename| { const escaped_rename = try std.fmt.allocPrint(arena, "{}", .{std.zig.fmtId(rename.newName)}); - var changes = std.StringArrayHashMapUnmanaged(std.ArrayListUnmanaged(types.TextEdit)){}; + var changes: std.StringArrayHashMapUnmanaged(std.ArrayListUnmanaged(types.TextEdit)) = .{}; for (locations.items) |loc| { - const gop = try changes.getOrPutValue(arena, loc.uri, .{}); + const gop = try changes.getOrPutValue(arena, loc.uri, .empty); try gop.value_ptr.append(arena, .{ .range = loc.range, .newText = escaped_rename, @@ -521,7 +516,7 @@ pub fn referencesHandler(server: *Server, arena: std.mem.Allocator, request: Gen }, .references => return .{ .references = locations.items }, .highlight => { - var highlights = try std.ArrayListUnmanaged(types.DocumentHighlight).initCapacity(arena, locations.items.len); + var highlights: std.ArrayListUnmanaged(types.DocumentHighlight) = try .initCapacity(arena, locations.items.len); const uri = handle.uri; for (locations.items) |loc| { if (!std.mem.eql(u8, loc.uri, uri)) continue; diff --git a/src/features/selection_range.zig b/src/features/selection_range.zig index 4444ab552..f5aab0a3e 100644 --- a/src/features/selection_range.zig +++ b/src/features/selection_range.zig @@ -22,13 +22,13 @@ pub fn generateSelectionRanges( // A faster algorithm would be to walk the tree starting from the root, // descending into the child containing the position at every step. const result = try arena.alloc(types.SelectionRange, positions.len); - var locs = try std.ArrayListUnmanaged(offsets.Loc).initCapacity(arena, 32); + var locs: std.ArrayListUnmanaged(offsets.Loc) = try .initCapacity(arena, 32); for (positions, result) |position, *out| { const index = offsets.positionToIndex(handle.tree.source, position, offset_encoding); locs.clearRetainingCapacity(); for (0..handle.tree.nodes.len, handle.tree.nodes.items(.tag)) |i, tag| { - const node = @as(Ast.Node.Index, @intCast(i)); + const node: Ast.Node.Index = @intCast(i); const loc = offsets.nodeToLoc(handle.tree, node); if (!(loc.start <= index and index <= loc.end)) continue; diff --git a/src/features/semantic_tokens.zig b/src/features/semantic_tokens.zig index 78dbc881d..1e251cb82 100644 --- a/src/features/semantic_tokens.zig +++ b/src/features/semantic_tokens.zig @@ -65,7 +65,7 @@ const Builder = struct { handle: *DocumentStore.Handle, previous_source_index: usize = 0, source_index: usize = 0, - token_buffer: std.ArrayListUnmanaged(u32) = .{}, + token_buffer: std.ArrayListUnmanaged(u32) = .empty, encoding: offsets.Encoding, limited: bool, diff --git a/src/features/signature_help.zig b/src/features/signature_help.zig index 8c832fdaa..249691f4e 100644 --- a/src/features/signature_help.zig +++ b/src/features/signature_help.zig @@ -35,7 +35,7 @@ fn fnProtoToSignatureInfo( break :blk commas + @intFromBool(has_self_param); } else commas; - var params = std.ArrayListUnmanaged(types.ParameterInformation){}; + var params: std.ArrayListUnmanaged(types.ParameterInformation) = .empty; var param_it = proto.iterate(&tree); while (ast.nextFnParam(¶m_it)) |param| { const param_comments = if (param.first_doc_comment) |dc| @@ -115,9 +115,9 @@ pub fn getSignatureInfo( }; } }; - var symbol_stack = try std.ArrayListUnmanaged(StackSymbol).initCapacity(arena, 8); + var symbol_stack: std.ArrayListUnmanaged(StackSymbol) = try .initCapacity(arena, 8); var curr_commas: u32 = 0; - var comma_stack = try std.ArrayListUnmanaged(u32).initCapacity(arena, 4); + var comma_stack: std.ArrayListUnmanaged(u32) = try .initCapacity(arena, 4); var curr_token = last_token; while (curr_token >= first_token and curr_token != 0) : (curr_token -= 1) { switch (token_tags[curr_token]) { diff --git a/src/main.zig b/src/main.zig index c1bce2c99..02be3e61d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -230,7 +230,7 @@ fn parseArgs(allocator: std.mem.Allocator) ParseArgsError!ParseArgsResult { const stdout = std.io.getStdOut().writer(); - var args_it = try std.process.ArgIterator.initWithAllocator(allocator); + var args_it: std.process.ArgIterator = try .initWithAllocator(allocator); defer args_it.deinit(); const zls_exe_path = args_it.next() orelse ""; @@ -335,16 +335,16 @@ const stack_frames = switch (zig_builtin.mode) { }; pub fn main() !u8 { - var allocator_state = if (exe_options.use_gpa) - std.heap.GeneralPurposeAllocator(.{ .stack_trace_frames = stack_frames }){} + var allocator_state: if (exe_options.use_gpa) + std.heap.GeneralPurposeAllocator(.{ .stack_trace_frames = stack_frames }) else - binned_allocator.BinnedAllocator(.{}){}; + binned_allocator.BinnedAllocator(.{}) = .init; defer _ = allocator_state.deinit(); - var tracy_state = if (tracy.enable_allocation) tracy.tracyAllocator(allocator_state.allocator()) else void{}; + var tracy_state = if (tracy.enable_allocation) tracy.tracyAllocator(allocator_state.allocator()) else {}; const inner_allocator: std.mem.Allocator = if (tracy.enable_allocation) tracy_state.allocator() else allocator_state.allocator(); - var failing_allocator_state = if (exe_options.enable_failing_allocator) zls.debug.FailingAllocator.init(inner_allocator, exe_options.enable_failing_allocator_likelihood) else void{}; + var failing_allocator_state = if (exe_options.enable_failing_allocator) zls.debug.FailingAllocator.init(inner_allocator, exe_options.enable_failing_allocator_likelihood) else {}; const allocator: std.mem.Allocator = if (exe_options.enable_failing_allocator) failing_allocator_state.allocator() else inner_allocator; const result = try parseArgs(allocator); @@ -361,7 +361,7 @@ pub fn main() !u8 { .ChildTransport = zls.lsp.TransportOverStdio, .thread_safe_read = false, .thread_safe_write = true, - }) = .{ .child_transport = zls.lsp.TransportOverStdio.init(std.io.getStdIn(), std.io.getStdOut()) }; + }) = .{ .child_transport = .init(std.io.getStdIn(), std.io.getStdOut()) }; log_transport = if (result.disable_lsp_logs) null else transport.any(); log_stderr = result.enable_stderr_logs; diff --git a/src/tools/config_gen.zig b/src/tools/config_gen.zig index 4be8a49c3..146e2fe8e 100644 --- a/src/tools/config_gen.zig +++ b/src/tools/config_gen.zig @@ -135,7 +135,7 @@ fn fmtDocs(text: []const u8) std.fmt.Formatter(formatDocs) { } fn generateConfigFile(allocator: std.mem.Allocator, config: Config, path: []const u8) (std.fs.Dir.WriteFileError || std.mem.Allocator.Error)!void { - var buffer = std.ArrayList(u8).init(allocator); + var buffer: std.ArrayList(u8) = .init(allocator); defer buffer.deinit(); const writer = buffer.writer(); @@ -171,7 +171,7 @@ fn generateConfigFile(allocator: std.mem.Allocator, config: Config, path: []cons const source_unformatted = try buffer.toOwnedSliceSentinel(0); defer allocator.free(source_unformatted); - var tree = try std.zig.Ast.parse(allocator, source_unformatted, .zig); + var tree: std.zig.Ast = try .parse(allocator, source_unformatted, .zig); defer tree.deinit(allocator); std.debug.assert(tree.errors.len == 0); @@ -190,7 +190,7 @@ fn generateSchemaFile(allocator: std.mem.Allocator, config: Config, path: []cons var buff_out = std.io.bufferedWriter(schema_file.writer()); - var schema = Schema{ .properties = .{} }; + var schema: Schema = .{ .properties = .{} }; defer schema.properties.map.deinit(allocator); try schema.properties.map.ensureTotalCapacity(allocator, @intCast(config.options.len)); @@ -446,7 +446,7 @@ const Builtin = struct { /// parses a `langref.html.in` file and extracts builtins from this section: `https://ziglang.org/documentation/master/#Builtin-Functions` /// the documentation field contains poorly formatted html fn collectBuiltinData(allocator: std.mem.Allocator, version: []const u8, langref_file: []const u8) error{OutOfMemory}![]Builtin { - var tokenizer = Tokenizer{ .buffer = langref_file }; + var tokenizer: Tokenizer = .{ .buffer = langref_file }; const State = enum { /// searching for this line: @@ -463,7 +463,7 @@ fn collectBuiltinData(allocator: std.mem.Allocator, version: []const u8, langref }; var state: State = .searching; - var builtins = std.ArrayListUnmanaged(Builtin){}; + var builtins: std.ArrayListUnmanaged(Builtin) = .empty; errdefer { for (builtins.items) |*builtin| { builtin.documentation.deinit(allocator); @@ -506,7 +506,7 @@ fn collectBuiltinData(allocator: std.mem.Allocator, version: []const u8, langref try builtins.append(allocator, .{ .name = content_name, .signature = "", - .documentation = .{}, + .documentation = .empty, }); }, .builtin_content => unreachable, @@ -782,7 +782,7 @@ fn writeMarkdownFromHtmlInternal(html: []const u8, single_line: bool, depth: u32 /// takes in a signature like this: `@intToEnum(comptime DestType: type, integer: anytype) DestType` /// and outputs its arguments: `comptime DestType: type`, `integer: anytype` fn extractArgumentsFromSignature(allocator: std.mem.Allocator, signature: []const u8) error{OutOfMemory}![][]const u8 { - var arguments = std.ArrayListUnmanaged([]const u8){}; + var arguments: std.ArrayListUnmanaged([]const u8) = .empty; defer arguments.deinit(allocator); var argument_start: usize = 0; @@ -806,7 +806,7 @@ fn extractArgumentsFromSignature(allocator: std.mem.Allocator, signature: []cons /// takes in a signature like this: `@intToEnum(comptime DestType: type, integer: anytype) DestType` /// and outputs a snippet: `@intToEnum(${1:comptime DestType: type}, ${2:integer: anytype})` fn extractSnippetFromSignature(allocator: std.mem.Allocator, signature: []const u8) error{OutOfMemory}![]const u8 { - var snippet = std.ArrayListUnmanaged(u8){}; + var snippet: std.ArrayListUnmanaged(u8) = .empty; defer snippet.deinit(allocator); var writer = snippet.writer(allocator); @@ -871,7 +871,7 @@ fn generateVersionDataFile(allocator: std.mem.Allocator, version: []const u8, ou \\ arguments: []const []const u8, \\}; \\ - \\pub const builtins = std.StaticStringMap(Builtin).initComptime(&.{ + \\pub const builtins: std.StaticStringMap(Builtin) = .initComptime(&.{ \\ ); @@ -899,7 +899,7 @@ fn generateVersionDataFile(allocator: std.mem.Allocator, version: []const u8, ou }); const html = builtin.documentation.items["".len..]; - var markdown = std.ArrayListUnmanaged(u8){}; + var markdown: std.ArrayListUnmanaged(u8) = .empty; defer markdown.deinit(allocator); try writeMarkdownFromHtml(html, markdown.writer(allocator)); @@ -941,7 +941,7 @@ fn generateVersionDataFile(allocator: std.mem.Allocator, version: []const u8, ou } pub fn main() !void { - var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; + var general_purpose_allocator: std.heap.GeneralPurposeAllocator(.{}) = .init; defer std.debug.assert(general_purpose_allocator.deinit() == .ok); const gpa = general_purpose_allocator.allocator(); diff --git a/src/tools/publish_http_form.zig b/src/tools/publish_http_form.zig index 41464dcee..e8eca6380 100644 --- a/src/tools/publish_http_form.zig +++ b/src/tools/publish_http_form.zig @@ -5,7 +5,7 @@ const std = @import("std"); pub fn main() !void { - var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); + var arena_allocator: std.heap.ArenaAllocator = .init(std.heap.page_allocator); const arena = arena_allocator.allocator(); var arg_it = try std.process.argsWithAllocator(arena); @@ -14,7 +14,7 @@ pub fn main() !void { var uri: ?std.Uri = null; var authorization: std.http.Client.Request.Headers.Value = .default; - var form_fields = std.ArrayList(FormField).init(arena); + var form_fields: std.ArrayListUnmanaged(FormField) = .empty; while (arg_it.next()) |arg| { if (std.mem.eql(u8, arg, "--user")) { @@ -44,7 +44,7 @@ pub fn main() !void { .value = try arena.dupe(u8, content), }; }; - try form_fields.append(form_field); + try form_fields.append(arena, form_field); } else if (uri == null) { uri = try std.Uri.parse(arg); } else { @@ -106,7 +106,7 @@ fn createMultiPartFormDataBody( boundary: []const u8, fields: []const FormField, ) error{OutOfMemory}![]const u8 { - var body: std.ArrayListUnmanaged(u8) = .{}; + var body: std.ArrayListUnmanaged(u8) = .empty; errdefer body.deinit(allocator); const writer = body.writer(allocator); diff --git a/src/translate_c.zig b/src/translate_c.zig index d8af55320..318302c90 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -38,7 +38,7 @@ pub fn convertCInclude(allocator: std.mem.Allocator, tree: Ast, node: Ast.Node.I std.debug.assert(ast.isBuiltinCall(tree, node)); std.debug.assert(std.mem.eql(u8, Ast.tokenSlice(tree, main_tokens[node]), "@cImport")); - var output = std.ArrayListUnmanaged(u8){}; + var output: std.ArrayListUnmanaged(u8) = .empty; errdefer output.deinit(allocator); var buffer: [2]Ast.Node.Index = undefined; @@ -167,7 +167,7 @@ pub fn translate( }; const argc = base_args.len + 2 * include_dirs.len + 1; - var argv = try std.ArrayListUnmanaged([]const u8).initCapacity(allocator, argc); + var argv: std.ArrayListUnmanaged([]const u8) = try .initCapacity(allocator, argc); defer argv.deinit(allocator); argv.appendSliceAssumeCapacity(base_args); @@ -179,7 +179,7 @@ pub fn translate( argv.appendAssumeCapacity(file_path); - var process = std.process.Child.init(argv.items, allocator); + var process: std.process.Child = .init(argv.items, allocator); process.stdin_behavior = .Pipe; process.stdout_behavior = .Pipe; process.stderr_behavior = .Ignore; @@ -195,7 +195,7 @@ pub fn translate( log.err("zig translate-c process did not terminate, error: {}", .{wait_err}); }; - var zcs = ZCSTransport.init(.{ + var zcs: ZCSTransport = .init(.{ .gpa = allocator, .in = process.stdout.?, .out = process.stdin.?, diff --git a/src/uri.zig b/src/uri.zig index e52584383..d1ae19d05 100644 --- a/src/uri.zig +++ b/src/uri.zig @@ -7,7 +7,7 @@ pub fn fromPath(allocator: std.mem.Allocator, path: []const u8) error{OutOfMemor if (path.len == 0) return try allocator.dupe(u8, "/"); const prefix = if (builtin.os.tag == .windows) "file:///" else "file://"; - var buf = try std.ArrayListUnmanaged(u8).initCapacity(allocator, prefix.len + path.len); + var buf: std.ArrayListUnmanaged(u8) = try .initCapacity(allocator, prefix.len + path.len); errdefer buf.deinit(allocator); buf.appendSliceAssumeCapacity(prefix); diff --git a/tests/ErrorBuilder.zig b/tests/ErrorBuilder.zig index 7aff19163..fb79cbc51 100644 --- a/tests/ErrorBuilder.zig +++ b/tests/ErrorBuilder.zig @@ -8,7 +8,7 @@ const offsets = zls.offsets; const ErrorBuilder = @This(); allocator: std.mem.Allocator, -files: std.StringArrayHashMapUnmanaged(File) = .{}, +files: std.StringArrayHashMapUnmanaged(File) = .empty, message_count: usize = 0, /// similar to `git diff --unified` /// show error messages with n lines of context. @@ -21,7 +21,7 @@ file_name_visibility: enum { } = .multi_file, pub fn init(allocator: std.mem.Allocator) ErrorBuilder { - return ErrorBuilder{ .allocator = allocator }; + return .{ .allocator = allocator }; } pub fn deinit(builder: *ErrorBuilder) void { @@ -283,7 +283,7 @@ fn write(context: FormatContext, writer: anytype) @TypeOf(writer).Error!void { const File = struct { source: []const u8, - messages: std.ArrayListUnmanaged(MsgItem) = .{}, + messages: std.ArrayListUnmanaged(MsgItem) = .empty, }; const MsgItem = struct { @@ -335,7 +335,7 @@ const MsgItemIterator = struct { // test ErrorBuilder { - var eb = ErrorBuilder.init(std.testing.allocator); + var eb: ErrorBuilder = .init(std.testing.allocator); defer eb.deinit(); try std.testing.expect(!eb.hasMessages()); @@ -350,7 +350,7 @@ test ErrorBuilder { } test "ErrorBuilder - write" { - var eb = ErrorBuilder.init(std.testing.allocator); + var eb: ErrorBuilder = .init(std.testing.allocator); defer eb.deinit(); try std.testing.expectFmt("", "{}", .{eb}); @@ -478,7 +478,7 @@ test "ErrorBuilder - write" { } test "ErrorBuilder - write on empty file" { - var eb = ErrorBuilder.init(std.testing.allocator); + var eb: ErrorBuilder = .init(std.testing.allocator); defer eb.deinit(); try eb.addFile("empty.zig", ""); diff --git a/tests/build_runner_check.zig b/tests/build_runner_check.zig index 37c518b7c..647a6db46 100644 --- a/tests/build_runner_check.zig +++ b/tests/build_runner_check.zig @@ -19,7 +19,7 @@ pub fn main() !u8 { defer gpa.free(actual_unsanitized); const actual = blk: { - var base_dir_buffer: std.ArrayListUnmanaged(u8) = .{}; + var base_dir_buffer: std.ArrayListUnmanaged(u8) = .empty; defer base_dir_buffer.deinit(gpa); try std.json.encodeJsonStringChars(args[3], .{}, base_dir_buffer.writer(gpa)); diff --git a/tests/context.zig b/tests/context.zig index d2ad8ec5f..ec99f97bd 100644 --- a/tests/context.zig +++ b/tests/context.zig @@ -40,7 +40,7 @@ pub const Context = struct { const config_string = try std.json.stringifyAlloc(allocator, server.config, .{ .whitespace = .indent_2 }); defer allocator.free(config_string); - var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); errdefer arena.deinit(); const duped_config = try std.json.parseFromSliceLeaky(Config, arena.allocator(), config_string, .{ .allocate = .alloc_always }); @@ -51,7 +51,7 @@ pub const Context = struct { var context: Context = .{ .server = server, - .arena = std.heap.ArenaAllocator.init(allocator), + .arena = .init(allocator), }; _ = try context.server.sendRequestSync(context.arena.allocator(), "initialize", .{ .capabilities = .{} }); @@ -84,7 +84,7 @@ pub const Context = struct { .{ self.file_id, @tagName(options.mode) }, ); - const params = types.DidOpenTextDocumentParams{ + const params: types.DidOpenTextDocumentParams = .{ .textDocument = .{ .uri = uri, .languageId = "zig", diff --git a/tests/helper.zig b/tests/helper.zig index 9a0479368..6faba7a0a 100644 --- a/tests/helper.zig +++ b/tests/helper.zig @@ -5,7 +5,7 @@ const offsets = zls.offsets; /// returns an array of all placeholder locations pub fn collectPlaceholderLocs(allocator: std.mem.Allocator, source: []const u8) ![]offsets.Loc { - var locations = std.ArrayListUnmanaged(offsets.Loc){}; + var locations: std.ArrayListUnmanaged(offsets.Loc) = .empty; errdefer locations.deinit(allocator); var source_index: usize = 0; @@ -25,7 +25,7 @@ pub fn collectPlaceholderLocs(allocator: std.mem.Allocator, source: []const u8) /// returns `source` where every placeholder is replaced with `new_name` pub fn replacePlaceholders(allocator: std.mem.Allocator, source: []const u8, new_name: []const u8) ![]const u8 { - var output = std.ArrayListUnmanaged(u8){}; + var output: std.ArrayListUnmanaged(u8) = .empty; errdefer output.deinit(allocator); var source_index: usize = 0; @@ -69,10 +69,10 @@ pub fn collectClearPlaceholders(allocator: std.mem.Allocator, source: []const u8 } pub fn collectReplacePlaceholders(allocator: std.mem.Allocator, source: []const u8, new_name: []const u8) !CollectPlaceholdersResult { - var locations = std.MultiArrayList(CollectPlaceholdersResult.LocPair){}; + var locations: std.MultiArrayList(CollectPlaceholdersResult.LocPair) = .empty; errdefer locations.deinit(allocator); - var new_source = std.ArrayListUnmanaged(u8){}; + var new_source: std.ArrayListUnmanaged(u8) = .empty; errdefer new_source.deinit(allocator); var source_index: usize = 0; diff --git a/tests/language_features/cimport.zig b/tests/language_features/cimport.zig index 018b5d688..b74d28afa 100644 --- a/tests/language_features/cimport.zig +++ b/tests/language_features/cimport.zig @@ -71,7 +71,7 @@ fn testConvertCInclude(cimport_source: []const u8, expected: []const u8) !void { const source: [:0]u8 = try std.fmt.allocPrintZ(allocator, "const c = {s};", .{cimport_source}); defer allocator.free(source); - var tree = try Ast.parse(allocator, source, .zig); + var tree: Ast = try .parse(allocator, source, .zig); defer tree.deinit(allocator); const node_tags = tree.nodes.items(.tag); @@ -106,7 +106,7 @@ fn testConvertCInclude(cimport_source: []const u8, expected: []const u8) !void { fn testTranslate(c_source: []const u8) !translate_c.Result { if (!std.process.can_spawn) return error.SkipZigTest; - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); var result = (try translate_c.translate(allocator, zls.DocumentStore.Config.fromMainConfig(ctx.server.config), &.{}, c_source)).?; diff --git a/tests/lifecycle.zig b/tests/lifecycle.zig index 90b3eb3cc..d260bf0bd 100644 --- a/tests/lifecycle.zig +++ b/tests/lifecycle.zig @@ -14,7 +14,7 @@ test "LSP lifecycle" { .global_cache_path = test_options.global_cache_path, }, .{}); - var arena_allocator = std.heap.ArenaAllocator.init(allocator); + var arena_allocator: std.heap.ArenaAllocator = .init(allocator); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); diff --git a/tests/lsp_features/code_actions.zig b/tests/lsp_features/code_actions.zig index a4f8245f6..4119043d2 100644 --- a/tests/lsp_features/code_actions.zig +++ b/tests/lsp_features/code_actions.zig @@ -855,7 +855,7 @@ fn testDiagnostic( want_zir: bool = true, }, ) !void { - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); ctx.server.config.prefer_ast_check_as_child_process = !options.want_zir; @@ -894,7 +894,7 @@ fn testDiagnostic( return error.InvalidResponse; }; - var text_edits: std.ArrayListUnmanaged(types.TextEdit) = .{}; + var text_edits: std.ArrayListUnmanaged(types.TextEdit) = .empty; defer text_edits.deinit(allocator); for (response) |action| { diff --git a/tests/lsp_features/completion.zig b/tests/lsp_features/completion.zig index 03cbeab0f..38196357a 100644 --- a/tests/lsp_features/completion.zig +++ b/tests/lsp_features/completion.zig @@ -413,7 +413,7 @@ test "std.ArrayList" { try testCompletion( \\const std = @import("std"); \\const S = struct { alpha: u32 }; - \\const array_list: std.ArrayList(S) = undefined; + \\const array_list: std.ArrayListUnmanaged(S) = undefined; \\const foo = array_list.items[0]. , &.{ .{ .label = "alpha", .kind = .Field, .detail = "u32" }, @@ -434,7 +434,7 @@ test "std.ArrayHashMap" { try testCompletion( \\const std = @import("std"); \\const S = struct { alpha: u32 }; - \\const map: std.AutoArrayHashMap(u32, S) = undefined; + \\const map: std.AutoArrayHashMapUnmanaged(u32, S) = undefined; \\const s = map.get(0); \\const foo = s.?. , &.{ @@ -443,8 +443,8 @@ test "std.ArrayHashMap" { try testCompletion( \\const std = @import("std"); \\const S = struct { alpha: u32 }; - \\const map: std.AutoArrayHashMap(u32, S) = undefined; - \\const gop = try map.getOrPut(0); + \\const map: std.AutoArrayHashMapUnmanaged(u32, S) = undefined; + \\const gop = try map.getOrPut(undefined, 0); \\const foo = gop.value_ptr. , &.{ .{ .label = "*", .kind = .Operator, .detail = "S" }, @@ -466,7 +466,7 @@ test "std.HashMap" { try testCompletion( \\const std = @import("std"); \\const S = struct { alpha: u32 }; - \\const map: std.AutoHashMap(u32, S) = undefined; + \\const map: std.AutoHashMapUnmanaged(u32, S) = undefined; \\const s = map.get(0); \\const foo = s.?. , &.{ @@ -475,8 +475,8 @@ test "std.HashMap" { try testCompletion( \\const std = @import("std"); \\const S = struct { alpha: u32 }; - \\const map: std.AutoHashMap(u32, S) = undefined; - \\const gop = try map.getOrPut(0); + \\const map: std.AutoHashMapUnmanaged(u32, S) = undefined; + \\const gop = try map.getOrPut(undefined, 0); \\const foo = gop.value_ptr. , &.{ .{ .label = "*", .kind = .Operator, .detail = "S" }, @@ -3758,7 +3758,7 @@ fn testCompletionWithOptions( const text = try std.mem.concat(allocator, u8, &.{ source[0..cursor_idx], source[cursor_idx + "".len ..] }); defer allocator.free(text); - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); ctx.server.client_capabilities.completion_doc_supports_md = true; @@ -3773,7 +3773,7 @@ fn testCompletionWithOptions( const test_uri = try ctx.addDocument(.{ .source = text }); - const params = types.CompletionParams{ + const params: types.CompletionParams = .{ .textDocument = .{ .uri = test_uri }, .position = offsets.indexToPosition(source, cursor_idx, ctx.server.offset_encoding), }; @@ -3802,7 +3802,7 @@ fn testCompletionWithOptions( var unexpected = try set_difference(actual, expected); defer unexpected.deinit(allocator); - var error_builder = ErrorBuilder.init(allocator); + var error_builder: ErrorBuilder = .init(allocator); defer error_builder.deinit(); errdefer error_builder.writeDebug(); @@ -3915,7 +3915,7 @@ fn testCompletionWithOptions( } if (missing.count() != 0 or unexpected.count() != 0) { - var buffer = std.ArrayListUnmanaged(u8){}; + var buffer: std.ArrayListUnmanaged(u8) = .empty; defer buffer.deinit(allocator); const out = buffer.writer(allocator); @@ -3928,7 +3928,7 @@ fn testCompletionWithOptions( } fn extractCompletionLabels(items: anytype) error{ DuplicateCompletionLabel, OutOfMemory }!std.StringArrayHashMapUnmanaged(void) { - var set = std.StringArrayHashMapUnmanaged(void){}; + var set: std.StringArrayHashMapUnmanaged(void) = .empty; errdefer set.deinit(allocator); try set.ensureTotalCapacity(allocator, items.len); for (items) |item| { @@ -3948,7 +3948,7 @@ fn extractCompletionLabels(items: anytype) error{ DuplicateCompletionLabel, OutO } fn set_intersection(a: std.StringArrayHashMapUnmanaged(void), b: std.StringArrayHashMapUnmanaged(void)) error{OutOfMemory}!std.StringArrayHashMapUnmanaged(void) { - var result = std.StringArrayHashMapUnmanaged(void){}; + var result: std.StringArrayHashMapUnmanaged(void) = .empty; errdefer result.deinit(allocator); for (a.keys()) |key| { if (b.contains(key)) try result.putNoClobber(allocator, key, {}); @@ -3957,7 +3957,7 @@ fn set_intersection(a: std.StringArrayHashMapUnmanaged(void), b: std.StringArray } fn set_difference(a: std.StringArrayHashMapUnmanaged(void), b: std.StringArrayHashMapUnmanaged(void)) error{OutOfMemory}!std.StringArrayHashMapUnmanaged(void) { - var result = std.StringArrayHashMapUnmanaged(void){}; + var result: std.StringArrayHashMapUnmanaged(void) = .empty; errdefer result.deinit(allocator); for (a.keys()) |key| { if (!b.contains(key)) try result.putNoClobber(allocator, key, {}); @@ -4001,7 +4001,7 @@ fn testCompletionTextEdit( const expected_replace_text = try std.mem.concat(allocator, u8, &.{ text[0..cursor_line_loc.start], options.expected_replace_line, text[cursor_line_loc.end..] }); defer allocator.free(expected_replace_text); - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); ctx.server.client_capabilities.supports_snippets = true; @@ -4013,7 +4013,7 @@ fn testCompletionTextEdit( const handle = ctx.server.document_store.getHandle(test_uri).?; const cursor_position = offsets.indexToPosition(options.source, cursor_idx, ctx.server.offset_encoding); - const params = types.CompletionParams{ + const params: types.CompletionParams = .{ .textDocument = .{ .uri = test_uri }, .position = cursor_position, }; diff --git a/tests/lsp_features/definition.zig b/tests/lsp_features/definition.zig index 056723662..05c3523be 100644 --- a/tests/lsp_features/definition.zig +++ b/tests/lsp_features/definition.zig @@ -238,12 +238,12 @@ fn testDefinition(source: []const u8) !void { var phr = try helper.collectClearPlaceholders(allocator, source); defer phr.deinit(allocator); - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); const test_uri = try ctx.addDocument(.{ .source = phr.new_source }); - var error_builder = ErrorBuilder.init(allocator); + var error_builder: ErrorBuilder = .init(allocator); defer error_builder.deinit(); errdefer error_builder.writeDebug(); @@ -301,9 +301,9 @@ fn testDefinition(source: []const u8) !void { const cursor_position = offsets.indexToPosition(phr.new_source, cursor_index, ctx.server.offset_encoding); - const declaration_params = types.DeclarationParams{ .textDocument = .{ .uri = test_uri }, .position = cursor_position }; - const definition_params = types.DefinitionParams{ .textDocument = .{ .uri = test_uri }, .position = cursor_position }; - const type_definition_params = types.TypeDefinitionParams{ .textDocument = .{ .uri = test_uri }, .position = cursor_position }; + const declaration_params: types.DeclarationParams = .{ .textDocument = .{ .uri = test_uri }, .position = cursor_position }; + const definition_params: types.DefinitionParams = .{ .textDocument = .{ .uri = test_uri }, .position = cursor_position }; + const type_definition_params: types.TypeDefinitionParams = .{ .textDocument = .{ .uri = test_uri }, .position = cursor_position }; const maybe_declaration_response = if (declaration_loc != null) try ctx.server.sendRequestSync(ctx.arena.allocator(), "textDocument/declaration", declaration_params) diff --git a/tests/lsp_features/document_symbol.zig b/tests/lsp_features/document_symbol.zig index 642da9dbe..81ec01a19 100644 --- a/tests/lsp_features/document_symbol.zig +++ b/tests/lsp_features/document_symbol.zig @@ -94,12 +94,12 @@ test "nested struct with self" { } fn testDocumentSymbol(source: []const u8, want: []const u8) !void { - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); const test_uri = try ctx.addDocument(.{ .source = source }); - const params = types.DocumentSymbolParams{ + const params: types.DocumentSymbolParams = .{ .textDocument = .{ .uri = test_uri }, }; @@ -108,10 +108,10 @@ fn testDocumentSymbol(source: []const u8, want: []const u8) !void { return error.InvalidResponse; }; - var got = std.ArrayListUnmanaged(u8){}; + var got: std.ArrayListUnmanaged(u8) = .empty; defer got.deinit(allocator); - var stack = std.BoundedArray([]const types.DocumentSymbol, 16){}; + var stack: std.BoundedArray([]const types.DocumentSymbol, 16) = .{}; stack.appendAssumeCapacity(response.array_of_DocumentSymbol); var writer = got.writer(allocator); diff --git a/tests/lsp_features/folding_range.zig b/tests/lsp_features/folding_range.zig index b460a6220..80d99ef2b 100644 --- a/tests/lsp_features/folding_range.zig +++ b/tests/lsp_features/folding_range.zig @@ -299,12 +299,12 @@ test "weird code" { } fn testFoldingRange(source: []const u8, expect: []const types.FoldingRange) !void { - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); const test_uri = try ctx.addDocument(.{ .source = source }); - const params = types.FoldingRangeParams{ .textDocument = .{ .uri = test_uri } }; + const params: types.FoldingRangeParams = .{ .textDocument = .{ .uri = test_uri } }; const response = try ctx.server.sendRequestSync(ctx.arena.allocator(), "textDocument/foldingRange", params) orelse { std.debug.print("Server returned `null` as the result\n", .{}); diff --git a/tests/lsp_features/hover.zig b/tests/lsp_features/hover.zig index bf5836826..e43464d5c 100644 --- a/tests/lsp_features/hover.zig +++ b/tests/lsp_features/hover.zig @@ -1421,7 +1421,7 @@ fn testHoverWithOptions( const text = try std.mem.concat(allocator, u8, &.{ source[0..cursor_idx], source[cursor_idx + "".len ..] }); defer allocator.free(text); - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); ctx.server.client_capabilities.hover_supports_md = options.markup_kind == .markdown; @@ -1431,7 +1431,7 @@ fn testHoverWithOptions( .source = text, }); - const params = types.HoverParams{ + const params: types.HoverParams = .{ .textDocument = .{ .uri = uri }, .position = offsets.indexToPosition(text, cursor_idx, ctx.server.offset_encoding), }; diff --git a/tests/lsp_features/inlay_hints.zig b/tests/lsp_features/inlay_hints.zig index 468f71652..cbd2d1970 100644 --- a/tests/lsp_features/inlay_hints.zig +++ b/tests/lsp_features/inlay_hints.zig @@ -513,7 +513,7 @@ fn testInlayHints(source: []const u8, options: Options) !void { var phr = try helper.collectClearPlaceholders(allocator, source); defer phr.deinit(allocator); - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); ctx.server.config.inlay_hints_show_parameter_name = options.kind == .Parameter; @@ -525,12 +525,12 @@ fn testInlayHints(source: []const u8, options: Options) !void { const test_uri = try ctx.addDocument(.{ .source = phr.new_source }); - const range = types.Range{ + const range: types.Range = .{ .start = types.Position{ .line = 0, .character = 0 }, .end = offsets.indexToPosition(phr.new_source, phr.new_source.len, .@"utf-16"), }; - const params = types.InlayHintParams{ + const params: types.InlayHintParams = .{ .textDocument = .{ .uri = test_uri }, .range = range, }; @@ -541,10 +541,10 @@ fn testInlayHints(source: []const u8, options: Options) !void { return error.InvalidResponse; }; - var visited = try std.DynamicBitSetUnmanaged.initEmpty(allocator, hints.len); + var visited: std.DynamicBitSetUnmanaged = try .initEmpty(allocator, hints.len); defer visited.deinit(allocator); - var error_builder = ErrorBuilder.init(allocator); + var error_builder: ErrorBuilder = .init(allocator); defer error_builder.deinit(); errdefer error_builder.writeDebug(); diff --git a/tests/lsp_features/references.zig b/tests/lsp_features/references.zig index 10100ec93..447ded3d6 100644 --- a/tests/lsp_features/references.zig +++ b/tests/lsp_features/references.zig @@ -223,19 +223,19 @@ fn testReferences(source: []const u8) !void { fn testMFReferences(sources: []const []const u8) !void { const placeholder_name = "placeholder"; - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); const File = struct { source: []const u8, new_source: []const u8 }; const LocPair = struct { file_index: usize, old: offsets.Loc, new: offsets.Loc }; - var files = std.StringArrayHashMapUnmanaged(File){}; + var files: std.StringArrayHashMapUnmanaged(File) = .empty; defer { for (files.values()) |file| allocator.free(file.new_source); files.deinit(allocator); } - var loc_set: std.StringArrayHashMapUnmanaged(std.MultiArrayList(LocPair)) = .{}; + var loc_set: std.StringArrayHashMapUnmanaged(std.MultiArrayList(LocPair)) = .empty; defer { for (loc_set.values()) |*locs| locs.deinit(allocator); loc_set.deinit(allocator); @@ -257,7 +257,7 @@ fn testMFReferences(sources: []const []const u8) !void { } } - var error_builder = ErrorBuilder.init(allocator); + var error_builder: ErrorBuilder = .init(allocator); defer error_builder.deinit(); errdefer error_builder.writeDebug(); @@ -273,7 +273,7 @@ fn testMFReferences(sources: []const []const u8) !void { const file_uri = files.keys()[file_index]; const middle = new_loc.start + (new_loc.end - new_loc.start) / 2; - const params = types.ReferenceParams{ + const params: types.ReferenceParams = .{ .textDocument = .{ .uri = file_uri }, .position = offsets.indexToPosition(file.new_source, middle, ctx.server.offset_encoding), .context = .{ .includeDeclaration = true }, @@ -289,7 +289,7 @@ fn testMFReferences(sources: []const []const u8) !void { // keeps track of expected locations that have been given by the server // used to detect double references and missing references - var visited = try std.DynamicBitSetUnmanaged.initEmpty(allocator, locs.len); + var visited: std.DynamicBitSetUnmanaged = try .initEmpty(allocator, locs.len); defer visited.deinit(allocator); for (actual_locations) |response_location| { diff --git a/tests/lsp_features/selection_range.zig b/tests/lsp_features/selection_range.zig index 069f05f4e..45e484c7d 100644 --- a/tests/lsp_features/selection_range.zig +++ b/tests/lsp_features/selection_range.zig @@ -33,14 +33,14 @@ fn testSelectionRange(source: []const u8, want: []const []const u8) !void { var phr = try helper.collectClearPlaceholders(allocator, source); defer phr.deinit(allocator); - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); const test_uri = try ctx.addDocument(.{ .source = phr.new_source }); const position = offsets.locToRange(phr.new_source, phr.locations.items(.new)[0], .@"utf-16").start; - const params = types.SelectionRangeParams{ + const params: types.SelectionRangeParams = .{ .textDocument = .{ .uri = test_uri }, .positions = &[_]types.Position{position}, }; @@ -51,13 +51,13 @@ fn testSelectionRange(source: []const u8, want: []const []const u8) !void { return error.InvalidResponse; }; - var got = std.ArrayList([]const u8).init(allocator); - defer got.deinit(); + var got: std.ArrayListUnmanaged([]const u8) = .empty; + defer got.deinit(allocator); var it: ?*const types.SelectionRange = &selectionRanges[0]; while (it) |r| { const slice = offsets.rangeToSlice(phr.new_source, r.range, .@"utf-16"); - (try got.addOne()).* = slice; + try got.append(allocator, slice); it = r.parent; } const last = got.pop(); diff --git a/tests/lsp_features/semantic_tokens.zig b/tests/lsp_features/semantic_tokens.zig index 9270d349d..12f01b108 100644 --- a/tests/lsp_features/semantic_tokens.zig +++ b/tests/lsp_features/semantic_tokens.zig @@ -1952,7 +1952,7 @@ fn testSemanticTokensOptions( mode: std.zig.Ast.Mode = .zig, }, ) !void { - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); const uri = try ctx.addDocument(.{ @@ -1960,7 +1960,7 @@ fn testSemanticTokensOptions( .mode = options.mode, }); - const params = types.SemanticTokensParams{ + const params: types.SemanticTokensParams = .{ .textDocument = .{ .uri = uri }, }; const response = try ctx.server.sendRequestSync(ctx.arena.allocator(), "textDocument/semanticTokens/full", params) orelse { @@ -1971,13 +1971,13 @@ fn testSemanticTokensOptions( const actual = response.data; try std.testing.expect(actual.len % 5 == 0); // every token is represented by 5 integers - var error_builder = ErrorBuilder.init(allocator); + var error_builder: ErrorBuilder = .init(allocator); defer error_builder.deinit(); errdefer error_builder.writeDebug(); try error_builder.addFile(uri, source); - var token_it = TokenIterator.init(source, actual); + var token_it: TokenIterator = .init(source, actual); var last_token_end: usize = 0; for (expected_tokens) |expected_token| { diff --git a/tests/lsp_features/signature_help.zig b/tests/lsp_features/signature_help.zig index dc4967c41..6ea5066d5 100644 --- a/tests/lsp_features/signature_help.zig +++ b/tests/lsp_features/signature_help.zig @@ -269,12 +269,12 @@ fn testSignatureHelp(source: []const u8, expected_label: []const u8, expected_ac const text = try std.mem.concat(allocator, u8, &.{ source[0..cursor_idx], source[cursor_idx + "".len ..] }); defer allocator.free(text); - var ctx = try Context.init(); + var ctx: Context = try .init(); defer ctx.deinit(); const test_uri = try ctx.addDocument(.{ .source = text }); - const params = types.SignatureHelpParams{ + const params: types.SignatureHelpParams = .{ .textDocument = .{ .uri = test_uri }, .position = offsets.indexToPosition(text, cursor_idx, ctx.server.offset_encoding), }; diff --git a/tests/utility/ast.zig b/tests/utility/ast.zig index ee520530c..61356495b 100644 --- a/tests/utility/ast.zig +++ b/tests/utility/ast.zig @@ -97,7 +97,7 @@ fn testNodesAtLoc(source: []const u8) !void { }; const uri = "file.zig"; - var error_builder = ErrorBuilder.init(allocator); + var error_builder: ErrorBuilder = .init(allocator); defer error_builder.deinit(); errdefer error_builder.writeDebug(); diff --git a/tests/utility/diff.zig b/tests/utility/diff.zig index 2012fb0de..1b9e28195 100644 --- a/tests/utility/diff.zig +++ b/tests/utility/diff.zig @@ -18,7 +18,7 @@ test "diff - random" { } fn testDiff(allocator: std.mem.Allocator, seed: u64, encoding: zls.offsets.Encoding) !void { - var rand = std.Random.DefaultPrng.init(seed); + var rand: std.Random.DefaultPrng = .init(seed); const before = try gen(allocator, rand.random()); defer allocator.free(before); const after = try gen(allocator, rand.random()); diff --git a/tests/utility/position_context.zig b/tests/utility/position_context.zig index cec07a679..22639501c 100644 --- a/tests/utility/position_context.zig +++ b/tests/utility/position_context.zig @@ -518,7 +518,7 @@ fn testContext(source: []const u8, expected_tag: std.meta.Tag(Analyser.PositionC const ctx = try Analyser.getPositionContext(allocator, tree, cursor_index, lookahead); - var error_builder = ErrorBuilder.init(allocator); + var error_builder: ErrorBuilder = .init(allocator); defer error_builder.deinit(); errdefer error_builder.writeDebug();