resolution

package
v0.0.0-...-480d8ff Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2025 License: AGPL-3.0 Imports: 6 Imported by: 0

Documentation

Overview

Package resolution provides type information structures for type resolution and inference.

This package defines the type system used by the type inference engine and registry packages. It contains data structures that track variable bindings and function scopes during type analysis.

Type Information

The core type information is defined in the core package (core.TypeInfo), while this package focuses on scope and binding management:

typeInfo := &core.TypeInfo{
    TypeFQN:    "builtins.str",
    Source:     "literal",
    Confidence: 1.0,
}

binding := &resolution.VariableBinding{
    VarName: "username",
    Type:    typeInfo,
}

Function Scopes

FunctionScope tracks variable bindings within a function:

scope := resolution.NewFunctionScope("myapp.views.login")
scope.AddVariable(&resolution.VariableBinding{
    VarName: "user",
    Type:    &core.TypeInfo{TypeFQN: "myapp.models.User"},
})

Breaking Circular Dependencies

This package was created to resolve the circular dependency between builtin_registry.go and type_inference.go by providing shared type definitions that both packages can depend on without depending on each other.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractCallSites

func ExtractCallSites(filePath string, sourceCode []byte, importMap *core.ImportMap) ([]*core.CallSite, error)

ExtractCallSites extracts all function/method call sites from a Python file. It traverses the AST to find call expressions and builds CallSite objects with caller context, callee information, and arguments.

Algorithm:

  1. Parse source code with tree-sitter Python parser
  2. Traverse AST to find call expressions
  3. For each call, extract: - Caller function/method (containing context) - Callee name (function/method being called) - Arguments (positional and keyword) - Source location (file, line, column)
  4. Build CallSite objects for each call

Parameters:

  • filePath: absolute path to the Python file being analyzed
  • sourceCode: contents of the Python file as byte array
  • importMap: import mappings for resolving qualified names

Returns:

  • []CallSite: list of all call sites found in the file
  • error: if parsing fails or source is invalid

Example:

Source code:
  def process_data():
      result = sanitize(data)
      db.query(result)

Extracts CallSites:
  [
    {Caller: "process_data", Callee: "sanitize", Args: ["data"]},
    {Caller: "process_data", Callee: "db.query", Args: ["result"]}
  ]

func ExtractImports

func ExtractImports(filePath string, sourceCode []byte, registry *core.ModuleRegistry) (*core.ImportMap, error)

ExtractImports extracts all import statements from a Python file and builds an ImportMap. It handles four main import styles:

  1. Simple imports: import module
  2. From imports: from module import name
  3. Aliased imports: from module import name as alias
  4. Relative imports: from . import module, from .. import module

The resulting ImportMap maps local names (aliases or imported names) to their fully qualified module paths, enabling later resolution of function calls.

Algorithm:

  1. Parse source code with tree-sitter Python parser
  2. Traverse AST to find all import statements
  3. Process each import to extract module paths and aliases
  4. Resolve relative imports using module registry
  5. Build ImportMap with resolved fully qualified names

Parameters:

  • filePath: absolute path to the Python file being analyzed
  • sourceCode: contents of the Python file as byte array
  • registry: module registry for resolving module paths and relative imports

Returns:

  • ImportMap: map of local names to fully qualified module paths
  • error: if parsing fails or source is invalid

Example:

Source code:
  import os
  from myapp.utils import sanitize
  from myapp.db import query as db_query
  from . import helper
  from ..config import settings

Result ImportMap:
  {
    "os": "os",
    "sanitize": "myapp.utils.sanitize",
    "db_query": "myapp.db.query",
    "helper": "myapp.submodule.helper",
    "settings": "myapp.config.settings"
  }

func MergeReturnTypes

func MergeReturnTypes(statements []*ReturnStatement) map[string]*core.TypeInfo

MergeReturnTypes combines multiple return statements for same function. Takes the highest confidence return type.

func ResolveClassInstantiation

func ResolveClassInstantiation(
	callNode *sitter.Node,
	sourceCode []byte,
	modulePath string,
	importMap *core.ImportMap,
	registry *core.ModuleRegistry,
) *core.TypeInfo

ResolveClassInstantiation attempts to resolve class instantiation patterns.

Types

type FunctionScope

type FunctionScope struct {
	FunctionFQN string                      // Fully qualified name of the function
	Variables   map[string]*VariableBinding // Variable name -> binding
	ReturnType  *core.TypeInfo              // Inferred return type of the function
}

FunctionScope represents the type environment within a function. It tracks variable types and return type for a specific function.

func NewFunctionScope

func NewFunctionScope(functionFQN string) *FunctionScope

NewFunctionScope creates a new function scope with initialized maps.

Parameters:

  • functionFQN: fully qualified name of the function

Returns:

  • Initialized FunctionScope

func (*FunctionScope) AddVariable

