goloader

package
v0.9.9-dev.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package goloader loads Go packages with full type information for the registered repositories.

Loading always goes through go/packages with the complete semantic mode of the plan: anything less would force Kivgraph to reconstruct type identity by hand. Every load creates a fresh go/types universe, so objects of different loads are never mixed; callers must normalise before the session ends.

Index

Constants

View Source
const GoLanguage = "go"

GoLanguage is the language recorded in every Go stable key identity.

InspectMode asks the go command for names and files and nothing else. It is what `go list` alone can answer, so it costs a fraction of a load: no type universe is built, no dependency is parsed.

LoadMode is the semantic mode required by the analysis phases.

View Source
const PrecisionFailGate = "GO_SEMANTIC_FAIL"

PrecisionFailGate is emitted when any requirement is not met.

View Source
const PrecisionGate = "GO_SEMANTIC_PASS"

PrecisionGate is the gate emitted when the measurement is clean.

Variables

View Source
var ErrMissingModulePath = errors.New("definition has no module path")

ErrMissingModulePath reports a definition outside any module.

View Source
var ErrMissingRepository = errors.New("definition has no repository")

ErrMissingRepository reports a definition without the repository it belongs to: identity cannot be global without it.

View Source
var ErrNoPackages = errors.New("patterns matched no Go package")

ErrNoPackages reports that the patterns matched no package at all.

View Source
var ErrNoPatterns = errors.New("no load patterns were provided")

ErrNoPatterns reports a load request with nothing to load.

Functions

func PackageDefinitions

func PackageDefinitions(definitions []Definition) map[string][]Definition

PackageDefinitions groups definitions by package path, preserving order.

func PrecisionCaseRow

func PrecisionCaseRow(entry PrecisionCaseReport) string

PrecisionCaseRow renders one case as a Markdown table row.

func PrecisionSummary

func PrecisionSummary(metrics PrecisionMetrics) []string

PrecisionSummary renders the totals as text lines, for reports and logs.

func QualifiedNames

func QualifiedNames(definitions []Definition) []string

QualifiedNames returns the qualified names of definitions, for diagnostics.

Types

type CrossRepositoryOptions

type CrossRepositoryOptions struct {
	// ConsumerRepository is the repository the load belongs to.
	ConsumerRepository string
	// IncludeSameModule keeps uses whose target is in the consumer module.
	// They are intra-repository facts and are excluded by default.
	IncludeSameModule bool
	// ConflictingModules are module paths whose replacement the synthetic
	// workspace had to guess. No edge may be built on them.
	ConflictingModules []string
}

CrossRepositoryOptions tunes resolution.

type CrossRepositoryReference

type CrossRepositoryReference struct {
	Use

	// ConsumerRepository is the repository that contains the use.
	ConsumerRepository string
	// Provider is the repository that declares the target module.
	Provider ModuleProvider
	// Providers lists every candidate when the module path is ambiguous.
	Providers []ModuleProvider

	Status CrossRepositoryStatus
	// TargetObjectPath addresses the target inside its package.
	TargetObjectPath string
	// TargetStableKey is the durable identity of the target symbol.
	TargetStableKey hotsnapshot.StableKey
	// TargetCanonicalIdentity is the auditable text behind the key.
	TargetCanonicalIdentity string
}

CrossRepositoryReference is one use whose target lives in another module.

func ResolveCrossRepository

func ResolveCrossRepository(
	ctx context.Context,
	uses []Use,
	registry *ModuleRegistry,
	options CrossRepositoryOptions,
) ([]CrossRepositoryReference, error)

ResolveCrossRepository attributes each use to the repository that provides its target module and derives the durable identity of that target.

The module path comes from the loader, which already followed the synthetic workspace and any replace directive, so the provider is the module that really supplied the code, not the one the import path spells.

type CrossRepositoryStatus

type CrossRepositoryStatus string

CrossRepositoryStatus reports whether a use could be attributed to a registered module provider.

