Skip to content

Type hint comment directives #2050

Open
@mnemnion

Description

@mnemnion

I didn't see this in the open issues, apologies if I missed it.

I have some code like this, in the usual sort of type-returning function:

return struct {
    stdout: WriteType,
    buf_write: std.io.BufferedWriter(4096, WriteType),
    writer: std.io.Writer,
    is_tty: bool,

As should be clear, the intended type of stdout is File, but I want the code to be type-generic for various reasons, mainly testing.

In the event (as will be the case) that WriteType resolves to more than one type, it seems that providing hover and completion for stdout is undecidable even with compiler support. A least-common-denominator approach for completion names (covering the subset of methods/fields/etc the types have in common) might work ok, but there's the question of the canonical documentation for hovering.

So even given the expected improvements in comptime analysis, it might remain useful to allow an annotation like this:

return struct {
    stdout: WriteType,  // zls type-hint: std.fs.File
    buf_write: std.io.BufferedWriter(4096, WriteType),
    writer: std.io.Writer,
    is_tty: bool,

It also has the advantage that it would work right now, and is relatively straightforward to add in comparison to full compiler integration.

Another strength of this approach is that someone reading the file can see what stdout is "supposed" to be, clearly there are a lot of ways to document that but this is one good option.

I think we'd need two ways to do this, type parameters applied to a field is the most common case but it isn't the only one. This won't work because of "pointless discard":

_ = WriteType; // zls type-hint: std.fs.File

I think it would be a bit strange to apply it to lines where the type is actively used in any way. That leaves something like a comment on its own line that looks like this:

// zls type-hint: WriteType = std.fs.File

Maybe that isn't the perfect syntax but something like that.

It's definitely a brute-force solution, but perhaps that's a good thing here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions