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

codemap

package
v0.57.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: AGPL-3.0 Imports: 31 Imported by: 0

Documentation

Overview

Package codemap produces a compact structural outline of a single source file — every top-level declaration and the line range it occupies — so an agent can jump straight to the region it needs with a bounded read instead of pulling the whole file into context.

Outlines are computed on demand, not indexed. Tree-sitter parses a typical source file in single-digit milliseconds, which is far below the cost of the tool call that asks for it, and parsing fresh buys the property that matters most here: the line ranges always describe the file as it is right now. There is no store to migrate, nothing to invalidate when a file is edited, and no way for a stale range to send a reader to the wrong code.

Index

Constants

View Source
const (
	// MaxFileSize bounds what Outline will parse. Files past this are almost
	// always generated or minified — bundles under web/dist, vendored blobs —
	// where parsing costs real time and the outline is unusable anyway.
	MaxFileSize = 2 << 20 // 2 MiB

	// MaxSymbols caps a single outline. A file with more declarations than this
	// is not one an agent should be navigating symbol-by-symbol, and an
	// unbounded outline would reintroduce the context flooding this package
	// exists to prevent. The overflow count is reported rather than dropped
	// silently.
	MaxSymbols = 400
)
View Source
const MaxDiagnostics = 20

MaxDiagnostics caps how many problems one check reports. Tree-sitter recovers after each error and keeps parsing, so a file damaged near the top can cascade into dozens of complaints that all describe the same mistake. The first few locate the damage; the rest are noise the agent would pay context for.

View Source
const NewerSyntaxCaveat = "" /* 164-byte string literal not displayed */

NewerSyntaxCaveat closes every report of errors. A grammar can lag its language — TypeScript's `export type *`, C# 14's extension blocks — and a construct newer than the grammar reads as an error. Rewriting valid code to satisfy the parser is worse than the error it would fix, so the reader is told how to tell the two apart.

Variables

View Source
var ErrBinary = errors.New("binary file")

ErrBinary is returned for files holding NUL bytes.

View Source
var ErrDirectory = errors.New("is a directory")

ErrDirectory is returned for a path that names a directory, which has no syntax or outline of its own.

Functions

func FormatDiagnostics added in v0.25.0

func FormatDiagnostics(diags []Diagnostic) string

FormatDiagnostics renders diagnostic lines on their own, for a caller that supplies its own heading — the write and edit tools append a short version of this to their result rather than the whole RenderCheck report.

func LanguageNames added in v0.26.0

func LanguageNames() []string

LanguageNames returns the name of every language a real grammar covers, sorted and de-duplicated. It exists so callers that describe that coverage to a model — FileMapTool.Description — can be pinned against the registry instead of against a list someone remembered to update. Adding a grammar without saying so leaves the agent treating an approximate scan as exact, and vice versa.

func LooksBinary added in v0.26.1

func LooksBinary(data []byte) bool

LooksBinary reports whether data holds a NUL byte — the heuristic this package uses to tell binary content from source text. Exported so other packages (e.g. the read tool) can apply the same rule before treating a file's bytes as text.

func Render

func Render(fm *FileMap) string

Render formats a FileMap for a model to read.

The output is plain text rather than the JSON the pdf_index tool returns. That is a deliberate break from the neighbouring tool: JSON spends roughly three times the tokens on braces, quotes and repeated key names to carry the same fields, and token economy is the entire reason this tool exists. A model reads an aligned two-column table just as reliably.

func RenderCheck added in v0.25.0

func RenderCheck(res *CheckResult) string

RenderCheck formats a CheckResult for a model to read.

The three outcomes are worded to be unmistakable from each other, because the cost of confusing them is the whole point of the check: a clean parse says move on, a diagnostic says stop and fix, and an unchecked file says this proved nothing. The last is the one worth being loud about — an agent that reads "no grammar" as "no errors" has bought false confidence.

Types

type CheckResult added in v0.25.0

type CheckResult struct {
	Path string
	Lang string
	// Checked is false when nothing could check this file — no parser covers
	// its type, or (see Reason) its content is not the language yet. The file
	// was not parsed, which is not the same as it being clean: nothing may be
	// concluded from an empty Diagnostics in that case.
	Checked bool
	// Reason says why a file of a checkable type was still not checked — a
	// YAML file holding template syntax, say. Empty when the type itself has
	// no parser.
	Reason string
	// Diagnostics is empty for a file that parses cleanly.
	Diagnostics []Diagnostic
	// Truncated is true when MaxDiagnostics cut the list short.
	Truncated bool
}

CheckResult is the outcome of a syntax check on one file.