const (
	// CrossRepositoryResolved means provider and target identity are known.
	CrossRepositoryResolved CrossRepositoryStatus = "RESOLVED"
	// ModuleProviderNotFound means no registered repository declares the
	// module that owns the target.
	ModuleProviderNotFound CrossRepositoryStatus = "MODULE_PROVIDER_NOT_FOUND"
	// AmbiguousModuleProvider means several repositories declare it.
	AmbiguousModuleProvider CrossRepositoryStatus = "AMBIGUOUS_MODULE_PROVIDER"
	// ObjectPathUnavailable means the exported target has no object path, so
	// it cannot be addressed from another repository.
	ObjectPathUnavailable CrossRepositoryStatus = "OBJECT_PATH_UNAVAILABLE"
	// ReplaceConflictTarget means the workspace had to guess the replacement
	// of the target module, so no edge may depend on it.
	ReplaceConflictTarget CrossRepositoryStatus = "REPLACE_CONFLICT"
)

type Definition

type Definition struct {
	Repository  string
	ModulePath  string
	PackagePath string
	PackageName string
	FileName    string
	Name        string
	// QualifiedName is Owner.Name for methods and fields, Name otherwise.
	QualifiedName string
	Kind          DefinitionKind
	// Owner is the named type a method or field belongs to.
	Owner    string
	Exported bool
	// Signature is the type of the object with package-qualified names.
	Signature string
	// Receiver is the receiver type of a method, package qualified.
	Receiver string
	// Offsets and positions of the declared name, one based for lines.
	NameOffset  int
	StartLine   int
	StartColumn int
	// Declaration span of the whole syntax node that introduces the name.
	DeclarationStartOffset int
	DeclarationEndOffset   int
	EndLine                int
	// contains filtered or unexported fields
}

Definition is one declaration backed by a go/types object.

func ExtractDefinitions

func ExtractDefinitions(ctx context.Context, result Result, options DefinitionOptions) ([]Definition, error)

ExtractDefinitions collects declarations from the roots of one load.

Only the root packages are traversed: their dependencies are loaded to give types their identity, not to be indexed here. Function-local variables, parameters and labels are deliberately omitted; they are not addressable symbols of the graph.

func (Definition) Object

func (definition Definition) Object() types.Object

Object returns the go/types object of this definition.

The object belongs to the type universe of the load that produced it and must not be compared across loads.

type DefinitionKind

type DefinitionKind string

DefinitionKind classifies one Go declaration.

const (
	// KindFunc is a package-level function.
	KindFunc DefinitionKind = "func"
	// KindMethod is a method of a named type or an interface.
	KindMethod DefinitionKind = "method"
	// KindType is a defined type.
	KindType DefinitionKind = "type"
	// KindAlias is a type alias.
	KindAlias DefinitionKind = "alias"
	// KindConst is a package-level constant.
	KindConst DefinitionKind = "const"
	// KindVar is a package-level variable.
	KindVar DefinitionKind = "var"
	// KindField is a struct field.
	KindField DefinitionKind = "field"
)

type DefinitionOptions

type DefinitionOptions struct {
	// Repository is recorded on every definition. It is metadata, not a
	// resolution input.
	Repository string
	// IncludeUnexported keeps unexported declarations. Default is to keep
	// them: they are real symbols of the repository.
	ExcludeUnexported bool
}

DefinitionOptions tunes extraction.

type ErrorKind

type ErrorKind string

ErrorKind classifies one partial failure reported by the loader.

const (
	// ListError comes from the go command: resolution or configuration.
	ListError ErrorKind = "LIST"
	// ParseError is a syntax failure in a source file.
	ParseError ErrorKind = "PARSE"
	// TypeError is a semantic failure reported by the type checker.
	TypeError ErrorKind = "TYPE"
	// UnknownError is anything go/packages could not classify.
	UnknownError ErrorKind = "UNKNOWN"
)

type InspectResult added in v0.8.0

type InspectResult struct {
	Packages []InspectedPackage
}

InspectResult is one list-only pass over a module.

func Inspect added in v0.8.0

func Inspect(ctx context.Context, options Options) (InspectResult, error)

Inspect lists the packages of one module under the same environment and the same build tags a load would use, without building a type universe.

It exists so a caller can ask "would this module contribute" without paying for the answer to "what does it contain". Asking the go command is the only honest way: the rule that decides whether a file is selected is the build configuration's, and reimplementing it here would answer for a build nobody runs.

type InspectedPackage added in v0.8.0

