Skip to content

A spaced // line … is treated as the Go //line directive, so ordinary comments survive a strip in fragments #27

Description

@P4suta

Found running ocomment fix --policy legal over a Go repository of ~1000 files.

What happens

Go’s line directive is //line file:line with no space after the slashes —
a // comment with a space is an ordinary comment and the compiler ignores it.
ocomment matches the spaced form as a directive and keeps it:

$ ocomment scan --policy legal internal/discover/guard.go
guard.go:484:1: directive keep (tool or language directive) 11313..11389: // line the user put it on. Two of those deletions are as long as the s…
guard.go:485:1: line remove 11390..11392: //
guard.go:486:1: directive keep (tool or language directive) 11393..11409: // line break in

Nothing there is a directive. Line 484 is the middle of a sentence and line 486
is the middle of another.

Why it matters more than a missed comment

A Go doc comment is a run of // lines. Keeping one line out of the middle of a
run and removing the rest does not leave the comment — it leaves a fragment that
reads as a sentence about something else:

// line the user put it on. Two of those deletions are as long as the source
//
//	line break in
func (g *guardResolver) cutIsLineFree(spec *ast.ValueSpec) bool {

Across the repository this left about 200 such fragments in 70 files, each one
prose with its subject deleted. A partially removed comment is worse than a kept
one, because a reader cannot tell it is partial.

The rule

From the Go spec and cmd/compile: a line directive is
//line :line, //line :line:col, //line filename:line, or
//line filename:line:col, and the // must be followed immediately by
line// line is not one. The same holds for //go: directives, which
ocomment already appears to get right.

Suggested fix: require the directive name to start at byte 2 of the comment.

What I did instead

Wrote a throwaway go/ast pass to find the real comment spans and remove them,
which also has the property that it cannot touch a // inside a raw string
literal — Go test files in this repository embed whole Go programs as backquoted
strings, and those contain comments that must survive.

Versions

ocomment 0.1.0, macOS 27. Related to #26, which is about the same run.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions