mast

package
v0.0.0-...-21c7a56 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 9 Imported by: ? 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 mast ("multi-AST") loads Go source code across multiple packages and build constraints, type-checks every file, and links all go/ast.Ident nodes that refer to the same logical entity into rename groups.

Overview

Standard Go tooling type-checks one build-tag configuration at a time, so platform-specific files are invisible to each other. mast solves this by discovering every .go file in a package directory, partitioning them by build constraint, type-checking each partition separately, and merging the results into a single Index. The result is a unified view of every identifier across all platforms.

Loading

Call Load with one or more package patterns:

ix, err := mast.Load(&mast.Config{Dir: "."}, "./...")

Load returns an Index containing:

  • Fset — the shared go/token.FileSet for position information.
  • Pkgs — all loaded packages with their files and parsed ASTs.
  • Errors — non-fatal errors encountered during loading.

Identifier groups

Every go/ast.Ident that refers to a user-defined entity is assigned to a Group. A group collects all identifiers — both definitions and uses — that refer to the same logical entity across files and build-tag partitions. Renaming a group means renaming every identifier in it.

grp := ix.Group(ident) // returns *Group or nil
for _, id := range grp.Idents {
    fmt.Printf("%s at %s (%v)\n",
        id.Ident.Name,
        ix.Fset.Position(id.Ident.Pos()),
        id.Kind)
}

Each Group carries:

  • Name — the identifier name.
  • Kind — the entity classification ([TypeName], [Func], [Method], [Field], [Var], [Const], [PackageName], [Label]).
  • Pkg — the package path where the entity is defined.
  • Idents — every occurrence, each marked as [Def] or [Use].

Identifiers that are blank (_), builtins, or universe-scope return nil from Index.Group.

Build constraints and test files

mast discovers all .go files in a package directory, including _test.go files, and extracts build constraints from //go:build directives and filename conventions (_linux.go, _amd64.go, etc.).

Files are partitioned into sets that can be type-checked together. When platform-specific files define conflicting top-level names (e.g. the same function in both _linux.go and _windows.go), each constraint group is type-checked in a separate pass with the unconstrained files included in every pass. When there are no conflicts all files are type-checked in a single pass.

Identifiers that appear in multiple passes (for example a type defined in a shared file and used in two platform files) are automatically merged into the same group.

Same-package test files (package foo in _test.go files) are type-checked together with the main package files. External test files (package foo_test) are type-checked in a separate pass after the main package, so they can import it, and are returned as a separate Package with path "pkg_test".

Every File carries a Pkg pointer back to the Package it belongs to, so from any Ident the containing package is available via ident.File.Pkg. This is needed when moving declarations between packages, where each use site may need its package qualifier and imports adjusted.

Embedded fields

For embedded (anonymous) struct fields the field identifier is linked to the embedded type's group, so that renaming the type also renames the embedding site.

Limitations

Type-checker errors are intentionally suppressed. This allows loading cross-platform code that would fail to compile under the host's build tags (e.g. a syscall used only on Linux), but it also means that invalid code is silently accepted. Only AST definitions, uses, and selections from the type-checker are retained; diagnostics are discarded.

Build-constraint partitioning uses syntactic conflict detection: constrained files are type-checked together when they do not define the same top-level function, type, variable, or constant names. When they do conflict (e.g. the same function in _linux.go and _windows.go), each constraint group is type-checked in a separate pass with the unconstrained files included in every pass. This is based on name equality only — indirect conflicts (A conflicts with B, B conflicts with C, but not A with C) and method-level conflicts are not detected and may lead to type-check failures that are silently swallowed.

Cross-partition linking relies on go/ast.File.Unresolved: after all type-check passes, identifiers that remain untracked are matched to package-scope groups by name. This only links package-level symbols (not local variables, fields, or methods). If two package-scope symbols share a name (which cannot happen in valid Go but can in constraint-partitioned code with suppressed errors), the linking is ambiguous.

Fields in anonymous (unnamed) struct types use position-based keys, so they form isolated groups that cannot be merged across build constraint partitions. Named struct fields are keyed by the owning type name, found by scanning the package scope; if the owner cannot be determined (e.g. fields from generic type instantiations), the field falls back to a position-based key. Position-based keys are stable within a single load but are not meaningful across separate invocations.

Import aliases are treated as file-scoped (each gets a position-based key) to prevent merging two files' aliases for different packages into the same group. This means renaming one import alias does not automatically rename another file's alias for the same package.

Embedded field identifiers are linked to the embedded type's group rather than a dedicated field group. Index.EmbeddedFieldGroups returns synthetic Use-only groups for composite literal keys and selectors that refer to the embedded field by name, but these groups have no Def ident — the definition site is part of the type name's group.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReadModulePath

func ReadModulePath(dir string) string

ReadModulePath reads the module path from the go.mod file in dir. Returns "" if no go.mod exists or the module line cannot be parsed.

func ReceiverTypeName

func ReceiverTypeName(recv *ast.FieldList) string

ReceiverTypeName extracts the type name from a method receiver field list.

Types

type Config

type Config struct {
	Dir string   // working directory
	Env []string // environment variables
}

Config controls how packages are loaded.

type File

type File struct {
	Path     string
	Pkg      *Package // the package this file belongs to
	Syntax   *ast.File
	Src      []byte // original source bytes
	BuildTag string // the build constraint, if any
}

File represents a single Go source file.

type Group

type Group struct {
	Name   string
	Kind   ObjectKind
	Pkg    string // package path where defined
	Idents []*Ident
}

Group represents a set of identifiers that refer to the same entity.

func (*Group) DefIdent

func (g *Group) DefIdent() *Ident

DefIdent returns the first Def ident in the group, or nil if none exists.

func (*Group) FindIdent

func (g *Group) FindIdent(target *ast.Ident, kind IdentKind) *Ident

FindIdent returns the ident in the group that matches target by pointer identity and has the given kind, or nil if no match exists.

func (*Group) HasUses

func (g *Group) HasUses() bool

HasUses reports whether the group has any Use idents.

func (*Group) IsPackageScope

func (g *Group) IsPackageScope() bool

IsPackageScope reports whether the group represents a package-scope declaration (as opposed to a local variable, parameter, or result). A package-scope group has at least one Def ident at file top-level — not nested inside any FuncDecl or FuncLit.

type Ident

type Ident struct {
	Ident     *ast.Ident
	Qualifier *ast.Ident // package qualifier ident in pkg.Name expressions, or nil
	File      *File
	Kind      IdentKind
}

Ident is a single identifier occurrence within a group.

type IdentKind

type IdentKind int

IdentKind distinguishes definitions from uses.

const (
	IdentInvalid IdentKind = iota
	IdentDef
	IdentUse
)

func (IdentKind) String

func (k IdentKind) String() string

type Index

type Index struct {
	Fset        *token.FileSet
	Pkgs        []*Package
	Errors      []error
	FilesByPath map[string]*File // populated after loading
	// contains filtered or unexported fields
}

Index holds the result of loading and linking identifiers.

func Load

func Load(cfg *Config, patterns ...string) (*Index, error)

Load parses and type-checks packages matching patterns, including all files regardless of build constraints. Returns an Index linking all identifiers.

func (*Index) EmbeddedFieldGroups

func (ix *Index) EmbeddedFieldGroups(name, pkg string) []*Group

EmbeddedFieldGroups returns Field groups with the given name and package that represent embedded (anonymous) fields. These groups contain only Use idents (composite literal keys and selectors) because the embedded field definition ident is linked to the type name's group instead.

func (*Index) FindDef

func (ix *Index) FindDef(name, source string) *ast.Ident

FindDef searches loaded packages for a top-level definition with the given name and returns its defining *ast.Ident, suitable for use in relo.Relo.

Package-level declarations (functions, types, variables, constants) take precedence over methods. A method is returned only as a fallback, when no package-level declaration with that name exists — this is what lets a bare method name like "Render" resolve when it is not shadowed by a top-level function. When both a top-level function and a method share a name, the top-level function wins, regardless of declaration order.

If source is non-empty, the search is narrowed: source is matched against package import paths (exact match) and file paths (suffix match), so it can be a full import path like "example.com/pkg" or a relative file name like "model.go".

Returns nil if no tracked definition is found.

func (*Index) FindFieldDef

func (ix *Index) FindFieldDef(typeName, fieldPath, source string) *ast.Ident

FindFieldDef searches for a field or method definition within a type declaration named typeName. For struct types it looks for a field named fieldPath in the struct's field list; for interface types it looks for a method with that name in the interface's method list. The source parameter filters the search (same rules as FindDef).

The type may be a named type (type T struct{...} or type T interface{...}) or an anonymous struct used as the type or value of a variable declaration (var V struct{...} or var V = struct{...}{}).

fieldPath may be a dotted path to reach fields in nested anonymous structs. For example, "TLS.CertFile" first finds the field TLS, then looks for CertFile in TLS's anonymous struct type. Interface methods must be simple (non-dotted) names.

If the field or method is not found inline, it falls back to searching for a receiver-based method (FuncDecl with Recv) on the type.

Returns nil if the type, field, or method is not found, or if the ident is not tracked by the index.

func (*Index) Group

func (ix *Index) Group(id *ast.Ident) *Group

Group returns all idents that must be renamed together with id, or nil if id is untracked (blank, builtin, universe).

type ObjectKind

type ObjectKind int

ObjectKind classifies the entity an identifier refers to.

const (
	ObjectUnknown ObjectKind = iota
	ObjectTypeName
	ObjectFunc
	ObjectMethod
	ObjectField
	ObjectVar
	ObjectConst
	ObjectPackageName
	ObjectLabel
)

func (ObjectKind) HasStub

func (k ObjectKind) HasStub() bool

HasStub reports whether this kind gets its own backward-compatibility stub when moved cross-package with stubs enabled. Methods are excluded because they follow the receiver type's alias automatically.

func (ObjectKind) String

func (k ObjectKind) String() string

func (ObjectKind) TravelsWithType

func (k ObjectKind) TravelsWithType() bool

TravelsWithType reports whether this kind represents an entity that moves with its parent type (methods and fields). These are accessed through instances (e.g. svc.Start(), cfg.Host), not as bare package- qualified identifiers, so they must not be package-qualified during cross-package moves.

type Package

type Package struct {
	Name      string
	Path      string
	GoVersion string // go directive of the containing module ("1.27"), or "" if unknown
	Files     []*File
}

Package represents a parsed and type-checked Go package.

Jump to

Keyboard shortcuts

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