Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Struct skeleton with pointer to element in a slice not found #1872

Open
ThisAccountHasBeenSuspended opened this issue Apr 24, 2024 · 3 comments
Labels
bug Something isn't working

Comments

@ThisAccountHasBeenSuspended
Copy link
Contributor

Zig Version

0.12.0

Zig Language Server Version

0750844

Client / Code Editor / Extensions

VSCode Zig Language

Steps to Reproduce and Observed Behavior

const std = @import("std");

const Blub = struct {
    pub fn printHello(_: @This()) void {
        std.debug.print("Hello\n", .{});
    }
};

pub fn main() anyerror!void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();

    var array = std.ArrayList(?Blub).init(allocator);
    defer array.deinit();
    try array.append(Blub{});

    for (array.items[0..]) |*item| {
        // Function not found
        item.*.?.printHello();
    }

    for (array.items[0..]) |item| {
        // Function found
        item.?.printHello();
    }
}

image

Expected Behavior

Get the same result as with a "normal" variable or without a pointer.

(Image created with GIMP)
image

Relevant log output

No response

@ThisAccountHasBeenSuspended ThisAccountHasBeenSuspended added the bug Something isn't working label Apr 24, 2024
@llogick
Copy link
Member

llogick commented Apr 24, 2024

Hmm
diff --git a/src/analysis.zig b/src/analysis.zig
index c49780b2..1f7b5c41 100644
--- a/src/analysis.zig
+++ b/src/analysis.zig
@@ -887,7 +887,7 @@ pub fn resolveFuncProtoOfCallable(analyser: *Analyser, ty: Type) error{OutOfMemo
 /// resolve a pointer dereference
 /// `pointer.*`
 pub fn resolveDerefType(analyser: *Analyser, pointer: Type) error{OutOfMemory}!?Type {
-    if (pointer.is_type_val) return null;
+    // if (pointer.is_type_val) return null;
 
     switch (pointer.data) {
         .pointer => |info| switch (info.size) {
@@ -904,6 +904,9 @@ pub fn resolveDerefType(analyser: *Analyser, pointer: Type) error{OutOfMemory}!?
                 else => return null,
             }
         },
+        // XXX: Look into just returning the type as is? the following expr is very common
+        // `const type_expr = try analyser.resolveDerefType(result) orelse result;`
+        // although there's a couple of places where it really matters
         else => return null,
     }
 }
