semantic

package
v0.0.0-...-67befd4 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package semantic contains PHP symbols, scopes, references, and immutable document snapshots. It is independent from persistence and LSP transport.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnonymousClassName

func AnonymousClassName(path string, start uint32) string

AnonymousClassName returns the internal, workspace-unique name used for an anonymous class declaration. PHP does not expose a source-level class name, but the semantic graph still needs a stable nominal identity so methods, properties, and $this can be resolved without treating the class body as part of its enclosing function.

Types

type Attribute

type Attribute struct {
	Name      string
	Arguments []AttributeArgument
	Range     cst.TextRange
}

Attribute records a resolved attribute name, its constant arguments, and the declaration range.

func AttributeNamed

func AttributeNamed(attributes []Attribute, expected string) (*Attribute, bool)

AttributeNamed returns the first attribute matching either a short or fully qualified PHP class name. Attribute names are case-insensitive in PHP.

func (*Attribute) Argument

func (attribute *Attribute) Argument(
	name string,
	index int,
) (AttributeValue, bool)

Argument returns a named argument when present, otherwise the positional argument at index. This mirrors how JetBrains attribute constructors expose stable parameter names while remaining compatible with positional usage.

type AttributeArgument

type AttributeArgument struct {
	Name  string
	Value AttributeValue
	Range cst.TextRange
}

AttributeArgument preserves declaration order and optional PHP 8 named argument syntax.

type AttributeArrayItem

type AttributeArrayItem struct {
	Key    AttributeValue
	HasKey bool
	Value  AttributeValue
}

AttributeArrayItem preserves both list and keyed PHP array entries.

type AttributeValue

type AttributeValue struct {
	Kind       AttributeValueKind
	Value      string
	Expression string
	Items      []AttributeArrayItem
}

AttributeValue is a lossless-enough, immutable representation of a PHP attribute constant expression. Expression retains valid insertion text; Value contains the decoded scalar or resolved constant identity where one is available. Array values recursively retain their ordered entries.

type AttributeValueKind

type AttributeValueKind uint8

AttributeValueKind describes the constant subset of PHP expressions that can be retained from an attribute argument without keeping CST nodes alive.

const (
	AttributeValueUnknown AttributeValueKind = iota
	AttributeValueString
	AttributeValueInteger
	AttributeValueFloat
	AttributeValueBool
	AttributeValueNull
	AttributeValueConstant
	AttributeValueClassConstant
	AttributeValueArray
	AttributeValueExpression
)

type CallContract

type CallContract struct {
	Target               CallTarget
	Return               CallReturnContract
	ExpectedArguments    []ExpectedArgumentContract
	ExpectedReturnValues []CallValue
	ExitPoint            bool
	ExitArguments        []ExpectedArgumentContract
}

CallContract is persisted with the semantic document that declared it. Fields intentionally use MessagePack's map representation so future expected-value, map, and exit-point metadata remains backward compatible.

type CallMapEntry

type CallMapEntry struct {
	Key    CallValue
	Result CallValue
}

type CallReturnContract

type CallReturnContract struct {
	Kind     CallReturnKind
	Argument uint16
	Map      []CallMapEntry
}

CallReturnContract is the normalized return rule for one callable.

type CallReturnKind

type CallReturnKind uint8

CallReturnKind describes how a metadata contract derives a call's result. Additional PhpStorm metadata rules can be added without changing the call inference extension or encoding contracts as opaque signature strings.

const (
	CallReturnUnknown CallReturnKind = iota
	CallReturnArgumentType
	CallReturnArgumentElementType
	CallReturnArgumentMap
)

type CallTarget

type CallTarget struct {
	Kind  CallTargetKind
	Name  string
	Class string
}

CallTarget identifies a callable independently from its declaration ID. Metadata files commonly describe vendor callables that may not be indexed yet, so stable PHP names are a better persistence boundary than SymbolID.

func NewFunctionCallTarget

func NewFunctionCallTarget(name string) CallTarget

func NewMethodCallTarget

func NewMethodCallTarget(className, methodName string) CallTarget

type CallTargetKind

type CallTargetKind uint8

CallTargetKind distinguishes global functions from class methods in dynamic call metadata. Constructors are represented as methods named __construct.

const (
	FunctionCallTarget CallTargetKind = iota
	MethodCallTarget
)

type CallValue

type CallValue struct {
	Kind       CallValueKind
	Value      string
	Expression string
}

CallValue preserves both normalized meaning and insertion-ready PHP source. Value contains an unquoted literal for strings and the normalized source name for constants; Expression is what completion inserts.

func (CallValue) Label

func (value CallValue) Label() string

type CallValueKind

type CallValueKind uint8

CallValueKind describes a source-level PHP value retained for expected-value completion and argument-to-return maps.

const (
	CallValueExpression CallValueKind = iota
	CallValueString
	CallValueNumber
	CallValueConstant
	CallValueClassConstant
)

type Confidence

type Confidence uint8
const (
	UnknownConfidence Confidence = iota
	InferredConfidence
	DocumentedConfidence
	DeclaredConfidence
)

type ConstantArrayItem

type ConstantArrayItem struct {
	Key        string
	KeyRange   cst.TextRange
	Value      string
	ValueRange cst.TextRange
	Type       types.Type
}

ConstantArrayItem preserves a top-level key/value declaration from a PHP array constant. Framework integrations use this semantic metadata without reopening or reparsing vendor source files.

type ConstantReturn

type ConstantReturn struct {
	Receiver string
	Name     string
	Range    cst.TextRange
}

ConstantReturn records a class-constant return expression declared directly by a function or method. Receiver contains either a resolved class name or one of self, static, and parent for context-dependent resolution.

type Deprecation

type Deprecation struct {
	Reason      string
	Replacement string
	Since       string
}

Deprecation describes the structured JetBrains/PHP attribute payload used by hover text, diagnostics, and future replacement quick-fixes.

func DeprecationOf

func DeprecationOf(attributes []Attribute) (Deprecation, bool)

DeprecationOf extracts both JetBrains\PhpStorm\Deprecated and the native Deprecated attribute conventions. The boolean reports attribute presence, even when no structured details were supplied.

type Document

type Document struct {
	Path              string
	Version           int
	WorkspaceRevision uint64
	Namespace         string
	Symbols           []Symbol
	Scopes            []Scope
	References        []Reference
	CallContracts     []CallContract
	TypeFacts         map[NodeID]TypeFact

	TypeAliases map[string]types.Type
	Issues      []Issue
	// contains filtered or unexported fields
}

Document is an immutable semantic snapshot for one source version.

func (*Document) Clone

func (d *Document) Clone() *Document

func (*Document) DeleteTypeFact

func (d *Document) DeleteTypeFact(identity NodeID)

DeleteTypeFact removes either representation of a syntax fact.

func (*Document) ReserveTypeFacts

func (d *Document) ReserveTypeFacts(capacity int)

ReserveTypeFacts prepares compact storage for the estimated non-literal fact count. It is intended for parsers that know the syntax shape before inference.

func (*Document) ScopeAt

func (d *Document) ScopeAt(offset uint32) (Scope, bool)

func (*Document) SetTypeFact

func (d *Document) SetTypeFact(identity NodeID, fact TypeFact)

SetTypeFact stores common facts in the compact map and keeps uncommon explanatory text in the detailed side map.

func (*Document) TypeFact

func (d *Document) TypeFact(identity NodeID) (TypeFact, bool)

TypeFact returns the stored fact for a syntax identity. Common facts without explanatory text use a compact side map and are expanded on demand.

func (*Document) TypeFactCount

func (d *Document) TypeFactCount() int

TypeFactCount reports detailed and compact syntax facts.

func (*Document) TypeOf

func (d *Document) TypeOf(node *cst.Node) TypeFact

func (*Document) WorkspaceGraph

func (d *Document) WorkspaceGraph() *Document

WorkspaceGraph returns the compact declaration/reference view needed by a workspace Snapshot. File-local scopes, locals, parameters, closures, type facts, aliases, diagnostics, and variable references stay persisted and are loaded only when a caller requests that document. Nested data in retained symbols and references is shared and must remain immutable.

type ExpectedArgumentContract

type ExpectedArgumentContract struct {
	Argument uint16
	Values   []CallValue
}

type Flags

type Flags uint32
const (
	StaticFlag Flags = 1 << iota
	FinalFlag
	AbstractFlag
	ReadonlyFlag
	ByReferenceFlag
	VariadicFlag
	PromotedFlag
	DeprecatedFlag
	InternalFlag
	SyntheticFlag
	GeneratedStubFlag
	ClassAliasFlag
	SoftFinalFlag
)

func (Flags) Has

func (f Flags) Has(flag Flags) bool

type ImportTable

type ImportTable struct {
	Classes   map[string]string
	Functions map[string]string
	Constants map[string]string
}

type Issue

type Issue struct {
	Range   cst.TextRange
	Code    string
	Message string
}

type LiteralReturn

type LiteralReturn struct {
	Value string
	Range cst.TextRange
	Type  types.Type
}

LiteralReturn records a scalar/null return expression declared directly by a function or method. Nested closure/function returns are excluded.

type NameKind

type NameKind uint8
const (
	ClassName NameKind = iota
	FunctionName
	ConstantName
	MemberName
	VariableName
)

type NodeID

type NodeID struct {
	Kind  cst.Kind
	Start uint32
	End   uint32
}

func NodeIdentity

func NodeIdentity(node *cst.Node) NodeID

type Parameter

type Parameter struct {
	ID             SymbolID
	Name           string
	Type           types.Type
	NativeType     types.Type
	DocType        types.Type
	AssistantTags  []string
	Attributes     []Attribute
	DefaultValue   *AttributeValue
	Range          cst.TextRange
	SelectionRange cst.TextRange
	DefaultRange   cst.TextRange
	Flags          Flags
	Optional       bool
}

Parameter captures a function/method parameter in declaration order.

type Reference

type Reference struct {
	Name     string
	Receiver types.Type
	Resolved SymbolID

	Range      cst.TextRange
	Scope      ScopeID
	Kind       NameKind
	TargetKind SymbolKind
	Static     bool
	Write      bool
	// contains filtered or unexported fields
}

Reference is a syntactic name use, resolved or unresolved.

func (*Reference) AddCandidate

func (r *Reference) AddCandidate(id SymbolID)

AddCandidate stores the common unique target without allocating a candidate slice. A second target promotes both IDs to Candidates and clears Resolved.

func (Reference) CandidateIDs

func (r Reference) CandidateIDs() []SymbolID

CandidateIDs returns every ambiguous target in resolution order.

func (*Reference) ClearCandidateIDs

func (r *Reference) ClearCandidateIDs()

ClearCandidateIDs releases ambiguous targets and the side record when it no longer contains qualified names.

func (Reference) QualifiedNameAt

func (r Reference) QualifiedNameAt(index int) string

QualifiedNameAt returns one resolver-normalized lookup candidate. Callers must pass an index smaller than QualifiedNameCount.

func (Reference) QualifiedNameCount

func (r Reference) QualifiedNameCount() int

QualifiedNameCount reports the number of resolver-normalized lookup candidates without materializing a slice.

func (Reference) QualifiedNames

func (r Reference) QualifiedNames() []string

QualifiedNames returns ordered, resolver-normalized lookup candidates.

func (*Reference) SetCandidateIDs

func (r *Reference) SetCandidateIDs(candidates []SymbolID)

SetCandidateIDs replaces the ambiguous resolution targets. The caller transfers ownership of candidates.

func (*Reference) SetQualifiedName

func (r *Reference) SetQualifiedName(name string)

SetQualifiedName replaces the qualified-name candidates with one value without allocating a one-element slice.

func (*Reference) SetQualifiedNames

func (r *Reference) SetQualifiedNames(names []string)

SetQualifiedNames replaces the ordered qualified-name candidates. The caller transfers ownership of names, matching the former slice-field semantics.

type ReferenceLocation

type ReferenceLocation struct {
	Path       string
	RangeStart uint32
	RangeEnd   uint32
}

type Scope

type Scope struct {
	ID        ScopeID
	Kind      ScopeKind
	Parent    ScopeID
	Range     cst.TextRange
	Owner     SymbolID
	Namespace string
	Imports   ImportTable
	// contains filtered or unexported fields
}

Scope contains declaration IDs keyed by the PHP-normalized lookup name.

func (*Scope) AddSymbol

func (s *Scope) AddSymbol(symbolIndex uint32)

AddSymbol records a declaration's document-local symbol index in this scope. The compact entry list preserves insertion order and represents duplicate normalized names without duplicating the Symbol's name and ID strings.

func (Scope) AllSymbolIDs

func (s Scope) AllSymbolIDs(symbols []Symbol) iter.Seq[SymbolID]

AllSymbolIDs iterates every declaration in insertion order.

func (Scope) AppendSymbolIDs

func (s Scope) AppendSymbolIDs(
	symbols []Symbol,
	target []SymbolID,
	name string,
) []SymbolID

AppendSymbolIDs appends declarations matching name in insertion order.

func (Scope) HasSymbol

func (s Scope) HasSymbol(symbols []Symbol, name string) bool

func (Scope) SymbolIDs

func (s Scope) SymbolIDs(symbols []Symbol, name string) iter.Seq[SymbolID]

SymbolIDs iterates declarations matching one normalized name in insertion order without materializing a one-element slice for the common case.

type ScopeID

type ScopeID uint32

type ScopeKind

type ScopeKind uint8
const (
	FileScope ScopeKind = iota
	NamespaceScope
	ClassScope
	FunctionScope
	ClosureScope
	BlockScope
)

type Snapshot

type Snapshot struct {
	Revision uint64
	// contains filtered or unexported fields
}

Snapshot is an immutable workspace-wide semantic generation.

func NewSnapshot

func NewSnapshot(revision uint64, documents []*Document) *Snapshot

func (*Snapshot) AllSymbols

func (s *Snapshot) AllSymbols() []Symbol

func (*Snapshot) AsSupertype

func (s *Snapshot) AsSupertype(
	candidate types.Type,
	target string,
) (types.Type, bool)

func (*Snapshot) CallableSignature

func (s *Snapshot) CallableSignature(
	candidate types.Type,
) (types.Type, bool)

CallableSignature returns the effective __invoke contract for an object. It follows traits and parents while preserving generic class arguments.

func (*Snapshot) ClassAliasTarget

func (s *Snapshot) ClassAliasTarget(id SymbolID) (Symbol, bool)

ClassAliasTarget resolves the target relationship retained by a synthetic class_alias declaration.

func (*Snapshot) ClassAliases

func (s *Snapshot) ClassAliases(name string) []Symbol

ClassAliases returns synthetic class_alias declarations targeting name.

func (*Snapshot) ClassViews

func (s *Snapshot) ClassViews(name string) []SymbolView

func (*Snapshot) Classes

func (s *Snapshot) Classes(name string) []Symbol

func (*Snapshot) CloneSymbols

func (s *Snapshot) CloneSymbols() map[SymbolID]Symbol

func (*Snapshot) ConstantViews

func (s *Snapshot) ConstantViews(name string) []SymbolView

func (*Snapshot) Constants

func (s *Snapshot) Constants(name string) []Symbol

func (*Snapshot) DirectSubtypes

func (s *Snapshot) DirectSubtypes(name string) []Symbol

DirectSubtypes returns classes and interfaces that directly extend or implement name. Transitive hierarchy traversal intentionally remains a query concern so the snapshot does not retain a closure of every relationship.

func (*Snapshot) DirectSupertypes

func (s *Snapshot) DirectSupertypes(id SymbolID) []Symbol

DirectSupertypes returns the declarations named directly by a class or interface's extends and implements clauses. Trait use is exposed separately because it is composition rather than nominal subtyping.

func (*Snapshot) FunctionViews

func (s *Snapshot) FunctionViews(name string) []SymbolView

func (*Snapshot) Functions

func (s *Snapshot) Functions(name string) []Symbol

func (*Snapshot) GlobalClassViews

func (s *Snapshot) GlobalClassViews() []SymbolView

GlobalClassViews filters global declarations before materialization so callers that need only classes do not allocate public function/constant symbols and their optional side data.

func (*Snapshot) GlobalSymbolViews

func (s *Snapshot) GlobalSymbolViews() []SymbolView

GlobalSymbolViews returns lightweight class-like, function, and constant declaration views without materializing complete public symbols.

func (*Snapshot) GlobalSymbols

func (s *Snapshot) GlobalSymbols() []Symbol

GlobalSymbols returns class-like, function, and constant declarations without scanning locals and members in the workspace symbol table.

func (*Snapshot) HasDocument

