Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

panic when incorrectly formatted code #52

Open
reinierkors opened this issue Aug 26, 2020 · 2 comments
Open

panic when incorrectly formatted code #52

reinierkors opened this issue Aug 26, 2020 · 2 comments

Comments

@reinierkors
Copy link

Hello,

This might be a real edge case, but just wanting to share.
When for example, missing a package main you will get a panic:
panic: runtime error: invalid memory address or nil pointer dereference

func TestDecorator(t *testing.T) {
	code := `import "github.com/MyPackage/Name/package1"


func main() {
	fmt.Println("Hello!")
}`
	decorator.Parse(code)
}

I think earlier versions did not fail this test, and feel like it should gracefully return an error.

@dave
Copy link
Owner

dave commented Aug 26, 2020

It's been a while since I created the dst package so I'd have to familiarise myself with the internals before making a call on this one. But, a panic is definitely not ideal and it should be returning an error.

However, I'm pretty sure you'd never want to feed any less than an entire valid go file into dst... because in ast the comments are stored on the ast.File object, so trying to parse and decorate a fragment (just an ast.Node on it's own without the ast.File) wouldn't work at all. I guess in your example this is more of a mistake rather than the intention.

@jlewi
Copy link

jlewi commented Oct 6, 2023

I hit this as well when using ParseFile.

fset := token.NewFileSet()
fset.AddFile(path, 1, 0)
root, err := decorator.ParseFile(fset, path, nil, parser.ParseComments)

The contents of the file being parsed.

func (s *SomeStruct) SomeFunc() {}

This ends up causing a panic here

max := tokenf.Base() + tokenf.Size()

Because tokenf is nil.

Its nil because astf.Pos() uses the package line to determine the first line of the file

https://github.com/golang/go/blob/10da3b64af1aebfd146fa3b7ecf765ee1b0f0d7d/src/go/ast/ast.go#L1054

But f.package is nil because there is no package statement in the file.

In my case its expected that files maybe missing the package statement; I was hoping to use the dst package to fix that. But it looks like the dst package will panic in that case.

Not expecting a fix since it looks like the package isn't being actively developed. Just intended as an FYI for anyone else hitting this issue. I'll probably work around it by ensuring there is a package statement in all my code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants