--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/eQxFFSRKL24/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/01c4a98c-30f4-4cd6-bc7f-a7edf781641an%40googlegroups.com.
In Go, if you want to convert a type or a type name (go/types.TypeName) to an ast.Decl, you're essentially looking to map a type information structure from the go/types package to its corresponding declaration in the go/token package.
The go/types.TypeName represents a type name in the Go type system, while ast.Decl is part of the abstract syntax tree (AST) and represents a declaration in Go source code.
Here's a general approach you can take to achieve this:
Locate the Source Position: Use the go/types package to get the position of the type declaration. The go/types.TypeName object should have information about its position in the source code, but this might be a bit indirect since go/types does not provide direct mapping to ast.Decl.
Read the Source File: Once you have the position, you can use the go/parser package to read and parse the source file to find the specific declaration.
Map the Position to the AST Declaration: Using the source file content and the position, you can find the corresponding declaration in the AST.
Here’s a step-by-step outline of how you might implement this:
Example CodeLoad Package: Use golang.org/x/tools/go/packages to load the Go package you’re interested in. This will give you access to the syntax trees and type information.
Search for Type Declaration: Iterate through the syntax trees to find the type declaration that matches your typeName. This is done by checking each declaration in the file to see if it matches the type you're looking for.
Get Position: Once you find the type declaration, get its position using pkg.Fset.Position(). This gives you the line and column information of the declaration.
Return Results: Return the position and filename where the type declaration was found.
This method is useful for tooling and analysis where you need to connect type information with its corresponding code in the source file.