func (s *Snapshot) HasDocument(path string) bool

HasDocument reports whether path contributes a document to this generation.

func (*Snapshot) IsSubtypeOf

func (s *Snapshot) IsSubtypeOf(candidate, target string) bool

func (*Snapshot) MemberViews

func (s *Snapshot) MemberViews(container SymbolID, name string) []SymbolView

func (*Snapshot) MemberViewsOf

func (s *Snapshot) MemberViewsOf(container SymbolID) []SymbolView

func (*Snapshot) Members

func (s *Snapshot) Members(container SymbolID, name string) []Symbol

func (*Snapshot) MembersOf

func (s *Snapshot) MembersOf(container SymbolID) []Symbol

func (*Snapshot) MethodOverrides

func (s *Snapshot) MethodOverrides(id SymbolID) []Symbol

MethodOverrides returns workspace methods that implement or override the selected method declaration. A method is related to every matching ancestor declaration, including through an intermediate class that does not redeclare it; this is a declaration edge, not a materialized type-hierarchy closure.

func (*Snapshot) ReferencesTo

func (s *Snapshot) ReferencesTo(id SymbolID) []ReferenceLocation

func (*Snapshot) Relations

func (s *Snapshot) Relations() types.Relations

func (*Snapshot) ResolveTypeAlias

func (s *Snapshot) ResolveTypeAlias(value types.Type) (types.Type, bool)

ResolveTypeAlias expands a nominal PHPDoc alias through the declaring class's synthetic alias member.

func (*Snapshot) Symbol

func (s *Snapshot) Symbol(id SymbolID) (Symbol, bool)

func (*Snapshot) SymbolView

func (s *Snapshot) SymbolView(id SymbolID) (SymbolView, bool)

SymbolView returns a lightweight immutable symbol owned by this snapshot.

func (*Snapshot) SymbolsIn

func (s *Snapshot) SymbolsIn(path string) []Symbol

func (*Snapshot) TemplateVariance

func (s *Snapshot) TemplateVariance(name string, index int) types.Variance

func (*Snapshot) TraitConsumers

func (s *Snapshot) TraitConsumers(name string) []Symbol

TraitConsumers returns classes that directly use the named trait.

func (*Snapshot) VisitClassViews

func (s *Snapshot) VisitClassViews(
	name string,
	visit func(SymbolView) bool,
) bool

VisitClassViews visits matching classes without materializing a result slice. Returning false stops the traversal; the result reports whether all matching declarations were visited.

func (*Snapshot) VisitConstantViews

func (s *Snapshot) VisitConstantViews(
	name string,
	visit func(SymbolView) bool,
) bool

VisitConstantViews is the non-materializing counterpart of ConstantViews.

func (*Snapshot) VisitFunctionCallContracts

func (s *Snapshot) VisitFunctionCallContracts(
	name string,
	visit func(CallContract) bool,
) bool

VisitFunctionCallContracts visits dynamic return contracts for a resolved function name. Open-document overlays shadow persisted contracts from the same path without copying the base snapshot's contract indexes.

func (*Snapshot) VisitFunctionViews

func (s *Snapshot) VisitFunctionViews(
	name string,
	visit func(SymbolView) bool,
) bool

VisitFunctionViews is the non-materializing counterpart of FunctionViews.

func (*Snapshot) VisitMemberViews

func (s *Snapshot) VisitMemberViews(
	container SymbolID,
	name string,
	visit func(SymbolView) bool,
) bool

VisitMemberViews visits named members without materializing a result slice.

func (*Snapshot) VisitMethodCallContracts

func (s *Snapshot) VisitMethodCallContracts(
	receiver types.Type,
	name string,
	visit func(CallContract) bool,
) bool

VisitMethodCallContracts visits contracts whose declaring class is a supertype of receiver. This makes metadata declared for an interface or parent class apply to concrete implementations without duplicating records.

func (*Snapshot) WithDeclarations

func (s *Snapshot) WithDeclarations(document *Document) *Snapshot

WithDeclarations returns an overlay containing the supplied document's declarations but not its reference graph. This is sufficient while linking and inferring one document and avoids packing references that background indexing immediately discards.

func (*Snapshot) WithDocument

func (s *Snapshot) WithDocument(document *Document) *Snapshot

WithDocument returns an overlay generation in which declarations from the supplied document replace persisted declarations from the same path.

func (*Snapshot) WithUpdatedFunctionReturns

func (s *Snapshot) WithUpdatedFunctionReturns(document *Document) *Snapshot

WithUpdatedFunctionReturns overlays function-like declarations during local fixed-point inference without copying unrelated declarations.

func (*Snapshot) WithUpdatedSymbols

func (s *Snapshot) WithUpdatedSymbols(document *Document) *Snapshot

WithUpdatedSymbols overlays values for declarations already present in the generation. Index keys and reverse references remain shared because stable declaration IDs, names, and ranges do not change during type fixed-point analysis.

func (*Snapshot) WorkspaceStorageStats

func (s *Snapshot) WorkspaceStorageStats() WorkspaceStorageStats

WorkspaceStorageStats returns cardinalities for this snapshot's retained base documents. Overlay generations report their locally replaced documents; callers profiling a complete workspace should invoke it on the base generation returned by Store.Snapshot.

type Store

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

Store publishes immutable workspace snapshots. Per-file updates are cheap; readers never observe a partially-mutated symbol graph.

func NewStore

func NewStore() *Store

func (*Store) Clear

func (s *Store) Clear() *Snapshot

func (*Store) Document

func (s *Store) Document(path string) (*Document, bool)

func (*Store) EnsureDocumentDetails

func (s *Store) EnsureDocumentDetails(path string) error

