analysis

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: 0BSD Imports: 49 Imported by: 0

Documentation

Overview

Package analysis schedules native rules over shared run-owned representations.

Index

Constants

View Source
const (
	// ModuleReadonly refuses go.mod and go.sum updates.
	ModuleReadonly ModuleMode = "readonly"
	// ModuleVendor loads dependencies from the selected vendor tree.
	ModuleVendor ModuleMode = "vendor"
	// DefaultMaxPackages bounds the complete package graph retained by one
	// typed analysis load.
	DefaultMaxPackages = 10_000
	// DefaultMaxSourceFiles bounds unique physical Go sources retained by one
	// typed analysis load.
	DefaultMaxSourceFiles = 20_000
	// DefaultMaxSourceBytes bounds aggregate unique physical Go source bytes
	// retained by one typed analysis load.
	DefaultMaxSourceBytes int64 = 256 << 20
)
View Source
const (
	ProfilePhasePackages         = "packages"
	ProfilePhaseSourceModel      = "source-model"
	ProfilePhaseEffectFacts      = "effect-facts"
	ProfilePhaseTypes            = "types"
	ProfilePhaseControlFlow      = "control-flow"
	ProfilePhaseSSA              = "ssa"
	ProfilePhasePackageAnalyzers = "package-analyzers"
	ProfilePhaseResult           = "result"
)
View Source
const (
	// UnitcheckerModeEnvironment selects one hidden exact analyzer mode in the
	// Glippy binary when it is invoked by the Go command as a vet tool.
	UnitcheckerModeEnvironment = "GLIPPY_INTERNAL_UNITCHECKER"
	// UnitcheckerPrintfIdentity is the versioned exact printf analyzer mode.
	UnitcheckerPrintfIdentity = "printf-v1"
)

Variables

This section is empty.

Functions

func AdaptAnalyzer

func AdaptAnalyzer(
	analyzer *goanalysis.Analyzer,
	options AnalyzerAdapterOptions,
) (rules.Rule, error)

AdaptAnalyzer wraps one suitable go/analysis analyzer as a native rule.

func AdaptAnalyzerFactory

func AdaptAnalyzerFactory(
	factory AnalyzerFactory,
	options AnalyzerAdapterOptions,
) (rules.Rule, error)

AdaptAnalyzerFactory wraps independently constructed analyzer graphs so native options can be bound without mutating shared flag state.

func IsPackageConfigurationError

func IsPackageConfigurationError(err error) bool

IsPackageConfigurationError reports whether package loading failed because the selected module or workspace inputs are inconsistent.

func OrderDiagnostics

func OrderDiagnostics(diagnostics []rules.Diagnostic) []rules.Diagnostic

OrderDiagnostics returns one canonically ordered diagnostic slice.

func RunControlFlow

func RunControlFlow(
	ctx context.Context,
	loaded PackageLoadResult,
	registry *rules.Registry,
	selection []rules.Selection,
) ([]rules.Diagnostic, error)

RunControlFlow executes selected CFG-tier rules once per function over one graph shared by all eligible rules.

func RunSSA

func RunSSA(
	ctx context.Context,
	loaded PackageLoadResult,
	registry *rules.Registry,
	selection []rules.Selection,
) ([]rules.Diagnostic, error)

RunSSA executes selected SSA-tier rules once per source function through one bounded package-wave program shared by all eligible rules.

func RunSyntax

func RunSyntax(
	ctx context.Context,
	file *source.File,
	registry *rules.Registry,
	selection []rules.Selection,
) ([]rules.Diagnostic, error)

RunSyntax executes selected syntax rules through one shared AST traversal.

func RunTypes

func RunTypes(
	ctx context.Context,
	loaded PackageLoadResult,
	registry *rules.Registry,
	selection []rules.Selection,
) ([]rules.Diagnostic, error)

RunTypes executes selected types-tier rules through one shared package AST traversal over the exact source versions captured by LoadPackages.

func RunUnitcheckerMode

func RunUnitcheckerMode(mode string) bool

RunUnitcheckerMode dispatches one hidden exact analyzer mode. The selected unitchecker owns process termination under the Go vet protocol.

func WithPackageFactAnalyzerRunner

func WithPackageFactAnalyzerRunner(
	ctx context.Context,
	runner PackageFactAnalyzerRunner,
) context.Context

WithPackageFactAnalyzerRunner installs one run-owned external analyzer boundary. A nil runner leaves the existing in-process adapter active.

Types

type AnalyzerAdapterOptions

type AnalyzerAdapterOptions struct {
	Metadata              rules.Metadata
	SuggestedFixes        []AnalyzerFixMapping
	FlagBindings          []AnalyzerFlagBinding
	ReadOnlyAudited       bool
	DependencyFactFilter  *AnalyzerDependencyFactFilter
	ExternalFactExecution *AnalyzerExternalFactExecution
}

AnalyzerAdapterOptions supplies the native product contract for an analyzer.

type AnalyzerDependencyFactFilter

type AnalyzerDependencyFactFilter struct {
	Identity         string
	PackageMayExport func([]AnalyzerDependencyFactSource) (bool, error)
	Audited          bool
}

AnalyzerDependencyFactFilter proves from exact dependency source bytes that a fact-bearing analyzer cannot export facts for one package. Reporter roots are always analyzed because they may also produce diagnostics.

type AnalyzerDependencyFactSource

type AnalyzerDependencyFactSource struct {
	Path  string
	Bytes []byte
}

AnalyzerDependencyFactSource is one exact compiled dependency source passed to an audited package-level fact-export predicate.

type AnalyzerExternalFactExecution

type AnalyzerExternalFactExecution struct {
	Identity string
	Analyzer string
	Audited  bool
}

AnalyzerExternalFactExecution declares one audited exact external execution mode for a fact-bearing analyzer.

type AnalyzerFactory

type AnalyzerFactory func() *goanalysis.Analyzer

AnalyzerFactory constructs one independent analyzer graph for a single run.

type AnalyzerFixMapping

type AnalyzerFixMapping struct {
	Message         string
	Name            string
	Description     string
	Safety          rules.FixSafety
	Audited         bool
	RequiredImports []rules.ImportRequirement
}

AnalyzerFixMapping binds one exact go/analysis suggestion to native metadata.

type AnalyzerFlagBinding

type AnalyzerFlagBinding struct {
	Option   string
	Analyzer string
	Flag     string
}

AnalyzerFlagBinding maps one native typed option to one analyzer flag.

type ModuleMode

type ModuleMode string

ModuleMode selects a non-mutating Go module resolution policy.

type PackageCacheOptions

type PackageCacheOptions struct {
	Store           *cache.Store
	ToolVersion     string
	BuildGoVersion  string
	SourceGoVersion string
	Configuration   cache.Digest
	CGOEnabled      bool
	FormatterMode   string
}

PackageCacheOptions binds a caller-owned persistent store to the complete non-source identity of one typed analysis run. Source, package, module, workspace, environment, export, overlay, and imported-fact inputs are derived from the exact package load.

type PackageConfigurationError

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

PackageConfigurationError reports a Go module or workspace configuration that prevents the standard package driver from constructing a graph.

func (*PackageConfigurationError) Error

func (e *PackageConfigurationError) Error() string

func (*PackageConfigurationError) Unwrap

func (e *PackageConfigurationError) Unwrap() error

type PackageDiagnostic

type PackageDiagnostic struct {
	PackageID string
	Targets   []string
	Position  string
	Message   string
	Kind      packages.ErrorKind
	Cause     PackageDiagnosticCause
}

PackageDiagnostic is one canonical package-loading or type-checking error.

func (PackageDiagnostic) IsCgoBoundary

func (d PackageDiagnostic) IsCgoBoundary() bool

IsCgoBoundary reports whether a diagnostic identifies a retained cgo source that the standard package loader could not represent in the typed syntax graph.

type PackageDiagnosticCause

type PackageDiagnosticCause uint8

PackageDiagnosticCause identifies a Glippy-owned package-loading boundary independently from its human-facing message.

const (
	PackageDiagnosticCauseNone PackageDiagnosticCause = iota
	PackageDiagnosticCauseCgoBoundary
)

type PackageFactAnalyzerDiagnostic

type PackageFactAnalyzerDiagnostic struct {
	Analyzer       string
	Path           string
	Range          source.Range
	Message        string
	SuggestedFixes []PackageFactAnalyzerSuggestedFix
}

PackageFactAnalyzerDiagnostic is one external analyzer diagnostic over an exact retained source version.

type PackageFactAnalyzerEdit

type PackageFactAnalyzerEdit struct {
	Path    string
	Range   source.Range
	NewText string
}

PackageFactAnalyzerEdit is one exact source edit from an external analyzer.

type PackageFactAnalyzerRequest

type PackageFactAnalyzerRequest struct {
	Identity      string
	Analyzer      string
	PackageErrors bool
	LoadOptions   PackageLoadOptions
	Sources       PackageSourceSet
}

PackageFactAnalyzerRequest describes one exact external analyzer execution.

type PackageFactAnalyzerRunner

type PackageFactAnalyzerRunner interface {
	RunPackageFactAnalyzer(
		context.Context,
		PackageFactAnalyzerRequest,
	) ([]PackageFactAnalyzerDiagnostic, error)
}

PackageFactAnalyzerRunner executes one audited fact-bearing analyzer without retaining its complete dependency type graph in the Glippy process.

func NewUnitcheckerFactAnalyzerRunner

func NewUnitcheckerFactAnalyzerRunner(
	options UnitcheckerFactAnalyzerRunnerOptions,
) (PackageFactAnalyzerRunner, error)

NewUnitcheckerFactAnalyzerRunner creates one process-wide bounded runner.

type PackageFactAnalyzerSuggestedFix

type PackageFactAnalyzerSuggestedFix struct {
	Message string
	Edits   []PackageFactAnalyzerEdit
}

PackageFactAnalyzerSuggestedFix is one external analyzer suggestion.

type PackageGraphResult

type PackageGraphResult struct {
	RootPackagePaths       []string
	DependencyPackagePaths []string
	Diagnostics            []PackageDiagnostic
}

PackageGraphResult is one metadata-only package identity snapshot.

func DiscoverPackageGraph

func DiscoverPackageGraph(
	ctx context.Context,
	options PackageLoadOptions,
) (PackageGraphResult, error)

DiscoverPackageGraph resolves package identities without retaining syntax, types, control flow, SSA, export data, or effect facts.

type PackageLoadOptions

type PackageLoadOptions struct {
	Dir                  string
	Patterns             []string
	Requirement          rules.Requirement
	Tests                bool
	LoadDependencySyntax bool
	LoadEffectFacts      bool
	BuildTags            []string
	ModuleMode           ModuleMode
	Env                  []string
	Overlay              map[string][]byte
	AllowNetwork         bool
	GOOS                 string
	GOARCH               string
	MaxPackages          int
	MaxSourceFiles       int
	MaxSourceBytes       int64
	Contracts            contracts.Set
	// contains filtered or unexported fields
}

PackageLoadOptions defines one run-owned Go package loading request.

type PackageLoadResult

type PackageLoadResult struct {
	Requirement rules.Requirement
	Packages    []*packages.Package
	Diagnostics []PackageDiagnostic
	Sources     PackageSourceSet
	// contains filtered or unexported fields
}

PackageLoadResult owns one compatible typed package graph for a run.

func LoadPackages

func LoadPackages(ctx context.Context, options PackageLoadOptions) (PackageLoadResult, error)

LoadPackages loads the typed prerequisite shared by types, CFG, and SSA tiers. Lexical and syntax-only execution must use the file-owned frontend and never reach this boundary.

type PackageResult

type PackageResult struct {
	Requirement            rules.Requirement
	Selection              []rules.Selection
	RootPackagePaths       []string
	DependencyPackagePaths []string
	LoadDiagnostics        []PackageDiagnostic
	SourceProblems         []PackageSourceProblem
	Sources                PackageSourceSet
	Files                  []Result
}

PackageResult is one suppression-aware package analysis run over a shared typed load.

func RunPackages

func RunPackages(
	ctx context.Context,
	registry *rules.Registry,
	options RunOptions,
	loadOptions PackageLoadOptions,
) (PackageResult, error)

RunPackages resolves a typed rule plan, loads its maximum prerequisite once, and combines syntax, types, CFG, and SSA diagnostics before suppressing.

type PackageSession

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

PackageSession owns bounded typed state that may be reused by successive editor snapshots. It retains compact dependency type graphs, never dependency syntax or type-value maps.

func NewPackageSession

func NewPackageSession() *PackageSession

NewPackageSession creates one empty persistent typed-analysis session.

func (*PackageSession) InvalidateAll

func (s *PackageSession) InvalidateAll()

InvalidateAll drops every retained typed graph. Editor file notifications use this conservative boundary when disk or project metadata may have changed outside an exact document overlay.

func (*PackageSession) Statistics

func (s *PackageSession) Statistics() PackageSessionStatistics

Statistics returns one immutable session snapshot.

type PackageSessionStatistics

type PackageSessionStatistics struct {
	FullLoads        uint64
	IncrementalLoads uint64
	ImportLoads      uint64
}

PackageSessionStatistics reports how a persistent typed-analysis session satisfied package loading requests.

type PackageSourceProblem

type PackageSourceProblem struct {
	Path    string
	Digest  source.Digest
	Targets []string
	Message string
}

PackageSourceProblem records why one captured source is diagnostic-only.

type PackageSourceSet

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

PackageSourceSet is one immutable index of the exact bytes parsed by a package load.

func MergePackageSourceSets

func MergePackageSourceSets(sets ...PackageSourceSet) (PackageSourceSet, error)

MergePackageSourceSets combines compatible immutable source indexes.

func (PackageSourceSet) Lookup

func (s PackageSourceSet) Lookup(path string) (*source.File, bool)

Lookup returns the immutable source version parsed for path.

func (PackageSourceSet) Paths

func (s PackageSourceSet) Paths() []string

Paths returns normalized physical source identities in canonical order.