type InspectedPackage struct {
	// PackagePath is the import path, or the directory when the go command
	// could not name one.
	PackagePath string
	// Errors are the go command's own messages, verbatim. A package whose
	// files are all excluded by build constraints is reported here and
	// nowhere else.
	Errors []string
}

InspectedPackage is one package the go command resolved, with whatever it refused to resolve about it.

type KeyedDefinition

type KeyedDefinition struct {
	Definition
	// ObjectPath is the go/types object path when the object is reachable
	// from the package scope. Unexported and local objects have none.
	ObjectPath string
	// CanonicalIdentity is the auditable text the key is derived from.
	CanonicalIdentity string
	StableKey         hotsnapshot.StableKey
}

KeyedDefinition is a definition with its durable identity.

func AssignStableKeys

func AssignStableKeys(ctx context.Context, definitions []Definition) ([]KeyedDefinition, error)

AssignStableKeys derives the durable identity of every definition.

The identity uses module path, package path, object path, kind and repository, as the plan requires, and never source positions: moving a declaration must not change its key.

type MethodResolution

type MethodResolution struct {
	Use

	// Selection is the selector form: value, expression or none.
	Selection SelectionKind
	// ReceiverTypeName is the named receiver type, without pointer.
	ReceiverTypeName string
	// ReceiverPackagePath is the package that declares the receiver type.
	ReceiverPackagePath string
	// ReceiverIsPointer reports a pointer receiver expression.
	ReceiverIsPointer bool
	// ReceiverIsInterface reports a call through an interface value.
	ReceiverIsInterface bool

	// DeclaringTypeName is the type that declares the method.
	DeclaringTypeName string
	// DeclaringPackagePath is the package of the declaring type.
	DeclaringPackagePath string
	// DeclaringReceiverIsPointer reports a method declared on a pointer.
	DeclaringReceiverIsPointer bool

	// Promoted reports a method reached through embedded fields.
	Promoted bool
	// EmbeddedPath names the embedded fields traversed, outermost first.
	EmbeddedPath []string
}

MethodResolution is one method use resolved to the type that declares it.

The receiver is what the expression has; the declaring type is where the method really lives. They differ when a method is promoted from an embedded field, and that difference is the fact the graph needs.

func ResolveMethods

func ResolveMethods(ctx context.Context, result Result, uses []Use) ([]MethodResolution, error)

ResolveMethods resolves every method use to its receiver and declaring type.

Only uses the checker already resolved are considered, and the receiver is read from the selection, so an embedded method is attributed to the type that declares it instead of the type that exposes it.

type Module

type Module struct {
	Path         string
	Version      string
	Directory    string
	ManifestPath string
	// ReplacedBy is the module path that replaced Path, when a replace
	// directive applied. Empty when the module was used directly.
	ReplacedBy string
	// ReplacedDirectory is the directory the replacement resolved to.
	ReplacedDirectory string
	Main              bool
}

Module is the module metadata observed for a loaded package.

type ModuleProvider

type ModuleProvider struct {
	Repository   string
	ModulePath   string
	RootPath     string
	ManifestPath string
}

ModuleProvider is one module offered by a registered repository.

type ModuleRegistry

type ModuleRegistry struct {
	// contains filtered or unexported fields
}

ModuleRegistry indexes module paths across every registered repository.

Ambiguity is preserved, never resolved by preference: two repositories declaring the same module path is a fact the caller must see.

func NewModuleRegistry

func NewModuleRegistry(ctx context.Context, repositories []workspace.Repository) (*ModuleRegistry, error)

NewModuleRegistry builds the cross-repository module index.

func (*ModuleRegistry) ModulePaths

func (registry *ModuleRegistry) ModulePaths() []string

ModulePaths returns every indexed module path, sorted.

func (*ModuleRegistry) Providers

func (registry *ModuleRegistry) Providers(modulePath string) []ModuleProvider

Providers returns every repository declaring modulePath.

type ObjectIdentity

type ObjectIdentity struct {
	Repository    string
	ModulePath    string
	PackagePath   string
	QualifiedName string
	Kind          DefinitionKind
	Signature     string
	Object        types.Object
}

ObjectIdentity is everything needed to derive the durable key of one Go object, whether it was extracted as a definition or reached as the target of a use in another repository.

func (ObjectIdentity) Resolve

func (identity ObjectIdentity) Resolve(
	encoders map[string]*objectpath.Encoder,
) (ResolvedIdentity, error)