EnsureDocumentDetails pins the complete persisted payload for path before a repository mutation can replace or remove it. Existing immutable snapshots can then continue serving their original generation after publication.

func (*Store) Remove

func (s *Store) Remove(paths ...string) *Snapshot

func (*Store) Replace

func (s *Store) Replace(document *Document) *Snapshot

func (*Store) ReplaceCanonicalWorkspaceGraphsOwned

func (s *Store) ReplaceCanonicalWorkspaceGraphsOwned(
	graphs ...*WorkspaceGraph,
) *Snapshot

ReplaceCanonicalWorkspaceGraphsOwned publishes graphs that were already detached and canonicalized together by a WorkspaceGraphDetacher. Ownership of every accepted graph transfers to the store. This avoids rebuilding temporary interning maps at the end of a large scanner batch.

func (*Store) ReplaceMany

func (s *Store) ReplaceMany(documents ...*Document) *Snapshot

ReplaceMany atomically publishes a set of persisted document replacements. Building one immutable generation for a scanner batch avoids quadratic workspace rebuilds during cold indexing and cache restoration.

func (*Store) ReplaceManyOwned

func (s *Store) ReplaceManyOwned(documents ...*Document) *Snapshot

ReplaceManyOwned transfers already compacted, immutable workspace graphs into the store without another projection or defensive clone. Callers must not mutate a document after this call.

func (*Store) ReplaceWorkspaceGraphsOwned

func (s *Store) ReplaceWorkspaceGraphsOwned(
	graphs ...*WorkspaceGraph,
) *Snapshot

ReplaceWorkspaceGraphsOwned atomically publishes graphs that were compacted before the scanner batch ended. Ownership of every accepted graph transfers to the store.

func (*Store) RestoreOwned

func (s *Store) RestoreOwned(
	load func(accept func(*Document)) error,
) (*Snapshot, error)

RestoreOwned replaces the store contents from a streaming loader and publishes exactly one immutable generation. The loader transfers ownership of each document to the store, so it must not mutate accepted documents.

Cache restoration uses this API to intern a decoded graph immediately instead of retaining every uninterned graph until the final publication.

func (*Store) RestoreWorkspaceGraphsDecodedWithCapacity

func (s *Store) RestoreWorkspaceGraphsDecodedWithCapacity(
	capacity WorkspaceRestoreCapacity,
	load func(
		decoder *WorkspaceGraphDecoder,
		accept func(*WorkspaceGraph),
	) error,
) (*Snapshot, error)

RestoreWorkspaceGraphsDecodedWithCapacity lets a streaming loader decode graphs through a restore-scoped decoder. String and type values are interned directly into the temporary publication maps, avoiding throwaway decoded copies before the graph is accepted.

func (*Store) RestoreWorkspaceGraphsOwned

func (s *Store) RestoreWorkspaceGraphsOwned(
	load func(accept func(*WorkspaceGraph)) error,
) (*Snapshot, error)

RestoreWorkspaceGraphsOwned restores already compacted graphs without expanding them into public Documents during cache startup.

func (*Store) RestoreWorkspaceGraphsOwnedWithCapacity

func (s *Store) RestoreWorkspaceGraphsOwnedWithCapacity(
	capacity WorkspaceRestoreCapacity,
	load func(accept func(*WorkspaceGraph)) error,
) (*Snapshot, error)

RestoreWorkspaceGraphsOwnedWithCapacity is the capacity-aware variant used by repositories that can cheaply count their rows before streaming them.

func (*Store) Snapshot

func (s *Store) Snapshot() *Snapshot

type Symbol

type Symbol struct {
	ID                 SymbolID
	Kind               SymbolKind
	Name               string
	FullyQualified     string
	Container          SymbolID
	Path               string
	Range              cst.TextRange
	SelectionRange     cst.TextRange
	BodyRange          cst.TextRange
	Visibility         Visibility
	WriteVisibility    Visibility
	HasWriteVisibility bool
	Flags              Flags

	Type       types.Type
	NativeType types.Type
	DocType    types.Type
	ReturnType types.Type

	Parameters []Parameter
	// contains filtered or unexported fields
}

Symbol is a declaration visible to semantic queries.

func (Symbol) Assertions

func (s Symbol) Assertions() []TypeAssertion

func (Symbol) Attributes

func (s Symbol) Attributes() []Attribute

Attributes returns the immutable attributes attached to the declaration.

func (Symbol) ConstantArray

func (s Symbol) ConstantArray() []ConstantArrayItem

ConstantArray returns top-level items retained from an array constant.

func (Symbol) ConstantReturns

func (s Symbol) ConstantReturns() []ConstantReturn

func (Symbol) DocSummary

func (s Symbol) DocSummary() string

DocSummary returns the declaration's PHPDoc summary.

func (Symbol) Extends

func (s Symbol) Extends() []string

func (Symbol) ExtendsTypes

func (s Symbol) ExtendsTypes() []types.Type

func (Symbol) Implements

func (s Symbol) Implements() []string

func (Symbol) ImplementsTypes

func (s Symbol) ImplementsTypes() []types.Type

func (Symbol) IsClassLike

func (s Symbol) IsClassLike() bool

func (Symbol) IsFunctionLike

func (s Symbol) IsFunctionLike() bool

func (Symbol) LiteralReturns

func (s Symbol) LiteralReturns() []LiteralReturn

func (*Symbol) SetAssertions

func (s *Symbol) SetAssertions(assertions []TypeAssertion)

func (*Symbol) SetAttributes

func (s *Symbol) SetAttributes(attributes []Attribute)

SetAttributes replaces the declaration attributes.

