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

x/tools/gopls: improve support for authoring cgo packages #35721

Open
heschik opened this issue Nov 20, 2019 · 43 comments
Open

x/tools/gopls: improve support for authoring cgo packages #35721

heschik opened this issue Nov 20, 2019 · 43 comments
Labels

Comments

@heschik
Copy link
Contributor

@heschik heschik commented Nov 20, 2019

Forked from #31561. This issue is not for users of cgo packages; that issue is #35720.

Beta instructions: #35721 (comment) contains instructions on how to build a version of Go and gopls that should work well for authoring cgo packages.

Files that import "C" are not really valid Go. They depend heavily on extra information that is produced by the go tool when it builds the package. They can be parsed, but not type checked, though there is some rudimentary support for working around the issues by setting the go/types.Config.FakeImportC flag.

Many people have suggested that gopls use the package's GoFiles rather than its CompiledGoFiles. The GoFiles are the original (invalid) files. Using those may give a slightly better experience for people editing the package, but it will completely break anything that depends on the type information, since the package will no longer type check. We would have to evaluate the effects very carefully before making that change in the current architecture.

We could consider type checking cgo packages twice, once with the real code and once with the user's code. That would be a significant architectural change.

Alternatively, we could run the cgo tool as the .go files change to produce the real code. This is a much more robust approach, but the cost of running cgo processing may be too high, especially on large packages.

No matter what, this is a large project that will need a lot of testing and thought. It's unlikely we'll make huge improvements here very soon.

@OneOfOne
Copy link
Contributor

@OneOfOne OneOfOne commented Nov 20, 2019

A suggestion (not sure how viable it is) would be to use clangd if it's available and proxy the C code to it.

@heschik
Copy link
Contributor Author

@heschik heschik commented Nov 20, 2019

That's probably overkill, but does point to an approach I didn't mention: tightly integrate cgo processing into gopls so that we can mitigate the performance problems of running the actual cgo tool. As you imply, the expensive part of cgo is learning about the C code. If we could separate that part from the code generation part, we could cache the C information and run just code generation when .go files changed. That might be the ideal solution, but would require changes to the cgo tool's implementation.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 20, 2019

Possibly related to #16623?