Resolve derives the object path, canonical identity and stable key.

Encoders are cached per package path; pass the same map across calls to avoid rebuilding the object path index of a package.

type Options

type Options struct {
	// Directory is the working directory of the go command.
	Directory string
	// WorkFile is the synthetic go.work of LUQUE-0801. Empty disables
	// workspace mode.
	WorkFile string
	// Patterns default to "./..." when empty.
	Patterns []string
	// IncludeTests loads test packages as well.
	IncludeTests bool
	// GOOS and GOARCH select the target platform for the go command. Empty
	// values preserve the toolchain defaults.
	GOOS       string
	GOARCH     string
	CGOEnabled *bool
	// BuildTags are the build constraints the load satisfies, passed to the
	// go command as -tags. A package guarded by a tag that is absent here
	// declares no file to select and contributes nothing to the graph.
	BuildTags []string
	// AllowNetwork permits the go command to reach a module proxy. Indexing
	// is hermetic by default: a missing dependency is reported, not fetched.
	AllowNetwork bool
	// Environment overrides entries of the inherited environment.
	Environment []string
}

Options configures one load.

type PackageDependency

type PackageDependency struct {
	Repository  string
	ModulePath  string
	PackagePath string

	// TargetModulePath is empty for the standard library, exactly like
	// Use.TargetModulePath.
	TargetModulePath  string
	TargetPackagePath string

	// The fields below describe the witness use chosen to represent the
	// whole dependency: the earliest one, by file name then position. A
	// package edge summarises many uses and cannot anchor its evidence to
	// all of them at once, so a deterministic witness is picked instead of
	// an arbitrary one — the first one observed in iteration order would
	// depend on how the caller happened to gather uses, and would not
	// survive a rerun in a different order byte for byte.
	FileName    string
	Name        string
	Offset      int
	EndOffset   int
	StartLine   int
	StartColumn int
}

PackageDependency is one dependency between two packages, deduplicated across every use that crosses the boundary between them.

A package can be used by many symbols in many files, but the graph wants one edge per dependency, not one per occurrence: deduplicating here, in the loader, keeps the grouping next to the raw material it consumes instead of pushing every caller of this pass to repeat the same (source, target) grouping that facts.NormalizeGo would otherwise have to redo for both PACKAGE_DEPENDS_ON and MODULE_DEPENDS_ON. References stay one per occurrence by design, because each is its own edge with its own evidence; a package dependency is a summary fact instead, so it is built as one from the start.

func ResolvePackageDependencies

func ResolvePackageDependencies(ctx context.Context, uses []Use) ([]PackageDependency, error)

ResolvePackageDependencies groups every use that crosses a package boundary into one PackageDependency per (source, target) package pair.

Whether a pair becomes PACKAGE_DEPENDS_ON, additionally MODULE_DEPENDS_ON, or nothing at all because its target cannot be attributed to an indexed package, is decided later by facts.NormalizeGo, exactly like it already decides for a plain reference. This pass only proves the pair exists and picks its evidence, so it takes no CrossRepositoryReference input of its own: the witness it returns carries the file name and offset of a real use, which is precisely how NormalizeGo already keys CrossRepositoryReference to resolve a reference's target, so the same lookup resolves a dependency's target too.

type PackageError

type PackageError struct {
	PackageID   string
	PackagePath string
	Kind        ErrorKind
	Position    string
	Message     string
}

PackageError is one partial failure attached to the package that produced it.

func (PackageError) Blocking

func (failure PackageError) Blocking() bool

Blocking reports whether the diagnostic makes the facts of its package untrustworthy. Only a blocking diagnostic may abort an index.

func (PackageError) NoPackage

func (failure PackageError) NoPackage() bool

NoPackage reports whether the diagnostic states that the directory declares no package the current build configuration selects.

type PrecisionCaseReport

type PrecisionCaseReport struct {
	Name                 string           `json:"name"`
	Metrics              PrecisionMetrics `json:"metrics"`
	MissingEdges         []string         `json:"missing_edges"`
	UnexpectedEdges      []string         `json:"unexpected_edges"`
	MissingUnresolved    []string         `json:"missing_unresolved"`
	UnexpectedUnresolved []string         `json:"unexpected_unresolved"`
}