func (PackageSourceSet) Problems

func (s PackageSourceSet) Problems() []PackageSourceProblem

Problems returns source-model failures in canonical order.

func (PackageSourceSet) WithProblemTargets

func (s PackageSourceSet) WithProblemTargets(targets []string) (PackageSourceSet, error)

WithProblemTargets returns the same immutable source set with one canonical target set attached to every source-model problem.

type PhaseProfiler

type PhaseProfiler interface {
	Capture(phase string) error
}

PhaseProfiler observes explicit retained-analysis boundaries. Implementations may force garbage collection or write heap profiles, so profiling is opt-in and is never enabled by ordinary CLI or editor analysis.

type Result

type Result struct {
	Path                   string
	Digest                 source.Digest
	PackageID              string
	Targets                []string
	Requirement            rules.Requirement
	Selection              []rules.Selection
	Diagnostics            []rules.Diagnostic
	PreexistingDiagnostics []rules.Diagnostic
	Baselined              []rules.Diagnostic
	BaselineProblems       []baseline.Problem
	Suppressed             []suppressions.SuppressedDiagnostic
	UnusedSuppressions     []suppressions.Directive
	SuppressionProblems    []suppressions.Problem
}

Result is one reporter-ready syntax analysis result over one source version.

func Run

func Run(
	ctx context.Context,
	file *source.File,
	registry *rules.Registry,
	options RunOptions,
) (Result, error)

Run resolves, schedules, and suppresses native syntax diagnostics.

type RunOptions

type RunOptions struct {
	SourceGoVersion          string
	Profile                  config.Profile
	ProfileRules             map[string]rules.Severity
	Preset                   rules.Preset
	Presets                  []rules.Preset
	WarningsAsErrors         bool
	Overrides                map[string]rules.Severity
	RuleOptions              map[string]rules.OptionSet
	PathRoot                 string
	PathOverrides            []config.LintOverride
	LintLevels               []rules.LintLevelDirective
	Only                     []string
	Except                   []string
	RequireSuppressionReason bool
	SuppressionExpiryCutoff  string
	Cache                    *PackageCacheOptions
	Statistics               *Statistics
	Profiler                 PhaseProfiler
	PackageSession           *PackageSession
}

RunOptions selects native rules and suppression policy for one source file.

func (RunOptions) RuleResolution

func (options RunOptions) RuleResolution() (rules.ResolveOptions, error)

RuleResolution returns the canonical registry selection bound to this run.

func (RunOptions) RuleResolutionForPath

func (options RunOptions) RuleResolutionForPath(sourcePath string) (rules.ResolveOptions, error)

RuleResolutionForPath resolves the exact policy for one physical source file.

type Statistics

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

Statistics collects opt-in process-local analysis measurements. Callers share one collector across every file and package in one CLI invocation.

func NewStatistics

func NewStatistics() *Statistics

NewStatistics creates an empty opt-in analysis statistics collector.

func (*Statistics) Snapshot

func (s *Statistics) Snapshot() StatisticsSnapshot

Snapshot returns a deterministic, independently owned statistics view.

type StatisticsCache

type StatisticsCache struct {
	Lookups       uint64
	Hits          uint64
	Misses        uint64
	Invalidations uint64
	Writes        uint64
}

StatisticsCache records observable persistent analysis-cache outcomes.

type StatisticsMetric

type StatisticsMetric struct {
	Calls          uint64
	Duration       time.Duration
	Allocations    uint64
	AllocatedBytes uint64
}

StatisticsMetric is one aggregate process-local measurement.

type StatisticsRule

type StatisticsRule struct {
	ID          string
	Requirement rules.Requirement
	Metric      StatisticsMetric
}

StatisticsRule is one rule's aggregate execution cost.

type StatisticsSnapshot

type StatisticsSnapshot struct {
	Total                   StatisticsMetric
	MaximumRequirement      rules.Requirement
	DependencySyntaxReasons []string
	EffectFactReasons       []string
	PackageLoads            StatisticsMetric
	Tiers                   []StatisticsTier
	Rules                   []StatisticsRule
	Cache                   StatisticsCache
	Packages                int
	Files                   int
}

StatisticsSnapshot is one immutable, canonically ordered collector view.

type StatisticsTier

type StatisticsTier struct {
	Requirement rules.Requirement
	Reasons     []string
	Metric      StatisticsMetric
}

StatisticsTier explains and measures one analysis representation.

type UnitcheckerFactAnalyzerRunnerOptions

type UnitcheckerFactAnalyzerRunnerOptions struct {
	Executable  string
	GoBinary    string
	Parallelism int
}

UnitcheckerFactAnalyzerRunnerOptions configure the bounded Go unitchecker subprocess used for exact dependency-fact propagation.

Jump to

Keyboard shortcuts

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