func (fs *FunctionScope) AddVariable(binding *VariableBinding)

AddVariable adds or updates a variable binding in the scope.

Parameters:

  • binding: the variable binding to add

func (*FunctionScope) GetVariable

func (fs *FunctionScope) GetVariable(varName string) *VariableBinding

GetVariable retrieves a variable binding by name.

Parameters:

  • varName: the variable name to look up

Returns:

  • VariableBinding if found, nil otherwise

func (*FunctionScope) HasVariable

func (fs *FunctionScope) HasVariable(varName string) bool

HasVariable checks if a variable exists in the scope.

Parameters:

  • varName: the variable name to check

Returns:

  • true if the variable exists, false otherwise

type Location

type Location struct {
	File      string // File path
	Line      uint32 // Line number
	Column    uint32 // Column number
	StartByte uint32 // Starting byte offset
	EndByte   uint32 // Ending byte offset
}

Location represents a source code location.

type ReturnStatement

type ReturnStatement struct {
	FunctionFQN string
	ReturnType  *core.TypeInfo
	Location    Location
}

ReturnStatement represents a return statement in a function.

func ExtractReturnTypes

func ExtractReturnTypes(
	filePath string,
	sourceCode []byte,
	modulePath string,
	builtinRegistry *registry.BuiltinRegistry,
) ([]*ReturnStatement, error)

ExtractReturnTypes analyzes return statements in all functions in a file.

type StdlibRegistryRemote

type StdlibRegistryRemote interface{}

StdlibRegistryRemote will be defined in registry package. For now, use an interface or accept nil.

type TypeInferenceEngine

type TypeInferenceEngine struct {
	Scopes         map[string]*FunctionScope   // Function FQN -> scope
	ReturnTypes    map[string]*core.TypeInfo   // Function FQN -> return type
	Builtins       *registry.BuiltinRegistry   // Builtin types registry
	Registry       *core.ModuleRegistry        // Module registry reference
	Attributes     *registry.AttributeRegistry // Class attributes registry (Phase 3 Task 12)
	StdlibRegistry *core.StdlibRegistry        // Python stdlib registry (PR #2)
	StdlibRemote   interface{}                 // Remote loader for lazy module loading (PR #3)
}

TypeInferenceEngine manages type inference across the codebase. It maintains function scopes, return types, and references to other registries.

func NewTypeInferenceEngine

func NewTypeInferenceEngine(registry *core.ModuleRegistry) *TypeInferenceEngine

NewTypeInferenceEngine creates a new type inference engine. The engine is initialized with empty scopes and return types.

Parameters:

  • registry: module registry for resolving module paths

Returns:

  • Initialized TypeInferenceEngine

func (*TypeInferenceEngine) AddReturnTypesToEngine

func (te *TypeInferenceEngine) AddReturnTypesToEngine(returnTypes map[string]*core.TypeInfo)

AddReturnTypesToEngine populates TypeInferenceEngine with return types.

func (*TypeInferenceEngine) AddScope

func (te *TypeInferenceEngine) AddScope(scope *FunctionScope)

AddScope adds or updates a function scope in the engine.

Parameters:

  • scope: the function scope to add

func (*TypeInferenceEngine) GetScope

func (te *TypeInferenceEngine) GetScope(functionFQN string) *FunctionScope

GetScope retrieves a function scope by its fully qualified name.

Parameters:

  • functionFQN: fully qualified name of the function

Returns:

  • FunctionScope if found, nil otherwise

func (*TypeInferenceEngine) ResolveVariableType

func (te *TypeInferenceEngine) ResolveVariableType(
	assignedFrom string,
	confidence float32,
) *core.TypeInfo

ResolveVariableType resolves the type of a variable assignment from a function call. It looks up the return type of the called function and propagates it with confidence decay.

Parameters:

  • assignedFrom: Function FQN that was called
  • confidence: Base confidence from assignment

Returns:

  • TypeInfo with propagated type, or nil if function has no return type

func (*TypeInferenceEngine) UpdateVariableBindingsWithFunctionReturns

func (te *TypeInferenceEngine) UpdateVariableBindingsWithFunctionReturns()

UpdateVariableBindingsWithFunctionReturns resolves "call:funcName" placeholders. It iterates through all scopes and replaces placeholder types with actual return types.

This enables inter-procedural type propagation:

user = create_user()  # Initially typed as "call:create_user"
# After update, typed as "test.User" based on create_user's return type

type VariableBinding

type VariableBinding struct {
	VarName      string         // Variable name
	Type         *core.TypeInfo // Inferred type information
	AssignedFrom string         // FQN of function that assigned this value (if from function call)
	Location     Location       // Source location of the assignment
}

VariableBinding tracks a variable's type within a scope. It captures the variable name, its inferred type, and source location.

Jump to

Keyboard shortcuts

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