PrecisionCaseReport is the measurement of one fixture repository.

type PrecisionMetrics

type PrecisionMetrics struct {
	ExpectedEdges  int     `json:"expected_edges"`
	TruePositives  int     `json:"true_positives"`
	FalsePositives int     `json:"false_positives"`
	FalseNegatives int     `json:"false_negatives"`
	Precision      float64 `json:"precision"`
	Recall         float64 `json:"recall"`
	// FalseExactEdges are edges the fixtures prove wrong. The gate needs zero.
	FalseExactEdges               int `json:"false_exact_edges"`
	ExpectedUnresolved            int `json:"expected_unresolved"`
	UnresolvedCorrectlyClassified int `json:"unresolved_correctly_classified"`
	UnresolvedMisclassified       int `json:"unresolved_misclassified"`
}

PrecisionMetrics are the counts required by LUQUE-0813.

type PrecisionReport

type PrecisionReport struct {
	Fixtures []string              `json:"fixtures"`
	Cases    []PrecisionCaseReport `json:"cases"`
	Totals   PrecisionMetrics      `json:"totals"`
	Gate     string                `json:"gate"`
}

PrecisionReport is the complete measurement.

func MeasurePrecision

func MeasurePrecision(ctx context.Context, fixtureRoot string) (PrecisionReport, error)

MeasurePrecision runs both fixtures and compares the produced facts with the ground truth of LUQUE-0811 and LUQUE-0812.

fixtureRoot is the directory holding `cross-repository` and `cross-repository-negative`, normally `testdata/go`.

type Reference

type Reference struct {
	Use
	Kind ReferenceKind
}

Reference is one use classified as a graph edge.

func ClassifyReferences

func ClassifyReferences(ctx context.Context, result Result, uses []Use) ([]Reference, error)

ClassifyReferences turns resolved uses into classified edges.

The classification comes from the syntax the checker already resolved: the callee of a call expression is a direct call, a type target is a type use, and everything else is a plain reference. Calling a variable that happens to hold a function is not a direct call to a function symbol, so it stays a reference.

type ReferenceKind

type ReferenceKind string

ReferenceKind classifies a resolved use as a graph edge.

const (
	// ReferenceRead is a plain use of a symbol.
	ReferenceRead ReferenceKind = "REFERENCES"
	// ReferenceCallsDirect is the callee of a call expression.
	ReferenceCallsDirect ReferenceKind = "CALLS_DIRECT"
	// ReferenceTypeUses is a use of a type in a type position or conversion.
	ReferenceTypeUses ReferenceKind = "TYPE_USES"
	// ReferencePassesAsCallback is a function or method handed over as a
	// value in a call argument, never invoked at that site.
	ReferencePassesAsCallback ReferenceKind = "PASSES_AS_CALLBACK"
	// ReferenceAssignsFunction is a function or method stored in a variable
	// or constant, never invoked at that site.
	ReferenceAssignsFunction ReferenceKind = "ASSIGNS_FUNCTION"
	// ReferenceReturnsFunction is a function or method returned as a value.
	ReferenceReturnsFunction ReferenceKind = "RETURNS_FUNCTION"
)

type ResolvedIdentity

type ResolvedIdentity struct {
	ObjectPath        string
	CanonicalIdentity string
	StableKey         hotsnapshot.StableKey
}

ResolvedIdentity is the durable identity of one object.

type Result

type Result struct {
	Fset *token.FileSet
	// Packages are the roots the patterns matched, sorted by package path.
	Packages []*packages.Package
	// Modules are the modules observed across roots, sorted by module path.
	Modules []Module
	// Errors are partial failures. A load can succeed with errors present.
	Errors []PackageError
}

Result is one complete load: a private type universe plus its diagnostics.

func Load

func Load(ctx context.Context, options Options) (Result, error)

Load resolves the patterns and returns the packages with type information.

Partial failures do not abort the load: a repository that does not compile still yields the packages that do, and every failure is reported.

func (Result) BlockingErrors

func (result Result) BlockingErrors() []PackageError

BlockingErrors returns the diagnostics that make the facts of this load untrustworthy, in the order of Errors.

type SelectionKind

type SelectionKind string

SelectionKind classifies a use that came through a selector expression.

