ast

package
v0.0.0-...-c17f4fc Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BackendLanguageStatus

type BackendLanguageStatus struct {
	Language  string `json:"language"`
	Preferred string `json:"preferred"`
	Active    string `json:"active"`
	Reason    string `json:"reason,omitempty"`
}

type BackendStatus

type BackendStatus struct {
	Preferred string                  `json:"preferred"`
	Active    string                  `json:"active"`
	Reason    string                  `json:"reason,omitempty"`
	Languages []BackendLanguageStatus `json:"languages,omitempty"`
}

type Call

type Call struct {
	Callee string `json:"callee"`
	Line   int    `json:"line"`
}

Call is one call-site occurrence inside a parsed file. Callee is the identifier (possibly dotted) as written -- `f`, `obj.method`, `pkg.func`, `pkg.sub.func` all surface verbatim. Resolution to a concrete target (defined in which file, what receiver type) is deferred to phase 2; this struct just captures what the source said and where.

func ExtractCalls

func ExtractCalls(lang string, content []byte) []Call

ExtractCalls walks `content` line by line and returns every identifier-followed-by-paren occurrence that looks like a call, in source order. Returns nil for languages with no call-site regex wired (Java / Ruby / Rust are intentionally postponed -- they'd compound the keyword-list maintenance burden without pulling weight for the security-scanner consumers).

Filtering: declaration lines (`func foo(`, `def foo(`) are skipped so the function being declared doesn't appear as a call to itself. Per-language keyword lists filter out control-flow shapes (`if (...)`, `for (...)`, `while (...)`) that share the `keyword(...)` skeleton with real calls. Comment lines are skipped via the shared isCommentLine helper.

type Definition

type Definition struct {
	Name     string           `json:"name"`
	File     string           `json:"file"`
	Line     int              `json:"line"`
	Kind     types.SymbolKind `json:"kind"`
	Language string           `json:"language,omitempty"`
}

Definition is one place where a callable symbol is defined. Multiple Definitions can share the same Name when the same identifier is declared in different files (e.g. a method `Run` on two unrelated types). Resolution tiebreakers in SymbolIndex pick the most likely target.

type Engine

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

Engine provides caching AST parsing with tree-sitter and regex fallback. Thread-safe for concurrent use.

func New

func New() *Engine

New constructs an AST engine with the default parse-cache capacity.

func NewWithCacheSize

func NewWithCacheSize(cacheSize int) *Engine

NewWithCacheSize constructs an AST engine with an explicit LRU capacity.

func (*Engine) BackendStatus

func (e *Engine) BackendStatus() BackendStatus

func (*Engine) Close

func (e *Engine) Close() error

Close releases cache-held memory.

func (*Engine) ParseContent

func (e *Engine) ParseContent(ctx context.Context, path string, content []byte) (*ParseResult, error)

func (*Engine) ParseFile

func (e *Engine) ParseFile(ctx context.Context, path string) (*ParseResult, error)

func (*Engine) ParseMetrics

func (e *Engine) ParseMetrics() ParseMetrics

func (*Engine) Walk

func (e *Engine) Walk(ctx context.Context, path string, content []byte, visitor SymbolVisitor) (*ParseResult, error)

Walk parses `content` (going through the cache exactly like ParseContent) and invokes `visitor` for each extracted symbol in source order. Returns the underlying ParseResult so callers can also inspect imports / errors / backend without making a separate ParseContent call.

A nil visitor is treated as "parse only" -- semantically identical to ParseContent. Useful for callers that want the side-effect of caching the parse without committing to a visitor signature.

Errors from ParseContent are surfaced unchanged. The returned ParseResult is nil only when ParseContent itself errored.

func (*Engine) WalkPath

func (e *Engine) WalkPath(ctx context.Context, path string, visitor SymbolVisitor) (*ParseResult, error)

WalkPath is the convenience entry point that reads the file from disk before walking. Useful when callers already have a path but not the content. Equivalent to ReadFile + Walk; the read error is wrapped so callers can distinguish "I/O failed" from "parse failed".

type ImportAlias

type ImportAlias struct {
	Module string `json:"module"`
	Symbol string `json:"symbol,omitempty"`
	Local  string `json:"local"`
}

ImportAlias is one local binding produced by an import / require / use statement. The fields capture:

  • Module: the module path / package identifier as imported. For `from os import path as p` this is "os"; for `import { foo as bar } from 'pkg'` it's "pkg".

  • Symbol: the imported member name, BEFORE rename. For `from os import path as p` it's "path"; for plain `import os` it's empty (the whole module is the binding). For star imports / re-exports we use "*".

  • Local: the identifier the surrounding file uses. For `from os import path as p` this is "p"; for plain `import os` it's "os".

Callers that resolve `p.join(...)` look up `p` in Local and find (Module="os", Symbol="path"), then know `p.join` is actually `os.path.join`.

type ParseError

type ParseError struct {
	Line    int    `json:"line"`
	Column  int    `json:"column"`
	Message string `json:"message"`
}

type ParseMetrics

type ParseMetrics struct {
	Requests             int64            `json:"requests"`
	Parsed               int64            `json:"parsed"`
	CacheHits            int64            `json:"cache_hits"`
	CacheMisses          int64            `json:"cache_misses"`
	Unsupported          int64            `json:"unsupported"`
	Errors               int64            `json:"errors"`
	TotalParseDurationMs int64            `json:"total_parse_duration_ms"`
	AvgParseDurationMs   float64          `json:"avg_parse_duration_ms"`
	LastLanguage         string           `json:"last_language,omitempty"`
	LastBackend          string           `json:"last_backend,omitempty"`
	ByLanguage           map[string]int64 `json:"by_language,omitempty"`
	ByBackend            map[string]int64 `json:"by_backend,omitempty"`
}

type ParseResult

type ParseResult struct {
	Path     string         `json:"path"`
	Language string         `json:"language"`
	Symbols  []types.Symbol `json:"symbols"`
	Imports  []string       `json:"imports"`
	// ImportAliases is the per-binding alias table: every entry pairs
	// the source module + imported symbol with the local identifier
	// the surrounding code uses to reach it. Imports is a flat list of
	// just the module paths (deduped); ImportAliases keeps the
	// (Module, Symbol, Local) link so callers can resolve
	// `p.join(...)` back to `os.path.join` when the source said
	// `from os import path as p`. Nil for languages without alias
	// extraction; see internal/ast/imports_aliases.go.
	ImportAliases []ImportAlias `json:"import_aliases,omitempty"`
	Errors        []ParseError  `json:"errors,omitempty"`
	Hash          uint64        `json:"hash"`
	ParsedAt      time.Time     `json:"parsed_at"`
	Duration      time.Duration `json:"duration"`
	// Backend records which extractor produced the symbols: "tree-sitter"
	// when the CGO bindings parsed the file cleanly, or "regex" when we
	// fell back (CGO disabled, parse failed, or language stub). Callers
	// surface this so consumers know when results are best-effort.
	Backend string `json:"backend,omitempty"`
}

ParseResult holds the extracted symbols and metadata for a single parsed file.

type ResolvedEdge

type ResolvedEdge struct {
	Call   Call        `json:"call"`
	Target *Definition `json:"target,omitempty"`
}

ResolvedEdge pairs a Call with the resolved (or unresolved) Target. Used by callers that want the entire call graph for a file at once.

type StringVisitor

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

type SymbolIndex

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

SymbolIndex is a workspace-wide map from bare symbol name to every declaration site that name appears at. Used to answer "what does this call point to?" queries by ResolveCall.

Nil-safe: every method returns the zero value (nil / empty slice) on a nil receiver, so callers can treat "no index" and "index says unknown" identically.

func BuildSymbolIndex

func BuildSymbolIndex(files []*ParseResult) *SymbolIndex

BuildSymbolIndex indexes every callable symbol in a corpus of parsed files. Order of `files` matches insertion order in the resulting per-name slices, so callers that want deterministic tiebreakers should pass files in a stable order (lexicographic by path is the convention).

func (*SymbolIndex) Lookup

func (idx *SymbolIndex) Lookup(name string) []Definition

Lookup returns every Definition for the given bare name (no dot resolution -- callers that want dotted-name lookup should use Resolve). The returned slice is a fresh copy so callers can mutate it without affecting the index.

func (*SymbolIndex) Resolve

func (idx *SymbolIndex) Resolve(callerFile, callee string) *Definition

Resolve attempts to resolve a call's Callee to a single Definition. Dotted callees use the LAST segment as the lookup key (`os.path.join` -> `join`), since the leading segments describe the module path which we may not have indexed.

Tiebreakers:

  1. A definition in callerFile wins over any other match. This captures the common case where the caller calls its own helper.

  2. A single workspace-wide match resolves cleanly.

  3. Multiple matches with no same-file winner: return nil. Ambiguity is reported as "unresolved" rather than guessed.

Returns nil for an empty / unknown name, or when ambiguity cannot be resolved without additional type information.

func (*SymbolIndex) ResolveCalls

func (idx *SymbolIndex) ResolveCalls(callerFile string, calls []Call) []ResolvedEdge

ResolveCalls applies Resolve to every Call in `calls`, treating `callerFile` as the caller's source path for tiebreaker purposes. Unresolved calls appear in the result with Target=nil so callers can see the full edge list including misses.

func (*SymbolIndex) Size

func (idx *SymbolIndex) Size() int

Size reports the number of distinct bare names in the index. Useful for diagnostics / status surfaces; not load-bearing for resolution itself.

type SymbolVisitor

type SymbolVisitor func(sym types.Symbol) WalkAction

SymbolVisitor is invoked once per symbol during Walk. The visitor receives a value copy (types.Symbol is small) and returns a WalkAction. Returning WalkStop terminates the walk; any other return value (including the zero value) continues.

type WalkAction

type WalkAction int

WalkAction tells Walk what to do after visiting a symbol. The zero value (WalkContinue) is the common case so visitors that "always want everything" can just return the zero value.

const (
	// WalkContinue keeps walking, passing the next symbol to the
	// visitor. Default behaviour when the visitor returns the zero
	// value.
	WalkContinue WalkAction = iota
	// WalkStop terminates the walk immediately. Remaining symbols
	// are not visited. The Walk call still returns the underlying
	// ParseResult so callers can inspect imports / errors / backend
	// after an early stop.
	WalkStop
)

Jump to

Keyboard shortcuts

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