Help us shape the future of Go! Take the 2026 Go Developer Survey

model

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package model holds the language-neutral contracts shared by every graphmaster layer: language and kind enums, the per-file Facts produced by parsing, and the LanguageSpec / RepoContext interfaces used by parse and resolve.

The package is intentionally dependency-free (no cgo, no tree-sitter) so it can be imported from anywhere. Enum values are persisted in graph.db and must never be renumbered; append new values at the end.

Index

Constants

View Source
const MaxSigLen = 200

MaxSigLen is the maximum byte length of a stored signature.

View Source
const NoParent int32 = -1

NoParent marks a top-level definition (Def.Parent) or a file-scope reference (Ref.Enclosing).

Variables

This section is empty.

Functions

func CleanRel

func CleanRel(p string) string

CleanRel normalizes a repo-relative path: backslashes become slashes, "." and ".." are resolved, and the root becomes "". Paths that are absolute or escape the repository return "".

func FindUp

func FindUp(ctx RepoContext, dir, name string) (string, bool)

FindUp searches dir and its ancestors (up to the repo root) for a file named name and returns its repo-relative path.

func IsCodePath

func IsCodePath(path string) bool

IsCodePath reports whether path has an extension of a supported language.

func NormalizeSig

func NormalizeSig(s string) string

NormalizeSig collapses whitespace runs to single spaces, trims, and truncates to at most MaxSigLen bytes on a rune boundary, appending "…" when truncated.

Types

type Def

type Def struct {
	Kind NodeKind
	Name string
	// Parent is the index into Facts.Defs of the lexically enclosing
	// definition, or NoParent. Parents always precede their children.
	Parent int32
	// Scope holds extra qualifier segments that are not represented by a
	// parent def in this file, e.g. the receiver type of a Go method
	// ("Server") or "ns::Cls" of an out-of-line C++ method definition.
	Scope []string
	Span
	Sig   string // normalized, at most MaxSigLen bytes (see NormalizeSig)
	Flags DefFlags
}

Def is a definition extracted from one file.

type DefFlags

type DefFlags uint16

DefFlags is a bit set of definition attributes stored in nodes.flags.

const (
	FlagExported    DefFlags = 1 << iota // visible outside its module/package
	FlagTest                             // a test function/method/class
	FlagAsync                            // async function/method
	FlagStatic                           // static member
	FlagAbstract                         // abstract member or type
	FlagDeclaration                      // declaration without body (C prototype, forward decl)
)

Definition flags. Append only; never reorder bits.

func (DefFlags) Has

func (f DefFlags) Has(m DefFlags) bool

Has reports whether all bits of m are set in f.

func (DefFlags) String

func (f DefFlags) String() string

String renders set flags joined by "|", e.g. "exported|async".

type EdgeKind

type EdgeKind uint8

EdgeKind classifies a graph edge. Values are stored in graph.db.

const (
	EdgeUnknown EdgeKind = iota
	EdgeContains
	EdgeCalls
	EdgeReferences
	EdgeImports
	EdgeExtends
	EdgeImplements
	EdgeEmbeds
	EdgeTests
	EdgeIncludes
	EdgeDeclares // header declaration -> definition (C/C++)

)

Edge kinds. Append only; never renumber.

func AllEdgeKinds

func AllEdgeKinds() []EdgeKind

AllEdgeKinds returns every known edge kind (excluding EdgeUnknown).

func ParseEdgeKind

func ParseEdgeKind(s string) (EdgeKind, error)

ParseEdgeKind parses the lowercase name produced by String.

func (EdgeKind) IsInheritance

func (k EdgeKind) IsInheritance() bool

IsInheritance reports whether k is extends, implements or embeds.

func (EdgeKind) String

func (k EdgeKind) String() string

func (EdgeKind) Valid

func (k EdgeKind) Valid() bool

Valid reports whether k is a known, non-unknown edge kind.

type Facts

type Facts struct {
	Lang Lang
	// Package is the package / namespace declared in the file, if the
	// language has such a clause (Go package, Java package, C#/PHP namespace).
	Package  string
	TestFile bool // file is a test file by naming convention or content
	Defs     []Def
	Refs     []Ref
	Imports  []Import
	Inherits []Inherit
	Tests    []TestMark
}

Facts is the language-neutral parse output for one file. It is cached in cache.db keyed by content, so it must not contain path-dependent data.

func (*Facts) AddDef

func (f *Facts) AddDef(d Def) int32

AddDef appends d and returns its index.

func (*Facts) QNameParts

func (f *Facts) QNameParts(i int32) []string

QNameParts returns the qualified name segments of def i, from outermost container to the def itself, including Scope segments. Module identity is not included; resolvers prepend it. Out-of-range indices return nil.

func (*Facts) Validate

func (f *Facts) Validate() error

Validate checks structural invariants that downstream layers rely on.

type FileStatus

type FileStatus uint8

FileStatus records why a file was or was not parsed. Values match the files.status column in graph.db.

