golang.org/x/tools

repository·master·Indexed 27 days ago

https://github.com/golang/tools

A suite of tools and libraries for Go static analysis. It includes gopls (the official Go language server), the go/analysis framework, and various command-line utilities such as goimports, callgraph, stringer, and the signature-fuzzer. The repository provides core functionality for loading, parsing, and type checking Go programs, as well as generating static single-assignment (SSA) intermediate representations and control-flow graphs (CFG).

Tokens
58.9K
Snippets
151
Records
471
Agent score
91%

What's inside golang-tools

  1. Overview of gopls, the Go language server

    master
    gopls (pronounced "Go please") is the official language server for Go, developed and maintained by the Go team. It implements the Language Server Protocol (LSP) to provide a wide variety of IDE features to any LSP-compatible editor.
  2. Overview of Go Tools

    master
    The golang.org/x/tools module provides a collection of tools and packages primarily designed for the static analysis of Go programs. It includes the gopls module, which is a Language Server Protocol (LSP) server that enables IDE-like functionality (such as code completion and analysis) in editors like VSCode and Vim.
  3. Overview of gopls Design and Evolution

    master

    gopls is the official Language Server Protocol (LSP) implementation for Go, serving as the default editor backend for VS Code Go and many other editors.

    Key Evolution Notes:

    • Extensibility: While originally intended to be highly extensible, the current implementation requires modifying gopls code to add new features.
    • Scalability: To handle large workspaces and reduce memory footprint, gopls uses a hybrid approach of on-disk indexes and in-memory caches.
    • Syntax Highlighting: Supported via LSP semantic tokens.
    • Build Systems: While optimized for the standard go command, it aims to support alternate build systems and file layouts (though experience with systems like Bazel may vary).
    • Telemetry: An opt-in Go telemetry feature is available to help improve stability and prioritize features.
  4. Overview of gopls LSP features

    master

    The gopls language server provides a wide range of features accessible via the Language Server Protocol (LSP). These features are categorized as follows:

    • Passive Features: Always-on capabilities including Hover (symbol info), Signature Help (type info), Document Highlight, Inlay Hints (implicit names), Semantic Tokens (syntax coloring), Folding Ranges, and Document Links (URL extraction).
    • Diagnostics: Reporting of compile errors and static analysis findings.
    • Navigation: Tools for moving through code, including Definition, Type Definition, References, Implementation, Document Symbol (file outline), Symbol (fuzzy search), Selection Range, Call Hierarchy, and Type Hierarchy.
    • Completion: Context-aware completion for identifiers and statements.
    • Code Transformation: Refactorings and fixes such as Formatting, Rename, Organize Imports, Extract (to file/function/variable), Inline, Miscellaneous rewrites, and Add test for func.
    • Web-based Queries: Commands that open a browser, such as Package documentation, Free symbols, Assembly listings, and Split package.
    • Non-Go File Support: Support for Template files (text/template, html/template), go.mod and go.work files, and Go assembly (*.s) files.
    • AI Integration: Support for the Model Context Protocol (MCP) for use in AI-assisted environments.
  5. Understand gopls architecture and components

    master

    gopls is structured in layers ranging from low-level protocol definitions to high-level language features.

    • Protocol Layer: Defines LSP request/response types (protocol package) and non-standard commands (command package) invoked via workspace/executeCommand.
    • Data Structures Layer: Provides core abstractions like file identity/handles (file package), parsed Go source trees (parsego package), and package metadata/import graphs (metadata package).
    • Settings Layer: Manages gopls configuration options and their JSON encoding.
    • Cache Layer: The core state management engine. It handles sessions, folders, workspace views, snapshots, file contents (disk vs. overlay), and memoized computations. It also includes the go/analysis driver.
    • Language Feature Layer: Contains language-specific logic: mod (go.mod), work (go.work), template (text/template), and golang (the primary package for Go navigation, analysis, and refactoring).
    • Service Layer: Implements the LSP service (server package) and connects it to the JSON-RPC transport (lsprpc and jsonrpc2).
  6. Understand gopls code transformation features

    master

    Gopls provides several types of code transformations to assist with refactoring, formatting, and editing. These include:

    • Refactorings: Behavior-preserving changes like extracting functions or inlining variables.
    • Formatting: Applying canonical Go formatting.
    • Simplifications: Automatic code improvements (e.g., simplifying for _ = range m to for range m).
    • Code Repair (Fixes): Applying safe fixes to diagnostics.
    • Editing Support: Filling in struct literals and switch statements.

    Important Caveats:

    • Comment Loss: Transformations like Extract and Inline may lose comments due to how Go's syntax tree represents them.
    • Generated Files: Files containing the // DO NOT EDIT comment are excluded from code action transformations.
  7. Understand gopls architecture and lifecycle

    master

    gopls is designed as a long-running Language Server Protocol (LSP) process that is managed by your editor. To ensure high performance and low latency, it uses several key architectural patterns:

    • Process Lifetime: The gopls process lasts as long as your editor session. It is designed to be easily restarted if it encounters state issues.
    • In-Memory Caching: gopls performs type checking and analysis by caching results in memory. It does not use a persistent disk cache, which makes the server stateless across restarts. If gopls behaves unexpectedly, restarting the editor or the gopls process is the recommended way to clear its state.
    • Communication Protocol: gopls communicates with editors using JSON-RPC 2.0 over stdin and stdout. This allows for easy integration across different operating systems and editors.
  8. Understand the gopls LSP Protocol implementation

    master

    The gopls Language Server Protocol (LSP) implementation exchanges JSON-encoded messages between a client and the server (gopls).

    Messages are categorized into:

    • Requests: Require a corresponding Response.
    • Notifications: Do not require a response.

    Each message is identified by a Method name (e.g., "textDocument/hover"). The protocol is derived from the official LSP specification and the vscode-languageserver-node repository's metaModel.json file.

  9. Understand gopls diagnostic sources

    master

    Gopls provides real-time feedback by annotating open files with diagnostics. These diagnostics originate from three primary sources:

    1. Compilation errors: These include syntax and type errors (e.g., MismatchedTypes). They are derived from go list metadata and gopls' internal parsing/type-checking phases. The LSP source field will indicate either "go list" or "compiler".
    2. Analysis findings: These are static checks provided by the Go analysis framework (similar to go vet). Examples include the printf analyzer. The LSP source field contains the name of the specific analyzer.
    3. Compiler optimization details: These report on optimization decisions like variable escape analysis, nil-pointer check elimination, or function inlining. This source is disabled by default.
  10. Implement the interactive refactoring workflow

    master

    To support interactive refactoring (like gopls.modify_tags), a client must follow this multi-step interaction flow:

    1. Receive Command: The server returns a Code Action containing a Command.
    2. Resolve Command: Before execution, the client calls command/resolve with ExecuteCommandParams.
    3. Handle Form Fields: The server responds with formFields. The client must render a UI to collect user input for these fields.
    4. Submit Answers: The client calls command/resolve again, this time populating formAnswers with the user's input.
    5. Handle Validation/Success:
      • Validation Failure: If the server returns formFields again with an error field attached to a specific field ID, the client should allow the user to correct the input.
      • Success: If the server returns a response with formFields omitted, the input is valid. The client then proceeds to execute the command via workspace/executeCommand using the finalized parameters including formAnswers.
  11. Navigate to a symbol's definition in gopls

    master

    Use the textDocument/definition request to find the location where a symbol is declared.

    Special behaviors:

    • Import paths: Returns locations of package declarations in the imported package.
    • Package declarations: Returns the location of the package declaration providing the documentation.
    • go:linkname directive: Returns the location of the symbol's declaration.
    • Doc links: Returns the location of the linked symbol.
    • go:embed directive: Returns the location of the embedded file.
    • Non-Go function declarations: Returns the location of the assembly implementation, if available.
    • Return statements: Returns the location of the function's result variables.
    • Control flow (goto, break, continue): Returns the location of the label, the closing brace of the block, or the start of the loop, respectively.
    gopls definition file.go:#offset