How golang/tools works
Project type and purpose
• This is a monorepo module (“golang.org/x/tools”) containing both:
a. A suite of CLI tools under cmd/ (e.g. goimports, callgraph, stringer, digraph, etc.).
b. A collection of Go libraries and frameworks for static analysis (under go/), plus the gopls LSP server module (under gopls/).
• Purpose: provide reusable analysis libraries (AST, SSA IR, call graphs, CFG, go/packages, go/analysis framework) and deliver end-user tools and an LSP server to editors.
High-level architecture components
a. CLI tools layer (cmd/)
• Each command is a small “main” program that imports the shared libraries.
• Examples: cmd/goimports → uses go/analysis/… and go/ast/astutil; cmd/callgraph → uses go/callgraph; cmd/stringer → uses go/types.
b. Library layer (go/*)
• go/ast, go/ast/inspector
• go/packages (loading/parsing/type-checking)
• go/analysis (framework for analyzers)
• go/ssa (intermediate representation)
• go/callgraph, go/cfg
• gcexportdata/gccgoexportdata (compiler export formats)
c. LSP server (gopls/)
• Protocol layer: JSON-RPC over StdIO/HTTP (gopls/internal/lsprpc + protocol definitions).
• Server core: command dispatchers (gopls/internal/cmd), workspace management, snapshot/caching (gopls/internal/cache & gopls/internal/work), diagnostics pipeline.
• Language analysis back-end: invokes go/packages, go/analysis passes, SSA, call graphs, etc., to compute completions, diagnostics, refactorings.
• Integration with editors: clients send LSP requests → gopls translates to internal commands → analysis libraries → response back via protocol.
d. Support subsystems
• File watching and overlays (gopls/internal/filewatcher)
• Caching/memoization (gopls/internal/cache)
• Telemetry, progress reporting, logging (gopls/internal/telemetry, gopls/internal/debug)
• Utilities (internal/, imports/, container/, etc.) used by both CLI tools and gopls.
Relationships & data flow
• Editors/clients ↔ JSON-RPC ↔ gopls LSP protocol layer
• Protocol layer → dispatch to server core commands → workspace state → analysis pipeline → library APIs (go/packages, go/analysis, go/ssa) → results → protocol layer → back to editor
• CLI tools → import libraries directly → run analysis on disk files → print to stdout
Key architectural patterns & design principles
• Layered design: presentation (CLI or LSP), server core, analysis libraries, utility packages
• Modular analyzers: go/analysis framework supports pluggable “passes”
• Caching layer for expensive operations (parsing, type-checking) using snapshots
• Decoupling between protocol I/O and analysis logic
• Reuse of common primitives (AST utils, graph algorithms) across all tools