const (
	StatusOK FileStatus = iota
	StatusTooBig
	StatusGenerated
	StatusMinified
	StatusBinary
	StatusParseErr
	StatusUnsupported
)

File statuses. Append only; never renumber.

func ParseFileStatus

func ParseFileStatus(s string) (FileStatus, error)

ParseFileStatus parses the name produced by String.

func (FileStatus) Indexed

func (s FileStatus) Indexed() bool

Indexed reports whether the file's facts are stored. Files with syntax errors are still indexed best-effort from tree-sitter's error-tolerant tree.

func (FileStatus) String

func (s FileStatus) String() string

type Import

type Import struct {
	// Spec is the import path as written, without quotes. C/C++ includes
	// keep their delimiters ("<stdio.h>" or "\"util.h\"") so resolvers can
	// tell system and local includes apart.
	Spec  string
	Alias string   // local alias, "" if none ("_" and "." kept verbatim for Go)
	Names []string // imported member names (Python from-import, JS named, Java single-type)
	// Wildcard is set for on-demand imports: Java a.b.*, Python from x import *,
	// C# using / C++ using namespace, JS export * from.
	Wildcard bool
	Line     uint32
}

Import is an import / include / use declaration.

type ImportTarget

type ImportTarget struct {
	Kind ImportTargetKind
	// Path is the repo-relative target file (TargetFile) or directory
	// (TargetModule); empty otherwise.
	Path string
	// Module is the target module identity in the same form ModuleOf
	// returns, or the external module name for TargetExternal.
	Module string
}

ImportTarget is where an import points.

func (ImportTarget) Resolved

func (t ImportTarget) Resolved() bool

Resolved reports whether the import points into the repository.

type ImportTargetKind

type ImportTargetKind uint8

ImportTargetKind classifies the result of ResolveImport.

const (
	TargetUnresolved ImportTargetKind = iota // could not be resolved
	TargetFile                               // a single in-repo file
	TargetModule                             // an in-repo package/module (directory or namespace)
	TargetExternal                           // outside the repo (stdlib, npm, system header)
)

Import target kinds.

func (ImportTargetKind) String

func (k ImportTargetKind) String() string

type Inherit

type Inherit struct {
	Child     int32    // index into Facts.Defs
	Kind      EdgeKind // EdgeExtends, EdgeImplements or EdgeEmbeds
	Name      string   // target type name
	Qualifier string   // target qualifier text, "" if unqualified
	Line      uint32
	Col       uint32
}

Inherit is a type relationship declared in this file.

type Lang

type Lang uint8

Lang identifies a source language. Values are stored in graph.db.

const (
	LangUnknown Lang = iota
	LangGo
	LangPython
	LangTypeScript
	LangTSX
	LangJavaScript
	LangRust
	LangJava
	LangC
	LangCPP
	LangCSharp
	LangPHP
)

Supported languages. Append only; never renumber.

func AllLangs

func AllLangs() []Lang

AllLangs returns every supported language in stable order.

func LangFromExt

func LangFromExt(ext string) Lang

LangFromExt maps an extension (with leading dot) to a language. Exact case is tried first so ".C"/".H" map to C++; then a lowercase match.

func LangFromPath

func LangFromPath(path string) Lang

LangFromPath maps a file path (slash or backslash separated) to a language by its extension. Unknown or extensionless files return LangUnknown.

func ParseLang

func ParseLang(s string) (Lang, error)

ParseLang parses a canonical name or common alias, case-insensitively.

func (Lang) Extensions

func (l Lang) Extensions() []string

Extensions returns a copy of the file extensions (with leading dot) claimed by l.

func (Lang) MarshalText

func (l Lang) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Lang) String

func (l Lang) String() string

String returns the canonical lowercase name (e.g. "cpp", "csharp").

func (*Lang) UnmarshalText

func (l *Lang) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (Lang) Valid

func (l Lang) Valid() bool

Valid reports whether l is a supported (non-unknown) language.

type LanguageSpec

type LanguageSpec interface {
	// Lang returns the language this spec handles.
	Lang() Lang
	// Extensions returns the file extensions (with leading dot) handled.
	Extensions() []string
	// Grammar returns the raw TSLanguage pointer exported by the grammar's
	// Go binding (e.g. tree_sitter_go.Language()). The parse layer wraps it
	// with tree_sitter.NewLanguage; keeping it opaque here keeps model free
	// of cgo.
	Grammar() unsafe.Pointer
	// QuerySource returns the tree-sitter query (.scm) used for extraction.
	QuerySource() string
	// ExtractorVersion must be bumped whenever extraction output changes;
	// it invalidates cached facts for this language only.
	ExtractorVersion() int
	// ModuleOf returns the module identity of the repo-relative file path,
	// e.g. a Go import path, Python dotted module, Java package, or the
	// file path itself for TS/JS. facts may be nil.
	ModuleOf(path string, facts *Facts, ctx RepoContext) string
	// ResolveImport maps an import spec written in fromFile (repo-relative)
	// to its target.
	ResolveImport(spec string, fromFile string, ctx RepoContext) ImportTarget
}

