codeapi

package
v0.0.0-...-6320ad3 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package codeapi provides a clean read interface for querying the code graph. It offers two main interfaces:

  • CodeReader: Repository-scoped entity queries (find classes, methods, fields)
  • GraphAnalyzer: Graph traversals (call graphs, data dependencies)

These are combined in the CodeAPI facade for convenient access.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CallEdge

type CallEdge struct {
	CallerID ast.NodeID
	CalleeID ast.NodeID
	CallSite *Location // where the call occurs
}

CallEdge represents a call relationship

type CallGraph

type CallGraph struct {
	Root      *CallNode
	Nodes     map[ast.NodeID]*CallNode
	Edges     []*CallEdge
	Direction Direction
	MaxDepth  int
	Truncated bool // true if results were limited
}

CallGraph represents a function call graph

type CallGraphOptions

type CallGraphOptions struct {
	Direction       Direction
	MaxDepth        int
	IncludeExternal bool         // include calls to external packages
	IncludeTests    bool         // include test files
	StopAt          []ast.NodeID // don't traverse past these nodes
}

CallGraphOptions controls call graph traversal

func DefaultCallGraphOptions

func DefaultCallGraphOptions() CallGraphOptions

DefaultCallGraphOptions returns sensible defaults

type CallNode

type CallNode struct {
	ID        ast.NodeID
	Name      string
	ClassName string // empty if top-level function
	FilePath  string
	FileID    int32
	Depth     int // distance from root
	Range     base.Range
}

CallNode represents a function in the call graph

type ClassFilter

type ClassFilter struct {
	Name     string // exact match
	NameLike string // pattern match (e.g., "*Service")
	FilePath string // exact file path
	FileID   *int32

	Limit  int
	Offset int
}

ClassFilter specifies criteria for finding classes

type ClassInfo

type ClassInfo struct {
	ID       ast.NodeID
	Name     string
	FilePath string
	FileID   int32
	Range    base.Range
	Language string

	// Metadata contains additional attributes (e.g., annotations, modifiers)
	Metadata map[string]any `json:"metadata,omitempty"`

	// Populated on demand
	Methods []*MethodInfo
	Fields  []*FieldInfo

	// Inheritance
	ParentClasses []ast.NodeID
	ChildClasses  []ast.NodeID
}

ClassInfo contains information about a class/struct

type ClassWithCallGraph

type ClassWithCallGraph struct {
	Class       *ClassInfo
	MethodCalls map[ast.NodeID]*CallGraph // methodID -> call graph
}

ClassWithCallGraph combines class info with call graphs for its methods

type CodeAPI

type CodeAPI interface {
	// Reader returns the CodeReader for entity queries
	Reader() CodeReader

	// Analyzer returns the GraphAnalyzer for graph traversals
	Analyzer() GraphAnalyzer

	// ExecuteCypher executes a raw Cypher query and returns the results.
	// Use this for complex queries not covered by Reader or Analyzer.
	// The query should be read-only; use ExecuteCypherWrite for mutations.
	ExecuteCypher(ctx context.Context, query string, params map[string]any) ([]map[string]any, error)

	// ExecuteCypherWrite executes a write Cypher query (create, update, delete).
	// Returns the result records if any.
	ExecuteCypherWrite(ctx context.Context, query string, params map[string]any) ([]map[string]any, error)
}

CodeAPI is the main entry point for querying the code graph. It provides access to both entity queries (CodeReader) and graph traversals (GraphAnalyzer).

func NewCodeAPI

func NewCodeAPI(graph *codegraph.CodeGraph, logger *zap.Logger) CodeAPI

NewCodeAPI creates a new CodeAPI instance backed by the given CodeGraph

type CodeReader

type CodeReader interface {
	// Repo returns a reader scoped to a specific repository
	Repo(name string) RepoReader

	// ListRepos returns all available repository names
	ListRepos(ctx context.Context) ([]string, error)
}

CodeReader provides repository-scoped access to code entities. It follows a hierarchical pattern: CodeReader → RepoReader → FileReader

type DependencyEdge

type DependencyEdge struct {
	SourceID ast.NodeID
	TargetID ast.NodeID
	FlowType string // "assignment", "parameter", "return", etc.
}