func Check added in v0.25.0

func Check(path string) (*CheckResult, error)

Check parses path and reports its syntax errors.

It returns the same errors Outline does for the same reasons — ErrBinary, ErrDirectory, *TooLargeError, and whatever os.Stat/os.ReadFile produce — so a caller can share one error switch across both.

func CheckSource added in v0.25.0

func CheckSource(path string, src []byte) (*CheckResult, error)

CheckSource is Check over content already in hand, for a caller that has just written the bytes and would otherwise read them back.

func (*CheckResult) CountLabel added in v0.41.0

func (r *CheckResult) CountLabel() string

CountLabel is the error count as a reader should see it: "20+" when the cap cut the list short, since a bare 20 would be a count the file does not have.

func (*CheckResult) OK added in v0.25.0

func (r *CheckResult) OK() bool

OK reports whether the file was parsed and had no syntax errors. An unchecked file is never OK: it is unknown.

type Diagnostic added in v0.25.0

type Diagnostic struct {
	Line   int
	Column int
	// EndLine is the last line the problem covers, equal to Line for a
	// single-line one. A damaged region can run for many lines, and its extent
	// is what tells a reader whether they are looking at one bad token or a
	// file that needs rewriting.
	EndLine int
	// Missing marks a diagnostic the parser inferred from a token that should
	// have been there rather than from bytes it could not use. These carry the
	// better message — the parser names the exact token it wanted.
	Missing bool
	Message string
	// Source is the file's line at Line, trimmed of trailing space. Empty when
	// the diagnostic points past the last line.
	Source string
}

Diagnostic is one syntax problem recovered from a parse.

Line and Column are 1-based, matching the numbering file_map prints and read accepts, so a diagnostic can be handed straight to a ranged read. Column counts characters, not bytes, so it agrees with an editor on a line that holds non-ASCII text.

type FileMap

type FileMap struct {
	Path       string
	Lang       string
	TotalLines int
	Symbols    []*Symbol
	// FromLine and ToLine bound a map of one region (see OutlineRange); both
	// are zero for a map of the whole file.
	FromLine, ToLine int
	// Omitted counts symbols dropped by the MaxSymbols cap.
	Omitted int
	// OmittedDepth, when the cap dropped anything, is the shallowest nesting
	// level it dropped: every entry that deep or deeper is left out, all
	// through the file, so what remains still covers the file end to end. Zero
	// when even the file-scope entries did not fit, and the map ends at
	// StopLine instead.
	OmittedDepth int
	// StopLine is the last line a map cut short by the cap still covers; zero
	// when it runs to the end.
	StopLine int
	// Fallback is true when no grammar covered this extension and the
	// heuristic scanner produced the outline.
	Fallback bool
	// ParseError is true when tree-sitter hit a syntax error. The outline is
	// still usable — tree-sitter recovers and keeps going — but it may be
	// missing declarations after the damaged region, and a reader deserves to
	// know that before trusting a gap.
	ParseError bool
}

FileMap is the outline of one file.

func Outline

func Outline(path string) (*FileMap, error)

Outline parses path and returns its structural map.

func OutlineRange added in v0.41.0

func OutlineRange(path string, from, to int) (*FileMap, error)

OutlineRange maps only the declarations that reach into lines from through to (1-based, inclusive; to 0 runs to the end of the file), together with the ones enclosing them, so a region the whole-file map had to leave out can be seen in full. from 0 maps the whole file.

The MaxSymbols cap applies to what the region holds, not to the file, which is what makes zooming in on a region of a capped map useful.

type Symbol

type Symbol struct {
	Kind      string // func, method, type, const, var, import, and fallback kinds
	Name      string // primary identifier; empty for import blocks
	Signature string // rendered display form, already collapsed and capped
	Doc       string // first line of the doc comment, markers stripped
	StartLine int
	EndLine   int
	// Depth is how many symbols enclose this one — 0 at file scope, 1 for a
	// class member. Rendered as indentation.
	Depth int
	// contains filtered or unexported fields
}

Symbol is one declaration in a file.

StartLine and EndLine are 1-based and inclusive, and StartLine includes any doc comment attached to the declaration: the comment is the part a reader most needs and excluding it would make every jump a two-step operation.

type TooLargeError

type TooLargeError struct {
	Size int64
}

TooLargeError reports a file above MaxFileSize.

func (*TooLargeError) Error

func (e *TooLargeError) Error() string

Directories

Path Synopsis
grammars
swift
Package swift provides the tree-sitter grammar for Swift.
Package swift provides the tree-sitter grammar for Swift.

Jump to

Keyboard shortcuts

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