@@ -2402,9 +2405,9 @@ pub const Type = struct {
     }
 
     pub fn instanceTypeVal(self: Type, analyser: *Analyser) error{OutOfMemory}!?Type {
-        if (!self.is_type_val) return null;
         return switch (self.data) {
             .ip_index => |payload| {
+                if (!self.is_type_val) return null;
                 if (payload.index == .unknown_type) return null;
                 return Type{
                     .data = .{
@@ -2602,7 +2605,7 @@ pub const Type = struct {
     }
 
     pub fn fmtTypeVal(ty: Type, analyser: *Analyser, options: FormatOptions) std.fmt.Formatter(format) {
-        std.debug.assert(ty.is_type_val);
+        // std.debug.assert(ty.is_type_val);
         return .{ .data = .{ .ty = ty, .analyser = analyser, .options = options } };
     }
 
@@ -3284,7 +3287,9 @@ pub fn getPositionContext(
                 .period, .period_asterisk => switch (curr_ctx.ctx) {
                     .empty, .pre_label => curr_ctx.ctx = .{ .enum_literal = tok.loc },
                     .enum_literal => curr_ctx.ctx = .empty,
-                    .field_access => {},
+                    .field_access => curr_ctx.ctx = .{
+                        .field_access = tokenLocAppend(curr_ctx.ctx.loc().?, tok),
+                    },
                     .other => {},
                     .global_error_set => {},
                     .label => |filled| if (filled) {
@@ -3301,7 +3306,9 @@ pub fn getPositionContext(
                     curr_ctx.ctx = .empty;
                 },
                 .question_mark => switch (curr_ctx.ctx) {
-                    .field_access => {},
+                    .field_access => curr_ctx.ctx = .{
+                        .field_access = tokenLocAppend(curr_ctx.ctx.loc().?, tok),
+                    },
                     else => curr_ctx.ctx = .empty,
                 },
                 .l_paren => try stack.append(allocator, .{ .ctx = .empty, .stack_id = .Paren }),
@@ -3737,13 +3744,29 @@ pub const DeclWithHandle = struct {
                 })) orelse return null,
                 .error_set,
             ),
-            .for_loop_payload => |pay| try analyser.resolveBracketAccessType(
-                (try analyser.resolveTypeOfNodeInternal(.{
-                    .node = pay.condition,
-                    .handle = self.handle,
-                })) orelse return null,
-                .Single,
-            ),
+            .for_loop_payload => |pay| flp: {
+                const node = try analyser.resolveBracketAccessType(
+                    (try analyser.resolveTypeOfNodeInternal(.{
+                        .node = pay.condition,
+                        .handle = self.handle,
+                    })) orelse return null,
+                    .Single,
+                ) orelse return null;
+                break :flp if (self.handle.tree.tokens.items(.tag)[pay.identifier - 1] == .asterisk) ptr: {
+                    const ty = try analyser.arena.allocator().create(Type);
+                    ty.* = node;
+                    break :ptr .{
+                        .data = .{
+                            .pointer = .{
+                                .size = .One,
+                                .elem_ty = ty,
+                                .is_const = true,
+                            },
+                        },
+                        .is_type_val = false,
+                    };
+                } else node;
+            },
             .assign_destructure => |pay| {
                 const type_node = pay.getFullVarDecl(tree).ast.type_node;
                 if (type_node != 0) {
diff --git a/src/features/completions.zig b/src/features/completions.zig
index abd802c0..4a5e3424 100644
--- a/src/features/completions.zig
+++ b/src/features/completions.zig
@@ -49,11 +49,14 @@ fn typeToCompletion(
                     ),
                 });
 
-                if (info.size == .C) return;
+                // XXX: `for (array.items[0..]) |*item| { item.*.?.printHello(); }` requires the `.*`
+                // Reevaluate conditions or delete:
 
-                if (try builder.analyser.resolveDerefType(ty)) |child_ty| {
-                    try typeToCompletion(builder, child_ty, null);
-                }
+                // if (info.size == .C) return;
+
+                // if (try builder.analyser.resolveDerefType(ty)) |child_ty| {
+                //     try typeToCompletion(builder, child_ty, null);
+                // }
             },
             .Slice => {
                 if (ty.is_type_val) return;
diff --git a/src/features/inlay_hints.zig b/src/features/inlay_hints.zig
index 4e267977..751309fa 100644
--- a/src/features/inlay_hints.zig
+++ b/src/features/inlay_hints.zig
@@ -389,11 +389,10 @@ fn writeForCaptureHint(builder: *Builder, for_node: Ast.Node.Index) !void {
         const capture_by_ref = token_tags[capture_token] == .asterisk;
         const name_token = capture_token + @intFromBool(capture_by_ref);
         if (try typeStrOfToken(builder, name_token)) |type_str| {
-            const prepend = if (capture_by_ref) "*" else "";
             try appendTypeHintString(
                 builder,
                 name_token,
-                try std.fmt.allocPrint(builder.arena, "{s}{s}", .{ prepend, type_str }),
+                try std.fmt.allocPrint(builder.arena, "{s}", .{type_str}),
             );
         }
         capture_token = name_token + 2;
diff --git a/tests/lsp_features/completion.zig b/tests/lsp_features/completion.zig
index 6de690af..4916236e 100644
--- a/tests/lsp_features/completion.zig
+++ b/tests/lsp_features/completion.zig
@@ -320,7 +320,7 @@ test "std.ArrayHashMap" {
         \\const foo = gop.value_ptr.<cursor>
     , &.{
         .{ .label = "*", .kind = .Operator, .detail = "S" },
-        .{ .label = "alpha", .kind = .Field, .detail = "u32" },
+        // .{ .label = "alpha", .kind = .Field, .detail = "u32" },
     });
 }
 
@@ -352,7 +352,7 @@ test "std.HashMap" {
         \\const foo = gop.value_ptr.<cursor>
     , &.{
         .{ .label = "*", .kind = .Operator, .detail = "S" },
-        .{ .label = "alpha", .kind = .Field, .detail = "u32" },
+        // .{ .label = "alpha", .kind = .Field, .detail = "u32" },
     });
 }
 
@@ -456,7 +456,7 @@ test "pointer deref" {
         \\const bar = foo.<cursor>
     , &.{
         .{ .label = "*", .kind = .Operator, .detail = "S" },
-        .{ .label = "alpha", .kind = .Field, .detail = "u32" },
+        // .{ .label = "alpha", .kind = .Field, .detail = "u32" },
     });
     try testCompletion(
         \\const S = struct { alpha: u32 };
@@ -597,7 +597,7 @@ test "address of" {
         \\const foo = value_ptr.<cursor>;
     , &.{
         .{ .label = "*", .kind = .Operator, .detail = "S" },
-        .{ .label = "alpha", .kind = .Field, .detail = "u32" },
+        // .{ .label = "alpha", .kind = .Field, .detail = "u32" },
     });
 }
 
@@ -659,7 +659,7 @@ test "single pointer to array" {
         \\const bar = foo.<cursor>
     , &.{
         .{ .label = "*", .kind = .Operator, .detail = "[3]u32" },
-        .{ .label = "len", .kind = .Field, .detail = "usize = 3" },
+        // .{ .label = "len", .kind = .Field, .detail = "usize = 3" },
     });
     try testCompletion(
         \\const S = struct { alpha: u32 };

@ThisAccountHasBeenSuspended
Copy link
Contributor Author

Hmm

Tested and now it works in my projects and this example above.

image

@wizzymore
Copy link

Can confirm, i was following the ziglings exercises and had a little bit of trouble at exercise 58 because of this:
image
Instead of *?NotebookEntry i get ?NotebookEntry and when trying to return the correct &entry.*.? i get no autocomplete. I get the autocomplete for entry.?.something which is wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants