parser

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MatchBuildContext

func MatchBuildContext(buildCtx build.Context, name, content string) bool

MatchBuildContext returns true when (name, content) should be parsed under buildCtx — i.e. the filename suffix doesn't conflict with GOOS/GOARCH and any `//go:build` / `// +build` constraint lines evaluate to true. Mirrors build.Context.MatchFile for callers that have file content in-memory rather than on disk.

The constraint evaluator recognizes:

  • GOOS/GOARCH name tags (matches when ctx.GOOS == tag etc.)
  • "cgo" if buildCtx.CgoEnabled is true
  • language version tags (e.g. "go1.21") if at or below the configured release; falls back to true to avoid spurious exclusions
  • any tag listed in buildCtx.BuildTags or buildCtx.ToolTags
  • the special "ignore" tag (always false — Go convention for manually excluding a file)

Unknown tags evaluate to false. This matches build.Context's behavior for tags it doesn't recognize.

func ParseGoMod

func ParseGoMod(path, content string) (*golang.GoResolutionResult, error)

ParseGoMod parses go.mod content into a golang.GoResolutionResult. Mirrors org.openrewrite.golang.GoModParser on the Java side.

func ParseGoModFile added in v0.0.9

func ParseGoModFile(path, content string) (*golang.GoMod, error)

ParseGoModFile parses go.mod content into a lossless golang.GoMod LST. Mirrors org.openrewrite.golang.GoModParser on the Java side (the LST path, not the legacy PlainText+marker path).

The structure is taken from modfile.ParseLax's low-level FileSyntax — ParseLax (not Parse) so unknown/future directives (godebug, tool, ignore, …) are preserved as generic directive lines instead of erroring. All whitespace and comments are reconstructed from the original byte ranges so re-printing yields the input verbatim; modfile is used only to locate token, paren, and line boundaries.

func ParseGoSum

func ParseGoSum(content string) []golang.GoResolvedDependency

ParseGoSum parses go.sum content into a slice of GoResolvedDependency, one per (module, version) pair. Bad lines are logged and skipped — go.sum is best-effort metadata, not an authoritative spec; a single malformed line should never tank a parse.

Mirrors org.openrewrite.golang.GoModParser#parseSumSibling. The Go side is content-based (not filesystem-based) because the parser is invoked via RPC where sources are passed as strings.

Types

type FileInput

type FileInput struct {
	Path    string
	Content string
}

FileInput is one file given to ParsePackage.

type GoParser

type GoParser struct {
	// Importer resolves imported packages for type checking.
	// Defaults to importer.Default() which resolves stdlib packages.
	Importer types.Importer

	// BuildContext drives `//go:build` and filename-suffix constraint
	// evaluation in ParsePackage. Defaults to build.Default (the host's
	// GOOS/GOARCH). Recipe authors that need cross-platform analysis can
	// set this explicitly via NewGoParserWithBuildContext.
	BuildContext build.Context
}

GoParser parses Go source code into OpenRewrite LST nodes.

func NewGoParser

func NewGoParser() *GoParser

func NewGoParserWithBuildContext

func NewGoParserWithBuildContext(buildCtx build.Context) *GoParser

NewGoParserWithBuildContext returns a parser that filters input files against the given build context. Useful for recipes that need to analyze code as it would compile under a specific GOOS/GOARCH/cgo configuration. To switch contexts, build a new parser — A3 keeps BuildContext immutable per parser to avoid cache-key complexity.

func (*GoParser) Parse

func (gp *GoParser) Parse(sourcePath string, source string) (*golang.CompilationUnit, error)

Parse parses a single Go source file and returns its CompilationUnit. Convenience wrapper around ParsePackage for the common one-file case; type attribution that depends on sibling files in the same package won't resolve here. Use ParsePackage when sibling files matter.

func (*GoParser) ParsePackage

func (gp *GoParser) ParsePackage(files []FileInput) ([]*golang.CompilationUnit, error)

ParsePackage parses every file in a single Go package together so type-checking sees them as one unit. File A's reference to file B's symbol resolves; the resulting CompilationUnits share a single types.Info populated by one types.Config.Check call.

All files MUST belong to the same package (same `package` clause). Order in the returned slice matches the input order.

type ProjectImporter

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

ProjectImporter resolves Go imports for a parsed file against four layers, in order:

  1. Sibling sources within the same project (registered via AddSource). Yields real *types.Package objects from parsing + type-checking.
  2. Vendored sources at `<projectRoot>/vendor/<importPath>/*.go`. When a `replace` directive applies, the lookup target is resolved accordingly: local replace (`./` / `../` prefix) walks the local path; module-path replace walks `vendor/<NewPath>/`. Yields real *types.Package objects with full method/field types.
  3. Modules declared in go.mod's `require` directives (registered via AddRequire). Yields a STUB *types.Package — right path and name, empty scope — so references like `import "github.com/x/y"` make the identifier `y` non-nil even when the module's source isn't present locally.
  4. The fallback (importer.Default by default), which resolves stdlib packages from GOROOT.

Mirrors the role of MavenProject/JavaSourceSet classpath resolution on the Java side: when a recipe parses a Go file inside a project, imports of `<modulePath>/<sub>` resolve against that sub-package's parsed sources, vendored deps resolve against on-disk files, and requires without vendor sources fall back to typed-but-empty stubs.

Vendor walking is lazy on each Import() call (matching the existing 3-tier resolver's laziness). No eager startup walk.

func NewProjectImporter

func NewProjectImporter(modulePath string, fallback types.Importer) *ProjectImporter

NewProjectImporter creates an importer rooted at the given module path. Pass importer.Default() (or nil for the same default) as the stdlib fallback. Project root is unset and must be configured via SetProjectRoot for vendor walking to find anything.

func (*ProjectImporter) AddReplace

func (p *ProjectImporter) AddReplace(oldPath, newPath, newVersion string)

AddReplace registers a go.mod `replace oldPath [oldVersion] => newPath [newVersion]` entry. At Import() time, requests for oldPath (or sub-paths under it) are redirected to newPath. Local-path replacements (`./` / `../`) resolve against the project root; module-path replacements resolve against `vendor/<NewPath>/`.

func (*ProjectImporter) AddRequire

func (p *ProjectImporter) AddRequire(modulePath string)

AddRequire registers a module path declared in go.mod's `require` list. Imports of this path (or any sub-path under it) that aren't already satisfied by AddSource'd sibling sources resolve to a stub *types.Package — non-nil, with the right path and name, but with an empty scope. Real method/field types still need the module's actual sources (vendor dir or go-mod cache walk; not done yet).

func (*ProjectImporter) AddSource

func (p *ProjectImporter) AddSource(relPath, content string)

AddSource registers a .go file with the importer. relPath is the file's path relative to the module root, e.g. "main.go" or "sub/sub.go". Only .go files are indexed; anything else is ignored.

func (*ProjectImporter) Import

func (p *ProjectImporter) Import(importPath string) (*types.Package, error)

Import implements types.Importer.

func (*ProjectImporter) SetProjectRoot

func (p *ProjectImporter) SetProjectRoot(root string)

SetProjectRoot configures the directory the vendor walker scans relative to. Without this set, vendor lookups always miss and the resolver falls through to the require-stub tier. Pass the directory containing the project's go.mod.

Jump to

Keyboard shortcuts

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