func (*Symbol) SetConstantArray

func (s *Symbol) SetConstantArray(items []ConstantArrayItem)

SetConstantArray replaces the retained top-level constant array items.

func (*Symbol) SetConstantReturns

func (s *Symbol) SetConstantReturns(returns []ConstantReturn)

func (*Symbol) SetDocSummary

func (s *Symbol) SetDocSummary(summary string)

SetDocSummary replaces the declaration's PHPDoc summary.

func (*Symbol) SetExtends

func (s *Symbol) SetExtends(values []string)

func (*Symbol) SetExtendsTypes

func (s *Symbol) SetExtendsTypes(values []types.Type)

func (*Symbol) SetHierarchy

func (s *Symbol) SetHierarchy(
	extends []string,
	implements []string,
	traits []string,
	extendsTypes []types.Type,
	implementsTypes []types.Type,
	traitTypes []types.Type,
	aliases []TraitAlias,
)

func (*Symbol) SetImplements

func (s *Symbol) SetImplements(values []string)

func (*Symbol) SetImplementsTypes

func (s *Symbol) SetImplementsTypes(values []types.Type)

func (*Symbol) SetLiteralReturns

func (s *Symbol) SetLiteralReturns(returns []LiteralReturn)

func (*Symbol) SetMetadata

func (s *Symbol) SetMetadata(
	attributes []Attribute,
	constantArray []ConstantArrayItem,
	docSummary string,
)

SetMetadata replaces all infrequent declaration metadata in one operation. Replacing rather than mutating the compact handle preserves Symbol value-copy semantics when callers derive a new symbol from an existing snapshot value.

func (*Symbol) SetSignatureExtras

func (s *Symbol) SetSignatureExtras(
	templates []TemplateParameter,
	throws []types.Type,
	assertions []TypeAssertion,
	literalReturns []LiteralReturn,
	constantReturns []ConstantReturn,
)

func (*Symbol) SetTemplates

func (s *Symbol) SetTemplates(templates []TemplateParameter)

func (*Symbol) SetThrows

func (s *Symbol) SetThrows(throws []types.Type)

func (*Symbol) SetTraitAliases

func (s *Symbol) SetTraitAliases(values []TraitAlias)

func (*Symbol) SetTraitTypes

func (s *Symbol) SetTraitTypes(values []types.Type)

func (*Symbol) SetTraits

func (s *Symbol) SetTraits(values []string)

func (Symbol) Templates

func (s Symbol) Templates() []TemplateParameter

func (Symbol) Throws

func (s Symbol) Throws() []types.Type

func (Symbol) TraitAliases

func (s Symbol) TraitAliases() []TraitAlias

func (Symbol) TraitTypes

func (s Symbol) TraitTypes() []types.Type

func (Symbol) Traits

func (s Symbol) Traits() []string

type SymbolID

type SymbolID string

SymbolID is stable across index generations for the same declaration.

func NewSymbolID

func NewSymbolID(kind SymbolKind, fullyQualified, path string, start uint32) SymbolID

NewSymbolID creates a deterministic declaration ID. The source offset disambiguates anonymous/local declarations while named declarations remain stable when unrelated declarations are added elsewhere in the file.

type SymbolKind

type SymbolKind uint8
const (
	NamespaceSymbol SymbolKind = iota
	ClassSymbol
	InterfaceSymbol
	TraitSymbol
	EnumSymbol
	MethodSymbol
	FunctionSymbol
	ClosureSymbol
	PropertySymbol
	ParameterSymbol
	ClassConstantSymbol
	GlobalConstantSymbol
	EnumCaseSymbol
	LocalSymbol
	TemplateSymbol
	TypeAliasSymbol
)

type SymbolView

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

func (SymbolView) Attributes

func (view SymbolView) Attributes() []Attribute

Attributes returns immutable snapshot-owned symbol attributes without materializing the full symbol and its signature.

func (SymbolView) Container

func (view SymbolView) Container() SymbolID

func (SymbolView) Flags

func (view SymbolView) Flags() Flags

func (SymbolView) FullyQualified

func (view SymbolView) FullyQualified() string

func (SymbolView) HierarchyNames

func (view SymbolView) HierarchyNames() (
	traits,
	extends,
	implements []string,
)

HierarchyNames returns the immutable trait, parent-class, and implemented interface names retained by the snapshot.

func (SymbolView) HierarchyTypes

func (view SymbolView) HierarchyTypes() (extends, implements []types.Type)

HierarchyTypes returns the immutable typed parent-class and implemented interface edges retained by the snapshot. Like HierarchyNames, the data is resident summary state and never triggers a full document graph load.

func (SymbolView) ID

func (view SymbolView) ID() SymbolID

func (SymbolView) Kind

func (view SymbolView) Kind() SymbolKind

func (SymbolView) Materialize

func (view SymbolView) Materialize() Symbol

Materialize returns the complete public Symbol value represented by the view. Its nested slices remain immutable snapshot-owned data.

func (SymbolView) Name

func (view SymbolView) Name() string

func (SymbolView) Path

func (view SymbolView) Path() string

func (SymbolView) Range

func (view SymbolView) Range() cst.TextRange

func (SymbolView) SelectionRange

func (view SymbolView) SelectionRange() cst.TextRange

func (SymbolView) TraitAliases

func (view SymbolView) TraitAliases() []TraitAlias

TraitAliases returns method adaptations declared by the viewed class.

func (SymbolView) Visibility

func (view SymbolView) Visibility() Visibility

type TemplateParameter

type TemplateParameter struct {
	Name          string
	Bound         types.Type
	Default       types.Type
	Covariant     bool
	Contravariant bool
}