const (
	// SelectionNone marks a use that is not a selector.
	SelectionNone SelectionKind = ""
	// SelectionField is x.f where f is a struct field.
	SelectionField SelectionKind = "field"
	// SelectionMethodValue is x.M, a method bound to a receiver value.
	SelectionMethodValue SelectionKind = "method_value"
	// SelectionMethodExpression is T.M, a method used as a function value.
	SelectionMethodExpression SelectionKind = "method_expression"
)

type TypeRelation

type TypeRelation struct {
	Use
	Kind TypeRelationKind

	// Pointer qualifies IMPLEMENTS and EMBEDS. For IMPLEMENTS it reports
	// that only the pointer type satisfies the interface, the value type
	// does not. For EMBEDS it reports an embedded field of pointer type.
	// OVERRIDES leaves it false; pointerness is not what OVERRIDES decides.
	Pointer bool

	// PromotionDepth is the length of the embedding path OVERRIDES walked,
	// starting at the outer type's own embedded field, to reach the method
	// it hides. Unused by IMPLEMENTS and EMBEDS.
	PromotionDepth int
}

TypeRelation is one structural relation between two named types or methods, resolved entirely by the type checker.

It embeds Use so both ends carry the same raw material ExtractDefinitions and AssignStableKeys consume: module path, package path, qualified name, kind, and the go/types object itself. A target that lives in another repository resolves exactly like a reference does, through ResolveCrossRepository over this same Use.

func ResolveTypeRelations

func ResolveTypeRelations(ctx context.Context, result Result, options TypeRelationOptions) ([]TypeRelation, error)

ResolveTypeRelations computes every IMPLEMENTS, EMBEDS and OVERRIDES relation reachable from the root packages of one load.

Interfaces are gathered from every loaded package, including dependencies: a type declared in a root package can implement an interface it never imports by name. Concrete types, embedding declarations and overriding methods are read only from the root packages, matching ExtractDefinitions: a symbol this pass cannot key locally is not a fact this pass can originate from.

type TypeRelationKind

type TypeRelationKind string

TypeRelationKind classifies one structural relation the type checker decides on its own, with no corresponding source occurrence to anchor it: interface satisfaction, embedding, or a promoted method hidden by one declared directly on the outer type.

const (
	// RelationImplements reports that a concrete named type satisfies a
	// named interface, decided by types.Implements alone. IMPLEMENTS never
	// targets the empty interface: it is satisfied by everything and would
	// report nothing about the type.
	RelationImplements TypeRelationKind = "IMPLEMENTS"
	// RelationEmbeds reports an anonymous struct field, or an interface
	// embedding another named interface.
	RelationEmbeds TypeRelationKind = "EMBEDS"
	// RelationOverrides reports a method declared directly on a struct that
	// hides a promoted method of the same name reachable through one of its
	// embedded fields. Go has no virtual dispatch: this is shadowing of a
	// promoted method, never a runtime override.
	RelationOverrides TypeRelationKind = "OVERRIDES"
)

type TypeRelationOptions

type TypeRelationOptions struct {
	// Repository is recorded on every relation.
	Repository string
}

TypeRelationOptions tunes resolution.

type UnresolvedOptions

type UnresolvedOptions struct {
	// Repository is the repository being indexed.
	Repository string
	// WorkspaceConflicts are the conflicts reported by LUQUE-0801 when the
	// synthetic workspace was built.
	WorkspaceConflicts []goworkspace.Conflict
}

UnresolvedOptions supplies the facts that do not come from the load itself.

type UnresolvedReason

type UnresolvedReason string

UnresolvedReason classifies a Go fact Kivgraph could not turn into an exact edge.