DependencyEdge represents a data flow relationship

type DependencyGraph

type DependencyGraph struct {
	Root      *DependencyNode
	Nodes     map[ast.NodeID]*DependencyNode
	Edges     []*DependencyEdge
	Direction Direction
	Truncated bool
}

DependencyGraph represents data dependencies

type DependencyNode

type DependencyNode struct {
	ID       ast.NodeID
	Name     string
	NodeType ast.NodeType
	FilePath string
	FileID   int32
	Depth    int
}

DependencyNode represents a node in the dependency graph

type DependencyOptions

type DependencyOptions struct {
	MaxDepth        int
	IncludeIndirect bool           // transitive dependencies
	FilterTypes     []ast.NodeType // only return these node types
}

DependencyOptions controls dependency graph traversal

func DefaultDependencyOptions

func DefaultDependencyOptions() DependencyOptions

DefaultDependencyOptions returns sensible defaults

type Direction

type Direction string

Direction specifies traversal direction for graph queries

const (
	DirectionOutgoing Direction = "outgoing" // follow outgoing edges (e.g., callees)
	DirectionIncoming Direction = "incoming" // follow incoming edges (e.g., callers)
	DirectionBoth     Direction = "both"     // follow both directions
)

type FieldAccessResult

type FieldAccessResult struct {
	Field   *FieldInfo
	Readers []*MethodAccessInfo // methods that read this field
	Writers []*MethodAccessInfo // methods that write this field
}

FieldAccessResult contains methods that access a field

type FieldFilter

type FieldFilter struct {
	Name       string
	NameLike   string
	ClassName  string
	ClassID    *ast.NodeID
	Visibility *Visibility

	Limit  int
	Offset int
}

FieldFilter specifies criteria for finding fields

type FieldInfo

type FieldInfo struct {
	ID         ast.NodeID
	Name       string
	Type       string
	ClassID    ast.NodeID
	Range      base.Range
	Visibility Visibility
	IsStatic   bool

	// Metadata contains additional attributes (e.g., annotations, modifiers)
	Metadata map[string]any `json:"metadata,omitempty"`
}

FieldInfo contains information about a class field

type FileFilter

type FileFilter struct {
	Path     string
	PathLike string // pattern match
	Language string

	Limit  int
	Offset int
}

FileFilter specifies criteria for finding files

type FileInfo

type FileInfo struct {
	ID       ast.NodeID
	Path     string
	Language string
	FileID   int32
	RepoName string

	// Metadata contains additional attributes
	Metadata map[string]any `json:"metadata,omitempty"`

	// Populated on demand
	Classes   []*ClassInfo
	Functions []*MethodInfo // top-level functions
}

FileInfo contains information about a source file

type FileReader

type FileReader interface {
	// Path returns the file path
	Path() string

	// FileID returns the file ID (0 if not yet resolved)
	FileID() int32

	// Info returns the file info
	Info(ctx context.Context) (*FileInfo, error)

	// ListClasses returns all classes in this file
	ListClasses(ctx context.Context) ([]*ClassInfo, error)

	// FindClassByName finds a class by name in this file
	FindClassByName(ctx context.Context, name string) (*ClassInfo, error)

	// ListMethods returns all methods (class methods) in this file
	ListMethods(ctx context.Context) ([]*MethodInfo, error)

	// ListFunctions returns all top-level functions in this file
	ListFunctions(ctx context.Context) ([]*MethodInfo, error)

	// FindMethodByName finds a method/function by name in this file
	FindMethodByName(ctx context.Context, name string) (*MethodInfo, error)

	// FindMethodInClass finds a method by name within a specific class
	FindMethodInClass(ctx context.Context, methodName, className string) (*MethodInfo, error)

	// ListFields returns all fields in this file
	ListFields(ctx context.Context) ([]*FieldInfo, error)

	// FindFieldByName finds a field by name, optionally scoped to a class
	FindFieldByName(ctx context.Context, fieldName, className string) (*FieldInfo, error)
}

FileReader provides access to code entities within a specific file

type FindAndAnalyzeRequest

type FindAndAnalyzeRequest struct {
	RepoName string
	FilePath string // optional, narrows search
	Name     string
	NodeType ast.NodeType // Function, Class, Field, Variable

	// Analysis options
	IncludeCallGraph bool
	CallGraphDepth   int
	IncludeDataFlow  bool
	DataFlowDepth    int
}

FindAndAnalyzeRequest specifies what to find and analyze

type FindAndAnalyzeResult

type FindAndAnalyzeResult struct {
	// The found entity (one of these will be set)
	Class    *ClassInfo
	Method   *MethodInfo
	Field    *FieldInfo
	Variable *VariableInfo

	// Analysis results
	CallGraph *CallGraph
	DataFlow  *DependencyGraph
	Impact    *ImpactResult
}

FindAndAnalyzeResult contains the found entity with analysis

type GraphAnalyzer

type GraphAnalyzer interface {

	// GetCallGraph returns the call graph starting from a function.
	// Use opts.Direction to control whether to get callees, callers, or both.
	GetCallGraph(ctx context.Context, functionID ast.NodeID, opts CallGraphOptions) (*CallGraph, error)

	// GetCallGraphByName finds a function by name and returns its call graph.
	// If className is empty, searches for top-level functions.
	// If filePath is empty, searches across all files in the repo.
	GetCallGraphByName(ctx context.Context, repoName, filePath, className, functionName string, opts CallGraphOptions) (*CallGraph, error)

	// GetCallers returns functions that call the specified function (convenience method).
	// Equivalent to GetCallGraph with Direction=Incoming.
	GetCallers(ctx context.Context, functionID ast.NodeID, maxDepth int) (*CallGraph, error)

	// GetCallees returns functions called by the specified function (convenience method).
	// Equivalent to GetCallGraph with Direction=Outgoing.
	GetCallees(ctx context.Context, functionID ast.NodeID, maxDepth int) (*CallGraph, error)

	// GetDataDependents returns nodes that depend on the value of the specified node.
	// Follows DATA_FLOW edges outward to find what uses this value.
	GetDataDependents(ctx context.Context, nodeID ast.NodeID, opts DependencyOptions) (*DependencyGraph, error)

	// GetDataSources returns nodes that contribute to the value of the specified node.
	// Follows DATA_FLOW edges backward to find where values come from.
	GetDataSources(ctx context.Context, nodeID ast.NodeID, opts DependencyOptions) (*DependencyGraph, error)

	// GetVariableDependents returns functions/methods that depend on a variable's value.
	// This is a higher-level query that finds the variable and traces its usage.
	GetVariableDependents(ctx context.Context, repoName, filePath, variableName string, opts DependencyOptions) (*DependencyGraph, error)

	// GetFieldAccessors returns methods that read or write a specific field.
	GetFieldAccessors(ctx context.Context, fieldID ast.NodeID) (*FieldAccessResult, error)

	// GetFieldAccessorsByName finds a field by name and returns its accessors.
	GetFieldAccessorsByName(ctx context.Context, repoName, className, fieldName string) (*FieldAccessResult, error)

	// GetInheritanceTree returns the inheritance hierarchy for a class.
	// Includes both ancestors (parents) and descendants (children).
	GetInheritanceTree(ctx context.Context, classID ast.NodeID) (*InheritanceTree, error)

	// GetParentClasses returns direct and indirect parent classes.
	GetParentClasses(ctx context.Context, classID ast.NodeID, maxDepth int) ([]*ClassInfo, error)

	// GetChildClasses returns direct and indirect child classes.
	GetChildClasses(ctx context.Context, classID ast.NodeID, maxDepth int) ([]*ClassInfo, error)

	// GetImpact returns all code elements that could be affected by changes to the specified node.
	// This combines call graph and data flow analysis.
	GetImpact(ctx context.Context, nodeID ast.NodeID, opts ImpactOptions) (*ImpactResult, error)

	// GetImpactByName is a convenience method for impact analysis by name.
	GetImpactByName(ctx context.Context, repoName, filePath, name string, nodeType ast.NodeType, opts ImpactOptions) (*ImpactResult, error)
}

GraphAnalyzer provides graph traversal operations on the code graph. It supports call graph analysis, data flow tracking, and inheritance queries.

type ImpactNode

type ImpactNode struct {
	ID       ast.NodeID
	Name     string
	NodeType ast.NodeType
	FilePath string
	FileID   int32
	Depth    int
	Impact   ImpactType // how this node is affected
}

ImpactNode represents a node in the impact analysis

type ImpactOptions

type ImpactOptions struct {
	MaxDepth         int  // max traversal depth (-1 for unlimited)
	IncludeCallGraph bool // include callers in impact
	IncludeDataFlow  bool // include data dependents in impact
	IncludeTests     bool // include test files
	Scope            ImpactScope
}

ImpactOptions controls impact analysis behavior

func DefaultImpactOptions

func DefaultImpactOptions() ImpactOptions

DefaultImpactOptions returns sensible defaults for impact analysis

type ImpactResult

type ImpactResult struct {
	// Source is the node being analyzed
	Source *ImpactNode

	// AffectedNodes are nodes that could be affected by changes
	AffectedNodes []*ImpactNode

	// AffectedByCallGraph are nodes affected via call relationships
	AffectedByCallGraph []*ImpactNode

	// AffectedByDataFlow are nodes affected via data dependencies
	AffectedByDataFlow []*ImpactNode

	// Summary statistics
	TotalAffected   int
	MaxDepthReached int
	Truncated       bool
}

ImpactResult contains the result of impact analysis

type ImpactScope

type ImpactScope string

ImpactScope defines the boundary for impact analysis

const (
	ImpactScopeFile    ImpactScope = "file"    // only within the same file
	ImpactScopePackage ImpactScope = "package" // within the same package/module
	ImpactScopeRepo    ImpactScope = "repo"    // within the repository
	ImpactScopeAll     ImpactScope = "all"     // including external dependencies
)

type ImpactType

type ImpactType string

ImpactType describes how a node is affected

const (
	ImpactTypeDirect     ImpactType = "direct"     // directly uses the source
	ImpactTypeTransitive ImpactType = "transitive" // indirectly affected
	ImpactTypeCallGraph  ImpactType = "call_graph" // affected via call relationship
	ImpactTypeDataFlow   ImpactType = "data_flow"  // affected via data dependency
)

type InheritanceNode

type InheritanceNode struct {
	ID       ast.NodeID
	Name     string
	FilePath string
	Parents  []*InheritanceNode
	Children []*InheritanceNode
	Depth    int
}

InheritanceNode represents a class in the inheritance tree

type InheritanceTree

type InheritanceTree struct {
	Root     *InheritanceNode
	Nodes    map[ast.NodeID]*InheritanceNode
	MaxDepth int
}

InheritanceTree represents class inheritance relationships

type LoadOptions

type LoadOptions struct {
	IncludeMethods     bool
	IncludeFields      bool
	IncludeInheritance bool
	IncludeParameters  bool
}

LoadOptions controls what data to load with entities

type Location

type Location struct {
	FilePath string
	FileID   int32
	Range    base.Range
}

Location represents a position in source code

type MethodAccessInfo

type MethodAccessInfo struct {
	Method      *MethodInfo
	AccessCount int        // number of times the field is accessed
	Locations   []Location // where in the method the access occurs
}

MethodAccessInfo contains info about a method that accesses a field

type MethodFilter

type MethodFilter struct {
	Name      string
	NameLike  string
	ClassName string
	ClassID   *ast.NodeID
	FilePath  string
	FileID    *int32

	IsMethod   *bool // nil = any, true = methods only, false = functions only
	IsAccessor *bool

	Limit  int
	Offset int
}

MethodFilter specifies criteria for finding methods

type MethodInfo

type MethodInfo struct {
	ID       ast.NodeID
	Name     string
	FilePath string
	FileID   int32
	Range    base.Range

	// Context
	ClassName string
	ClassID   ast.NodeID
	IsMethod  bool // true if belongs to a class, false if top-level function

	// Signature
	Parameters []*ParameterInfo
	ReturnType string

	// Flags
	IsAccessor    bool
	IsConstructor bool
	IsStatic      bool
	Visibility    Visibility

	// Metadata contains additional attributes (e.g., annotations, modifiers)
	Metadata map[string]any `json:"metadata,omitempty"`
}

MethodInfo contains information about a method/function

type MethodWithContext

type MethodWithContext struct {
	Method  *MethodInfo
	Class   *ClassInfo // nil if top-level function
	File    *FileInfo
	Callers *CallGraph
	Callees *CallGraph
}

MethodWithContext provides method info with surrounding context

type ParameterInfo

type ParameterInfo struct {
	ID       ast.NodeID
	Name     string
	Type     string
	Position int
}

ParameterInfo contains information about a function parameter

type RepoReader

type RepoReader interface {
	// Name returns the repository name
	Name() string

	// ListFiles returns files in the repository with pagination
	ListFiles(ctx context.Context, limit, offset int) ([]*FileInfo, error)

	// FindFiles returns files matching the filter
	FindFiles(ctx context.Context, filter FileFilter) ([]*FileInfo, error)

	// GetFile returns a file by its ID
	GetFile(ctx context.Context, id ast.NodeID) (*FileInfo, error)

	// GetFileByPath returns a file by its path
	GetFileByPath(ctx context.Context, path string) (*FileInfo, error)

	// File returns a reader scoped to a specific file
	File(path string) FileReader

	// FileByID returns a reader scoped to a specific file by ID
	FileByID(id int32) FileReader

	// ListClasses returns classes in the repository with pagination
	ListClasses(ctx context.Context, limit, offset int) ([]*ClassInfo, error)

	// FindClasses returns classes matching the filter
	FindClasses(ctx context.Context, filter ClassFilter) ([]*ClassInfo, error)

	// GetClass returns a class by its ID
	GetClass(ctx context.Context, id ast.NodeID) (*ClassInfo, error)

	// GetClassFull returns a class with methods and fields populated
	GetClassFull(ctx context.Context, id ast.NodeID, opts LoadOptions) (*ClassInfo, error)

	// FindClassByName finds a class by name (returns first match)
	FindClassByName(ctx context.Context, name string) (*ClassInfo, error)

	// ListMethods returns methods in the repository with pagination
	ListMethods(ctx context.Context, limit, offset int) ([]*MethodInfo, error)

	// ListFunctions returns top-level functions (not class methods) with pagination
	ListFunctions(ctx context.Context, limit, offset int) ([]*MethodInfo, error)

	// FindMethods returns methods matching the filter
	FindMethods(ctx context.Context, filter MethodFilter) ([]*MethodInfo, error)

	// GetMethod returns a method by its ID
	GetMethod(ctx context.Context, id ast.NodeID) (*MethodInfo, error)

	// FindMethodByName finds a method by name and optional class
	FindMethodByName(ctx context.Context, methodName string, className string) (*MethodInfo, error)

	// FindFields returns fields matching the filter
	FindFields(ctx context.Context, filter FieldFilter) ([]*FieldInfo, error)

	// GetField returns a field by its ID
	GetField(ctx context.Context, id ast.NodeID) (*FieldInfo, error)

	// GetClassMethods returns all methods belonging to a class
	GetClassMethods(ctx context.Context, classID ast.NodeID) ([]*MethodInfo, error)

	// GetClassFields returns all fields belonging to a class
	GetClassFields(ctx context.Context, classID ast.NodeID) ([]*FieldInfo, error)

	// GetMethodClass returns the class containing a method (nil if top-level function)
	GetMethodClass(ctx context.Context, methodID ast.NodeID) (*ClassInfo, error)
}

RepoReader provides access to code entities within a repository

type VariableInfo

type VariableInfo struct {
	ID       ast.NodeID
	Name     string
	Type     string
	FilePath string
	FileID   int32
	Range    Location
	Scope    string // "local", "parameter", "global"
}

VariableInfo contains information about a variable

type Visibility

type Visibility string

Visibility represents field/method visibility

const (
	VisibilityPublic    Visibility = "public"
	VisibilityPrivate   Visibility = "private"
	VisibilityProtected Visibility = "protected"
	VisibilityPackage   Visibility = "package" // Go's default, Java's package-private
)

Jump to

Keyboard shortcuts

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