Skip to content

Fprint can eat empty lines. #81

@sirkon

Description

@sirkon

Hi!

I run into an issue where dst eats empty lines on formatting.

Example:

// main.go
package main

import (
	"fmt"
	"github.com/dave/dst/decorator"
	"go/parser"
	"go/token"
	"os"
)

func main() {
	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "main.go", nil, parser.AllErrors|parser.ParseComments)
	if err != nil {
		panic(err)
	}

	d, err := decorator.DecorateFile(fset, file)
	if err != nil {
		panic(err)
	}

	if err := decorator.Fprint(os.Stdout, d); err != nil {
		panic(err)
	}


	a := "Hello, world!"
	fmt.Println(a)
}

As you see, there are two empty lines before the a := "…".

And go run main.go outputs (omitting the output's head):

…
        if err := decorator.Fprint(os.Stdout, d); err != nil {
                panic(err)
        }
        a := "Hello, world!"
        fmt.Println(a)
}
Hello, world!

It cuts all empty lines before the string declaration although it has to be remained exactly one empty line.

I don't really understand what's happening, something with white space literals may be? I definitely know this is something in dst though:

fs, ft, _ := decorator.RestoreFile(d)
printer.Fprint(os.Stdout, fs, ft)

also cuts these lines. Printing original fset/file with printer.Fprint works as expected with exactly one empty line remained.

PS These "fenced code blocks" may change WS characters, so I attached the original main.go too (github don't allow to attach *.go files, this .txt suffix is just a workaround).
main.go.txt

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