const (
	// UnresolvedModuleProviderNotFound means no registered repository
	// declares the module that owns the target.
	UnresolvedModuleProviderNotFound UnresolvedReason = "MODULE_PROVIDER_NOT_FOUND"
	// UnresolvedPackageNotLoaded means an imported package produced no type
	// information, so nothing inside it can be referenced.
	UnresolvedPackageNotLoaded UnresolvedReason = "PACKAGE_NOT_LOADED"
	// UnresolvedObjectPathUnavailable means the target cannot be addressed
	// from outside its package.
	UnresolvedObjectPathUnavailable UnresolvedReason = "OBJECT_PATH_UNAVAILABLE"
	// UnresolvedAmbiguousModuleProvider means several repositories declare
	// the module path of the target.
	UnresolvedAmbiguousModuleProvider UnresolvedReason = "AMBIGUOUS_MODULE_PROVIDER"
	// UnresolvedReplaceConflict means the synthetic workspace could not agree
	// on a replacement for a module.
	UnresolvedReplaceConflict UnresolvedReason = "REPLACE_CONFLICT"
	// UnresolvedTypecheckFailed means the package does not typecheck, so its
	// facts are not trustworthy.
	UnresolvedTypecheckFailed UnresolvedReason = "TYPECHECK_FAILED"
	// UnresolvedPackageNotBuildable means the directory declares no file the
	// build configuration of this index selects, so the package contributes
	// no fact at all. Its symbols are absent from the graph by construction,
	// not by failure.
	UnresolvedPackageNotBuildable UnresolvedReason = "PACKAGE_NOT_BUILDABLE"
	// UnresolvedDeclarationOutsideRepository means the file holding a
	// declaration is not inside the repository the pass is indexing. The Go
	// loader asks for compiled files, so a package built with cgo or from
	// generated sources reports positions inside the build cache. Such a
	// path is not evidence for this repository: it names a machine and a
	// cache entry, not source anybody can read at that path later.
	UnresolvedDeclarationOutsideRepository UnresolvedReason = "DECLARATION_OUTSIDE_REPOSITORY"
)

type UnresolvedReference

type UnresolvedReference struct {
	Repository  string
	PackagePath string
	FileName    string
	// RequestedModulePath is the module the fact needed, when known.
	RequestedModulePath string
	// RequestedPackagePath is the package the fact needed, when known.
	RequestedPackagePath string
	// RequestedSymbol is the qualified name of the target, when known.
	RequestedSymbol string
	Reason          UnresolvedReason
	// Detail carries the observed evidence: diagnostics or candidates.
	Detail string
	// Candidates lists the competing providers of an ambiguous module.
	Candidates []ModuleProvider

	StartLine   int
	StartColumn int
	Offset      int
}

UnresolvedReference is one classified failure with its evidence.

func ClassifyUnresolved

func ClassifyUnresolved(
	ctx context.Context,
	result Result,
	references []CrossRepositoryReference,
	options UnresolvedOptions,
) ([]UnresolvedReference, error)

ClassifyUnresolved reports every Go fact that did not become an exact edge.

Nothing here is inferred: each reason is backed by a load diagnostic, a registry answer or a workspace conflict.

type Use

type Use struct {
	Repository  string
	ModulePath  string
	PackagePath string
	FileName    string
	Name        string

	// SourceQualifiedName is the enclosing declaration, empty at file level.
	SourceQualifiedName string
	// SourceKind is the kind of the enclosing declaration.
	SourceKind DefinitionKind

	// TargetModulePath is empty for the standard library.
	TargetModulePath    string
	TargetPackagePath   string
	TargetQualifiedName string
	TargetKind          DefinitionKind
	// TargetIsLocalPackage reports a target defined in a root package of the
	// same load.
	TargetIsLocalPackage bool

	// Selection describes the selector this use came from, when any.
	Selection SelectionKind
	// ReceiverType is the receiver of a selection, package qualified.
	ReceiverType string
	// IndirectReceiver reports a selection that dereferences a pointer or
	// goes through an embedded field.
	IndirectReceiver bool

	Offset      int
	EndOffset   int
	StartLine   int
	StartColumn int
	// contains filtered or unexported fields
}

Use is one resolved occurrence of a symbol.

A use records what the type checker resolved, not what the source spells: the target is the object itself, so a homonym in another package can never be mistaken for it.

func ExtractUses

func ExtractUses(ctx context.Context, result Result, options UseOptions) ([]Use, error)

ExtractUses collects every resolved occurrence of an indexable symbol.

Only occurrences inside the root packages are reported; their targets may belong to any loaded package, which is what makes a cross-module reference exact. Local variables, parameters and package names are not targets: they are not symbols of the graph.

func (Use) Object

func (use Use) Object() types.Object

Object returns the go/types object the use resolved to.

type UseOptions

type UseOptions struct {
	// Repository is recorded on every use.
	Repository string
}

UseOptions tunes extraction.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL