Skip to content

proposal: go/doc: support explicit hotlinking syntax  #45533

Closed

Description

@dsnet

Introduction

Even though the hotlinks proposal (#25444) was accepted, one reason it wasn't implemented is because detection of identifiers experienced many false positives. See #44447#related-proposals for details.

I propose modifying the hotlinks proposal to use an explicit syntax to indicate the user's intent that some string is a reference to a Go identifier. An explicit syntax should drastically reduce false positives.

Proposal

(The following proposal uses brackets, but other delimiters are reasonable to consider. See #45533 (comment) for alternatives.)

I propose modifying https://pkg.go.dev/ to support hot-linking using a syntax similar to the Markdown syntax for reference-style links. For example, [Buffer.Write] in source code would rendered as Buffer.Write. The reference comprises of a left bracket (i.e, [), some text in-between (e.g., Buffer.Write), and a right bracket (i.e., ]). When rendering, the brackets are removed and the text in-between is linked to the referent. Functionally, it operates just like a Markdown inlined reference where the referent is implicitly provided by GoDoc.

The reference must match one of the following:

  • [ExportedIdent] where it references a method or field on the current type.
  • [ExportedIdent] where it references a variable, constant, type, or function in the current package.
    • E.g., [Buffer] in the bytes package would refer to the bytes.Buffer type.
  • [ExportedIdent.ExportedIdent] where it references a method or field on a type in the package.
  • [PackageName.ExportedIdent] where it references variable, constant, type, or function in another package.
    • E.g., [io.EOF] would refer to the io.EOF variable.
  • [PackageName.ExportedIdent.ExportedIdent] where it references a method or field on a type in another package.
  • ["ImportPath"] where it references a package or module.
    • E.g., ["google.golang.org/protobuf/proto"] would refer to the proto package.
  • ["ImportPath".ExportedIdent] where it references a method or field in another package.
    • E.g., ["google.golang.org/protobuf/proto".Message] would refer to the proto.Message type.
  • ["ImportPath".ExportedIdent.ExportedIdent] where it references a method or field on a type in another package.

ExportedIdent is a valid Go identifier that is exported.

The set of PackageNames that are allowed is determined by what that Go source file imports (e.g., [io.EOF] is only hot-linked if the io package is imported). For example, if the code imports github.com/other/json, then we will link [json.Marshal] to "github.com/other/json".Marshal and not "encoding/json".Marshal.

ImportPath must be a valid import path and either:

  • be a standard library package path, or
  • be a multi segment path where the first segment contains a dot and at least one letter (simple heuristic to detect valid domain names).

In order to avoid false positives, the left bracket must be preceded by whitespace and the right bracket must be succeeded by whitespace or punctuation (i.e., period, comma, or semi-colon). Hot-linking is not performed on pre-formatted code blocks (i.e., indented paragraphs).

Examples

This code snippet:

// FooMethod performs the foo functionality.
// It implements ["github.com/example/project".FooInterface].
// The arguments may be of either the map[Key]Foo or map[Key]Bar types.
// Under certain situation, it returns an error that matches [ErrCondition] according to [errors.Is].
// This method may print [INFO] messages to [os.Stderr].
//
// Example usage:
//    t.FooMethod(map[Key]Value{...})
func (t *MyType) FooMethod(...) error

would render as:

FooMethod performs the foo functionality.
It implements "github.com/example/project".FooInterface.
The arguments may be of either the map[Key]Foo or map[Key]Bar types.
Under certain situation, it returns an error that matches ErrCondition according to errors.Is.
This method may print [INFO] messages to os.Stderr.

Example usage:

t.FooMethod(map[Key]Value{...})

Observations:

  • The brackets for successfully hot-linked references are removed and replaced with an HTML anchor:
  • Supposing there is a local declaration for Key, the [Key] is not hot-linked since it is not surrounded by whitespace. We avoid hot-linking this since removal of the brackets would render poorly:
  • If the reference does not match anything, then it is left as is:
    • [Info]
  • Indented blocks do not have hot-linking applied:
    • t.FooMethod(map[Key]Value{...})

See CL/309430 for possible changes made to the protobuf module to make use of this feature.

Design and Analysis

(The following analysis uses the latest version (as of 2021-03-21) of all public modules.)

This feature can be broken down into two problems:

  1. How to identify references in Go documentation (e.g., io.EOF), and
  2. How to identify what these references refer to (e.g., https://pkg.go.dev/io#EOF).

Identifying references

The occurence of [...] occurs ~229k times in Go documentation, most of which should not be hot-linked.

First, we restrict the text within brackets to valid identifiers and/or valid import paths. This reduces the number of matches to ~19k.

Second, we restrict the grammar to require leading whitespace and trailing whitespace (or punctuation). We do this since some of the matches:

This restriction reduces the number of matches to ~6k.

Third, we avoid performing hot-linking within indented paragraphs. We do this because:

  • Indented paragraphs are printed as code blocks and should be preserved ad-verbatim if possible. The removal of brackets could break intentional character alignment that the user desired to be present.
  • Indented paragraphs often contain code-like snippets, which more often includes the bracket character, leading to false-positives.
  • This proposal aims to be subset of Markdown and [...] references are not respected within code blocks.
  • Not hot-linking indented paragraphs provides a means to opt-out of this feature.

This reduces the number of matches to ~3.7k. The list of results at this point can be found here.

For the remaining results:

Identifying referents

Of the ~3.7k results, the type of referents are as follows:

  • ~3k are references to locally defined identifier (e.g., MyType.MyMethod)
  • ~500 are references to locally defined identifier, but scoped within some type (e.g., MyMethod)
  • ~60 are references to an identifier in an imported package by package name (e.g., io.EOF)
  • ~5 are references to another package by import path (e.g., "google.golang.org/protobuf/proto")

Hot-linking local referents is relatively easy since we a can derive the set of explicitly defined identifiers within the package using the *doc.Package we have on hand. These referents will never have false positives, but may have false negatives (since we can't easily know implicit declarations obtained through embedding or type aliases).

Hot-linking remote referents is challenging and may lead to false positives. The GoDoc implementation does not assume that it has type information available for other remote packages and we should maintain this property for the implementation. As such, it cannot verify whether some remote reference truly exists and whether some declaration is defined within it.

For references by import path (e.g., ["google.golang.org/protobuf"]), we require that it be valid, that the first path segment must contain a dot since it is always a domain name, and that there be at least one letter. With this heuristic, there were no false positives in the above results.

For references by package name (e.g., [os.Exit]), we determine the set of supported package names based on what packages are imported by the current package. For example, [os.Exit] would not be hot-linked if the os package was not imported. Unfortunately, the package name cannot always be determined given the import statement alone (see #29036). As such, we use a heuristic where the package name is the last path segment if it is a valid identifier. While this may lead to false positives, it is actually the same heuristic that go/doc uses and the https://pkg.go.dev/ is already subject to this potential false positive. To explicitly avoid incorrectly identifying the correct package name, the user code can always use a named import if the real package name is different from the last import path segment.

Even if we could identify the package name, we don't know what declarations exist in that package. In theory we could fetch the documentation for that package, but that would incur significant complexity that doesn't currently exist. Furthermore, for cases where a go.mod file is missing or incomplete, we won't even know what version of the remote package to load. Instead, we hot-link package-scoped identifiers according to the following heuristics:

  1. we don't hot-link standalone package names (e.g., [os] will not be linked to https://pkg.go.dev/os),
  2. we require that the identifiers must be exported (e.g., [os.Exit] will be linked to https://pkg.go.dev/os#Exit, while [os.exit] will not be linked to https://pkg.go.dev/os#exit).

Using these heuristics, none of the existing ~60 matches had non-existing referrents.

Summary:

  • There is an unwritten goal that Go documentation remain readable without being passed through some type of renderer. The use of brackets adds two characters and does not seem to obstruct reading the documentation directly in source code.
  • Compared to the original (x/tools/cmd/godoc: add support for hotlinks #25444) proposal, code will generally need to be modified to opt-into using this feature. However, relatively little code will need to be modified to opt-out of accidental matches due to the drastically reduced amount of false-positives.
  • Over the years there has been requests for Go documentation to support markdown. This proposal does not prevent that possibility as this is a sub-set of Markdown.

Implementation

I can do the work for this since I implemented the original hot-linking proposal, which is actually already merged into the pkgsite code-base, but currently disabled. I suspect that the modifications to the original hot-linking implementation will be relatively minimal.

Note: I originally considered using back-ticks as the marker. Credit goes to @rsc for suggesting the use of brackets to match the Markdown syntax for reference-style links.

Activity

  1. added this to the Proposal milestone on Apr 13, 2021
  2. dsnet commented on Apr 13, 2021

    @dsnet
    MemberAuthor
  3. josharian commented on Apr 13, 2021

    @josharian
  4. dsnet commented on Apr 13, 2021

    @dsnet
    Author
  5. mvdan commented on Apr 13, 2021

    @mvdan
    Member

    I assume that full markdown links, such as [foo](bar) or [foo][3], would be left untouched by this change? That's how I understood the proposal, but just making sure.

    that the first path segment must contain a dot since it is always a domain name

    You might be interested in #32819, since this "domain" rule is currently unwritten.

    Also note #37641, though I don't think having pkgsite support links within module example or module test is hugely important.

    we don't hot-link standalone package names (e.g., [os] will not be linked to https://pkg.go.dev/os),

    I assume that the advice there would be to link the entire import path instead, which makes sense to me.

    I originally considered using back-ticks as the marker.

    I've seen lots of code use backticks in ways that fit your supported bracket syntax, modulo the surrounding character. I wonder if we could have some way to automatically convert those that would result in a valid link, such as `MyType.MyMethod` to [MyType.MyMethod]. Maybe via go fix, using the same heuristic code?

  6. peterbourgon commented on Apr 13, 2021

    @peterbourgon

    I strongly object to this proposal.

  7. mvdan commented on Apr 13, 2021

    @mvdan
    Member

    @peterbourgon care to explain why?

  8. peterbourgon commented on Apr 13, 2021

    @peterbourgon

    Go documentation currently reads fluently as prose, whether in source or lightly rendered form. Semantic markup turns it into something else: source code in the .go file, compiled artifact in the browser.

    Why? Why change this lovely, lightweight, refreshing aspect of the language into something that it explicitly chose not to be when designed?

    As usual, I understand the value that this proposal would deliver. Any conceivable change delivers value to someone, somehow, somewhere. Should we add everything that has some value to the language? I hope the clear answer of "no" is uncontroversial. But, man, there are just so many proposals being thrown against the wall in the last year, to add more and more stuff to the language, almost never (IMO) with sufficient motivating cause. The language loses its definition, its principles, as it expands in this way, but those things are important to maintain.

  9. mvdan commented on Apr 13, 2021

    @mvdan
    Member

    For what it's worth, I agree that plaintext documentation is nice. But links are also nice, and proposals to add some form of them were accepted as early as 2017. It's four years later, and automatic hot-linking has not worked, as Joe explained in the detailed proposal.

    Your answer then might be "we'll never have links then", but I'd personally find that very unfortunate.

    I ultimately defer to Joe, who has spent five years thinking about this problem and attempting different solutions. If we can agree that links are a nice thing to have, then I think any criticism would have far more value in the form of alternative ways to add the feature.

  10. peterbourgon commented on Apr 13, 2021

    @peterbourgon

    If we can agree that links are a nice thing to have,

    Insofar as links mean semantic markup, I don't agree. I don't want any kind of semantic markup in Go package docs.

  11. josharian commented on Apr 13, 2021

    @josharian
    Contributor

    there are just so many proposals being thrown against the wall in the last year

    This is a natural consequence of Go’s growth. I for one welcome this; it’s noisier, and messier, but I believe it’s also valuable. More voices leads to better outcomes (after more time and more work).

    In any case, that hardly seems to apply to this proposal. This is a refinement of a proposal accepted years ago—one which Joe chose not to implement because he didn’t feel at the time that it hit the high bar that Go maintains, despite it being accepted.

    Go documentation currently reads fluently as prose

    This particular proposal strikes me as not impeding fluent prose but augmenting it. (I would not say so about adding full markdown links, which adds extra non-textual letters.)

  12. 22 remaining items

  13. jba commented on Apr 14, 2021

    @jba
    Contributor

    It is a slippery slope, but the magnitude of the slope is 1 feature/decade.

  14. ChrisHines commented on Apr 16, 2021

    @ChrisHines
    Contributor

    I can see the value of the proposal, but like others am leary of adding noise to the experience of reading the docs in their native form. I am not strongly against the proposal, but I believe its implementation should be as lightweight as possible if it is accepted.

    When I've been intending to distinguish between a type or function that I'm referring to, and just a plain word that might be capitalized, I've usually written it with backticks.

    I have seen other developers do this as well, and it has always been back-ticks. I've seen back-ticks used to mark function parameter names used in the docs as well.

    Thinking ahead, I would not be in favor of a proposal for full markdown support. That's a bridge too far in my opinion. With that position staked out I don't see any value in choosing square brackets as the markup for this proposal. Back-ticks are lighter on the page and I think there is some precedent for using them to mark identifiers in documentation-ish things in Go. Consider that flag.PrintDefaults interprets back-ticks in a somewhat similar fashion in flag usage messages.

    My current position on this proposal is 👎 in it's current form due to the square brackets being too heavy and no reason to be compatible with markdown. Switching to back-ticks changes my opinion to a more neutral stance.

    @seebs asked:

    Of the ~280k backticked things that seem like they're valid references, how many are "valid" in the sense of "the thing they appear to refer to actually exists"? Establishing the rate of "plausibly-valid" vs "apparently doesn't exist" links that the tool would generate might be also informative. Basically, a higher rate of false positives that also comes with a higher rate of true positives may be better than a lower rate of both.

    I think this is a good question that hasn't been answered yet.

  15. rsc commented on Apr 21, 2021

    @rsc
    Contributor

    This proposal has been added to the active column of the proposals project
    and will now be reviewed at the weekly proposal review meetings.
    — rsc for the proposal review group

  16. changed the title [-]proposal: x/pkgsite: support explicit hotlinking syntax [/-] [+]proposal: go/doc: support explicit hotlinking syntax [/+] on Apr 21, 2021
  17. rsc commented on Apr 21, 2021

    @rsc
    Contributor

    x/pkgsite is a go/doc renderer. If we make a change here, it would be for all of go/doc, not just x/pkgsite. Retitled.

  18. kylelemons commented on Aug 28, 2021

    @kylelemons
    Contributor

    I have used backticks in my own documentation before, and I think the data looks like this would result in many more links without users having to do it themselves. I'm in support of this proposal under whichever syntax, but that's the one I'm drawn to. I also tend to think the markdown ship has sailed.

    I wonder if some of the code used for the analysis or implementation could be used to adjust whichever syntaxes we don't choose to make a gofix-like tool to swap them, and maybe even have an optional flag to add the syntax to #25444 compatible matches for authors to review.

  19. rsc commented on Sep 10, 2021

    @rsc
    Contributor

    See #48305.

  20. rsc commented on Feb 9, 2022

    @rsc
    Contributor

    Closing as duplicate of #51082.

  21. rsc commented on Feb 9, 2022

    @rsc
    Contributor

    This proposal is a duplicate of a previously discussed proposal, as noted above,
    and there is no significant new information to justify reopening the discussion.
    The issue has therefore been declined as a duplicate.
    — rsc for the proposal review group

  22. moved this to Declined in Proposalson Aug 10, 2022
  23. locked and limited conversation to collaborators on Feb 9, 2023
  24. removed this from Proposalson Feb 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions