Repository navigation
Description
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.- E.g.,
[Write]within the documentation of thebytes.Buffertype refers to thebytes.Buffer.Writemethod.
- E.g.,
[ExportedIdent]where it references a variable, constant, type, or function in the current package.- E.g.,
[Buffer]in thebytespackage would refer to thebytes.Buffertype.
- E.g.,
[ExportedIdent.ExportedIdent]where it references a method or field on a type in the package.- E.g.,
[Buffer.Write]in thebytespackage would refer to thebytes.Buffer.Writemethod.
- E.g.,
[PackageName.ExportedIdent]where it references variable, constant, type, or function in another package.- E.g.,
[io.EOF]would refer to theio.EOFvariable.
- E.g.,
[PackageName.ExportedIdent.ExportedIdent]where it references a method or field on a type in another package.- E.g.,
[io.Reader.Read]would refer to theio.Reader.Readmethod.
- E.g.,
["ImportPath"]where it references a package or module.- E.g.,
["google.golang.org/protobuf/proto"]would refer to theprotopackage.
- E.g.,
["ImportPath".ExportedIdent]where it references a method or field in another package.- E.g.,
["google.golang.org/protobuf/proto".Message]would refer to theproto.Messagetype.
- E.g.,
["ImportPath".ExportedIdent.ExportedIdent]where it references a method or field on a type in another package.- E.g.,
["google.golang.org/protobuf/proto".MarshalOptions.Deterministic]would refer to theproto.MarshalOptions.Deterministicfield.
- E.g.,
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(...) errorwould 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:- mapKeyFoo
- 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:
- How to identify references in Go documentation (e.g.,
io.EOF), and - 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:
- are Go code inlined within a paragraph of normal text:
- E.g., map[Key]bool
- E.g., [gcs.KeySize]byte
- While these are technically correct matches, the removal of the brackets would cause the documentation to render strangely (e.g., mapKeyFoo). We could improve this situation in the future, but it's probably better to not link these initially.
- are some pre-existing custom markup (usually Markdown):
- E.g., [ConsensusCreateTopicTransactionBody](#proto.ConsensusCreateTopicTransactionBody)
- E.g., [ListClusterAdminCredentials](https://docs.microsoft.com/en-us/rest/api/aks/managedclusters/listclusteradmincredentials)
- It appears that the most common markup syntax is some flavor of Markdown, but this proposal deliberately does not aim to handle arbitrary Markdown, which can be a future proposal.
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:
- Most of them are from the same module with it's own markup syntax:
- ~1.1k from godot-go/godot-go
- ~700 from tiezhong2004/iecp5 and forks of it
- ~200 from modernc.org/sqlite
- ~200 from yandex-cloud/go-genproto
- Some are generated packages, which don't tend to aim for readable GoDoc packages anyways.
- Some already contain non-standard markup (e.g., HTML). The Go documentation already renders strangely and I don't think this feature is going to make it any worse.
- Some matches seem to do what the user intended:
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:
- we don't hot-link standalone package names (e.g.,
[os]will not be linked to https://pkg.go.dev/os), - 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
dsnet commentedon Apr 13, 2021
\cc @julieqiu @jba @dmitshur
josharian commentedon Apr 13, 2021
dsnet commentedon Apr 13, 2021
mvdan commentedon Apr 13, 2021
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.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 exampleormodule testis hugely important.I assume that the advice there would be to link the entire import path instead, which makes sense to me.
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 viago fix, using the same heuristic code?peterbourgon commentedon Apr 13, 2021
I strongly object to this proposal.
mvdan commentedon Apr 13, 2021
@peterbourgon care to explain why?
peterbourgon commentedon Apr 13, 2021
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.
mvdan commentedon Apr 13, 2021
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.
peterbourgon commentedon Apr 13, 2021
Insofar as links mean semantic markup, I don't agree. I don't want any kind of semantic markup in Go package docs.
josharian commentedon Apr 13, 2021
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.
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.)
22 remaining items
jba commentedon Apr 14, 2021
It is a slippery slope, but the magnitude of the slope is 1 feature/decade.
ChrisHines commentedon Apr 16, 2021
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.
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:
I think this is a good question that hasn't been answered yet.
rsc commentedon Apr 21, 2021
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
[-]proposal: x/pkgsite: support explicit hotlinking syntax [/-][+]proposal: go/doc: support explicit hotlinking syntax [/+]rsc commentedon Apr 21, 2021
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.
kylelemons commentedon Aug 28, 2021
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.
rsc commentedon Sep 10, 2021
See #48305.
rsc commentedon Feb 9, 2022
Closing as duplicate of #51082.
rsc commentedon Feb 9, 2022
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