TemplateParameter represents a PHPDoc generic parameter.

type TraitAlias

type TraitAlias struct {
	Trait         string
	Method        string
	Alias         string
	Visibility    Visibility
	HasVisibility bool
}

TraitAlias records a method adaptation declared by a trait use statement. Trait and Method identify the original declaration; Alias is the effective method name exposed by the consuming class. A visibility-only adaptation keeps Alias equal to Method.

type TypeAssertion

type TypeAssertion struct {
	Target      string
	Type        types.Type
	WhenTrue    bool
	Conditional bool
	Negated     bool
}

TypeAssertion describes a PHPStan/Psalm conditional assertion made by a function or method when its boolean result has the selected value.

type TypeFact

type TypeFact struct {
	Type       types.Type
	Confidence Confidence
	Source     TypeSource
	Origin     cst.TextRange
	Reason     string
}

type TypeSource

type TypeSource uint8
const (
	UnknownSource TypeSource = iota
	LiteralSource
	AssignmentSource
	NativeSource
	PHPDocSource
	SignatureSource
	FlowSource
	FrameworkSource
)

type Visibility

type Visibility uint8
const (
	Public Visibility = iota
	Protected
	Private
)

type WorkspaceGraph

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

WorkspaceGraph is an opaque, compact declaration/reference graph ready for workspace publication. Its contents are immutable after construction.

func PackWorkspaceGraphOwned

func PackWorkspaceGraphOwned(document *Document) *WorkspaceGraph

PackWorkspaceGraphOwned compacts a workspace-projected Document without cloning its nested data. The caller transfers ownership of document and must not mutate it after this call.

func ProjectWorkspaceGraph

func ProjectWorkspaceGraph(document *Document) *WorkspaceGraph

ProjectWorkspaceGraph builds a detached retained workspace graph directly from a full semantic document. File-local declarations and variable references are omitted. The source document remains owned by the caller and may be released immediately.

func ProjectWorkspaceGraphBorrowed

func ProjectWorkspaceGraphBorrowed(document *Document) *WorkspaceGraph

ProjectWorkspaceGraphBorrowed builds the compact workspace projection while borrowing immutable strings and type nodes from document. All mutable nested slices are cloned. The caller must keep document alive until the graph is encoded and must call WorkspaceGraphDetacher.DetachOwned before retaining or publishing it.

func (*WorkspaceGraph) DecodeMsgpack

func (graph *WorkspaceGraph) DecodeMsgpack(decoder *msgpack.Decoder) error

DecodeMsgpack restores the compact graph directly.

func (*WorkspaceGraph) Document

func (graph *WorkspaceGraph) Document() *Document

Document materializes a defensive public document view of the graph.

func (*WorkspaceGraph) EncodeMsgpack

func (graph *WorkspaceGraph) EncodeMsgpack(encoder *msgpack.Encoder) error

EncodeMsgpack writes the compact graph without expanding public Symbols.

func (*WorkspaceGraph) Path

func (graph *WorkspaceGraph) Path() string

Path returns the source path represented by this graph.

func (*WorkspaceGraph) VisitSymbolViews

func (graph *WorkspaceGraph) VisitSymbolViews(
	visit func(SymbolView) bool,
) bool

VisitSymbolViews visits the compact declarations retained by this graph without materializing full Symbol values or allocating a Snapshot.

type WorkspaceGraphDecoder

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

WorkspaceGraphDecoder reuses parsed immutable PHP types across a stream of compact workspace graphs. One decoder should be kept for a cache restore and cleared when that bounded phase ends.

func NewWorkspaceGraphDecoder

func NewWorkspaceGraphDecoder() *WorkspaceGraphDecoder

func (*WorkspaceGraphDecoder) Clear

func (decoder *WorkspaceGraphDecoder) Clear()

func (*WorkspaceGraphDecoder) Decode

func (decoder *WorkspaceGraphDecoder) Decode(
	source *msgpack.Decoder,
	graph *WorkspaceGraph,
) error

func (*WorkspaceGraphDecoder) DecodeSummary

func (decoder *WorkspaceGraphDecoder) DecodeSummary(
	source *msgpack.Decoder,
	graph *WorkspaceGraph,
	loader WorkspaceGraphLoader,
) error

DecodeSummary restores the resident declaration core, hierarchy edges, and reference graph while deferring signatures and metadata to loader. The wire format is unchanged; skipped details remain available through the original persisted graph.

type WorkspaceGraphDetacher

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

WorkspaceGraphDetacher canonicalizes borrowed workspace projections. Reuse one detacher for a scanner batch so equal values are copied once across all committed files. A detacher is not safe for concurrent use.

func NewWorkspaceGraphDetacher

func NewWorkspaceGraphDetacher() *WorkspaceGraphDetacher

func NewWorkspaceGraphDetacherCapacity

func NewWorkspaceGraphDetacherCapacity(
	expectedStrings int,
) *WorkspaceGraphDetacher

NewWorkspaceGraphDetacherCapacity constructs a batch detacher with room for the expected number of distinct strings. The value is an allocation hint; underestimates grow normally and overestimates do not affect semantics.

func (*WorkspaceGraphDetacher) DetachOwned

func (detacher *WorkspaceGraphDetacher) DetachOwned(graph *WorkspaceGraph)

DetachOwned replaces every borrowed value in graph with storage owned by the detacher. The graph and its source document must not be mutated concurrently.

func (*WorkspaceGraphDetacher) Finish

func (detacher *WorkspaceGraphDetacher) Finish()

Finish releases construction-only indexes and trims the shared immutable symbol/reference string table after a batch has published all documents.

type WorkspaceGraphLoader