(It's been a while since I've worked on any go/types-based tools though. I seem to recall something changed where it became easier to process cgo-using packages, if still not perfect, and working on #16623 dropped in priority for me... maybe column position information?)

@heschik
Copy link
Contributor Author

@heschik heschik commented Nov 20, 2019

Definitely related. If the net result of that change was that GoFiles was [x.go, y.go] and CompiledGoFiles was [x.go,y.go,$GOCACHE/.../_cgo_gotypes.go] per #16623 (comment) then I think we would be in much better shape.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 20, 2019

@heschik To confirm, by "much better shape" do you mean you think there would still be further work to do to address this issue? (Seems like this would address #35720 too, actually.)

Looking at CLs 33677 and 33678 again, I think they're probably in reasonable shape to polish up for the next release cycle. I think the main issues are:

  1. Is go/types.Config.UsesCgo the right API for enabling that setting within go/types?

  2. CL 33678 needs to set go/types.Config.UsesCgo instead of FakeImportC. (CL 33677 PS1 originally just extended the semantics of FakeImportC; PS4 instead added UsesCgo, but it looks like I never pushed a matching revision of CL 33678.)

  3. It probably also needs to be ported to go/packages too? How does gopls actually invoke go/types?

@heschik
Copy link
Contributor Author

@heschik heschik commented Nov 21, 2019

Further work: Yes -- we'd still have to regenerate the generated file sometimes. But that's a much more manageable concern.

#35720: I think we want a fix for that before 1.15 is released. Otherwise I'd say yeah.

If you have a set of patches that work against master, even if the API is rough, I'm happy to work to get go/packages working on top of it if that's necessary. But as long as go list -json returns the right stuff in CompiledGoFiles there shouldn't be anything much to do for either go/packages or gopls -- both just follow go list's lead.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 21, 2019

@heschik FYI, I just rebased CL 33677 and fixed merge conflicts. I verified that tests still pass, but haven't done anything more extensive than that.

I don't see CompiledGoFiles when I run go list -json net though. Is cmd/go supposed to be running cmd/cgo?

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 21, 2019

Nevermind. Read the docs and realized it needs to be invoked as go list -json -compiled net.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 21, 2019

I think cmd/go will need a new flag to indicate that you want the unprocessed versions of CgoFiles rather than the processed versions. Old tools might not be able to handle the processed versions, and we can't just break those. I'm not sure what the best way to control this is.

However, for the short term, here's what I think you can do within go/packages:

  1. CompiledGoFiles consists of (in this order): GoFiles, cgo(CgoFiles), SFiles, CFiles, CXXFiles.

  2. The cgo(CgoFiles) list consists of 1 entry per CgoFiles, plus 2 more fixed entres. _cgo_types.go is the first element (and is what provides the C pseudo-package declarations); the last one is _cgo_dynimport.go (which just provides compiler directives that influence linker behavior, and isn't relevant to go/types).

  3. You want to pass to go/types: GoFiles, CgoFiles, and the first file from cgo(CgoFiles). I.e., rather than taking CompiledGoFiles and filtering out the non-go files, take GoFiles; and if CgoFiles is non-empty, take CgoFiles and CompiledGoFiles[len(GoFiles)] too.

  4. You also need to set go/types.Config.UsesCgo = true.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 21, 2019

https://go-review.googlesource.com/c/tools/+/208264 is an ugly hack to do the above. It passes go test, but I haven't tried using it with gopls.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 21, 2019

Updated CL 33677 for parity with CL 43970.

With CL 33677 and CL 208264 in place, I can run:

$ cd $(go env GOROOT)/misc/cgo/test
$ GOPACKAGESDRIVER=off gopackages -json -mode=types .

and confirm that it's processing the original .go sources, and it's type-checking okay.

Edit: GOPACKAGESDRIVER=off is necessary because I simply hacked the golist driver implementation. The proper solution here will probably require extending the go/packages driver interface.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 22, 2019

@heschik I think CLs 33677 and 208264 should be in good shape if you want to play with them in the context of gopls.

@heschik
Copy link
Contributor Author

@heschik heschik commented Nov 22, 2019

I'm just about done with #35720, and then I'm excited to give the patches a try. Should be Monday.

@heschik
Copy link
Contributor Author

@heschik heschik commented Nov 25, 2019

So, this is a bit of a good news/bad news situation.

The good news is that @mdempsky's patches work beautifully, and features like autocomplete start working in cgo files with no changes to gopls whatsoever. As I said before, there's still some work to re-trigger cgo compilation when appropriate, and the import "C" line currently shows an error, but these should be pretty tractable problems.

The bad news is that these are changes to the compiler and standard library. As such, they won't be ready until Go 1.15, scheduled for about 8 months from now. Hopefully we can land them early in the cycle so that people can try them out. If there's demand, I can write up some instructions on how to set up an environment with local patches even now.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 25, 2019

The bad news is that these are changes to the compiler and standard library.

It's only a standard library change, so it should be possible to backport the changes via vendoring if gopls users want to use it before 1.15.

@heschik
Copy link
Contributor Author

@heschik heschik commented Nov 25, 2019

I don't think that's a good option in module mode, unfortunately.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Nov 25, 2019

@heschik Fair enough. I'm still very much a modules noob, so I defer to your expertise on how best to address the issue. I mostly wanted to clarify that compiler changes aren't involved here.

I'd be curious what happens for "jump to definition" on a C.foo symbol. I'm guessing it jumps to the _cgo_gotypes.go file?

We could maybe get cgo to emit //line directives to make it point into the C preamble and/or header files if that would be more useful.

@sorenvonsarvort
Copy link

@sorenvonsarvort sorenvonsarvort commented Dec 22, 2019

So, this is a bit of a good news/bad news situation.

The good news is that @mdempsky's patches work beautifully, and features like autocomplete start working in cgo files with no changes to gopls whatsoever. As I said before, there's still some work to re-trigger cgo compilation when appropriate, and the import "C" line currently shows an error, but these should be pretty tractable problems.

The bad news is that these are changes to the compiler and standard library. As such, they won't be ready until Go 1.15, scheduled for about 8 months from now. Hopefully we can land them early in the cycle so that people can try them out. If there's demand, I can write up some instructions on how to set up an environment with local patches even now.

Wow, that would be so useful. There are many people who use cgo because of various reasons, I think all of us will appreciate the information so much.

@heschik

This comment was marked as outdated.

@sorenvonsarvort
Copy link

@sorenvonsarvort sorenvonsarvort commented Dec 24, 2019

GOROOT_BOOTSTRAP=$(dirname $(which go))/.. ./make.bash

In Arch Linux You should write GOROOT_BOOTSTRAP=/usr/lib/go, but $ which go returns /usr/bin/go.

Thank You, it works like magic!

@stamblerre stamblerre removed this from the gopls unplanned milestone Jan 29, 2020
@heschik
Copy link
Contributor Author

@heschik heschik commented May 20, 2020

Here's the current status: if you build gopls at master with tip Go, you should have a pretty good cgo authoring experience. The one bug I know of is autocomplete, which will offer symbols like _cgo_foo instead of C.foo.

One bump, though, is that it won't regenerate the cgo bindings unless you tell it to. To that end, there should be a "regenerate cgo" popup on top of the import "C" line in a file that uses cgo. You'll need to use it when you reference a new identifier from C, or change the magic comment in a way that affects the symbols Go can see.

To get set up, follow these instructions:

$ go get golang.org/dl/gotip
$ gotip download
[...]
Success. You may now run 'gotip'!
$ cd /
$ GO111MODULE=on gotip get golang.org/x/tools/gopls@master
$ gotip version
... devel +f7f9c8f ...
$ gotip version $(which gopls)
... devel +f7f9c8f ...

You don't need to use tip Go to work on your own project, just to build gopls.

Please leave a reaction on this comment if you try it out, and comment with any bugs you find.

xujianhai666 added a commit to xujianhai666/go-1 that referenced this issue May 21, 2020
This CL adds a UsesCgo config setting to go/types to specify that the
_cgo_gotypes.go file generated by cmd/cgo has been provided as a
source file. The type checker then internally resolves C.bar qualified
identifiers to _Cfoo_bar as appropriate.

It also adds support to srcimporter to automatically run cgo.
Unfortunately, this functionality is not compatible with overriding
OpenFile, because cmd/cgo and gcc will directly open files.

Updates golang#16623.
Updates golang#35721.

Change-Id: I1e1965fe41b765b7a9da3431f2a86cc16025dee2
Reviewed-on: https://go-review.googlesource.com/c/go/+/33677
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
xujianhai666 added a commit to xujianhai666/go-1 that referenced this issue May 21, 2020
(Reland of golang.org/cl/33677.)

This CL adds a UsesCgo config setting to go/types to specify that the
_cgo_gotypes.go file generated by cmd/cgo has been provided as a
source file. The type checker then internally resolves C.bar qualified
identifiers to _Cfoo_bar as appropriate.

It also adds support to srcimporter to automatically run cgo.
Unfortunately, this functionality is not compatible with overriding
OpenFile, because cmd/cgo and gcc will directly open files.

Updates golang#16623.
Updates golang#35721.

Change-Id: Ib179d55c8c589916f98ceeae0b9a3e746157253a
Reviewed-on: https://go-review.googlesource.com/c/go/+/231459
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
@beakbeak
Copy link

@beakbeak beakbeak commented May 21, 2020

Thanks for this! I encountered the following errors from gopls that do not occur when running go build:

// enum EnumType { EnumValue };
import "C"

func ReturnEnum() C.enum_EnumType { // enum_EnumType not declared by package C
	return C.EnumValue
}
// int ReturnInt(int x) { return x; }
import "C"
import "unsafe"

func ReturnFunctionAsPointer() unsafe.Pointer {
	return unsafe.Pointer(C.ReturnInt)
}

func CallFunction() C.int {
	return C.ReturnInt(1) // invalid operation: cannot call non-function C.ReturnInt (variable of type unsafe.Pointer)
}
// typedef struct Struct { int Member; } StructType;
import "C"

func (*C.StructType) method() int {
	return 0
}

func CallMethod(foo *C.StructType) {
	foo.method() // foo.method undefined (type *_Ctype_struct_Struct has no field or method method)
}
@heschik
Copy link
Contributor Author

@heschik heschik commented May 21, 2020

@beakbeak Thanks! @mdempsky, see https://golang.org/cl/234878 for tests. I checked that at least one of them works fine with the real compiler. Given that much of the other C stuff works, I don't think this is on my end of things.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented May 21, 2020

@beakbeak Thanks for the report. I'll look into those.

As a side note, I think func (*C.StructType) method() shouldn't be accepted, and I think it's a cmd/cgo issue that it's currently accepted. I'd recommend not relying on that if you can avoid it.

@ianlancetaylor
Copy link
Contributor

@ianlancetaylor ianlancetaylor commented May 21, 2020

@beakbeak Do you know of real code that defines a Go method on a type defined in C?

@beakbeak
Copy link

@beakbeak beakbeak commented May 21, 2020

@ianlancetaylor No, sorry. I encountered it in an old personal project of mine. I was a bit surprised to see that it was allowed.

@mdempsky
Copy link
Member

@mdempsky mdempsky commented May 22, 2020

@beakbeak Thanks. It certainly isn't intended to work. It's just an unfortunate consequence of how cmd/cgo is implemented, and an oversight in hiding those implementation details from users.

@ianlancetaylor
Copy link
Contributor

@ianlancetaylor ianlancetaylor commented Jun 15, 2020

Not sure why this is marked for 1.15. Moving to backlog.

@ianlancetaylor ianlancetaylor modified the milestones: Go1.15, Backlog Jun 15, 2020
@heschik heschik removed this from the Backlog milestone Jun 15, 2020
@heschik
Copy link
Contributor Author

@heschik heschik commented Jun 15, 2020

Because it depended on go/types changes, but those have landed, at least enough for us, for now.

@stamblerre
Copy link
Contributor

@stamblerre stamblerre commented Jul 23, 2020

@heschik: Will we be able to close this when Go 1.15 is released, or will there still be further work to do here?

@heschik
Copy link
Contributor Author

@heschik heschik commented Jul 23, 2020

#39072 is still a problem, but the fix is mostly or entirely in the stdlib, so I think it'd be reasonable to close this one if you want.

@stamblerre
Copy link
Contributor

@stamblerre stamblerre commented Jul 23, 2020

Oh ok, well let's keep this open for tracking as long as there are still open issues. Should we milestone #39072 for 1.16?

@heschik
Copy link
Contributor Author

@heschik heschik commented Jul 23, 2020

Done.

netbsd-srcmastr pushed a commit to NetBSD/pkgsrc that referenced this issue Jul 31, 2020
0.4.3

Disable the fillstruct analysis by default.
We recently uncovered some performance issues with the analysis, leading us to disable it by default.
Once those issues are resolved, we will enable it by default again.
You can still enable it by adding the following to your VS Code settings:

"gopls": {
	"analyses": {
		"fillstruct": true,
	}
}


gopls/v0.4.2

    Significant memory improvements (@heschik). Dependency test variants and vendored packages are no longer considered "workspace packages".
    Smart autocompletion for "append" (@muirdm).
    A "fill struct" code action to suggest populating a struct literal with default values (@luciolas, @joshbaum).
    Better cgo support with Go 1.15 (@heschik). Learn more: golang/go#35721 (comment).
    Code lens to run Go tests directly in the editor (@martskins). Currently opt-in:

"gopls": {
    "codelens": {
        "test": true,
    }
}

    Improved folding in composite literals (@joshbaum).
    Pop-up suggestion to run go mod vendor when inconsistent vendoring detected (@stamblerre).
    Respect GOPRIVATE for all document links and links on hover (@findleyr).
    A full list of issues resolved in this release can be found in the gopls/v0.4.2 milestone.

gopls/dev.go2go: You can use the new go2go prototype with gopls. See golang/go#39619.
@Zincr0
Copy link

@Zincr0 Zincr0 commented Jul 31, 2020

Here's the current status: if you build gopls at master with tip Go, you should have a pretty good cgo authoring experience. The one bug I know of is autocomplete, which will offer symbols like _cgo_foo instead of C.foo.

One bump, though, is that it won't regenerate the cgo bindings unless you tell it to. To that end, there should be a "regenerate cgo" popup on top of the import "C" line in a file that uses cgo. You'll need to use it when you reference a new identifier from C, or change the magic comment in a way that affects the symbols Go can see.

To get set up, follow these instructions:

$ go get golang.org/dl/gotip
$ gotip download
[...]
Success. You may now run 'gotip'!
$ cd /
$ GO111MODULE=on gotip get golang.org/x/tools/gopls@master
$ gotip version
... devel +f7f9c8f ...
$ gotip version $(which gopls)
... devel +f7f9c8f ...

You don't need to use tip Go to work on your own project, just to build gopls.

Please leave a reaction on this comment if you try it out, and comment with any bugs you find.

i'm seeing the "error" in the import "C" line and the "regenerate cgo definitions" in vscode but nothing happens when i click it, no errors, no nothing at all. Is there a way to force it? a console command or something?

@heschik
Copy link
Contributor Author

@heschik heschik commented Aug 3, 2020

@Zincr0 It would be good to add a progress notification, but right now there's no feedback. The only thing that should happen is that any changes you made in the cgo-using code will be reflected, resulting in errors going away or appearing as appropriate. Are you seeing changes not take effect? Can you be specific about what you're seeing vs. what you expect to see?

@Zincr0
Copy link

@Zincr0 Zincr0 commented Aug 5, 2020

I'm importing a static library and getting an error in the 'import "C"' line. Clicking regenerate cgo definitions doesn't make the linter error go away, i'm guessing that maybe all of this is for for embedded C code only, and not for static libraries?

@heschik
Copy link
Contributor Author

@heschik heschik commented Aug 5, 2020

The only errors regenerating cgo would fix are compiler errors related to the C "package". Lint errors are a separate issue.

Whatever you're seeing, I'm not sure it's related to this issue. Please file a new issue, particularly including the exact error.

@Zincr0
Copy link

@Zincr0 Zincr0 commented Aug 5, 2020

Created #40595

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

Successfully merging a pull request may close this issue.

None yet
9 participants
You can’t perform that action at this time.