LanguageSpec describes one language to the parse and resolve layers. Implementations live in internal/parse (lang_<x>.go) and self-register.

type MemRepo

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

MemRepo is an in-memory RepoContext for tests.

func NewMemRepo

func NewMemRepo(files map[string]string) *MemRepo

NewMemRepo builds a MemRepo from path -> content.

func (*MemRepo) DirExists

func (m *MemRepo) DirExists(rel string) bool

DirExists implements RepoContext.

func (*MemRepo) FileExists

func (m *MemRepo) FileExists(rel string) bool

FileExists implements RepoContext.

func (*MemRepo) ListDir

func (m *MemRepo) ListDir(dir string) []string

ListDir implements RepoContext.

func (*MemRepo) ReadFile

func (m *MemRepo) ReadFile(rel string) ([]byte, error)

ReadFile implements RepoContext.

type NodeKind

type NodeKind uint8

NodeKind classifies a definition node. Values are stored in graph.db.

const (
	KindUnknown NodeKind = iota
	KindPackage
	KindModule
	KindFile
	KindNamespace
	KindClass
	KindStruct
	KindInterface
	KindTrait
	KindEnum
	KindType // type alias / typedef / named type
	KindFunction
	KindMethod
	KindConstructor
	KindField
	KindVariable
	KindConstant
	KindMacro
	KindTest
	KindEnumMember
	KindProperty
)

Node kinds. Append only; never renumber.

func AllNodeKinds

func AllNodeKinds() []NodeKind

AllNodeKinds returns every known node kind (excluding KindUnknown).

func ParseNodeKind

func ParseNodeKind(s string) (NodeKind, error)

ParseNodeKind parses the lowercase name produced by String.

func (NodeKind) IsCallable

func (k NodeKind) IsCallable() bool

IsCallable reports whether k can be the target of a call edge.

func (NodeKind) IsContainer

func (k NodeKind) IsContainer() bool

IsContainer reports whether k can lexically contain other definitions.

func (NodeKind) IsType

func (k NodeKind) IsType() bool

IsType reports whether k declares a type.

func (NodeKind) String

func (k NodeKind) String() string

func (NodeKind) Valid

func (k NodeKind) Valid() bool

Valid reports whether k is a known, non-unknown kind.

type Ref

type Ref struct {
	Kind RefKind
	Name string // the referenced identifier, e.g. "Foo" in pkg.Foo()
	// Qualifier is the textual qualifier when it is a module/type path,
	// e.g. "pkg" in pkg.Foo() or "std::vector" in std::vector::push_back.
	Qualifier string
	// Receiver is the receiver expression text for member access on a
	// value, e.g. "s" in s.Start() or "this" / "self" / "$this".
	Receiver string
	// Enclosing is the index of the innermost enclosing def, or NoParent.
	Enclosing int32
	Line      uint32
	Col       uint32
}

Ref is an unresolved use of a name.

type RefKind

type RefKind uint8

RefKind classifies an unresolved reference found in a file.

const (
	RefUnknown RefKind = iota
	RefCall            // foo(), x.foo()
	RefType            // type usage: annotations, new T, casts
	RefMember          // non-call member access: x.field
)

Reference kinds.

func ParseRefKind

func ParseRefKind(s string) (RefKind, error)

ParseRefKind parses the lowercase name produced by String.

func (RefKind) EdgeKind

func (k RefKind) EdgeKind() EdgeKind

EdgeKind returns the edge kind a resolved reference produces.

func (RefKind) String

func (k RefKind) String() string

func (RefKind) Valid

func (k RefKind) Valid() bool

Valid reports whether k is a known, non-unknown reference kind.

type RepoContext

type RepoContext interface {
	// FileExists reports whether a regular, indexed-or-indexable file exists.
	FileExists(rel string) bool
	// DirExists reports whether a directory exists.
	DirExists(rel string) bool
	// ReadFile reads a small file such as go.mod, tsconfig.json or
	// composer.json. Implementations may cap the size. A missing file
	// returns an error wrapping fs.ErrNotExist.
	ReadFile(rel string) ([]byte, error)
	// ListDir returns the sorted base names of files (not directories)
	// directly inside dir.
	ListDir(dir string) []string
}

RepoContext is the read-only view of the repository that language specs use for module identity and import resolution. All paths are repo-relative, slash-separated, and "" denotes the repo root. Implementations must be safe for concurrent use.

type Span

type Span struct {
	StartLine uint32
	StartCol  uint32
	EndLine   uint32
	EndCol    uint32
	StartByte uint32
	EndByte   uint32
}

Span locates a syntax node. Lines are 1-based; columns are 0-based byte offsets within the line; bytes are 0-based offsets into the file with an exclusive end.

type TestMark

type TestMark struct {
	Def    int32
	Target string
}

TestMark records that a def is a test, optionally hinting the tested name (e.g. TestParseFoo -> "ParseFoo").

Jump to

Keyboard shortcuts

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