zls icon indicating copy to clipboard operation
zls copied to clipboard

Wrong variable type info when orelse assigns variable with an optional type

Open lucascool12 opened this issue 2 years ago • 0 comments

Zig Version

0.11.0-dev.4002+7dd1cf26f

Zig Language Server Version

8da21e159e3dec9bc6fe01320313cf8108ce4d0b

Steps to Reproduce

Paste this code into an editor with zls running as lsp. Send a textDocument/hover request of variable c.

pub fn opt_test(a: ?i32, b: ?i32) void {
    const c = a orelse b;
    std.debug.print("{s}\n", .{@typeName(@TypeOf(c))});
}

Running this code snippet prints ?i32 as type of c.

const std = @import("std");

pub fn main() !void {
    const a = null;
    const b = null;
    opt_test(a, b);
}

pub fn opt_test(a: ?i32, b: ?i32) void {
    const c = a orelse b;
    std.debug.print("{s}\n", .{@typeName(@TypeOf(c))});
}

Expected Behavior

Type of c being ?i32 .

Actual Behavior

zls reports the type of c being i32.

I took a stab at trying to come up with a fix by replacing this switch case with the one below:

                .@"orelse" => orelse_type: {
                    const base_right = .{ .node = datas[node].rhs, .handle = handle };
                    const base_type_right = (try analyser.resolveTypeOfNodeInternal(base_right));
                    if (base_type_right) |type_right| {
                        const ok = switch (type_right.type.data) {
                            .other => |node_type| switch (node_tags[node_type]) {
                                .optional_type => true,
                                else => false,
                            },
                            else => false,
                        };
                        if (ok) {
                            break :orelse_type base_type;
                        }
                    }
                    break :orelse_type try analyser.resolveUnwrapOptionalType(base_type);
                },

This worked for the example above, but when trying to open hover.zig with this change zls crashes.

lucascool12 avatar Jul 16 '23 19:07 lucascool12