### Basic godex usage examples Source: https://pkg.go.dev/golang.org/x/tools/cmd/godex These commands show how to use godex with full package paths, object names, multiple arguments, and partial paths (e.g., "go/types" gets prefixed with "golang.org/x/tools"). ```shell godex math ``` ```shell godex math.Sin ``` ```shell godex math.Sin fmt.Printf ``` ```shell godex go/types ``` -------------------------------- ### GOPATH Example Files Source: https://pkg.go.dev/golang.org/x/tools/internal/packagestest Example file paths for GOPATH layout. ```text golang.org/repoa#a/a.go golang.org/repob#b/b.go ``` -------------------------------- ### Install Go Tools Command Source: https://pkg.go.dev/golang.org/x/tools Use the go install command to fetch and install specific tools from the golang.org/x/tools repository. ```bash go install golang.org/x/tools/cmd/goimports@latest ``` -------------------------------- ### Install Go on Unix-like systems with curl Source: https://pkg.go.dev/golang.org/x/tools/cmd/getgo Downloads and runs the Go installer on Linux, macOS, or Windows using a shell. The command fetches the installer, makes it executable, runs it, and removes it. ```shell curl -LO https://get.golang.org/$(uname)/go_installer && chmod +x go_installer && ./go_installer && rm go_installer ``` -------------------------------- ### func Start() Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/filecache Starts the filecache background processes. ```APIDOC ## func Start ### Description Starts the filecache background processes. ### Signature `func Start()` ### Parameters None. ### Returns Nothing. ``` -------------------------------- ### Correct sync.WaitGroup usage Source: https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/waitgroup This example shows the correct pattern where Add is called before starting the goroutine to ensure proper synchronization. ```go // RIGHT var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() ... }() wg.Wait() ``` -------------------------------- ### Install Go on Windows with PowerShell/cmd.exe Source: https://pkg.go.dev/golang.org/x/tools/cmd/getgo Downloads and runs the Go installer on Windows using PowerShell or cmd.exe. The command downloads installer.exe, runs it, and removes the installer file. ```powershell (New-Object System.Net.WebClient).DownloadFile('https://get.golang.org/installer.exe', 'installer.exe'); Start-Process -Wait -NonewWindow installer.exe; Remove-Item installer.exe ``` -------------------------------- ### Install gonew Source: https://pkg.go.dev/golang.org/x/tools/cmd/gonew Installs the gonew command using the Go toolchain. Run this before using gonew. ```text go install golang.org/x/tools/cmd/gonew@latest ``` -------------------------------- ### Visit Example Source: https://pkg.go.dev/golang.org/x/tools/go/packages Example usage of Visit to log each package. It loads packages, then visits them with a post function that logs each package. ```go pkgs, err := Load(...) if err != nil { ... } Visit(pkgs, nil, func(pkg *Package) { log.Println(pkg) }) ``` -------------------------------- ### Example output Source: https://pkg.go.dev/golang.org/x/tools/go/analysis/checker Example output from the package example, showing the analysis driver printing package declarations and decl counts for example.com/a through example.com/d. The output is displayed in the Example section. ```text Output: printing pkgdecls@example.com/a printing pkgdecls@example.com/b printing pkgdecls@example.com/c printing pkgdecls@example.com/d example.com/a: 3 decls example.com/b: 2 decls example.com/c: 1 decls example.com/d: 4 decls ``` -------------------------------- ### Postorder Example Source: https://pkg.go.dev/golang.org/x/tools/go/packages Example usage of Postorder to iterate over packages in dependencies-first order and log each package. ```go for pkg := range Postorder(pkgs) { log.Println(pkg) } ``` -------------------------------- ### Example output placeholder Source: https://pkg.go.dev/golang.org/x/tools/go/packages A placeholder block representing the output of the package loading example. ```text Output: ``` -------------------------------- ### Examples of present2md usage Source: https://pkg.go.dev/golang.org/x/tools/cmd/present2md Examples showing how to convert a single file or multiple files in-place. ```bash present2md your.article present2md -w *.article ``` -------------------------------- ### Install goimports with go install Source: https://pkg.go.dev/golang.org/x/tools/cmd/goimports Use this command to install the goimports tool. Requires Go and fetches the latest version of the module. ```shell $ go install golang.org/x/tools/cmd/goimports@latest ``` -------------------------------- ### Test getgo with Docker Source: https://pkg.go.dev/golang.org/x/tools/cmd/getgo Builds and runs the getgo Docker image, then tests the installer inside the container. The output shows the installer downloading Go 1.8.3, setting up GOPATH, and updating PATH. ```shell $ docker build --rm --force-rm -t getgo . ... $ docker run --rm -it getgo bash root@78425260fad0:~# getgo -v Welcome to the Go installer! Downloading Go version go1.8.3 to /usr/local/go This may take a bit of time... Adding "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/bin" to /root/.bashrc Downloaded! Setting up GOPATH Adding "export GOPATH=/root/go" to /root/.bashrc Adding "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/bin:/root/go/bin" to /root/.bashrc GOPATH has been setup! root@78425260fad0:~# which go /usr/local/go/bin/go root@78425260fad0:~# echo $GOPATH /root/go root@78425260fad0:~# echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/bin:/root/go/bin ``` -------------------------------- ### gopls.start_profile Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/protocol/command Starts a CPU or memory profile. ```APIDOC ## gopls.start_profile ### Description Starts a CPU or memory profile. ### Method Command ### Endpoint gopls.start_profile ### Parameters #### Request Body - **Name** (string) - Required - The profile name (e.g., "cpu", "heap"). ### Response #### Success Response - **string** - The profile file path. #### Response Example ```json "/tmp/profile" ``` ``` -------------------------------- ### Video command examples Source: https://pkg.go.dev/golang.org/x/tools/present Shows two examples of the .video command with content type and optional dimensions, using underscore for aspect ratio. ```text .video videos/evangeline.mp4 video/mp4 400 600 .video videos/mabel.ogg video/ogg 500 _ ``` -------------------------------- ### Example input file for digraph Source: https://pkg.go.dev/golang.org/x/tools/cmd/digraph An example of an acyclic graph input file defining dependencies between tasks. ```text $ cat clothes.txt socks shoes "boxer shorts" pants pants belt shoes shirt tie sweater sweater jacket hat ``` -------------------------------- ### Image command examples Source: https://pkg.go.dev/golang.org/x/tools/present Shows two examples of the .image command: one with explicit height and width, and one using underscore to preserve aspect ratio. ```text .image images/betsy.jpg 100 200 .image images/janet.jpg _ 300 ``` -------------------------------- ### Lang function examples Source: https://pkg.go.dev/golang.org/x/tools/internal/versions Examples of Lang outputs for various inputs, showing the language version extraction. ```go Lang("go1.21rc2") = "go1.21" Lang("go1.21.2") = "go1.21" Lang("go1.21") = "go1.21" Lang("go1") = "go1" Lang("bad") = "" Lang("1.21") = "" ``` -------------------------------- ### MaybeStdPackage example output Source: https://pkg.go.dev/golang.org/x/tools/internal/packagepath Example output of MaybeStdPackage showing true for standard library paths and false positives, and false for non-standard paths. For a definitive answer, use stdlib.HasPackage. ```go MaybeStdPackage("fmt") = true MaybeStdPackage("maybe/tomorrow") = true // false positive MaybeStdPackage("example.com/foo") = false ``` -------------------------------- ### Example testdata directory structure Source: https://pkg.go.dev/golang.org/x/tools/internal/testfiles Shows the source directory structure used in the CopyToTmp example, including a go.mod.test file and Go source files. ```text testdata/ go.mod.test a/a.go b/b.go ``` -------------------------------- ### Example package painkiller with Pill constants Source: https://pkg.go.dev/golang.org/x/tools/cmd/stringer Example Go package with a type Pill and constants defined using iota, used to demonstrate stringer's behavior. ```go package painkiller type Pill int const ( Placebo Pill = iota Aspirin Ibuprofen Paracetamol Acetaminophen = Paracetamol ) ``` -------------------------------- ### Configure and Load Packages with loader.Config Source: https://pkg.go.dev/golang.org/x/tools/go/loader Demonstrates how to configure initial packages using command-line arguments, filenames, or imports, and then load the program. ```go var conf loader.Config // Use the command-line arguments to specify // a set of initial packages to load from source. // See FromArgsUsage for help. rest, err := conf.FromArgs(os.Args[1:], wantTests) // Parse the specified files and create an ad hoc package with path "foo". // All files must have the same 'package' declaration. conf.CreateFromFilenames("foo", "foo.go", "bar.go") // Create an ad hoc package with path "foo" from // the specified already-parsed files. // All ASTs must have the same 'package' declaration. conf.CreateFromFiles("foo", parsedFiles) // Add "runtime" to the set of packages to be loaded. conf.Import("runtime") // Adds "fmt" and "fmt_test" to the set of packages // to be loaded. "fmt" will include *_test.go files. conf.ImportWithTests("fmt") // Finally, load all the packages specified by the configuration. prog, err := conf.Load() ``` -------------------------------- ### func Start Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/filecache Start causes the filecache to initialize and start garbage collection. It is automatically called by the first call to Get, but may be called explicitly to pre-initialize the cache. ```APIDOC ## func Start ### Description Start causes the filecache to initialize and start garbage gollection. Start is automatically called by the first call to Get, but may be called explicitly to pre-initialize the cache. ### Signature ```go func Start() ``` ``` -------------------------------- ### NewDatabase usage example Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/vulncheck/vulntest Shows how to create a database, defer its Clean method, and create a client. The Clean method must be called to clean up the generated database. ```go db, err := NewDatabase(ctx, reports) ... defer db.Clean() client, err := NewClient(db) ... ``` -------------------------------- ### Markdown-enabled present file example Source: https://pkg.go.dev/golang.org/x/tools/present Complete example of a Markdown-enabled present file. Shows header, author block, section headings with optional {#anchor} IDs, bullet lists, indented code blocks, comments (lines starting with //), speaker notes (lines starting with ': '), and inline formatting. ```markdown # Title of Talk My Name 9 Mar 2020 me@example.com ## Title of Slide or Section (must begin with ##) Some Text ### Subsection {#anchor} - bullets - more bullets - a bullet continued on the next line #### Sub-subsection Some More text Preformatted text (code block) is indented (by one tab, or four spaces) Further Text, including command invocations. ## Section 2: Example formatting {#fmt} Formatting: _italic_ // A comment that is completely ignored. : Speaker notes. **bold** `program` Markup—_especially italic text_—can easily be overused. _Why use scoped\_ptr_? Use plain **\*ptr** instead. Visit [the Go home page](https://golang.org/). ``` -------------------------------- ### TestGoList example: running 'go list' with packagestest Source: https://pkg.go.dev/golang.org/x/tools/go/packages/packagestest This example defines a test function that uses packagestest.Export to create a temporary project with two modules, then runs the 'go list' command. It uses TestAll to run the test with all exporters (module and GOPATH modes). The test logs the output of the command. ```go // TestGoList exercises the 'go list' command in module mode and in GOPATH mode. func TestGoList(t *testing.T) { packagestest.TestAll(t, testGoList) } func testGoList(t *testing.T, x packagestest.Exporter) { e := packagestest.Export(t, x, []packagestest.Module{ { Name: "gopher.example/repoa", Files: map[string]interface{}{ "a/a.go": "package a", }, }, { Name: "gopher.example/repob", Files: map[string]interface{}{ "b/b.go": "package b", }, }, }) defer e.Cleanup() cmd := exec.Command("go", "list", "gopher.example/...") cmd.Dir = e.Config.Dir cmd.Env = e.Config.Env out, err := cmd.Output() if err != nil { t.Fatal(err) } t.Logf("'go list gopher.example/...' with %s mode layout:\n%s", x.Name(), out) } ``` -------------------------------- ### NameSpace Binding Example Source: https://pkg.go.dev/golang.org/x/tools/godoc/vfs Demonstrates how to initialize a NameSpace and bind multiple file systems to it. ```go ns := NameSpace{} ns.Bind("/", OS(`c:\Go`), "/", BindReplace) ns.Bind("/src/pkg", OS(`d:\Work1`), "/src", BindAfter) ns.Bind("/src/pkg", OS(`d:\Work2`), "/src", BindAfter) ``` -------------------------------- ### Example of incorrect call to t.Fatal from a goroutine Source: https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/testinggoroutine Shows a test function that starts a goroutine and calls t.Fatal inside it, which is an error because Fatal must be called from the test goroutine itself. ```go func TestFoo(t *testing.T) { go func() { t.Fatal("oops") // error: (*T).Fatal called from non-test goroutine }() } ``` -------------------------------- ### Package p with underscore constants for pkgfact Source: https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/pkgfact Example package with top-level constants whose names start and end with underscores. The pkgfact analysis gathers these constants into key/value pairs, stripping the underscores from the names. ```go package p const _greeting_ = "hello" const _audience_ = "world" ``` -------------------------------- ### RelString function name examples Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Examples of strings returned by RelString, showing how package-level functions, methods, thunks, and anonymous functions are formatted. ```text "math.IsNaN" // a package-level function "(*bytes.Buffer).Bytes" // a declared method or a wrapper "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) "main.main$1" // an anonymous function in main "main.init#1" // a declared init function "main.init" // the synthesized package initializer ``` -------------------------------- ### DetailedHelp method Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/cmd Implements tool.Application returning the main binary help, including short help for all sub commands. ```go func (app *Application) DetailedHelp(f *flag.FlagSet) ``` -------------------------------- ### Root().Preorder with Cursor API to find call expressions Source: https://pkg.go.dev/golang.org/x/tools/go/ast/inspector Uses the newer Cursor API to start the traversal at the root node and filter for *ast.CallExpr nodes. The example demonstrates extracting the node from the cursor before use. ```go for curCall := range in.Root().Preorder((*ast.CallExpr)(nil)) { call := curCall.Node().(*ast.CallExpr) ... } ``` -------------------------------- ### BitString method and examples Source: https://pkg.go.dev/golang.org/x/tools/container/intsets Returns the set as a string of 1s and 0s. Examples demonstrate how different sets are represented as bit strings. ```go func (s *Sparse) BitString() string ``` ```go {}.BitString() = "0" {4,5}.BitString() = "110000" {-3}.BitString() = "0.001" {-3,0,4,5}.BitString() = "110001.001" ``` -------------------------------- ### gopls.start_debugging Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/protocol/command Starts a debugging server. ```APIDOC ## gopls.start_debugging ### Description Starts a debugging server. ### Method Command ### Endpoint gopls.start_debugging ### Parameters #### Request Body - **Addr** (string) - Optional - The address for the debug server to listen on. ### Response #### Success Response - **DebuggingResult** - Contains the debug URLs. #### Response Example ```json { "URLs": ["http://localhost:0/debug"] } ``` ``` -------------------------------- ### ShortHelp method Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/cmd Implements tool.Application returning the main binary help. ```go func (app *Application) ShortHelp() string ``` -------------------------------- ### GoGetPackage Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/protocol/command Runs `go get` to fetch a package. ```APIDOC ## GoGetPackage ### Description Runs `go get` to fetch a package. ### Method GoGetPackage ### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **args** (GoGetPackageArgs) - Required - The arguments for the package, including the URI, the package, and whether to add a require. ### Response - **error** (error) - An error if the operation fails. ``` -------------------------------- ### StartPosition Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/util/safetoken Converts a start Pos in the FileSet into a Position. Call this function only if start represents the start of a token or parse tree, such as the result of Node.Pos(). If start is the end of an interval, such as Node.End(), call EndPosition instead, as it may need the correction described at Position. ```APIDOC ## StartPosition ### Description Converts a start Pos in the FileSet into a Position. Call this function only if start represents the start of a token or parse tree, such as the result of Node.Pos(). If start is the end of an interval, such as Node.End(), call EndPosition instead, as it may need the correction described at Position. ### Signature `func StartPosition(fset *token.FileSet, start token.Pos) (_ token.Position)` ### Parameters - **fset** (*token.FileSet) - Required - The FileSet containing the position. - **start** (token.Pos) - Required - The start position to convert. ### Returns - **token.Position** - The corresponding Position. ``` -------------------------------- ### NewStartProfileCommand Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/protocol/command Creates a new protocol.Command for the start profile command with the given title and arguments. ```APIDOC ## NewStartProfileCommand ### Description Creates a new protocol.Command for the start profile command with the given title and arguments. ### Parameters - **title** (string) - Required - The title of the command. - **a0** (StartProfileArgs) - Required - The arguments for the start profile command. ### Returns - **\*protocol.Command** - The generated command. ``` -------------------------------- ### ExampleNewImporter output Source: https://pkg.go.dev/golang.org/x/tools/go/gcexportdata Example output demonstrating the usage of NewImporter. ```text Output: type net/rpc.ServerError string // $GOROOT/src/net/rpc/client.go:20:1 const serverError net/rpc.ServerError = "" // myrpc.go:6:7 ``` -------------------------------- ### FieldAddr example printed form Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example of how a FieldAddr instruction is printed. ```text t1 = &t0.name [#1] ``` -------------------------------- ### Program.Build Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Builds all packages in the program. ```go func (prog *Program) Build() ``` -------------------------------- ### MapUpdate printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example output format for the MapUpdate instruction. ```text t0[t1] = t2 ``` -------------------------------- ### MakeSlice printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example output format for the MakeSlice instruction. ```text t1 = make []string 1:int t0 t1 = make StringSlice 1:int t0 ``` -------------------------------- ### NewStore constructor Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/util/memoize Initializes a new store with a specific eviction policy. ```go func NewStore(policy EvictionPolicy) *Store ``` -------------------------------- ### MakeMap printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example output format for the MakeMap instruction. ```text t1 = make map[string]int t0 t1 = make StringIntMap t0 ``` -------------------------------- ### New function Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/cmd Returns a new Application ready to run. ```go func New() *Application ``` -------------------------------- ### Jump printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example of the printed form for a Jump instruction. ```text jump done ``` -------------------------------- ### Querying reverse dependencies Source: https://pkg.go.dev/golang.org/x/tools/cmd/digraph Example command to find which items must be donned before a jacket. ```bash $ digraph reverse jacket ``` -------------------------------- ### IndexAddr printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example of the printed form for an IndexAddr instruction. ```text t2 = &t0[t1] ``` -------------------------------- ### CallCommon Printed Form Example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example of printed form for 'call' mode. ```text t2 = println(t0, t1) go t3() defer t5(...t6) ``` -------------------------------- ### Mount table example for /src/pkg Source: https://pkg.go.dev/golang.org/x/tools/godoc/vfs Shows a mount table with three entries mapping /src/pkg to different file systems and new paths. The first entry maps to c:\Go\src\pkg, the second to d:\Work1\src, and the third to d:\Work2\src. ```go {old: "/src/pkg", fs: OS(`c:\Go`), new: "/src/pkg"}, {old: "/src/pkg", fs: OS(`d:\Work1`), new: "/src"}, {old: "/src/pkg", fs: OS(`d:\Work2`), new: "/src"}, ``` -------------------------------- ### Type switch example Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillswitch An example of a type switch statement with missing cases. ```go var stmt ast.Stmt switch stmt.(type) { case *ast.IfStmt: } ``` -------------------------------- ### Enum switch example Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillswitch An example of an enum-style switch statement with missing cases. ```go type Suit int8 const ( Spades Suit = iota Hearts Diamonds Clubs ) var s Suit switch s { case Spades: } ``` -------------------------------- ### PathEnclosingInterval inexact interval example Source: https://pkg.go.dev/golang.org/x/tools/go/ast/astutil Example illustrating intervals that are considered inexact. ```text z := x + y // add them <--C--> <---E--> ^ D ``` -------------------------------- ### PathEnclosingInterval whitespace example Source: https://pkg.go.dev/golang.org/x/tools/go/ast/astutil Example illustrating how whitespace is considered enclosed by a node. ```text z := x + y // add them <-A-> <----B-----> ``` -------------------------------- ### ExtractDoc documentation format example Source: https://pkg.go.dev/golang.org/x/tools/internal/analysis/analyzerutil Example of the expected doc comment format for ExtractDoc. ```text # Analyzer NAME NAME: SUMMARY Full description... ``` -------------------------------- ### Link command example Source: https://pkg.go.dev/golang.org/x/tools/present Demonstrates creating a hyperlink with the .link command, using a URL and an optional label. ```text .link https://golang.org golang.org ``` -------------------------------- ### func AllPackages(initial []*packages.Package, mode ssa.BuilderMode) (*ssa.Program, []*ssa.Package) Source: https://pkg.go.dev/golang.org/x/tools/go/ssa/ssautil Builds an SSA program from a set of initial Go packages and returns the program along with the corresponding SSA packages in the same order. This is the primary entry point for program construction. ```APIDOC ## AllPackages(initial []*packages.Package, mode ssa.BuilderMode) (*ssa.Program, []*ssa.Package) ### Description Builds an SSA program from a list of initial packages and returns the program and the SSA representation of each package. The order of the returned packages matches the input order. ### Signature `func AllPackages(initial []*packages.Package, mode ssa.BuilderMode) (*ssa.Program, []*ssa.Package)` ### Parameters - **initial** ([]*packages.Package) - Required - The initial packages to build. - **mode** (ssa.BuilderMode) - Required - The SSA builder mode controls construction of function bodies. ### Returns - **(*ssa.Program)** - The built SSA program. - **([]*ssa.Package)** - The SSA packages for each initial package, in the same order. ``` -------------------------------- ### Panic with nil example Source: https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/nilness Example of panicking with a nil value, which is reported by the nilness checker. ```go if p == nil { panic(p) } ``` -------------------------------- ### ExampleRead output Source: https://pkg.go.dev/golang.org/x/tools/go/gcexportdata Example output demonstrating the usage of Read to load type information for the fmt package. ```text Output: Package path: fmt Package members: Println found Println type: func(a ...any) (n int, err error) Println location: $GOROOT/src/fmt/print.go:123:1 ``` -------------------------------- ### func (s *Span) Start() core.Event Source: https://pkg.go.dev/golang.org/x/tools/internal/event/export Start returns the event that marks the beginning of the span. ```APIDOC ## func (s *Span) Start() core.Event ### Description Start returns the event that marks the beginning of the span. ### Signature ```go func (s *Span) Start() core.Event ``` ### Returns - **core.Event** - The start event. ``` -------------------------------- ### CallCommon Invoke Mode Printed Form Example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example of printed form for 'invoke' mode. ```text t1 = invoke t0.String() go invoke t3.Run(t2) defer invoke t4.Handle(...t5) ``` -------------------------------- ### NewTCPServer Constructor Source: https://pkg.go.dev/golang.org/x/tools/internal/jsonrpc2/servertest Returns a new test server listening on a local TCP port. It panics on any error. ```go func NewTCPServer(ctx context.Context, server jsonrpc2.StreamServer, framer jsonrpc2.Framer) *TCPServer ``` -------------------------------- ### Run the default vet suite Source: https://pkg.go.dev/golang.org/x/tools/go/analysis/suite/vet This snippet demonstrates how to invoke the default vet suite using unitchecker.Main. ```go func main() { unitchecker.Main(vet.Suite...) } ``` -------------------------------- ### Call Instruction Printed Form Example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example of how Call instructions appear in printed form. ```text t2 = println(t0, t1) t4 = t3() t7 = invoke t5.Println(...t6) ``` -------------------------------- ### StartProfileArgs and StartProfileResult structs Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/protocol/command Placeholder structures for the StartProfile command. ```go type StartProfileArgs struct { } ``` ```go type StartProfileResult struct { } ``` -------------------------------- ### ExtractDoc usage example Source: https://pkg.go.dev/golang.org/x/tools/internal/analysis/analyzerutil Example of how to structure a doc comment section for an analyzer named printf. ```text # Analyzer printf printf: checks consistency of calls to printf The printf analyzer checks consistency of calls to printf. Here is the complete description... ``` -------------------------------- ### HTML command example Source: https://pkg.go.dev/golang.org/x/tools/present Demonstrates including an HTML file as unescaped HTML using the .html command. ```text .html file.html ``` -------------------------------- ### Clone hello template Source: https://pkg.go.dev/golang.org/x/tools/cmd/gonew Clones the basic command-line program template golang.org/x/example/hello as your.domain/myprog in the directory ./myprog. ```text gonew golang.org/x/example/hello your.domain/myprog ``` -------------------------------- ### Initializer example Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/cache/typerefs Shows an initializer scenario where type information misses the syntactic edge between a.A and b.B. ```go package a; var A = b.B() package b; func B() string { return "hi" } ``` -------------------------------- ### Function.TypeParams method signature and examples Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Signature for the TypeParams method and examples of how it behaves for different function definitions. ```go func (fn *Function) TypeParams() *types.TypeParamList ``` ```text func f // [] func f[P] // [P] func (T) m // [] func (T) m[P] // [P] func (T[P]) m // [P] func (T[P]) m[Q] // [P (index=0), Q (index=0)] ``` -------------------------------- ### OpenFile function Source: https://pkg.go.dev/golang.org/x/tools/go/buildutil Behaves like os.Open, but uses the build context's file system interface, if any. ```go func OpenFile(ctxt *build.Context, path string) (io.ReadCloser, error) ``` -------------------------------- ### Function.TypeArgs method signature and examples Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Signature for the TypeArgs method and examples of how it behaves for different function instantiations. ```go func (fn *Function) TypeArgs() []types.Type ``` ```text f // [] f[int] // [int] T.m // [] T.m[int] // [int] T[int].m // [int] T[int].m[uint] // [int, uint] ``` -------------------------------- ### NewGCDetailsCommand constructor Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/protocol/command Creates a protocol.Command for GC details. Takes a title and a protocol.DocumentURI. ```go func NewGCDetailsCommand(title string, a0 protocol.DocumentURI) *protocol.Command ``` -------------------------------- ### Writing a simple integration test with Run Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/test/integration The Run function sets up a temporary workspace from a txtar-encoded archive and executes the provided test function with an Env instance. ```go func TestOpenFile(t *testing.T) { const files = ` -- go.mod -- module mod.com go 1.12 -- foo.go -- package foo ` Run(t, files, func(t *testing.T, env *Env) { env.OpenFile("foo.go") }) } ``` -------------------------------- ### Field printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example output showing how Field instructions appear in the SSA representation. ```text t1 = t0.name [#1] ``` -------------------------------- ### Extract printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example output showing how Extract instructions appear in the SSA representation. ```text t1 = extract t0 #1 ``` -------------------------------- ### Defer printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example output showing how Defer instructions appear in the SSA representation. ```text defer println(t0, t1) defer t3() defer invoke t5.Println(...t6) ``` -------------------------------- ### Check specific files Source: https://pkg.go.dev/golang.org/x/tools/cmd/gotype Example of checking multiple Go source files. ```bash gotype a.go b.go c.go ``` -------------------------------- ### DebugRef printed form example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example output showing how DebugRef instructions appear in the SSA representation. ```text ; *ast.CallExpr @ 102:9 is t5 ; var x float64 @ 109:72 is x ; address of *ast.CompositeLit @ 216:10 is t0 ``` -------------------------------- ### Pointer Analysis Output Example Source: https://pkg.go.dev/golang.org/x/tools/go/pointer Example output showing a conservative call-graph and points-to set for a variable. ```text Output: (main.C).f --> fmt.Println main.init --> fmt.init main.main --> (main.C).f m may point to: myprog.go:18:21: makemap ``` -------------------------------- ### Verify pipe output Source: https://pkg.go.dev/golang.org/x/tools/cmd/gotype Example of piping package source code into gotype. ```bash echo "package foo" | gotype ``` -------------------------------- ### Tracker.Start example: generate operation with cancel and error handling Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/progress Shows how to use Tracker.Start to report a long-running operation (e.g., 'go generate') with a cancel function and proper error handling. The returned WorkDone handle must be ended via End, and the cancel function is called if the operation is cancelled. ```go func Generate(ctx) (err error) { ctx, cancel := context.WithCancel(ctx) defer cancel() work := s.progress.start(ctx, "generate", "running go generate", cancel) defer func() { if err != nil { work.end(ctx, fmt.Sprintf("generate failed: %v", err)) } else { work.end(ctx, "done") } }() // Do the work... } ``` -------------------------------- ### TagsFlag usage example Source: https://pkg.go.dev/golang.org/x/tools/go/buildutil Example usage of TagsFlag with flag.Var to set the build tags from a command-line flag. ```go flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc) ``` -------------------------------- ### Nil dereference example Source: https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/nilness Example of a nil pointer dereference where p is nil and print(*p) is called. ```go if p == nil { print(*p) // nil dereference } ``` -------------------------------- ### InitialPackages Source: https://pkg.go.dev/golang.org/x/tools/go/loader Returns the initial packages of the program. ```APIDOC ## InitialPackages ### Description Returns the initial packages of the program. These are the packages that were explicitly requested to be loaded. ### Method InitialPackages ### Parameters None. ### Returns - **[]*PackageInfo** - The list of initial packages. ``` -------------------------------- ### Example: Source code navigation tool notes Source: https://pkg.go.dev/golang.org/x/tools/go/expect Notes used to indicate feature positions, actions, and expected outcomes in a source code navigation tool test suite. ```go var x = 1 //@ x_decl ... print(x) //@ definition("x", x_decl) print(x) //@ typeof("x", "int") ``` -------------------------------- ### Offsets Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/util/safetoken Returns Offset(start) and Offset(end). It returns an error if either failed, or if start > end. ```APIDOC ## Offsets ### Description Returns Offset(start) and Offset(end). It returns an error if either failed, or if start > end. ### Signature `func Offsets(f *token.File, start, end token.Pos) (int, int, error)` ### Parameters - **f** (*token.File) - Required - The file to query. - **start** (token.Pos) - Required - The start position. - **end** (token.Pos) - Required - The end position. ### Returns - **int** - The offset of start. - **int** - The offset of end. - **error** - An error if either offset fails or if start > end. ``` -------------------------------- ### func Start(ctx context.Context, name string, labels ...label.Label) (context.Context, func()) Source: https://pkg.go.dev/golang.org/x/tools/internal/event Start sends a span start event with the supplied label list to the exporter. It also returns a function that will end the span, which should normally be deferred. ```APIDOC ## func Start ### Description Start sends a span start event with the supplied label list to the exporter. It also returns a function that will end the span, which should normally be deferred. ### Signature `func Start(ctx context.Context, name string, labels ...label.Label) (context.Context, func())` ### Parameters - **ctx** (context.Context) - Required - The context. - **name** (string) - Required - The span name. - **labels** (label.Label) - Optional - Additional labels. ### Returns - **context.Context** - The updated context. - **func()** - A function to end the span. ``` -------------------------------- ### VarValue identifier evaluation example Source: https://pkg.go.dev/golang.org/x/tools/go/ssa Example showing how VarValue returns constant values for identifiers in different states. ```go var x int // VarValue(x) returns Const 0 here x = 1 // VarValue(x) returns Const 1 here ``` -------------------------------- ### MarshalArgs example usage Source: https://pkg.go.dev/golang.org/x/tools/gopls/internal/protocol/command Example usage of MarshalArgs with mixed argument types. The result is a slice of json.RawMessage and an error. ```go jsonArgs, err := MarshalArgs(1, "hello", true, StructuredArg{42, 12.6}) ```