type WorkspaceGraphLoader interface {
	LoadWorkspaceGraph(path string) (*WorkspaceGraph, error)
}

WorkspaceGraphLoader resolves one persisted graph by source path. Warm cache restoration uses it to keep declaration cores and hierarchy edges resident while loading signatures and metadata only when requested.

type WorkspaceRestoreCapacity

type WorkspaceRestoreCapacity struct {
	Documents int
	Strings   int
	Types     int
}

WorkspaceRestoreCapacity reserves the temporary maps used while publishing a streamed cache restore. Hints affect allocation only and may be zero or underestimate the final cardinality without changing semantics.

type WorkspaceStorageStats

type WorkspaceStorageStats struct {
	Documents  int
	Symbols    int
	References int

	SymbolIndexEntries       int
	SymbolIndexCapacity      int
	PathIndexEntries         int
	SymbolCompactRanges      int
	SymbolFullRanges         int
	SymbolMissingSelections  int
	SymbolMissingBodies      int
	MaxSymbolRangeLength     int
	MaxSymbolSelectionOffset int
	MaxSymbolSelectionLength int
	MaxSymbolBodyOffset      int
	MaxSymbolBodyLength      int
	ClassNames               int
	ClassIDs                 int
	UniqueClassIDs           int
	FunctionNames            int
	FunctionIDs              int
	UniqueFunctionIDs        int
	ConstantNames            int
	ConstantIDs              int
	UniqueConstantIDs        int
	MemberContainers         int
	MemberNames              int
	MemberIDs                int
	UniqueMemberIDs          int
	MemberDuplicateIDs       int
	MemberAlternateNames     int
	MemberContainers1        int
	MemberContainers2To4     int
	MemberContainers5To8     int
	MemberContainers9To16    int
	MemberContainers17To32   int
	MemberContainersOver32   int
	MaxMembersPerContainer   int
	UniqueMemberNames        int
	MemberNameBytes          int
	UniqueMemberNameBytes    int
	GlobalIDs                int
	UniqueGlobalIDs          int
	SymbolTypeMasks          [16]int
	SymbolDistinctTypeCounts [5]int
	SymbolTypeEqualsNative   int
	SymbolTypeEqualsDoc      int
	SymbolReturnEqualsType   int
	SymbolTypeExtras         int
	SymbolTypeExtraCapacity  int

	SymbolSideFallbacks       int
	MaxSignaturesPerDocument  int
	MaxHierarchiesPerDocument int
	MaxMetadataPerDocument    int

	Signatures                  int
	Parameters                  int
	ParameterNativeTypes        int
	ParameterDocTypes           int
	ParameterExplicitTypes      int
	ParametersWithAssistantTags int
	ParameterAssistantTags      int
	ParameterFullRanges         int
	ParameterDerivedIDs         int
	ParameterFullIDs            int
	Templates                   int
	Throws                      int
	LiteralReturns              int
	ConstantReturns             int
	SignaturesWithExtras        int
	Hierarchies                 int
	Metadata                    int
	NoSideTables                int
	SignatureOnly               int
	HierarchyOnly               int
	MetadataOnly                int
	SignatureHierarchy          int
	SignatureMetadata           int
	HierarchyMetadata           int
	AllSideTables               int

	HierarchyExtendsNames         int
	HierarchyImplementsNames      int
	HierarchyTraitNames           int
	HierarchyExtendsTypes         int
	HierarchyImplementsTypes      int
	HierarchyTraitTypes           int
	HierarchyPairedNameTypes      int
	HierarchyExactNamedTypePairs  int
	HierarchiesWithExtends        int
	HierarchiesWithImplements     int
	HierarchiesWithTraits         int
	HierarchiesWithMultipleGroups int

	Attributes                 int
	ConstantArrayItems         int
	DocSummaryBytes            int
	MetadataAttributesOnly     int
	MetadataConstantArrayOnly  int
	MetadataDocSummaryOnly     int
	MetadataAttributesConstant int
	MetadataAttributesSummary  int
	MetadataConstantSummary    int
	MetadataAllFields          int

	ReferenceStrings               int
	ReferenceTypes                 int
	ReferenceValues                int
	ReferenceCompactRanges         int
	ReferenceFullRanges            int
	MaxQualified                   int
	MaxCandidates                  int
	MaxReferenceRangeLength        int
	MaxReferenceValueStart         int
	MaxReferenceStringsPerDocument int
	MaxReferenceTypesPerDocument   int
	MaxReferenceValuesPerDocument  int

	ReferenceStringCapacity int
	ReferenceBloomDocuments int
	ReferenceBloomBytes     int

	SymbolsUsingDocumentPath    int
	SymbolStringSlots           int
	UniqueSymbolStrings         int
	CoreSymbolStringSlots       int
	CoreSymbolNonEmptyStrings   int
	CoreSymbolUniquePerDocument int
	UniqueCoreSymbolStrings     int
	SymbolEmptyContainers       int
	SymbolNameEqualsQualified   int
	SymbolIDEqualsQualified     int
	SymbolStringTables          int
	SymbolStringTableValues     int
	SymbolStringTableCapacity   int
	UniqueReferenceStrings      int
	UniqueSymbolStringBytes     int
	UniqueReferenceStringBytes  int

	InternedStringSlots   int
	UniqueInternedStrings int
	UniqueInternedBytes   int

	TypeSlots       int
	UniqueTypeKeys  int
	UniqueTypeBytes int
}

WorkspaceStorageStats describes the cardinality of the immutable PHP declaration/reference graph. It is intended for opt-in profiling and does not retain the temporary uniqueness maps used to compute it.

Jump to

Keyboard shortcuts

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