Skip to content

go/parser: files parsed with mode 'parser.ImportsOnly|parser.ParseComments' can contain a comment after import declaration #47778

Open

Description

@ShoshinNikita

What version of Go are you using (go version)?

$ go version
go version go1.17 linux/amd64

Does this issue reproduce with the latest release?

Yes

What did you do?

  1. Parse the following source code with mode parser.ImportsOnly|parser.ParseComments:
// Package main
package main

import (
	// fmt import
	_ "fmt"
	_ "github.com/pkg/errors" // errors import
)

// F func
func F() {}

// B func
func B() {}

// Hello const
const Hello = "word"

func main() {
}
  1. Print *ast.File.Comments

The Go Playground link: https://play.golang.org/p/w0yK1K_q4tr

What did you expect to see?

3 comments:

"Package main\n"
"fmt import\n"
"errors import\n"

What did you see instead?

4 comments:

"Package main\n"
"fmt import\n"
"errors import\n"
"F func\n"

"F func\n" is an extra comment because the documentation for parser.ImportsOnly says stop parsing after import declarations. However, if an import declaration is followed by any code without comments, there will be no extra comments. For example:

// Package main
package main

import (
	_ "fmt" // fmt import
)

var A = 1

// F func
func F() {}

This bug was originally discovered in #47436 (comment)

Activity

  1. mknyszek commented on Aug 18, 2021

    @mknyszek
    Contributor
  2. added
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Aug 18, 2021
  3. mknyszek commented on Aug 18, 2021

    @mknyszek
    Contributor

    @ShoshinNikita is this new in 1.17? Putting in backlog for now assuming it isn't.

  4. added this to the Backlog milestone on Aug 18, 2021
  5. ShoshinNikita commented on Aug 18, 2021

    @ShoshinNikita
    Author

    @mknyszek I discovered this bug before 1.17 release

  6. gopherbot commented on Aug 18, 2021

    @gopherbot
    Contributor

    Change https://golang.org/cl/343369 mentions this issue: go/parser: fix incorrect comment parsing

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

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions