Documentation
¶
Overview ¶
Package analysis is protolsp's transport-free analysis engine : the document store, schema lookup, workspace/chain/config state, and every analysis pass (parse + schema diagnostics, hover, completion, definition, code actions, secret ranges, dataset regions, effective config) — importable without jsonrpc2 or Connect-RPC.
The entry point is the Workspace: construct one with New, install a Publisher to receive pushes (diagnostics + *Changed events), and feed documents through Documents(). The in-repo LSP server (internal/server) is one consumer; in-process embedders such as goed link this package directly and get the exact pipeline the LSP runs — same debounce, same workspace discovery, same secret handling.
API tiers ¶
The exported surface has two tiers. The EMBEDDER core is what an in-process consumer needs and is what we try hardest to keep stable: New + the Set* configuration knobs, Publisher and its payload types (SecretRange, DatasetRegion, ConfigValue), the Documents store and Document sync flow (EnsureWorkspaceForDoc, DetectLayerInfo, RunAnalyzeAndMaybeLiveReload, ScheduleAnalyzePipeline, CancelPendingAnalyze, PublishDiagnosticsRaw, MaybeEvictSubWorkspace), the feature queries (HoverFor, CompletionFor, DefinitionFor, CodeActionsFor, and friends), ScheduleWatchedFilesProcess, and the CancelBackground/Close teardown pair. Everything else — the LSP request/response DTOs, the protolsp/* Method constants, and the manager types' wider method sets — exists for the in-repo LSP/RPC shell and carries no compatibility promise while the module is pre-1.0.
Threading model ¶
Feature queries are safe to call concurrently with the analyze pipeline and with each other: they take per-document read locks and snapshot manager state internally. The one exception is CodeActionsFor, whose caller must hold doc.RLock so the computed edits stay consistent with the diagnostics passed in (see its doc comment). The Set* configuration knobs are setup-time plain writes: call them after New and before feeding documents or spawning queries, not concurrently with either. Mutating entry points — document open/update/close, the LoadWorkspace*/Rebuild* loaders, and watched-files processing — are individually thread-safe, but embedders are encouraged to serialize them on one goroutine the way both in-tree consumers do (the LSP shell via its connection loop, goed via a single worker): it makes operation ordering deterministic and keeps slow loads from interleaving. Publisher callbacks fire on pipeline goroutines (including debounce timers) and must not block; payload slices are shared with engine state and must be copied if retained.
URIs must be file-scheme (uri.File); guard foreign URIs with IsFileURI before feeding them in — several internal paths resolve URI.Filename, which panics on non-file schemes.
Workspace construction + the exported facade knobs.
The Workspace type itself (the former internal/server engine) is declared in engine.go; this file owns everything an embedder or the LSP shell needs to build and configure one:
- New — allocates a fully-wired Workspace with a no-op Publisher.
- SetPublisher — installs the outbound seam (LSP shell installs its jsonrpc2/RPC fan-out; in-process embedders install callbacks).
- The knob setters/accessors the LSP shell and the test suite use in place of the direct field pokes they had when Server and engine shared a package.
Keyed repeated fields (draft-trendvidia-protowire-01 §3.13, trendvidia/protowire#116): a `repeated <Message>` field carrying the (pxf.key) option is written as a block of named blocks — entry name = key-field value, document order = list order. This file holds the small primitives the editor surfaces share when they need to treat a keyed field's block specially: detecting a keyed field, pulling the entries out of its block, the canonical identifier-safe rule for deciding whether a rewritten key needs quoting, and the on-source span of an entry's name token.
The schema-layer machinery (typed decode errors, the tolerant diagnostics walker, canonicalization) lives in protowire-go's encoding/pxf; the descriptor helpers we build on are pxf.KeyField / pxf.IsKeyed / pxf.KeyFieldName.
Keyed-entry rename (draft-trendvidia-protowire-01 §3.13). A keyed repeated field's entry is identified by its collection's dotted path plus its key — e.g. children[loginButton] — so renaming it propagates across the workspace exactly like the path-based field rename in rename.go: every occurrence of the same entry (chain layers that define or override it) is rewritten in one edit. Each rewrite is keyed-aware: the entry name token is quoted or unquoted to match `pxf fmt` canonicalization, and any redundant explicit key assignment inside the entry is retargeted atomically.
Phase 1 of the protocheck → protolsp integration: runtime validation of .pxf data against schema-declared constraints. After validate(doc) unmarshals the source into a proto.Message, runProtocheck invokes the per-Server *protocheck.Validator and stores each violation as a protocheckFinding with a resolved source position; diagnosticsFor turns those into LSP diagnostics with source "protocheck".
Complements Phase 0 (which validates the constraint expressions themselves at .proto-edit time) by surfacing red squiggles on the data file when concrete values violate the resolved rules — `age: 200` against `lte: 150`, etc.
MVP scope for path resolution:
- Dotted descent through pxf.Block + pxf.Assignment(BlockVal) for nested-message access (`address.zip_code`).
- Bracket-indexed `[N]` for ListVal-backed repeated fields (`items[3].sku`).
- Map-key brackets (`labels["env"].value`) are NOT yet resolved — those violations land at the parent assignment's position. Acceptable for v1; map-targeted constraints are rare in practice.
- Anything that doesn't resolve falls back to the document origin (line 1, col 1) so the diagnostic still surfaces. ConstraintID + Message tell the user what failed even when the range is imprecise.
Phase 1 of the protovalidate → protolsp integration: runtime validation of .pxf data against Buf's `(buf.validate.*)` annotations. Mirror of the protocheck data validator; same shape, same emission pipeline, distinct diagnostic source ("buf/validate") so editors can color / filter independently.
Always tag-free since protovalidate-go is Apache 2.0 — this is the open-source path that ships in both the community and trendvidia builds of protolsp.
Path-resolution semantics match protocheck's: `FieldPathString` produces the same dotted + bracketed form ("address.zip_code", "items[3].sku", `labels["env"].value`) so the existing resolveProtocheckPath handles both engines without duplication.
Index ¶
- Constants
- Variables
- func ApplyContentChanges(initial []byte, changes []IncrementalChange, enc positions.Encoding) ([]byte, []error)
- func BuildRegistryURI(namespace, filePath string) uri.URI
- func DecodeRawByKind(raw json.RawMessage, kind workspaceconfig.AttributeKind) (any, error)
- func DiffSnapshots(before, after map[string]ConfigValue) map[string]ConfigValue
- func FindWorkspaceDirFor(docPath, workspaceRoot string) (string, bool)
- func FormatProto(path string, src []byte) ([]byte, error)
- func IsFileURI(u uri.URI) bool
- func IsProtoURI(u uri.URI) bool
- func IsRegistryProtoURI(u uri.URI) bool
- func IsValidKeyedEntryKey(name string) bool
- func IsValidPxfIdentifier(name string) bool
- func MessageText(m protocol.InlayHintTooltip) string
- func ParseRegistryURI(u uri.URI) (namespace, filePath string, ok bool)
- func PxfPosToLSP(p pxf.Position) protocol.Position
- func RedactChangeMap(changes map[string]ConfigValue) map[string]ConfigValue
- func SectionsOf(overrides map[string]any) []string
- func SemanticTokensLegend() protocol.SemanticTokensLegend
- func URIToFilePath(u uri.URI) (string, bool)
- func ValidateOverrides(overrides map[string]any) error
- type ChainStatusEnvironment
- type ChainStatusError
- type ChainStatusParams
- type ChainStatusResult
- type ClientCapabilities
- type ConfigAttribute
- type ConfigGetParams
- type ConfigGetResult
- type ConfigListResult
- type ConfigSetParams
- type ConfigSetResult
- type ConfigSource
- type ConfigState
- func (c *ConfigState) LockOverrides()
- func (c *ConfigState) SetSeededFromInitOptions(v bool)
- func (c *ConfigState) SnapshotEditorConfig() EditorConfig
- func (c *ConfigState) SnapshotSeededFromInitOptions() bool
- func (c *ConfigState) SwapEditorConfig(cfg EditorConfig) EditorConfig
- func (c *ConfigState) UnlockOverrides()
- type ConfigValue
- type DatasetRegion
- type DatasetRegionsChangedParams
- type DatasetRegionsParams
- type DatasetRegionsResult
- type DeclaredNames
- type Document
- func (d *Document) Lock()
- func (d *Document) RLock()
- func (d *Document) RUnlock()
- func (d *Document) SecretValues() []string
- func (d *Document) SetWorkspaceDir(dir string)
- func (d *Document) SnapshotForPipeline() (version int32, secrets []SecretRange, datasets []DatasetRegion)
- func (d *Document) Unlock()
- func (d *Document) WorkspaceDir() string
- type Documents
- type EditorConfig
- type EffectiveConfigChangedParams
- type EngineConfigResult
- type GetEffectiveConfigParams
- type GetEffectiveConfigResult
- type IncrementalChange
- type LayerInfoParams
- type LayerInfoResult
- type ListMessagesParams
- type ListMessagesResult
- type LiteralSecretData
- type LookupManager
- func (m *LookupManager) BeginRebuild(cfg schema.Config) (context.Context, bool)
- func (m *LookupManager) CancelInFlight()
- func (m *LookupManager) Close() error
- func (m *LookupManager) RecordBaseline(cfg schema.Config)
- func (m *LookupManager) Snapshot() schema.Lookup
- func (m *LookupManager) SnapshotProtoFiles() schema.Lookup
- func (m *LookupManager) Swap(newLookup schema.Lookup, newCloser io.Closer) (oldCloser io.Closer)
- type MessageEntry
- type NopPublisher
- func (NopPublisher) DatasetRegionsChanged(context.Context, uri.URI, int32, []DatasetRegion)
- func (NopPublisher) EffectiveConfigChanged(context.Context, string, map[string]ConfigValue)
- func (NopPublisher) LookupChanged(context.Context, string)
- func (NopPublisher) PublishDiagnostics(context.Context, uri.URI, uint32, []protocol.Diagnostic)
- func (NopPublisher) SecretRangesChanged(context.Context, uri.URI, int32, []SecretRange)
- func (NopPublisher) ShowMessage(context.Context, protocol.MessageType, string)
- type PositionShape
- type ProtocolRangeShape
- type Publisher
- type RegistryStatusResult
- type RenameTargetKind
- type RuntimeSourceRef
- type RuntimeViolation
- type SecretForm
- type SecretRange
- type SecretRangeEntry
- type SecretRangesChangedParams
- type SecretRangesParams
- type SecretRangesResult
- type SetOverridesApplied
- type SetOverridesParams
- type SetOverridesResult
- type SetRuntimeViolationsParams
- type SourceContentParams
- type SourceContentResult
- type UnknownFieldData
- type UnresolvedNameData
- type Workspace
- func (s *Workspace) Analyze(doc *Document)
- func (s *Workspace) AnalyzeCount() int64
- func (s *Workspace) ApplyOverridesLocked(overrides map[string]any)
- func (s *Workspace) CancelBackground()
- func (s *Workspace) CancelPendingAnalyze(doc *Document)
- func (s *Workspace) ChainForDoc(doc *Document) *chain.ActiveChain
- func (s *Workspace) ChainStatusSnapshot() ChainStatusResult
- func (s *Workspace) ClientCapabilities() ClientCapabilities
- func (s *Workspace) Close() error
- func (s *Workspace) CodeActionsFor(doc *Document, diags []protocol.Diagnostic) []protocol.CodeAction
- func (s *Workspace) CompletionFor(docURI uri.URI, pos protocol.Position) *protocol.CompletionList
- func (s *Workspace) ComputeLayerInfo(docURI uri.URI) *LayerInfoResult
- func (s *Workspace) Config() *ConfigState
- func (s *Workspace) ConfigDiagnostics(doc *Document) []protocol.Diagnostic
- func (s *Workspace) ConfigPathForWorkspace(workspaceDir string) (string, error)
- func (s *Workspace) DebounceWindow() time.Duration
- func (s *Workspace) DeclaredNames() DeclaredNames
- func (s *Workspace) DefinitionFor(docURI uri.URI, pos protocol.Position) *protocol.Location
- func (s *Workspace) DetectLayerInfo(doc *Document)
- func (s *Workspace) DiagnosticsFor(doc *Document) []protocol.Diagnostic
- func (s *Workspace) DocumentSymbolsFor(docURI uri.URI) []protocol.DocumentSymbol
- func (s *Workspace) Documents() *Documents
- func (s *Workspace) EffectiveRegistryConfig() schema.Config
- func (s *Workspace) EngineConfig() EngineConfigResult
- func (s *Workspace) EnsureSubWorkspace(dir string) *WorkspaceState
- func (s *Workspace) EnsureWorkspaceForDoc(doc *Document)
- func (s *Workspace) FoldingRangesFor(docURI uri.URI) []protocol.FoldingRange
- func (s *Workspace) FormattingEditsFor(docURI uri.URI) []protocol.TextEdit
- func (s *Workspace) HoverFor(docURI uri.URI, pos protocol.Position) *protocol.Hover
- func (s *Workspace) IsChainSpecDoc(doc *Document) bool
- func (s *Workspace) IsWorkspaceConfigDoc(doc *Document) bool
- func (s *Workspace) ListMessages(ctx context.Context, prefix string) (ListMessagesResult, error)
- func (s *Workspace) LoadProtoIndex()
- func (s *Workspace) LoadWorkspaceChain()
- func (s *Workspace) LoadWorkspaceFileConfig()
- func (s *Workspace) Logger() *slog.Logger
- func (s *Workspace) LookupForDoc(doc *Document) schema.Lookup
- func (s *Workspace) LookupForNamespace(namespace string) schema.Lookup
- func (s *Workspace) Lookups() *LookupManager
- func (s *Workspace) MaybeEvictSubWorkspace(dir string)
- func (s *Workspace) NotifyEffectiveConfigChanged(ctx context.Context, workspaceDir string, changes map[string]ConfigValue)
- func (s *Workspace) NotifyStaleSchemaIfApplicable(ctx context.Context)
- func (s *Workspace) OpenShadowProto(docURI uri.URI, source string)
- func (s *Workspace) OpenShadowProtoForWorkspace(docURI uri.URI, source, workspaceDir string)
- func (s *Workspace) PositionEncoding() positions.Encoding
- func (s *Workspace) ProtoCompletionFor(docURI uri.URI, pos protocol.Position) *protocol.CompletionList
- func (s *Workspace) ProtoFoldingRangesFor(docURI uri.URI) []protocol.FoldingRange
- func (s *Workspace) ProtoFormattingEditsFor(docURI uri.URI) []protocol.TextEdit
- func (s *Workspace) PublishDiagnostics(ctx context.Context, doc *Document)
- func (s *Workspace) PublishDiagnosticsRaw(ctx context.Context, u uri.URI, version uint32, diags []protocol.Diagnostic)
- func (s *Workspace) Publisher() Publisher
- func (s *Workspace) RFC001SourceRange(docURI uri.URI, descriptorPath string) (protocol.Range, bool)
- func (s *Workspace) ReanalyzeOpenDocsExcept(ctx context.Context, skip uri.URI)
- func (s *Workspace) RebuildLookupAsync(_ context.Context)
- func (s *Workspace) RebuildLookupFromEffectiveConfig(ctx context.Context)
- func (s *Workspace) RebuildProtocheckValidator(ctx context.Context)
- func (s *Workspace) RebuildRootProtoFilesLookup()
- func (s *Workspace) ReferencesFor(ctx context.Context, docURI uri.URI, pos protocol.Position, includeDecl bool) []protocol.Location
- func (s *Workspace) RegionAtPosition(doc *Document, pos protocol.Position) *DatasetRegion
- func (s *Workspace) RegistryStatus() RegistryStatusResult
- func (s *Workspace) ReloadAfterConfigEdit(ctx context.Context, workspaceDir string)
- func (s *Workspace) RenameEditFor(ctx context.Context, docURI uri.URI, pos protocol.Position, newName string) *protocol.WorkspaceEdit
- func (s *Workspace) RenameTargetKind(docURI uri.URI, pos protocol.Position) RenameTargetKind
- func (s *Workspace) ResolveSection(section string) ConfigValue
- func (s *Workspace) ResolvedChainSpecPath() string
- func (s *Workspace) RootProtoFilesErrs() *rootProtoFilesCompileErrors
- func (s *Workspace) RunAnalyzeAndMaybeLiveReload(ctx context.Context, docURI uri.URI, previousSecrets []SecretRange, ...)
- func (s *Workspace) ScheduleAnalyzePipeline(ctx context.Context, doc *Document, previousSecrets []SecretRange, ...)
- func (s *Workspace) ScheduleWatchedFilesProcess(ctx context.Context, events []*protocol.FileEvent)
- func (s *Workspace) SemanticTokensFor(docURI uri.URI) *protocol.SemanticTokens
- func (s *Workspace) SetActiveEnvironment(env string) (string, error)
- func (s *Workspace) SetBufLint(enabled bool)
- func (s *Workspace) SetBwSession(ctx context.Context, token string)
- func (s *Workspace) SetClientCapabilities(caps ClientCapabilities)
- func (s *Workspace) SetClientLocale(locale string)
- func (s *Workspace) SetDebounceWindow(d time.Duration)
- func (s *Workspace) SetHugeRegionBytes(n int)
- func (s *Workspace) SetHugeRegionRows(n int)
- func (s *Workspace) SetMaxReferencesFiles(n int)
- func (s *Workspace) SetPositionEncoding(enc positions.Encoding)
- func (s *Workspace) SetProtoIndexCacheRoot(root string)
- func (s *Workspace) SetPublisher(p Publisher)
- func (s *Workspace) SetRuntimeViolations(ctx context.Context, docURI uri.URI, violations []RuntimeViolation)
- func (s *Workspace) SetSeededFromInitOptions(v bool)
- func (s *Workspace) SetWatchedFilesWindow(d time.Duration)
- func (s *Workspace) SnapshotChain() *chain.ActiveChain
- func (s *Workspace) SnapshotEditorConfig() EditorConfig
- func (s *Workspace) SnapshotFileConfig() *workspaceconfig.Config
- func (s *Workspace) SnapshotProtoIndex() *protoindex.Index
- func (s *Workspace) SnapshotSectionsLocked(sections []string) map[string]ConfigValue
- func (s *Workspace) SnapshotSeededFromInitOptions() bool
- func (s *Workspace) SourceContent(ctx context.Context, u uri.URI) (SourceContentResult, error)
- func (s *Workspace) SourceContentForWorkspace(ctx context.Context, u uri.URI, workspaceDir string) (SourceContentResult, error)
- func (s *Workspace) SubWorkspaceByDir(dir string) (*WorkspaceState, bool)
- func (s *Workspace) SubWorkspaceCount() int
- func (s *Workspace) SubWorkspaceForDoc(doc *Document) *WorkspaceState
- func (s *Workspace) SwapChain(c *chain.ActiveChain) *chain.ActiveChain
- func (s *Workspace) SwapEditorConfig(cfg EditorConfig) EditorConfig
- func (s *Workspace) SwapFileConfig(cfg *workspaceconfig.Config) *workspaceconfig.Config
- func (s *Workspace) SwapSubWorkspaceLookup(ws *WorkspaceState, newLookup schema.Lookup, newCloser io.Closer) io.Closer
- func (s *Workspace) WatchedFilesDebounce() (timerArmed bool, pending int)
- func (s *Workspace) Workspaces() *WorkspaceManager
- type WorkspaceManager
- func (w *WorkspaceManager) SetWorkspaceRoot(u uri.URI)
- func (w *WorkspaceManager) SnapshotChain() *chain.ActiveChain
- func (w *WorkspaceManager) SnapshotFileConfig() *workspaceconfig.Config
- func (w *WorkspaceManager) SwapChain(c *chain.ActiveChain) *chain.ActiveChain
- func (w *WorkspaceManager) SwapFileConfig(cfg *workspaceconfig.Config) *workspaceconfig.Config
- func (w *WorkspaceManager) WorkspaceRoot() uri.URI
- type WorkspaceState
Constants ¶
const ( // MethodConfigList enumerates settable workspace attributes. // Request: no params (or null). Response: ConfigListResult. MethodConfigList = "protolsp/configList" // MethodConfigGet reads one attribute's literal value. // Request: ConfigGetParams. Response: ConfigGetResult. MethodConfigGet = "protolsp/configGet" // MethodConfigSet writes one attribute's value back to disk. // Request: ConfigSetParams. Response: ConfigSetResult. MethodConfigSet = "protolsp/configSet" )
const ( SectionRegistryAddress = "protolsp.registry.address" SectionRegistryNamespace = "protolsp.registry.namespace" SectionRegistryToken = "protolsp.registry.token" SectionRegistryCacheDir = "protolsp.registry.cacheDir" SectionSecurityInlineSecrets = "protolsp.security.inline_secrets" )
Section names the LSP shell pulls from the client. Each is a Tier 3 override for the corresponding workspace setting.
Names match the config-protocol design's dotted-path convention (rooted at `protolsp.`). Future sections — chameleon, dataset thresholds — will be added here as those features land.
const ( MethodSetOverrides = "protolsp/setOverrides" MethodEffectiveConfigChanged = "protolsp/effectiveConfigChanged" )
MethodSetOverrides and MethodEffectiveConfigChanged are the CP3 additions to the config-protocol custom-method surface.
const ( // MethodSecretRanges is the custom request returning the // current SecretRange list for a document. MethodSecretRanges = "protolsp/secretRanges" // MethodSecretRangesChanged is the push notification emitted // when an edit shifts SecretRanges. Editors refresh their // masking decoration from this without polling. MethodSecretRangesChanged = "protolsp/secretRangesChanged" )
const ( // DiagDataKindLiteralSecret marks a diagnostic produced for // a literal pxf.Secret value. The code-action handler reads // the payload to build the env-reference quick fix. DiagDataKindLiteralSecret = "literal_secret" )
const ( // DiagDataKindUnknownField marks a diagnostic produced by the // AST walk for a field assignment whose name doesn't exist on // the bound message. Payload also carries the field name and the // 0-indexed source line, used by the "Remove field" quick fix. DiagDataKindUnknownField = "unknown_field" )
Data payload kinds embedded in Diagnostic.Data so the code-action handler can recognize the diagnostic it's offering a fix for.
const DiagDataKindUnresolvedName = "unresolved_expression_name"
DiagDataKindUnresolvedName tags Diagnostic.Data on an unresolved engine-expression name so the code-action handler can offer the nearest declared functions as replacements.
const MaxFieldPathCompletionDepth = 5
MaxFieldPathCompletionDepth caps recursion through message-typed fields when enumerating completion candidates. 5 covers reasonable schemas; deeper paths can be typed manually. The cap also prevents the recursion-guard map from ballooning on pathological schemas that self-reference through multiple message types.
const MethodChainStatus = "protolsp/chainStatus"
MethodChainStatus is the custom request returning the workspace's current chameleon chain status.
const ( // MethodDatasetRegions is the custom request returning the // current DatasetRegion list for a document. Pull-style; the // editor calls at connect / cache invalidation. R2 adds a // push notification on structural changes. MethodDatasetRegions = "protolsp/datasetRegions" )
const ( // MethodDatasetRegionsChanged is the push notification emitted // when an edit shifts the dataset-region table for a document. // Editors refresh their masking / placeholder decoration from // this without polling. MethodDatasetRegionsChanged = "protolsp/datasetRegionsChanged" )
const MethodEngineConfig = "protolsp/engineConfig"
MethodEngineConfig is the custom LSP request editors call to read the workspace's effective engine configuration — the same answer `pxf build` resolves via RFC-001 §9.4 (nearest protowire.config.textproto walking up from the workspace root, PROTOWIRE_CONFIG, built-in defaults). pxfed and the VS Code extension render this next to the registry status so schema authors see which engine and libraries their expressions are checked against.
Request: no params (or null). Response: EngineConfigResult. Never a request error — a malformed configuration file is a state to report (Error field), not a protocol failure.
const MethodGetEffectiveConfig = "protolsp/getEffectiveConfig"
MethodGetEffectiveConfig is the custom LSP request that returns the four-tier-resolved configuration for the running server. See docs/design/config-protocol.md §"Custom protolsp methods".
const MethodLayerInfo = "protolsp/layerInfo"
MethodLayerInfo is the custom request returning the chain-layer classification for a document. Pull-only: layer assignment changes when chain.pxf changes, but the design's sketched chainStatusChanged push notification never shipped — editors re-fetch via this request after `effectiveConfigChanged` / `workspace/didChangeWatchedFiles` events fire.
const MethodListMessages = "protolsp/listMessages"
MethodListMessages is the custom LSP request that enumerates every message type visible to the bound resolver. Wraps schema.Lookup.RangeMessages (and pairs each result with its contributing namespace via FindFileByPathWithOrigin).
Pxfed's schema browser, the future hosted Monaco IDE, and any editor that wants a "browse all types" affordance all consume this — the alternative would be each editor opening its own protoregistry gRPC connection, duplicating auth + namespace-chain state. Going through protolsp keeps that state in one place.
Request: { "prefix": "<optional FQN prefix>" } Response: { "messages": [{ "fullName", "file", "namespace" }, ...] }
const MethodRegistryStatus = "protolsp/registryStatus"
MethodRegistryStatus is the custom LSP request editors call to learn whether the bound resolver is currently serving from a live registry connection or from a disk cache. The VS Code extension, pxfed, and the future hosted Monaco IDE all read this to render a status-bar indicator ("Schema: live / Schema: stale (cached)").
Request: no params (or null). Response: { "stale": bool, "configured": bool }
- configured: whether any registry was wired at initialize time. When false, the editor should show "no registry" rather than either of the connected states.
- stale: true when the resolver fell back to disk cache because the registry was unreachable. Recovering from stale requires a restart (no live reconnection logic at this layer).
const MethodSemanticTokensFull = protocol.MethodTextDocumentSemanticTokensFull
MethodSemanticTokensFull is the LSP method for the full-document semantic-tokens request. Re-exported from protocol so the dispatcher matches against a single source of truth.
const MethodSetRuntimeViolations = "protolsp/setRuntimeViolations"
MethodSetRuntimeViolations is the custom client→server notification replacing a document's runtime-violation overlay. Naming follows the state-push precedent (protolsp/setOverrides, pxfed/setBwSession): the client *sets* server-held state.
const MethodSourceContent = "protolsp/sourceContent"
MethodSourceContent is the custom LSP request the editor calls to fetch the bytes behind a `registry://` URI returned by go-to-definition. Namespaced under `protolsp/` to avoid collision with future LSP standard methods.
Request: { "uri": "registry://<namespace>/<file-path>" } Response: { "content": "<source bytes as utf-8>" }
On a malformed URI or unknown path the server replies with a JSON-RPC error rather than empty content — the editor's content provider surfaces the message in the placeholder document so failures are debuggable.
Variables ¶
var ( // ErrNotRegistryURI: the URI isn't of the // registry://<namespace>/<file-path> shape. ErrNotRegistryURI = errors.New("not a registry:// URI") // ErrNoSchemaLookup: no schema lookup is configured for the // requested namespace, so there is nowhere to fetch from. ErrNoSchemaLookup = errors.New("no schema lookup configured") )
SourceContent error classes, exposed as errors.Is targets so transport shims (and embedders rendering placeholder documents) can distinguish caller mistakes from missing configuration without string matching.
var ErrNoRootWorkspace = errors.New("no root workspace configured")
ErrNoRootWorkspace reports that ConfigPathForWorkspace was asked for the root workspace's config but no root is configured. Server- side condition — transports map it to their internal/precondition error code.
var ErrUnknownWorkspaceDir = errors.New("not a registered sub-workspace")
ErrUnknownWorkspaceDir reports that ConfigPathForWorkspace was given a directory that isn't a registered sub-workspace. Caller- side condition — transports map it to their invalid-argument code.
var KnownSections = []string{ SectionRegistryAddress, SectionRegistryNamespace, SectionRegistryToken, SectionRegistryCacheDir, SectionSecurityInlineSecrets, }
KnownSections enumerates every config section getEffectiveConfig knows about today. Drives the "all sections" default. New sections (chameleon.*, security.*, etc.) get added here as their features land.
var ( SemanticTokenTypes = []protocol.SemanticTokenTypes{ protocol.SemanticTokenTypesMacro, protocol.SemanticTokenTypesNamespace, protocol.SemanticTokenTypesProperty, protocol.SemanticTokenTypesStruct, protocol.SemanticTokenTypesString, protocol.SemanticTokenTypesNumber, protocol.SemanticTokenTypesKeyword, protocol.SemanticTokenTypesEnumMember, protocol.SemanticTokenTypes("decorator"), } )
SemanticTokens is the layered, schema-driven highlight surface (LSP 3.16+). The legend below maps each token type / modifier name to a numeric index; on the wire we emit those indices in the SemanticTokens.Data uint32 array.
Type indices and modifier bit positions are stable — clients negotiate by name on initialize and look the index up. Adding a new type/modifier means appending to the slice, never reordering.
Functions ¶
func ApplyContentChanges ¶
func ApplyContentChanges(initial []byte, changes []IncrementalChange, enc positions.Encoding) ([]byte, []error)
ApplyContentChanges walks a list of incremental changes and returns the resulting source bytes. Each change applies relative to the state after the previous one — matching the LSP spec.
Errors are non-fatal at the protocol layer; the dispatcher logs and continues with whatever state the apply loop produced. We still return them here so the dispatcher can log specific offending ranges.
func BuildRegistryURI ¶
BuildRegistryURI constructs the URI go-to-definition returns for a registry-only file: `registry://<namespace>/<file-path>`.
filePath is the FileDescriptor.Path() value — always relative within the schema (e.g. "acme/billing/v1/invoice.proto") and using forward slashes regardless of OS. The namespace component encodes which registry namespace contributed the file (per FindFileByPathWithOrigin). The LSP doesn't strictly need the namespace at fetch time (GetSource walks the chain), but it makes the URI self-describing in editor UI and logs.
func DecodeRawByKind ¶
func DecodeRawByKind(raw json.RawMessage, kind workspaceconfig.AttributeKind) (any, error)
DecodeRawByKind decodes a JSON RawMessage into the Go value SetAttribute expects for kind. Centralises the type-tag → Go-type mapping so the AttributeKind ↔ wire-shape contract has exactly one definition.
func DiffSnapshots ¶
func DiffSnapshots(before, after map[string]ConfigValue) map[string]ConfigValue
DiffSnapshots returns the subset of sections whose effective (value, source) pair changed between two snapshots. Equality is reflect-style on Value plus exact Source comparison — a same-value override-of-settings IS a change because the source shifted, but a no-op repeat-override is not.
func FindWorkspaceDirFor ¶
FindWorkspaceDirFor walks up from docPath looking for the nearest directory containing `.protolsp.pxf`. Walks stop at workspaceRoot — we never look at config files outside what the editor told us is the workspace.
Returns workspaceRoot when no `.protolsp.pxf` is found in the ancestry (including the case where one exists at the root, since that's still the root workspace). The discovery is monotonic: a deeper `.protolsp.pxf` always wins over a shallower one.
Non-file docs (URIs without a local filesystem mapping) yield ("", false) — those documents have no workspace context.
func FormatProto ¶ added in v0.24.0
FormatProto renders .proto source in canonical form with protocompile's printer. The Legacy preset is the one protocompile holds byte-compatible with `buf format`, so a file buf could already format keeps its layout; unlike buf, the parser reads v1.2 (RFC-001) syntax: annotation uses, `type`, `function`.
Errors when the source has a parse error (the user is mid-edit; rewriting from a partial AST would lose their text) and when the output does not carry every token and comment word of the input. The second check is a guard, not a formatting rule: the printer has dropped text before (annotation uses, protocompile#258; comments, protocompile#273), and refusing to format is always cheaper than deleting part of the user's file on save.
Exported for embedders that format a live editor buffer, which can be newer than the Workspace's copy of the document.
func IsFileURI ¶
IsFileURI reports whether the URI has the file:// scheme. Used to gate the analyze pipeline — non-file URIs (registry://, untitled://, etc.) are virtual or read-only and don't go through any of the per-document analysis we'd run for files on disk.
func IsProtoURI ¶
IsProtoURI reports whether the URI is a .proto document we can analyze. Requires the file:// scheme in addition to the suffix: non-file URIs (registry:// schema previews, etc.) are virtual read-only views served by the schema resolver, NOT files we can run protocompile against. They never go through the analyze pipeline.
Without the scheme check this routed registry:// .proto previews into analyzeProto, which then called URI.FsPath() and panicked because a filesystem path only exists for file://.
func IsRegistryProtoURI ¶
IsRegistryProtoURI reports whether the URI is a registry:// preview of a .proto source — the read-only, lookup-backed buffers an embedder opens for schema browsing and go-to-definition landings.
These are deliberately NOT IsProtoURI: that predicate gates the diagnostics-publishing analyze pipeline, which requires a file on disk (protocompile + URI.FsPath()). Registry previews have no disk path and never validate. Hover and go-to-definition, which only need the parsed AST, do route on this predicate so a preview is navigable (goed#26).
func IsValidKeyedEntryKey ¶
IsValidKeyedEntryKey reports whether name is acceptable as a keyed entry key. Any non-empty string that fits on one line qualifies: an identifier-unsafe key is simply quoted when written. Newlines and other control characters are rejected because they can't appear in a single-line entry name even quoted.
func IsValidPxfIdentifier ¶
IsValidPxfIdentifier validates the new name passed to a rename request against the PXF identifier grammar (letter / underscore start, alnum / underscore body). Rejecting at the server side surfaces a clear error in the editor rather than producing edits the parser will then reject.
func MessageText ¶ added in v0.24.0
func MessageText(m protocol.InlayHintTooltip) string
MessageText returns a diagnostic message as text, whichever form it takes on the wire.
func ParseRegistryURI ¶
ParseRegistryURI extracts (namespace, filePath) from a `registry://<namespace>/<path>` URI. Returns ok=false for any URI not matching the expected shape — including URIs of other schemes the dispatcher might receive.
func PxfPosToLSP ¶
PxfPosToLSP converts a pxf.Position (1-indexed line and column — standard parser convention) to a protocol.Position (0-indexed, LSP convention). Defensive clamps for zero or negative values from synthetic positions (e.g. errors lacking a real source location) land at the start of the document.
func RedactChangeMap ¶
func RedactChangeMap(changes map[string]ConfigValue) map[string]ConfigValue
RedactChangeMap returns a copy of changes with sensitive-named section values replaced by redact.Placeholder. Source + Origin are preserved so editors still know WHERE the change came from. revealSecrets has no meaning for notifications — the editor that wants the real value calls getEffectiveConfig with revealSecrets=true on demand.
func SectionsOf ¶
SectionsOf returns the sorted keys of an overrides map. Sorting keeps validation errors + iteration order deterministic.
func SemanticTokensLegend ¶
func SemanticTokensLegend() protocol.SemanticTokensLegend
SemanticTokensLegend exposes the legend the server publishes at initialize. Public so tests can assert the on-wire indices stay aligned with the stMacro / stNamespace / ... constants above.
func URIToFilePath ¶
URIToFilePath converts an LSP URI to a filesystem path. Returns (path, true) for file:// URIs; (zero, false) for any other scheme (non-file editors, remote workspaces) or a parse error.
Unifies what used to be three near-identical helpers (workspaceRootPath, documentFilePath, watchedURIToPath) — they all did `url.Parse + Scheme=="file" + .Path`. One signature covers all three because `uri.URI` is a type alias for `uri.URI` (per go.lsp.dev/protocol).
Non-file workspace roots are out of scope per the W1 design (see workspace-config.md §Subtleties on remote workspaces); callers should treat the (false) return as "no local path available; degrade gracefully."
func ValidateOverrides ¶
ValidateOverrides walks the requested map and rejects unknown sections + type mismatches. Wraps both into one error message so editors get a single InvalidParams response with the full list of problems. nil / null values pass type validation (they signal "clear" and bypass the type check).
Types ¶
type ChainStatusEnvironment ¶
type ChainStatusEnvironment struct {
Name string `json:"name"`
Ancestors []string `json:"ancestors"`
// KeyName mirrors chain.Environment.KeyName — the name of
// the entry in a sops PXF AgeKeyFile whose recipient is used
// when encrypting this environment's layers. Empty when the
// chain spec doesn't set it (the common case; the encrypt
// path falls back to the key file's default recipient).
KeyName string `json:"keyName,omitempty"`
}
ChainStatusEnvironment is one environment entry in the result.
type ChainStatusError ¶
type ChainStatusError struct {
Message string `json:"message"`
Line int `json:"line,omitempty"`
Column int `json:"column,omitempty"`
}
ChainStatusError surfaces a load- or expansion-time diagnostic from the chain spec. Line/Column are zero when the issue isn't tied to a specific token (e.g. an ancestry cycle).
type ChainStatusParams ¶
type ChainStatusParams struct{}
ChainStatusParams is the (empty) request shape. Chain status is workspace-scoped — no per-document context to pass. Kept as an explicit type so future fields (e.g. environment selector) can land without breaking clients.
type ChainStatusResult ¶
type ChainStatusResult struct {
Configured bool `json:"configured"`
ChainSpecPath string `json:"chainSpecPath,omitempty"`
Environments []ChainStatusEnvironment `json:"environments"`
SchemaFQN string `json:"schemaFQN,omitempty"`
Errors []ChainStatusError `json:"errors"`
Version string `json:"version,omitempty"`
DefaultEnvironment string `json:"defaultEnvironment,omitempty"`
// ActiveEnvironment is the session-scoped env the user picked via
// SetActiveEnv. Falls back to DefaultEnvironment when no override
// is set — the response always carries a concrete env name when
// the chain is configured, so editors don't have to model the
// "unset" case themselves.
ActiveEnvironment string `json:"activeEnvironment,omitempty"`
}
ChainStatusResult mirrors the design doc's chameleon-integration.md §"Request: protolsp/chainStatus" shape, extended with Version + DefaultEnvironment so the editor can surface "chain spec vX, default=Y" without a second call.
type ClientCapabilities ¶
type ClientCapabilities struct {
// WorkspaceConfiguration: client implements workspace/configuration.
// When false, the server doesn't pull; the initializationOptions
// seed sticks for the session.
WorkspaceConfiguration bool
// DidChangeConfigurationDynamic: client supports dynamic
// registration of workspace/didChangeConfiguration via
// client/registerCapability. When true we register and react to
// notifications; when false we still accept the notification if
// the client sends it unsolicited (most clients do).
DidChangeConfigurationDynamic bool
// DidChangeWatchedFilesDynamic: client supports dynamic
// registration of workspace/didChangeWatchedFiles via
// client/registerCapability. When false the server can't ask the
// client to watch files at all — config / chain reloads then
// require an LSP restart. W5 of workspace-config; degrades
// gracefully on clients that don't support it.
DidChangeWatchedFilesDynamic bool
}
ClientCapabilities captures the subset of LSP client capabilities protolsp's configuration plumbing cares about. Populated at initialize time and consulted in initialized + on every change.
We intentionally don't track every flag — only the ones that gate our own behavior. Adding more later is a one-line change to read the flag plus the code path that uses it.
func ReadClientCapabilities ¶
func ReadClientCapabilities(p *protocol.InitializeParams) ClientCapabilities
ReadClientCapabilities translates the relevant subset of InitializeParams.Capabilities into our internal struct.
type ConfigAttribute ¶
type ConfigAttribute struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
Description string `json:"description"`
Kind string `json:"kind"`
}
ConfigAttribute describes one settable attribute in a configList response. Kind values are stable across releases: "string", "string[]", "bool" — the client uses them to pick an input widget. displayName is the human-friendly label clients should render next to that widget.
type ConfigGetParams ¶
type ConfigGetParams struct {
WorkspaceDir string `json:"workspaceDir,omitempty"`
Name string `json:"name"`
}
ConfigGetParams is the request shape for MethodConfigGet. WorkspaceDir is optional; empty selects the root workspace.
type ConfigGetResult ¶
type ConfigGetResult struct {
Name string `json:"name"`
Kind string `json:"kind"`
Value any `json:"value"`
Present bool `json:"present"`
}
ConfigGetResult is the response shape for MethodConfigGet. Value is the literal JSON encoding of the attribute's stored value: a string, []string, or bool. Present=false when the attribute is not set in the file — Value is the zero value for its Kind in that case, so clients can blind-render without an extra nil check.
type ConfigListResult ¶
type ConfigListResult struct {
Attributes []ConfigAttribute `json:"attributes"`
}
ConfigListResult is the response shape for MethodConfigList. Attributes appear in the canonical declaration order from workspaceconfig.AttributeRegistry, which UIs render top-to-bottom.
type ConfigSetParams ¶
type ConfigSetParams struct {
WorkspaceDir string `json:"workspaceDir,omitempty"`
Name string `json:"name"`
Value json.RawMessage `json:"value"`
}
ConfigSetParams is the request shape for MethodConfigSet. Value's JSON type must match the attribute's Kind (string, list of strings, or bool). RawMessage lets us decode lazily against the kind we look up in the registry.
type ConfigSetResult ¶
type ConfigSetResult struct {
OK bool `json:"ok"`
}
ConfigSetResult is the response shape for MethodConfigSet. OK=true means the file was rewritten and the reload cascade fired. Errors flow through the JSON-RPC error channel, not as a false OK — the bool is here for client ergonomics.
type ConfigSource ¶
type ConfigSource string
ConfigSource names a tier in the four-tier model. JSON strings match the design doc.
const ( SourceDefault ConfigSource = "default" SourceFile ConfigSource = "file" SourceSettings ConfigSource = "settings" SourceOverride ConfigSource = "override" )
type ConfigState ¶
type ConfigState struct {
// EditorConfig is the merged Tier 3 view of editor-supplied
// settings. Seeded from InitializeParams.InitializationOptions;
// replaced / refined by workspace/configuration pulls. Drives
// schema-lookup rebuilds when registry-related fields change
// mid-session.
EditorConfig EditorConfig
// contains filtered or unexported fields
}
ConfigState owns the Tier 3 editor-settings, the Tier 4 session-override map, and the per-session client-capability snapshot. Constructed once at server construction time; the zero value is NOT usable — use newConfigState.
Concurrency:
- configMu (RWMutex) guards EditorConfig + seededRegistryFromInitOptions. Readers RLock; writers Lock.
- overridesMu (Mutex) guards the overrides map. Held across the dispatchSetOverrides snapshot→apply→snapshot window so concurrent readers can't see a half-applied state across multi-section calls (C5 of the audit roadmap).
- clientCaps is set once at initialize before any concurrent handler can race with it; no mutex needed.
Lock-order: configMu before overridesMu (overrides resolution reads EditorConfig as a fallback); never both held at once today, but documenting the order in case a future composite op needs both.
func (*ConfigState) LockOverrides ¶
func (c *ConfigState) LockOverrides()
LockOverrides / UnlockOverrides expose the Tier 4 overrides mutex so the dispatch/RPC setOverrides paths outside this package can hold it across their snapshot → ApplyOverridesLocked → snapshot window (C5 of the audit roadmap).
func (*ConfigState) SetSeededFromInitOptions ¶
func (c *ConfigState) SetSeededFromInitOptions(v bool)
SetSeededFromInitOptions writes the flag under the write lock. Called once from configureSchemaLookup; goes through the lock so the race detector doesn't flag the unguarded initial assignment on later reads.
func (*ConfigState) SnapshotEditorConfig ¶
func (c *ConfigState) SnapshotEditorConfig() EditorConfig
SnapshotEditorConfig returns a value-typed copy of the current editor-config snapshot.
func (*ConfigState) SnapshotSeededFromInitOptions ¶
func (c *ConfigState) SnapshotSeededFromInitOptions() bool
SnapshotSeededFromInitOptions reads the deprecation-nudge flag under the RLock.
func (*ConfigState) SwapEditorConfig ¶
func (c *ConfigState) SwapEditorConfig(cfg EditorConfig) EditorConfig
SwapEditorConfig replaces EditorConfig atomically and returns the prior value. applyEditorConfig uses the returned value to decide whether the registry-defining fields changed (and thus whether to schedule a rebuild).
func (*ConfigState) UnlockOverrides ¶
func (c *ConfigState) UnlockOverrides()
type ConfigValue ¶
type ConfigValue struct {
Value any `json:"value"`
Source ConfigSource `json:"source"`
Origin string `json:"origin,omitempty"`
}
ConfigValue is the per-section payload in getEffectiveConfig responses. Value is the resolved value (typed per the section); Source names which tier contributed it. Origin is a short human-readable hint — the originating section name for file / settings, or "session" for an override.
type DatasetRegion ¶
type DatasetRegion struct {
Range protocol.Range `json:"range"`
TypeFQN string `json:"typeFQN"`
Resolvable bool `json:"resolvable"`
RowCount int `json:"rowCount"` // -1 when parse hasn't determined it
ByteSize int `json:"byteSize"`
Huge bool `json:"huge"`
}
DatasetRegion captures one @dataset block found by the line-based scanner. Range covers the `@dataset` directive line through the closing `}` (or end-of-document for unclosed blocks). TypeFQN is the token after `@dataset` on the directive line, or "" when there is none. Resolvable and RowCount stay zero / -1 until the AST pass fills them in. Resolvable is true when the row type is known, so a region bound to an anonymous @proto has an empty TypeFQN and is Resolvable: that type's name is protolsp's own, and it is not sent.
func DetectDatasetRegions ¶
func DetectDatasetRegions(source []byte, hugeThresholdBytes int, enc positions.Encoding) []DatasetRegion
DetectDatasetRegions runs the line-based scanner against the document's source and returns the list of regions found. hugeThresholdBytes governs the Huge flag; pass 0 to use the default. Pure function — no Document mutation here; the caller stores the result on doc.DatasetRegions. enc controls how Range positions in the returned regions encode their Character component (UTF-16 code units vs UTF-8 byte offsets). The negotiated value flows from Server.positionEncoding.
type DatasetRegionsChangedParams ¶
type DatasetRegionsChangedParams struct {
TextDocument protocol.TextDocumentIdentifier `json:"textDocument"`
Version int32 `json:"version"`
Regions []DatasetRegion `json:"regions"`
}
DatasetRegionsChangedParams is the notification shape. Mirrors SecretRangesChangedParams so editor implementations can share notification-handling code between the two.
type DatasetRegionsParams ¶
type DatasetRegionsParams struct {
TextDocument protocol.TextDocumentIdentifier `json:"textDocument"`
}
DatasetRegionsParams is the request shape for MethodDatasetRegions.
type DatasetRegionsResult ¶
type DatasetRegionsResult struct {
Regions []DatasetRegion `json:"regions"`
}
DatasetRegionsResult is the response shape. Always returns an empty (non-nil) slice when no regions are present — LSP convention: empty array, not null.
type DeclaredNames ¶
type DeclaredNames struct {
// Annotations are declared annotation names, matched against
// @name use sites (without the leading @).
Annotations []string
// Types are declared type names: RFC-001 `type` aliases plus
// top-level messages, enums, and proto2 groups — the same type
// namespace the reference resolvers search.
Types []string
// Functions are declared `function` names.
Functions []string
}
DeclaredNames is the workspace's declared RFC-001 name sets: annotation, type, and function names some file in the workspace declares. Field shape mirrors the editor-side consumer (x/editor's DeclaredNames), so hosts convert field-for-field.
Each declaration contributes its bare name and, when the declaring file has a package, the package-qualified form ("pkg.name") — dotted use sites like `@acme.demo.v1.audited` match against the qualified entry. The sets are workspace-level and advisory: a line-based highlighter can't check import edges or lexical scope, so a bare entry blesses use sites in every file, not only those whose package (or imports) would bind it.
Slices are sorted and duplicate-free; empty sets are nil.
type Document ¶
type Document struct {
URI uri.URI
Version int32
Source []byte
// Parsed is the result of pxf.Parse(Source), or nil when the source
// failed to parse. ParseErr captures the parser error in that case;
// at most one of Parsed / ParseErr is meaningful at a time.
Parsed *pxf.Document
ParseErr error
// LastGoodParse is the most recent AST that parsed successfully.
// Falls in when Parsed is nil so completion (and any other AST-
// aware feature) keeps working through transient mid-edit parse
// failures — typing `field = ` produces a single broken line, but
// the structure of the rest of the document is unchanged.
LastGoodParse *pxf.Document
// SchemaErr captures errors from pxf.UnmarshalDescriptor that
// aren't per-field findings — type mismatches, missing-required,
// oneof violations. Unknown-field errors are suppressed via
// DiscardUnknown and reported through UnknownFields instead so
// each occurrence gets its own diagnostic.
SchemaErr error
// UnknownFields and deprecatedUses are AST-walk findings the
// validate() pass produces alongside SchemaErr. Each entry is one
// field assignment in the source that names something the bound
// message doesn't know (UnknownFields) or names a field marked
// `[deprecated = true]` (deprecatedUses). diagnosticsFor turns
// these into LSP diagnostics; the code-action handler reads
// UnknownFields back via Diagnostic.Data to offer "Remove field"
// quick fixes.
UnknownFields []fieldFinding
// SecretRanges records every pxf.Secret-typed value assignment
// in the source. Public, no value bytes — safe for the
// protolsp/secretRanges custom request (S2) and for the editor
// to consume directly. The corresponding plaintext lives in
// secretValues below, private to the server.
SecretRanges []SecretRange
// DatasetRegions records every @dataset block detected in the
// source. Populated by analyze via the line-based scanner
// from the dataset-regions design (R1). Surfaces to editors
// through the protolsp/datasetRegions custom request.
DatasetRegions []DatasetRegion
// LayerInfo caches the result of matching this document against
// the workspace's chameleon chain (C2 of chameleon-integration).
// Computed once at didOpen — the URI doesn't change, the chain
// is workspace-scoped, and the result depends only on those two.
// nil means "not computed yet" (no didOpen has run); a non-nil
// pointer with IsLayer=false means "computed, file is not a
// layer". The protolsp/layerInfo request reads this directly.
LayerInfo *LayerInfoResult
// ProtoDiagnostics is populated for .proto documents by
// analyzeProto — single-file protocompile compile errors
// translated to LSP diagnostics. Replaces the entire diagnostic
// set for .proto docs (the pxf-specific UnknownFields /
// deprecatedUses / SchemaErr fields are all nil for proto docs).
// Empty / nil for .pxf documents.
ProtoDiagnostics []protocol.Diagnostic
// contains filtered or unexported fields
}
Document is the in-memory state for one open .pxf file. M2 stores the parse result alongside source bytes so subsequent handlers (M4 hover, future completion) don't have to re-parse on every request.
Concurrency: mu guards every field below except URI (immutable post-construction) and workspaceDir (self-synchronized — see the field comment). analyze takes mu.Lock for its duration; handlers RLock for the duration of any read of a guarded field. The analyzeTimer / analyzeMu pair stays separate so timer scheduling doesn't serialize all reads.
func (*Document) Lock ¶
func (d *Document) Lock()
Lock / Unlock / RLock / RUnlock expose the Document's state mutex to callers outside the analysis package (the LSP dispatch shell snapshots Source/Analysis under it; tests inspect state through it). Same lock the analyze pipeline takes — lock order remains Documents.mu before Document.mu.
func (*Document) SecretValues ¶
SecretValues returns a copy of the private plaintext slice the redact package consumes. Defensive copy so callers can't poke at the server's internal state. Used by the diagnostic / hover / code-action emit paths to redact secret bytes before sending to the client.
Takes doc.mu.RLock. For callers that already hold the lock (publishDiagnostics, the handler RLock pattern), use secretValuesLocked to avoid the unsafe recursive RLock.
func (*Document) SetWorkspaceDir ¶
SetWorkspaceDir installs the doc → workspace-directory mapping. Production discovery goes through EnsureWorkspaceForDoc; exported for embedders and tests that construct Documents with a known mapping. Concurrent callers are last-writer-wins — discovery is deterministic for a given on-disk config layout, so racing writers carry the same value (or a fresher one when a config file just appeared).
func (*Document) SnapshotForPipeline ¶
func (d *Document) SnapshotForPipeline() (version int32, secrets []SecretRange, datasets []DatasetRegion)
SnapshotForPipeline returns the version / secret-ranges / dataset-regions triple that runAnalyzePipeline feeds into notification helpers AFTER analyze has run. Defensive copies for the slices so notify callsites can compare against the prior snapshot without holding the lock.
func (*Document) WorkspaceDir ¶
WorkspaceDir returns the absolute path of the directory holding this document's nearest-ancestor `.protolsp.pxf`, or "" when discovery hasn't found one yet (the next EnsureWorkspaceForDoc call re-attempts). May equal the LSP workspace root — the root workspace's state lives on Workspace directly.
Safe to call from any lock context: the backing field is atomic, not doc.mu-guarded (see the field comment).
type Documents ¶
type Documents struct {
// contains filtered or unexported fields
}
Documents is a thread-safe map of URI → Document. The LSP handler holds a single instance and mutates it from didOpen/didChange/didClose.
func (*Documents) Close ¶
Close removes a document from the store. Returns false if it was not open.
func (*Documents) Get ¶
Get returns the document for a URI, or nil if not open. The returned pointer is safe to read but not to mutate concurrently with Update.
func (*Documents) Open ¶
Open adds a document to the store, replacing any existing entry for the same URI. Used by textDocument/didOpen.
func (*Documents) Update ¶
Update replaces an existing document's source and bumps its version. Returns false if the URI was not previously opened.
Lock-order: takes Documents.mu briefly to find the doc, then Document.mu to write. Concurrent reads of other documents (via Get) aren't blocked by an in-flight Update.
type EditorConfig ¶
type EditorConfig struct {
Registry schema.Config
// InlineSecrets is the Tier 3 view of the security
// inline-secrets policy from the secret-handling design (S4).
// Empty when the editor hasn't supplied a value; lower tiers
// (file, default) take over via ResolveSection.
InlineSecrets string
}
EditorConfig is the per-session view of Tier 3 settings the server consumes. Mirrors schema.Config plus any non-registry fields (security policy, future log-level overrides). Values are merged from initializationOptions and workspace/configuration pulls.
type EffectiveConfigChangedParams ¶
type EffectiveConfigChangedParams struct {
WorkspaceDir string `json:"workspaceDir"`
Changes map[string]ConfigValue `json:"changes"`
}
EffectiveConfigChangedParams is the notification shape. Changes contains only sections whose effective value actually shifted — editors render status-bar / sidebar updates from this map.
type EngineConfigResult ¶
type EngineConfigResult struct {
// Configured reports whether any configuration file was resolved
// (discovered, named by PROTOWIRE_CONFIG, or explicit). False
// means Engine/DefaultMode/… are the built-in defaults.
Configured bool `json:"configured"`
// Path is the resolved configuration file; empty on defaults.
Path string `json:"path,omitempty"`
// Source names the winning precedence tier: "defaults",
// "discovered", "env", or "flag".
Source string `json:"source"`
// Error carries the loader's message when resolution failed (an
// unreadable or unparseable file, an invalid execution mode —
// hard errors per §9.4, never silently defaulted). The other
// fields are zero when set.
Error string `json:"error,omitempty"`
// Engine is whatever a configuration source set, and empty
// otherwise: RFC-001 §9.4 reserved the field (protowire#282, the
// expression language is fixed by §5.4), so there is no default.
Engine string `json:"engine,omitempty"`
FunctionLibraries []string `json:"functionLibraries,omitempty"`
CatalogLibraries []string `json:"catalogLibraries,omitempty"`
DefaultMode string `json:"defaultMode,omitempty"`
MaxRecursionDepth uint32 `json:"maxRecursionDepth,omitempty"`
StrictValidation bool `json:"strictValidation,omitempty"`
}
EngineConfigResult is the response shape for MethodEngineConfig: the effective configuration after every §9.4 precedence tier, plus where it came from. Mirrors engineconfig.Config field-for-field with enums rendered as their canonical strings.
type GetEffectiveConfigParams ¶
type GetEffectiveConfigParams struct {
WorkspaceDir string `json:"workspaceDir,omitempty"`
Sections []string `json:"sections,omitempty"`
RevealSecrets bool `json:"revealSecrets,omitempty"`
}
GetEffectiveConfigParams is the request shape. workspaceDir is reserved for multi-root support (W4 of workspace-config); CP2 ignores it. sections lets clients narrow the response to a subset; empty means "all known sections."
revealSecrets opts out of the default name-pattern redaction — editors that want to display real token / password / secret values (typically behind an explicit user action) pass true.
type GetEffectiveConfigResult ¶
type GetEffectiveConfigResult struct {
WorkspaceDir string `json:"workspaceDir"`
Values map[string]ConfigValue `json:"values"`
}
GetEffectiveConfigResult is the response shape. Values is keyed by section name. workspaceDir echoes the requested scope (empty for ambient until W4 lands).
type IncrementalChange ¶
type IncrementalChange struct {
Range *ProtocolRangeShape `json:"range,omitempty"`
Text string `json:"text"`
}
IncrementalChange mirrors LSP's TextDocumentContentChangeEvent but uses *Range so we can tell "range omitted" (full-document replacement) from "range at origin" (incremental edit at line 0:col 0) from the JSON alone, without the union decoding of the upstream protocol type.
Text is the replacement bytes (or the full document when Range is nil).
func UnmarshalIncrementalChanges ¶
func UnmarshalIncrementalChanges(raw json.RawMessage) ([]IncrementalChange, error)
UnmarshalIncrementalChanges parses the contentChanges array from a didChange notification's params. We unmarshal via the local IncrementalChange type (which uses *Range) so we can distinguish full-document events from incremental ones.
type LayerInfoParams ¶
type LayerInfoParams struct {
TextDocument protocol.TextDocumentIdentifier `json:"textDocument"`
}
LayerInfoParams is the request shape: which document to classify.
type LayerInfoResult ¶
type LayerInfoResult struct {
IsLayer bool `json:"isLayer"`
Environment string `json:"environment,omitempty"`
Ancestors []string `json:"ancestors,omitempty"`
Strategy string `json:"strategy,omitempty"`
Source string `json:"source,omitempty"`
Encrypted bool `json:"encrypted"`
}
LayerInfoResult mirrors the design doc's shape. Optional fields (environment, ancestors, strategy, source) are empty / nil when isLayer is false — the JSON tag uses ",omitempty" so the wire payload stays clean.
Encrypted is non-optional: it carries useful signal even on non-layer files (always false) and editors don't need to special- case "field absent" vs "field set to false".
type ListMessagesParams ¶
type ListMessagesParams struct {
Prefix string `json:"prefix,omitempty"`
}
ListMessagesParams is the request shape for MethodListMessages. Prefix is an optional filter — when non-empty, only message types whose FQN starts with it are returned. Useful for client-side search-as-you-type without re-fetching the full list each keystroke.
type ListMessagesResult ¶
type ListMessagesResult struct {
Messages []MessageEntry `json:"messages"`
}
ListMessagesResult is the response shape for MethodListMessages. Entries are sorted by FullName for deterministic UI rendering and deduped — RangeMessages can yield the same FQN twice when a child namespace re-exports a parent's type, but clients only want it once.
type LiteralSecretData ¶
LiteralSecretData is the JSON shape of Diagnostic.Data for literal-secret warnings. FieldPath drives the env-var name derivation in the quick fix. The Range comes back via Diagnostic.Range; no need to duplicate it here.
func DecodeLiteralSecretData ¶
func DecodeLiteralSecretData(v interface{}) *LiteralSecretData
DecodeLiteralSecretData turns a Diagnostic.Data round-tripped through the LSP client back into the typed payload. Same shape as DecodeUnknownFieldData — handles the typed struct (in-process tests) and the map[string]any form (real JSON-RPC clients).
type LookupManager ¶
type LookupManager struct {
// contains filtered or unexported fields
}
LookupManager owns the user-registry-backed schema.Lookup plus the rebuild-coalescing state. Constructed once at server construction time; the zero value is NOT usable — use newLookupManager.
Concurrency:
- lookupMu guards lookup + lookupCloser. Snapshot / Swap take it; readers RLock briefly, writers Lock.
- rebuildMu guards lastRebuiltCfg + rebuildCancel. Distinct from lookupMu so the rebuild scheduler doesn't contend with hot-path lookup reads.
- Lock-order between the two: never both at the same time. Snapshot/Swap don't touch rebuildMu; BeginRebuild doesn't touch lookupMu (the actual install happens via a separate Swap call from the goroutine the caller spawned).
func (*LookupManager) BeginRebuild ¶
BeginRebuild atomically decides whether a rebuild is needed for cfg and prepares its cancellation context. Returns (nil, false) when cfg equals the last-built baseline — the caller skips the rebuild entirely. Otherwise updates the baseline, cancels any in-flight rebuild's context, allocates a fresh cancel for the new attempt, and returns (newCtx, true).
The empty-Address path is the caller's concern: BeginRebuild still returns (ctx, true) so the caller can do its synchronous-teardown branch (close the old closer; don't dial). The cancel side-effect on prior rebuilds is the shared part.
func (*LookupManager) CancelInFlight ¶
func (m *LookupManager) CancelInFlight()
CancelInFlight cancels the in-flight rebuild's context (if any) and clears the stored cancel. Used at shutdown so the goroutine doesn't try to install into a torn-down server.
func (*LookupManager) Close ¶
func (m *LookupManager) Close() error
Close cancels any in-flight rebuild + closes both the registry- backed and proto_files-backed lookups. Returns the first non-nil close error (registry's takes precedence; proto_files' closer is a no-op today so the order rarely matters in practice). Server.Close cascades here.
func (*LookupManager) RecordBaseline ¶
func (m *LookupManager) RecordBaseline(cfg schema.Config)
RecordBaseline records cfg as the last successfully-installed rebuild baseline WITHOUT firing a rebuild. Used after the synchronous initial install in configureSchemaLookup so the next async rebuild's diff check sees the right baseline and skips redundant dials.
func (*LookupManager) Snapshot ¶
func (m *LookupManager) Snapshot() schema.Lookup
Snapshot returns the current lookup (may be nil). Concurrent- safe; callers can hold the returned interface without re- locking — schema.Lookup implementations are documented as concurrent-safe internally.
W2 fork: when no registry lookup is installed but a proto_files lookup is, return the proto_files one. W3 will compose the two at construction time; today's caller gets the source that's actually configured.
func (*LookupManager) SnapshotProtoFiles ¶
func (m *LookupManager) SnapshotProtoFiles() schema.Lookup
SnapshotProtoFiles returns the W2 proto_files-backed lookup, or nil when none is configured. Exposed separately from Snapshot so W3's composition path can read it without going through the W2 fallback ordering.
func (*LookupManager) Swap ¶
Swap installs newLookup + newCloser as the current lookup state and returns the prior closer for the caller to close outside the lock. Closing the old resolver inside the lock would risk a deadlock if the close ever called back into the server's handlers.
An actual install or teardown fires onChanged after the mutation (still before the caller closes the returned oldCloser — by then the old lookup is already unreachable via Snapshot, so a callback re-reading state sees only the new one).
type MessageEntry ¶
type MessageEntry struct {
FullName string `json:"fullName"`
File string `json:"file"`
Namespace string `json:"namespace,omitempty"`
}
MessageEntry describes one message type in a ListMessages response. Namespace is the registry namespace that contributed the type (per FindFileByPathWithOrigin) — empty when the type came from an ad-hoc parent whose identity isn't tracked.
type NopPublisher ¶
type NopPublisher struct{}
NopPublisher discards every push. It is the Publisher New installs so the analyze pipeline can always call s.pub without nil checks; real consumers replace it via SetPublisher.
func (NopPublisher) DatasetRegionsChanged ¶
func (NopPublisher) DatasetRegionsChanged(context.Context, uri.URI, int32, []DatasetRegion)
func (NopPublisher) EffectiveConfigChanged ¶
func (NopPublisher) EffectiveConfigChanged(context.Context, string, map[string]ConfigValue)
func (NopPublisher) LookupChanged ¶
func (NopPublisher) LookupChanged(context.Context, string)
func (NopPublisher) PublishDiagnostics ¶
func (NopPublisher) PublishDiagnostics(context.Context, uri.URI, uint32, []protocol.Diagnostic)
func (NopPublisher) SecretRangesChanged ¶
func (NopPublisher) SecretRangesChanged(context.Context, uri.URI, int32, []SecretRange)
func (NopPublisher) ShowMessage ¶
func (NopPublisher) ShowMessage(context.Context, protocol.MessageType, string)
type PositionShape ¶
type ProtocolRangeShape ¶
type ProtocolRangeShape struct {
Start PositionShape `json:"start"`
End PositionShape `json:"end"`
}
ProtocolRangeShape mirrors protocol.Range purely so its zero value isn't ambiguous with "absent". We can't use protocol.Range directly here because it's a struct (zero-valued when absent is indistinguishable from zero-valued when present); via this local alias we use a pointer.
type Publisher ¶
type Publisher interface {
// PublishDiagnostics delivers the full diagnostics set for one
// document (empty slice clears). Secrets are already scrubbed.
PublishDiagnostics(ctx context.Context, docURI uri.URI, version uint32, diags []protocol.Diagnostic)
// ShowMessage surfaces a user-facing notice (stale schema,
// truncated references walk, deprecation nudges).
ShowMessage(ctx context.Context, typ protocol.MessageType, message string)
// SecretRangesChanged fires when a re-analyze produced a
// different pxf.Secret range table for the document.
SecretRangesChanged(ctx context.Context, docURI uri.URI, version int32, ranges []SecretRange)
// DatasetRegionsChanged fires when a re-analyze produced a
// different @dataset region table for the document.
DatasetRegionsChanged(ctx context.Context, docURI uri.URI, version int32, regions []DatasetRegion)
// EffectiveConfigChanged fires when a setOverrides call (LSP or
// RPC) changed any effective config value. Values in changes are
// pre-redacted for sensitive sections.
EffectiveConfigChanged(ctx context.Context, workspaceDir string, changes map[string]ConfigValue)
// LookupChanged fires after a schema-lookup install or teardown
// completes — async rebuild install, proto_files rebuild,
// config-cleared teardown, shutdown Close — and after a rebuild
// dial fails. On the failed-dial path the observable state is
// unchanged (the previous lookup stays installed), so unlike the
// *Changed methods above this can fire without a snapshot
// difference: it means "a lookup transition finished; status
// surfaces should re-read RegistryStatus / Snapshot / the
// per-doc LookupForDoc". workspaceDir identifies whose lookup
// transitioned: "" for the root workspace's (the
// Lookups()/RegistryStatus surface), the sub-workspace directory
// for a per-workspace lookup — consumers with
// per-workspace surfaces refresh selectively on it. No further
// payload, deliberately: it is a refresh signal, not a state
// delta. Fires on the mutating goroutine (rebuild-dial and
// watched-files debounce goroutines included); embedders
// replacing a poll loop must not block in it.
LookupChanged(ctx context.Context, workspaceDir string)
}
Publisher receives every server→client push the analysis pipeline produces. It is the seam between the engine (analyze, validate, secret/dataset detection, effective-config resolution) and the transports that deliver results:
- the LSP + Connect-RPC server installs serverPublisher, which fans out to jsonrpc2 notifications (gated per legacy client) and to the sidecar's Subscribe streams;
- in-process embedders (goed) install their own implementation and receive direct callbacks — no transport.
Contract notes:
- Calls are best-effort fire-and-forget: implementations must not return errors and must not block the analyze pipeline on slow consumers (the RPC fan-out uses non-blocking buffered channels for exactly this reason).
- Change detection has already happened: the engine only calls the *Changed methods when the new snapshot differs from the previous one.
- EffectiveConfigChanged receives changes with sensitive sections already redacted (same shape both wire transports historically sent); unredacted values are only reachable via the pull path's explicit revealSecrets flag.
- Slices and maps are shared with engine state snapshots; implementations must not mutate them.
type RegistryStatusResult ¶
RegistryStatusResult is the response shape for MethodRegistryStatus.
type RenameTargetKind ¶
type RenameTargetKind int
RenameTargetKind classifies what a rename request at a position would affect, so the dispatch layer can validate the new name against the right grammar: an ordinary field/block path needs a PXF identifier; a keyed entry accepts any non-empty single-line key (quoted when it isn't identifier-safe).
const ( // RenameTargetNone: the cursor isn't on anything renameable. RenameTargetNone RenameTargetKind = iota // RenameTargetField: an ordinary field or block whose dotted path // the path-based rename rewrites across the workspace. RenameTargetField // RenameTargetKeyedEntry: a keyed repeated field's entry name. RenameTargetKeyedEntry )
type RuntimeSourceRef ¶
type RuntimeSourceRef struct {
File string `json:"file,omitempty"`
DescriptorPath string `json:"descriptorPath"`
}
RuntimeSourceRef mirrors protowire.schema.v1.SourceRef: the originating SourceMap.file plus the canonical §8.3.1 descriptor path. File is the artifact's module-relative path (as the compiler recorded it), while protolsp compiles open documents under their absolute filenames — so File matches when it equals the document's source-map file or is a path-boundary suffix of it. A File that matches neither drops the violation from the publish (a key for a different file must not resolve against this document's ordinals). Empty File imposes no constraint beyond the notification's textDocument scoping.
type RuntimeViolation ¶
type RuntimeViolation struct {
DescriptorPath string `json:"descriptorPath,omitempty"`
Message string `json:"message"`
ForKey bool `json:"forKey,omitempty"`
SourceRef *RuntimeSourceRef `json:"sourceRef,omitempty"`
}
RuntimeViolation is one runtime-reported constraint violation. The file half of the RFC-001 (file, descriptor_path) key is the notification's textDocument URI; DescriptorPath is the other half, verbatim as the runtime emitted it (e.g. "t.M[t.check#0]/arg#0/call#0").
SourceRef and ForKey mirror the protowire.schema.v1 EnrichedViolation fields of the same names (report.proto, vendored in protocompile v0.20.0), so a producer forwarding Report violations passes them through without re-keying:
- When SourceRef is set, its DescriptorPath is the join key and the top-level DescriptorPath is ignored — source_ref is the §8.3.1 rule identity, populated by engines whenever the rule resolved through an embedded source map. Its File half guards against mis-joins (see RuntimeSourceRef).
- ForKey marks a violation against a map entry's key rather than its value. Key and value violations of the same entry-level rule join to the same descriptor path and anchor, so the flag is surfaced in the rendered message instead.
type SecretForm ¶
type SecretForm int
SecretForm names the two PXF surface forms a pxf.Secret value can take. Per protowire-go's wellknown.go: scalar shorthand `pw = "x"` and block form `pw { value = "x"; hint = "..." }`.
const ( // SecretFormScalar is `pw = "x"` — scalar shorthand sugar for // the inner `value` field. Range covers the string literal. SecretFormScalar SecretForm = iota // SecretFormBlock is `pw { value = "x"; hint = "..." }`. Range // covers the inner `value = ...` line; hint and fingerprint // are non-sensitive by design and stay un-redacted. SecretFormBlock )
type SecretRange ¶
type SecretRange struct {
// Range covers the value token (scalar form) or the
// `value = "..."` assignment line inside a block form — NOT
// the field name. Editors mask exactly this range.
Range protocol.Range
// Path is the dotted field path, e.g. "credentials.password".
Path string
// Form names the surface syntax — useful for editor UI
// affordances ("Reveal" placement, etc.).
Form SecretForm
}
SecretRange records the source range of one pxf.Secret-typed value assignment. Public; surfaces to editors via the protolsp/secretRanges custom request (S2 phase).
type SecretRangeEntry ¶
type SecretRangeEntry struct {
Range protocol.Range `json:"range"`
FieldName string `json:"fieldName"`
Form string `json:"form"` // "scalar" | "block"
}
SecretRangeEntry is one element of the protocol-level response. Mirrors the in-memory SecretRange but uses string literals for the form field so the wire payload is self-describing without the client needing to know our int enum.
func ToSecretRangeEntries ¶
func ToSecretRangeEntries(ranges []SecretRange) []SecretRangeEntry
ToSecretRangeEntries converts the server-internal SecretRange slice to the wire-format SecretRangeEntry slice. Always returns a non-nil empty slice (LSP convention: empty array, not null).
type SecretRangesChangedParams ¶
type SecretRangesChangedParams struct {
TextDocument protocol.TextDocumentIdentifier `json:"textDocument"`
Version int32 `json:"version"`
Ranges []SecretRangeEntry `json:"ranges"`
}
SecretRangesChangedParams is the notification shape. Tagged with the document version so the editor can discard out-of-order notifications.
type SecretRangesParams ¶
type SecretRangesParams struct {
TextDocument protocol.TextDocumentIdentifier `json:"textDocument"`
}
SecretRangesParams is the request shape for MethodSecretRanges.
type SecretRangesResult ¶
type SecretRangesResult struct {
Ranges []SecretRangeEntry `json:"ranges"`
}
SecretRangesResult is the response shape for MethodSecretRanges.
type SetOverridesApplied ¶
type SetOverridesApplied struct {
PreviousSource ConfigSource `json:"previousSource"`
NewValue any `json:"newValue"`
}
SetOverridesApplied is one entry of the SetOverridesResult.applied map. PreviousSource lets editors render "Revert" actions that reset to the prior state without needing to know what it was.
type SetOverridesParams ¶
type SetOverridesParams struct {
WorkspaceDir string `json:"workspaceDir,omitempty"`
Overrides map[string]any `json:"overrides"`
}
SetOverridesParams is the request shape. WorkspaceDir is reserved for multi-root (W4 of workspace-config) and ignored in CP3. Overrides maps section name → new value; explicit `null` clears any existing override (lower tiers retake the section).
type SetOverridesResult ¶
type SetOverridesResult struct {
Applied map[string]SetOverridesApplied `json:"applied"`
}
SetOverridesResult is the response shape — one entry per requested override, regardless of whether the effective value actually changed (the user asked; we tell them what they got).
type SetRuntimeViolationsParams ¶
type SetRuntimeViolationsParams struct {
TextDocument protocol.TextDocumentIdentifier `json:"textDocument"`
Violations []RuntimeViolation `json:"violations"`
}
SetRuntimeViolationsParams is the notification shape for MethodSetRuntimeViolations. Violations is the document's full new overlay set (replace, not append); empty or omitted clears.
type SourceContentParams ¶
type SourceContentParams struct {
URI uri.URI `json:"uri"`
// WorkspaceDir optionally scopes the fetch to a sub-workspace's
// registry: the absolute directory of the sub-workspace
// the preview was opened from. Empty selects the root lookup —
// the earlier behavior — so callers with no multi-root context
// can omit it.
WorkspaceDir string `json:"workspaceDir,omitempty"`
}
SourceContentParams is the request shape for MethodSourceContent.
type SourceContentResult ¶
type SourceContentResult struct {
Content string `json:"content"`
}
SourceContentResult is the response shape for MethodSourceContent. Content is sent as a string (UTF-8); .proto files are text by convention and the LSP framing is JSON, so binary-safe encoding isn't required.
type UnknownFieldData ¶
type UnknownFieldData struct {
Kind string `json:"kind"`
FieldName string `json:"field_name"`
Line uint32 `json:"line"`
}
UnknownFieldData is the JSON shape of Diagnostic.Data for unknown- field diagnostics. The kind discriminator lets the code-action handler ignore unrelated diagnostics it might receive in the same request.
func DecodeUnknownFieldData ¶
func DecodeUnknownFieldData(v interface{}) *UnknownFieldData
DecodeUnknownFieldData turns a Diagnostic.Data round-tripped through the LSP client (which usually delivers it as map[string]any after JSON unmarshalling) into the typed UnknownFieldData. Returns nil when the payload isn't ours.
type UnresolvedNameData ¶
type UnresolvedNameData struct {
Kind string `json:"kind"`
// Name is the reference as written — the qualified callee of a
// call (`myco.is_emial`) or the bare identifier.
Name string `json:"name"`
// Candidates are the declared functions nearest to Name, spelled
// the way they resolve from the document (bare for same-package
// functions, fully qualified otherwise), closest first. Empty
// when nothing is close enough to suggest.
Candidates []string `json:"candidates,omitempty"`
}
UnresolvedNameData is the Diagnostic.Data payload for an unresolved name inside an engine expression.
func DecodeUnresolvedNameData ¶
func DecodeUnresolvedNameData(v interface{}) *UnresolvedNameData
DecodeUnresolvedNameData turns a Diagnostic.Data round-tripped through the LSP client into the typed UnresolvedNameData. Returns nil when the payload isn't ours.
type Workspace ¶
type Workspace struct {
// contains filtered or unexported fields
}
Workspace is the transport-free core of protolsp: the document store, schema lookup, workspace/chain/config state, and every analysis pass (parse + schema diagnostics, hover, completion, definition, code actions, secret ranges, dataset regions, effective config). It pushes results through the Publisher seam and never touches jsonrpc2 or the Connect-RPC sidecar.
The LSP Server (internal/server) embeds *Workspace, so dispatch and RPC handlers reach engine state through method promotion; in-process embedders (goed) construct one via New and drive it directly.
func New ¶
New creates a Workspace with an empty document store and a no-op Publisher. Callers that want push results (diagnostics, secret / dataset / effective-config change events) install their seam via SetPublisher before feeding documents in.
func (*Workspace) Analyze ¶
Analyze runs the full per-change pipeline against the document's current source: parse → (if @type bound and a lookup is configured) schema validation. ParseErr and SchemaErr are reset on each pass.
LastGoodParse is *not* reset on parse failure: completion and other AST-aware features fall back to it through transient mid-edit failures (typing `field = ` produces a single broken line, but the structure of the rest of the document hasn't changed).
func (*Workspace) AnalyzeCount ¶
AnalyzeCount reports completed analyze-pipeline runs (analyze + publish + notify). Tests use it to wait out a debounce window without sleeping.
func (*Workspace) ApplyOverridesLocked ¶
ApplyOverridesLocked mutates Server.overrides. Caller MUST hold overridesMu. Used by dispatchSetOverrides which takes the lock once around the snapshot→apply→snapshot window so a concurrent getEffectiveConfig can't see a half-applied state.
func (*Workspace) CancelBackground ¶
func (s *Workspace) CancelBackground()
CancelBackground stops the pending watched-files debounce timer and every pending per-document analyze timer. First half of teardown — the LSP shell calls it before stopping its RPC sidecar so no timer fires into a server that is going away, then finishes with Close.
func (*Workspace) CancelPendingAnalyze ¶
CancelPendingAnalyze stops any pending timer on the document. Called from didClose so a fired timer doesn't analyze a closed document.
func (*Workspace) ChainForDoc ¶
func (s *Workspace) ChainForDoc(doc *Document) *chain.ActiveChain
ChainForDoc returns the chain spec that applies to doc.
func (*Workspace) ChainStatusSnapshot ¶
func (s *Workspace) ChainStatusSnapshot() ChainStatusResult
ChainStatusSnapshot computes the current ChainStatusResult from the server's fileConfig + chain state. Pure function on the receiver — exposed at this seam so tests can assert against the composed shape without driving the JSON-RPC layer.
func (*Workspace) ClientCapabilities ¶
func (s *Workspace) ClientCapabilities() ClientCapabilities
ClientCapabilities returns the client-capability snapshot captured at initialize time (zero value for in-process embedders).
func (*Workspace) Close ¶
Close tears down sub-workspace lookups and the schema-lookup manager. Safe to call multiple times; safe to call when no lookup was configured. Callers that run background timers should call CancelBackground first (the LSP shell does, with its RPC-sidecar shutdown in between).
func (*Workspace) CodeActionsFor ¶
func (s *Workspace) CodeActionsFor(doc *Document, diags []protocol.Diagnostic) []protocol.CodeAction
CodeActionsFor builds the list of quick-fix CodeActions that apply to the given diagnostics. The client passes the diagnostics it considers active at the cursor; we just need to recognize ours (by Data.kind) and produce the corresponding edits.
The caller must hold doc.RLock: edits are computed against doc.Source, and the lock keeps that snapshot consistent with the diagnostics the client is acting on.
func (*Workspace) CompletionFor ¶
CompletionFor builds a CompletionList for (uri, position), or nil when no completions apply.
Three completion modes are wired:
- On an `@type` line, suggest every known message FQN from the resolver. Works without a successful parse — the line text is enough to identify the context.
- On the right-hand side of an assignment to an enum-typed field, suggest the enum's defined values.
- Otherwise, suggest field names on the message in scope at the cursor (descends into nested blocks via brace counting).
The AST-aware modes prefer the current parse but fall back to the last-good parse when the document is mid-edit and currently invalid (typing `field = ` produces a single broken line, but the rest of the AST is still meaningful).
func (*Workspace) ComputeLayerInfo ¶
func (s *Workspace) ComputeLayerInfo(docURI uri.URI) *LayerInfoResult
ComputeLayerInfo is the pure detection function shared by the didOpen warm-up and the dispatch handler's fallback path.
Returns a non-nil result; an empty / non-matching environment gives IsLayer=false. Path matching is exact against LayerInstance.ResolvedPath after computing the document's path relative to the workspace root.
Encrypted bit comes from the spec's static `encrypted = true` flag; the content-sniff for sops streams (chameleon-integration §"sops-encrypted layers") is a later refinement that lives alongside the diagnostic-skip behavior (C3+).
func (*Workspace) Config ¶
func (s *Workspace) Config() *ConfigState
Config exposes the Tier 3/4 config-state owner (editor settings, session overrides, client-capability snapshot).
func (*Workspace) ConfigDiagnostics ¶
func (s *Workspace) ConfigDiagnostics(doc *Document) []protocol.Diagnostic
ConfigDiagnostics returns the dedicated-parser diagnostics for the document. Empty when the doc isn't one of protolsp's own config files (matched by @type). Appended to diagnosticsFor's output for the workspace config + chain spec.
Severity is Warning across the board: the file still parses and loads; we're flagging things the parser found suspicious but can recover from. Source tag is "protolsp/workspaceconfig" or "protolsp/chainspec" so editors can group / color them distinctly from schema findings. proto_files compile errors (W2) surface as "protolsp/proto_files" with Error severity — they prevent schema-awareness on the affected types and deserve more attention than parser warnings.
func (*Workspace) ConfigPathForWorkspace ¶
ConfigPathForWorkspace resolves workspaceDir to the absolute `.protolsp.pxf` path for the workspace. Empty = root workspace; otherwise the dir must match a known sub-workspace (rejecting arbitrary paths protects against editor extensions accidentally targeting a workspace that protolsp isn't managing).
Errors wrap ErrNoRootWorkspace / ErrUnknownWorkspaceDir so the transport shells (JSON-RPC dispatch, Connect-RPC handlers) can map them onto their own error-code vocabularies with errors.Is.
func (*Workspace) DebounceWindow ¶
DebounceWindow reports the didChange coalescing window.
func (*Workspace) DeclaredNames ¶
func (s *Workspace) DeclaredNames() DeclaredNames
DeclaredNames returns the workspace's declared RFC-001 name sets, unioned from every source the analyze pass resolves against:
- workspace-local files in the proto index (the on-disk declaration set — BSR cache deps are excluded here so the accessor never mass-parses the module cache),
- open .proto documents' retained ASTs (keystroke-fresh: an unsaved declaration counts immediately after its analyze pass), and
- the open documents' imports — indexed imports by AST (this is where a cache-resident dep the workspace actually references enters), unindexed imports through the workspace's schema lookup via the compiled RFC-001 carrier options, mirroring resolveRFC001RemoteDecl's descriptor layer.
Hosts refresh on the analyze-completion path, same cadence as the secret-range / dataset-region payloads; the result is a snapshot and stale between passes by design.
func (*Workspace) DefinitionFor ¶
DefinitionFor computes the Location the cursor's target resolves to, or returns nil for "no definition available."
func (*Workspace) DetectLayerInfo ¶
DetectLayerInfo computes the document's classification and installs it on the Document. Called from dispatchDidOpen (before the first analyze) and from the reanalyze paths (after a chain or config reload).
Safe to call when chain is nil or workspaceRoot is empty — the result is just IsLayer=false. Takes doc.mu.Lock briefly to install the result so concurrent handler reads via doc.mu.RLock see a coherent value.
func (*Workspace) DiagnosticsFor ¶
func (s *Workspace) DiagnosticsFor(doc *Document) []protocol.Diagnostic
DiagnosticsFor maps a document's analysis state to LSP diagnostics. A parse failure suppresses schema diagnostics (the source didn't reach the validator). When parse succeeds, the list contains:
- one diagnostic per unknown field (Error severity, Data payload so the code-action handler can offer a removal quick-fix)
- one diagnostic per deprecated field use (Hint severity, Tags: [Deprecated] so editors render strikethrough)
- one diagnostic for SchemaErr if non-nil (type mismatch / missing-required / oneof violation from pxf.UnmarshalDescriptor)
The result is NOT secret-scrubbed: unlike the PublishDiagnostics path (which redacts before the Publisher sees anything), a caller pulling DiagnosticsFor directly and displaying it is responsible for redaction.
Takes the document read lock internally, like the other feature queries. Callers must NOT already hold doc.RLock — recursive RLock deadlocks against a queued writer (see PublishDiagnostics, which snapshots under one RLock window via diagnosticsForLocked instead).
func (*Workspace) DocumentSymbolsFor ¶
func (s *Workspace) DocumentSymbolsFor(docURI uri.URI) []protocol.DocumentSymbol
DocumentSymbolsFor builds the symbol tree for a document. Returns nil when the document isn't open or hasn't parsed; an empty (but non-nil) slice is reserved for "parsed, but nothing to show," which the current grammar never produces — a parsed doc always has at least @type or some directive / entry.
func (*Workspace) Documents ¶
Documents exposes the document store — the entry point embedders use to feed content in and tests use to reach per-document state.
func (*Workspace) EffectiveRegistryConfig ¶
EffectiveRegistryConfig merges Tier 2 (file) and Tier 3 (editor settings) into a single schema.Config the server can hand to schema.Open. Tier 3 wins per the config-protocol design — editor settings beat project defaults. Empty Tier 3 fields fall through to Tier 2 values. Tier 1 (default) is empty string for registry fields (per effective_config.go's defaultFor); Tier 4 (override) applies to individual sections at lookup time, not to the resolver itself.
This helper exists because schema.Open takes one schema.Config — it doesn't know about tiers. Computing the effective config in one place keeps the lookup-construction path simple.
func (*Workspace) EngineConfig ¶
func (s *Workspace) EngineConfig() EngineConfigResult
EngineConfig resolves the workspace's effective engine configuration through the shared §9.4 loader. Discovery starts at the workspace root (the LSP twin of the CLI's working directory); with no file:// root installed, the loader falls back to the server process's working directory, same as the CLI. KnownEngines stays nil — protolsp reports the configured engine, it doesn't execute one, so an engine name protolsp has never heard of is the editor's information rather than protolsp's error.
func (*Workspace) EnsureSubWorkspace ¶
func (s *Workspace) EnsureSubWorkspace(dir string) *WorkspaceState
EnsureSubWorkspace returns the loaded state for the given sub-workspace directory, creating it if needed. The first call reads `.protolsp.pxf` from dir + loads the chain it points at (if any); subsequent calls return the cached state.
dir MUST be an absolute path that's NOT equal to the root workspace dir (root state lives on Server directly).
Concurrency: holds workspacesMu across the load. The OLD pattern (publish placeholder → load on the published pointer outside the lock) let a concurrent subWorkspaceForDoc reader observe a half-loaded struct (FileConfig set, Chain not yet, etc.). Holding the lock means concurrent ensureSubWorkspace / SubWorkspaceForDoc callers serialize through it, but sub-workspace discovery only happens on the FIRST doc to touch each dir — once per workspace per session — so the added contention is negligible and the leaked-dial-on-race hazard a load-then-publish variant would introduce isn't worth the optimization.
loadSubWorkspaceState calls into:
- configContentForLoad (Documents.mu — distinct mutex, OK)
- rebuildLookupAsyncForWorkspace (per-workspace ws.rebuildMu + spawns a goroutine; the goroutine path never re-acquires workspacesMu)
- chain.ParseAt (pure)
so the held mutex doesn't risk lock-order issues.
func (*Workspace) EnsureWorkspaceForDoc ¶
EnsureWorkspaceForDoc populates the doc's workspace directory if not already set and lazily loads the sub-workspace state when the doc belongs to one. Safe to call multiple times; second + calls short-circuit on the cached WorkspaceDir. Safe to call concurrently: the check-then-set below isn't atomic, but racing callers compute the same wsDir from the same inputs, and EnsureSubWorkspace serializes internally on workspacesMu — the worst case is a redundant idempotent store.
Caller must hold no locks. This function takes s.ws.workspacesMu via ensureSubWorkspace if a sub-workspace load is needed.
func (*Workspace) FoldingRangesFor ¶
func (s *Workspace) FoldingRangesFor(docURI uri.URI) []protocol.FoldingRange
FoldingRangesFor builds the fold ranges for a .pxf document: one per multi-line block (nodes, `children`, `state`, `lifecycle`, map / list values) and per multi-line directive. Returns nil when the document isn't open or hasn't parsed. Single-line blocks aren't foldable and are dropped.
func (*Workspace) FormattingEditsFor ¶
FormattingEditsFor returns the TextEdits needed to bring a document to canonical form, or nil when there's nothing to apply (doc not open, doc didn't parse, doc already canonical).
"Already canonical" returns an empty (non-nil) slice rather than nil so the client treats it as "formatter ran, no edits needed" instead of "formatter unavailable" — the difference matters for editor commands like "format on save" that want to suppress no-op feedback.
func (*Workspace) HoverFor ¶
HoverFor computes the Hover response for a (uri, position), or returns nil to signal "no hover info." nil is the LSP-correct way to say "I have nothing to add here" — clients render nothing in that case.
func (*Workspace) IsChainSpecDoc ¶
IsChainSpecDoc reports whether the given doc IS the workspace's active chain spec. Like isWorkspaceConfigDoc, prefers @type and falls back to a path comparison against the currently-loaded chain's Path (so the user editing the exact file we loaded definitely counts).
Takes doc.mu.RLock to snapshot Parsed — same discipline (and same race) as IsWorkspaceConfigDoc. Callers must not already hold doc.mu.
func (*Workspace) IsWorkspaceConfigDoc ¶
IsWorkspaceConfigDoc reports whether the given doc IS the workspace's .protolsp.pxf. Routing is by @type FQN (most reliable, survives renamed files), falling back to URI basename match for docs that haven't parsed yet or that omit the directive.
Takes doc.mu.RLock to snapshot Parsed — the watched-files reanalyze pass rewrites it concurrently. Callers must not already hold doc.mu.
func (*Workspace) ListMessages ¶
ListMessages enumerates every message type visible to the bound resolver, optionally filtered to FQNs starting with prefix: deduped, origin-attributed (namespace per FindFileByPathWithOrigin, memoized per file), and sorted by FullName. When no lookup is configured the result is an empty list, not an error — schema-aware browsing simply isn't available. The composed recipe behind MethodListMessages and the RPC sidecar's ListMessages; exported so in-process embedders share it.
Long namespace chains can hold tens of thousands of types, so the walk respects ctx: on cancellation the partial result is dropped and ctx's error is returned.
func (*Workspace) LoadProtoIndex ¶
func (s *Workspace) LoadProtoIndex()
LoadProtoIndex (re)builds s.protoIndex from the current workspace root + buf.yaml / buf.lock. Soft-failure throughout: any error during bufconfig discovery degrades to a naive-fallback index (workspace root + proto/ subdir) rather than no index, so users in buf-less workspaces still get cross-file resolution for flat / proto-subdir layouts.
Called from dispatchInitialize after the workspace root is set and from ReloadAfterConfigEdit so a .protolsp.pxf or buf.yaml edit reflects in the next hover / go-to-def.
func (*Workspace) LoadWorkspaceChain ¶
func (s *Workspace) LoadWorkspaceChain()
LoadWorkspaceChain reads the chain.pxf path declared in the workspace's chameleon block (C1 of the chameleon-integration design), loads + expands it, and stores the result on Server.chain.
Soft-failure model matches LoadWorkspaceFileConfig: any failure here is logged at warn level and leaves s.chain nil. The LSP keeps running in standalone mode — chain-aware behaviors degrade gracefully.
Pre-conditions checked by caller: fileConfig is non-nil and has a chameleon block whose ChainSpec is set + Enabled is true.
func (*Workspace) LoadWorkspaceFileConfig ¶
func (s *Workspace) LoadWorkspaceFileConfig()
LoadWorkspaceFileConfig discovers + parses .protolsp.pxf at the LSP-reported workspace root. Stores the result on Server.fileConfig. Failure modes are all soft — no workspace root, file missing, file unreadable, file unparseable — log + continue with fileConfig = nil. The server stays usable through any failure mode.
Parse warnings (missing @type, unrecognized blocks) are logged at warn level so users see them in the editor's LSP log channel without disrupting the session. A future phase will publish these as diagnostics on the .protolsp.pxf file itself.
func (*Workspace) Logger ¶
Logger returns the Workspace's structured logger — the one New received (or slog.Default). The LSP shell logs dispatch-level events through the same logger so a session's output interleaves coherently.
func (*Workspace) LookupForDoc ¶
LookupForDoc returns the schema.Lookup that applies to doc. Routing logic:
- If doc maps to a SUB-workspace AND that sub-workspace declares its own schema source, return the sub's lookup (registry-backed if present, else proto_files-backed). The sub never falls back to the root once it's declared a source — that's the per-workspace isolation guarantee from the design.
- Otherwise fall through to the server-wide root lookup (lookupMgr.Snapshot, which already folds root.registry and root.proto_files together).
Returns nil when neither the sub-workspace nor the root has a configured lookup.
func (*Workspace) LookupForNamespace ¶
LookupForNamespace picks the right schema.Lookup to serve a root-scoped registry:// source-content request. The `_internal_` sentinel origin routes to the compiled-in internalLookup; everything else falls through to the root user-bound lookup.
This is the workspaceDir=="" case of [Workspace.lookupForNamespaceInWorkspace]; registry:// resolution originating from a sub-workspace goes through that doc/dir-scoped variant so a preview resolves against its own registry.
func (*Workspace) Lookups ¶
func (s *Workspace) Lookups() *LookupManager
Lookups exposes the schema-lookup manager. Tests install fakes via Lookups().Swap(fake, nil) — same shape as production; embedders can snapshot the active lookup for their own schema browsing.
func (*Workspace) MaybeEvictSubWorkspace ¶
MaybeEvictSubWorkspace removes the sub-workspace entry for dir IF no remaining open document maps to it. Called from dispatchDidClose after the closing doc has been removed from the store. R4 of the audit roadmap.
Eviction is exact (no idle timer or LRU): a sub-workspace stays loaded as long as ANY of its docs is open, and gets torn down the moment the last one closes. Re-opening a doc inside it triggers a fresh discover-and-load via ensureSubWorkspace.
Root workspaces are never evicted — their state lives on Server directly (s.ws.rootFileConfig / s.chain), not in s.ws.subWorkspaces, and we keep them for the session.
Concurrency: lock-order is Documents.mu (via URIs/Get) → workspacesMu. Multiple concurrent evictions for the same dir are safe; the loser finds the map entry already deleted and no-ops.
func (*Workspace) NotifyEffectiveConfigChanged ¶
func (s *Workspace) NotifyEffectiveConfigChanged(ctx context.Context, workspaceDir string, changes map[string]ConfigValue)
NotifyEffectiveConfigChanged fires protolsp/effectiveConfigChanged with the given changes map. Same-shape redaction as getEffectiveConfig — sensitive sections render <redacted> by default. The editor's UI updates from this; no acknowledgment expected.
func (*Workspace) NotifyStaleSchemaIfApplicable ¶
NotifyStaleSchemaIfApplicable sends a window/showMessage warning to the client when the resolver loaded stale at startup. Called from the `initialized` handler so the message lands after the LSP handshake has completed — clients (especially VS Code) drop notifications received before initialized.
Best-effort: failures log but don't fail anything. Stale state is already visible via protolsp/registryStatus, so the message is a courtesy nudge, not a hard requirement.
func (*Workspace) OpenShadowProto ¶
OpenShadowProto tracks a read-only registry:// .proto source as a Document and parses it into an AST so hover + go-to-definition resolve inside the read-only buffer. It is the "shadow document" support registry previews need: the navigation handlers read doc.protoAST, which the normal pipeline only builds for on-disk .proto files.
No diagnostics are published and the analyze pipeline is bypassed entirely. The buffer is an immutable snapshot the resolver produced (its bytes change only when the schema lookup rebuilds, at which point the embedder re-opens it), and its URI is not a client-editable file. Parsing happens directly, with a filename derived from the registry path — never URI.FsPath(), which panics on the registry:// scheme.
Idempotent: re-opening the same URI refreshes the source + AST in place. Non-registry / non-.proto URIs are a no-op, so embedders can route indiscriminately.
This opens the preview against the ROOT lookup's scope. Multi-root embedders use OpenShadowProtoForWorkspace to bind the preview to the sub-workspace it was opened from, so its cross-file navigation resolves against that sub-workspace's registry.
func (*Workspace) OpenShadowProtoForWorkspace ¶
OpenShadowProtoForWorkspace is OpenShadowProto with an explicit sub-workspace binding: workspaceDir is the absolute directory of the sub-workspace the preview was opened from. It records that on the shadow Document (SetWorkspaceDir) so hover + go-to-definition route the preview's cross-file registry resolution to the sub-workspace's own registry rather than the root's. An empty workspaceDir leaves the doc root-scoped — the OpenShadowProto behavior.
func (*Workspace) PositionEncoding ¶
PositionEncoding returns the negotiated position encoding every position↔byte conversion consults. UTF-16 zero value matches the LSP default.
func (*Workspace) ProtoCompletionFor ¶
func (s *Workspace) ProtoCompletionFor(docURI uri.URI, pos protocol.Position) *protocol.CompletionList
ProtoCompletionFor handles textDocument/completion for .proto files. Returns nil for "no completions" (treated as a null CompletionList by the dispatcher; see dispatchCompletion's notes).
func (*Workspace) ProtoFoldingRangesFor ¶
func (s *Workspace) ProtoFoldingRangesFor(docURI uri.URI) []protocol.FoldingRange
ProtoFoldingRangesFor builds the fold ranges for a .proto schema: one per message / enum / service / oneof / extend / rpc body (recursively, including nested types), plus the import group (kind=imports) and comment blocks (kind=comment). Returns nil when the document isn't open or hasn't parsed.
func (*Workspace) ProtoFormattingEditsFor ¶
ProtoFormattingEditsFor formats the .proto document with protocompile's printer (see FormatProto) and returns a whole-document TextEdit when that changes the source. Returns nil when:
- the doc isn't open or has no source,
- the source doesn't parse (typically mid-edit), or the printer's output would not keep every token and comment of the input; a log line goes out via slog so users can dig into it via the trace panel.
Returns an empty (non-nil) edit slice when the source is already canonical — mirrors FormattingEditsFor's contract so "format on save" doesn't dirty the buffer unnecessarily.
func (*Workspace) PublishDiagnostics ¶
PublishDiagnostics computes the diagnostic list for the document's current parse result and sends a textDocument/publishDiagnostics notification. Diagnostic messages are run through the secret redactor (S1 of the secret-handling design) so pxf.Secret values that triggered a finding don't echo back to the client.
func (*Workspace) PublishDiagnosticsRaw ¶
func (*Workspace) RFC001SourceRange ¶
RFC001SourceRange resolves a source-map descriptor_path key (RFC-001 §8.3.1 — the key a protowire runtime attaches to violations) to the editor range of its source anchor in the given document. This is the runtime-error → source mapping primitive: a future violation-overlay feed calls this per violation and renders the result as an informational diagnostic.
The returned range covers the token at the anchor (the `@` of a use site, the callee ident of a FUNCTION_CALL, the type ident of a TYPE_REFINEMENT). ok=false when the document isn't analyzed, holds no source map, the key doesn't parse, or no entry matches.
func (*Workspace) ReanalyzeOpenDocsExcept ¶
ReanalyzeOpenDocsExcept is reanalyzeOpenDocs with a one-URI skip. Used by live-reload so the doc that triggered the reload doesn't get analyzed twice (the trigger path already ran runAnalyzePipeline for it).
func (*Workspace) RebuildLookupAsync ¶
RebuildLookupAsync (re-)builds the schema lookup from the current effective config. Returns immediately; the actual schema.Open call runs in a background goroutine.
Diff-before-rebuild: when the effective config equals what we last built the lookup from, this is a no-op. Most live-reload triggers (a user editing the security or chameleon block of .protolsp.pxf) take this path — saving a dial per keystroke when only non-registry fields changed.
Coalescing: a fresh rebuild request cancels any in-flight dial via lookupMgr.BeginRebuild. The cancelled goroutine sees ctx.Err() after schema.Open returns and skips the install; only the most recent request gets to install its result.
The empty-registry path is handled synchronously (no async teardown needed — closing the old closer is fast).
func (*Workspace) RebuildLookupFromEffectiveConfig ¶
RebuildLookupFromEffectiveConfig is the public seam that callers (initialize, W5 watcher, live-reload) use to ask the server to pick up registry-config changes. The actual work — diff, optional dial, atomic install — happens in RebuildLookupAsync. Kept as a thin shim so existing call sites don't need updates.
Returns immediately; the dial (if any) runs in a goroutine. See lookup_rebuild.go for the diff + cancellation semantics.
func (*Workspace) RebuildProtocheckValidator ¶
RebuildProtocheckValidator re-resolves the effective engine config and swaps in a validator built against it. Cheap when the config fingerprint is unchanged; no-op in the OSS build. Called from initialize, the config-edit cascade, protowire.config.textproto watched-file events, and lookup swaps.
func (*Workspace) RebuildRootProtoFilesLookup ¶
func (s *Workspace) RebuildRootProtoFilesLookup()
RebuildRootProtoFilesLookup compiles the root workspace's `proto_files { ... }` sources (W2). The root counterpart to rebuildProtoFilesLookupForWorkspace: same shape, but the lookup installs on LookupManager and compile errors stash on the Server's rootProtoFilesErrs slot for the config-diagnostics path to read.
Soft-failure throughout: setup failures (path walks, fs errors) log + leave the previous state alone; compile errors land in the stashed slice without disturbing the installed lookup.
func (*Workspace) ReferencesFor ¶
func (s *Workspace) ReferencesFor(ctx context.Context, docURI uri.URI, pos protocol.Position, includeDecl bool) []protocol.Location
ReferencesFor resolves the path under the cursor and returns LSP Locations for every matching assignment / block in the open-doc set sharing the same WorkspaceDir. Returns nil when the cursor doesn't sit on a recognisable path target.
func (*Workspace) RegionAtPosition ¶
func (s *Workspace) RegionAtPosition(doc *Document, pos protocol.Position) *DatasetRegion
RegionAtPosition returns the DatasetRegion that contains pos, or nil when pos is outside every region. Containment is half-open in line/column space: a region's End position is exclusive (the byte after the closing `}` or the start of the first non-tuple line). Comparison is lexicographic on (Line, Character).
func (*Workspace) RegistryStatus ¶
func (s *Workspace) RegistryStatus() RegistryStatusResult
RegistryStatus reports whether a schema lookup is installed and whether it is serving from a stale disk cache. Never errors — this is status-badge surface, and "nothing configured" is a valid answer, not a failure. The composed recipe behind MethodRegistryStatus and the RPC sidecar's GetStatus; exported so in-process embedders share it instead of re-deriving status from Lookups().Snapshot().
func (*Workspace) ReloadAfterConfigEdit ¶
ReloadAfterConfigEdit fires the same cascade dispatchDidChangeWatchedFiles runs after a `.protolsp.pxf` edit. Centralised here so configSet's effect on lookups, diagnostics, and the chain is identical to what an external editor save would do — pxfed shouldn't be able to tell whether a config change came from a file watcher or from its own Set call.
func (*Workspace) RenameEditFor ¶
func (s *Workspace) RenameEditFor(ctx context.Context, docURI uri.URI, pos protocol.Position, newName string) *protocol.WorkspaceEdit
RenameEditFor builds the WorkspaceEdit for a rename request, or nil when the cursor doesn't sit on a renameable target.
Two kinds of rename are served, both propagating across the workspace:
- A keyed repeated field's entry (draft -01 §3.13), identified by its collection path + key. Every occurrence of that same entry (chain layers that define or override it) is rewritten, quoting or unquoting the key to match `pxf fmt` and retargeting any redundant explicit key assignment. Tried first.
- Otherwise the path-based field rename: every Assignment / Block whose dotted path matches the cursor's is rewritten.
func (*Workspace) RenameTargetKind ¶
RenameTargetKind reports what a rename at (docURI, pos) would target. Used by the dispatch layer to choose new-name validation.
func (*Workspace) ResolveSection ¶
func (s *Workspace) ResolveSection(section string) ConfigValue
ResolveSection walks the four tiers from highest to lowest precedence and returns the first one with a non-empty value. Tier 2 (file) is stubbed today — resolveFromFile returns (nil, false) until W1 lands. Tier 4 (override) reads from Server.overrides which CP3 populates via protolsp/setOverrides.
If no tier supplies a value, falls back to the Tier 1 default (typically the empty string).
func (*Workspace) ResolvedChainSpecPath ¶
ResolvedChainSpecPath returns the absolute filesystem path of the active chain spec, or "" when no chain is configured / the workspace root isn't on local disk. The path is what LoadWorkspaceChain would feed to chain.Load — chain.pxf relative to the .protolsp.pxf's directory, resolved against the workspace root.
Used by W5's watcher registration to register a watcher for the specific chain spec file when its name isn't the conventional `chain.pxf` (which is covered by the static `**/chain.pxf` pattern). Returns "" for the common path so the caller doesn't double-register.
func (*Workspace) RootProtoFilesErrs ¶
func (s *Workspace) RootProtoFilesErrs() *rootProtoFilesCompileErrors
RootProtoFilesErrs exposes the cached proto_files compile-error state for the root workspace. Test-surface accessor.
func (*Workspace) RunAnalyzeAndMaybeLiveReload ¶
func (s *Workspace) RunAnalyzeAndMaybeLiveReload( ctx context.Context, docURI uri.URI, previousSecrets []SecretRange, previousDatasets []DatasetRegion, )
RunAnalyzeAndMaybeLiveReload is the dispatch-path wrapper around runAnalyzePipeline. After the analyze step finishes, it checks whether the just-analyzed doc was protolsp's own config or chain spec and, if so, kicks off a live reload + re-analyze of every other open doc.
Used by dispatchDidOpen (synchronous) and the scheduleAnalyze path (which fires after the debounce window). The plain runAnalyzePipeline keeps its original signature and is what reanalyzeOpenDocs uses — that path skips the live-reload step to prevent infinite recursion.
func (*Workspace) ScheduleAnalyzePipeline ¶
func (s *Workspace) ScheduleAnalyzePipeline(ctx context.Context, doc *Document, previousSecrets []SecretRange, previousDatasets []DatasetRegion)
ScheduleAnalyzePipeline either runs the pipeline now or schedules it after Server.debounceWindow. Resetting the timer when one is already pending is what produces the coalescing behavior — N rapid edits within the window produce one analyze, not N.
The deferred goroutine uses context.Background — the request's own context is gone by the time the timer fires.
func (*Workspace) ScheduleWatchedFilesProcess ¶
ScheduleWatchedFilesProcess either runs the watched-files pipeline immediately (window == 0, today's test-default behavior) or buffers the events and starts / resets a timer that drains the buffer when no further events arrive within the window.
The buffer-and-drain approach is necessary because the concrete reload work depends on the union of all events that arrived during the window — a sequence of (config-change, chain-spec-change, proto-file-change) compresses into one pipeline run, not three.
The deferred goroutine uses context.Background — the request context that fired the notification is dead by the time the timer fires.
func (*Workspace) SemanticTokensFor ¶
func (s *Workspace) SemanticTokensFor(docURI uri.URI) *protocol.SemanticTokens
SemanticTokensFor builds the SemanticTokens response for a document or returns nil for an unopened / unparseable file.
func (*Workspace) SetActiveEnvironment ¶
SetActiveEnvironment validates env against the loaded chain spec and, on success, replaces the server's session-scoped activeEnv override. Returns the previous override (the value ChainStatusSnapshot.ActiveEnvironment would have reported just before the swap) so callers can confirm transitions without an extra round-trip.
Empty env resets to "fall back to default_environment" — the natural "go back" gesture. Any non-empty env that isn't declared in the chain spec returns an error and leaves state untouched; the chain spec is the source of truth for which envs are valid.
When the chain isn't configured we still accept empty env (idempotent reset) but reject non-empty values — there's no spec to validate against, so we'd be granting the client a fictional selection.
func (*Workspace) SetBufLint ¶
SetBufLint gates the buf-lint pass in the proto analyze path. New() enables it; tests flip it off so fixture files don't spin up buf subprocesses (and don't produce surprise lint diagnostics for files that weren't designed to pass buf's default ruleset).
func (*Workspace) SetBwSession ¶
SetBwSession updates the workspace-side BW_SESSION override and triggers a reanalyze of every open document so cached config values that previously resolved `${env.BW_SESSION}` to the empty string (or to a stale token) re-evaluate with the new value. Called from the pxfed/setBwSession notification handler (LSP) or directly by in-process embedders.
func (*Workspace) SetClientCapabilities ¶
func (s *Workspace) SetClientCapabilities(caps ClientCapabilities)
SetClientCapabilities records the client-capability snapshot. The LSP shell calls it once at initialize before any concurrent handler can race with it; embedders leave the zero value.
func (*Workspace) SetClientLocale ¶
SetClientLocale records the editor's UI locale (BCP 47, from InitializeParams.locale). Call before the first document lands — the render path reads the field without a lock, same discipline as SetPublisher.
func (*Workspace) SetDebounceWindow ¶
SetDebounceWindow sets the didChange coalescing window. 0 (the default) runs the analyze pipeline synchronously inside each change; > 0 defers analyze + publish onto a timer that resets on each subsequent edit.
func (*Workspace) SetHugeRegionBytes ¶
SetHugeRegionBytes overrides the byte-size threshold above which a @dataset region is marked Huge. 0 restores the default (100 KB).
func (*Workspace) SetHugeRegionRows ¶
SetHugeRegionRows overrides the row-count threshold above which a @dataset region is marked Huge. 0 restores the default (1000).
func (*Workspace) SetMaxReferencesFiles ¶
SetMaxReferencesFiles overrides the file-count cap used by references walks. 0 restores the default (10000). Tests use a small number to exercise the truncation path without writing 10k files to disk.
func (*Workspace) SetPositionEncoding ¶
SetPositionEncoding records the negotiated position encoding. Set once at initialize time (LSP) or construction time (embedders that index with UTF-8 offsets).
func (*Workspace) SetProtoIndexCacheRoot ¶
SetProtoIndexCacheRoot overrides the BSR-cache root the proto import-path index resolves module deps from. Empty means the production default (bufconfig.ModuleCacheDir()). Tests point it at a staged fake cache.
func (*Workspace) SetPublisher ¶
SetPublisher installs the outbound seam every server→client push flows through. A nil p resets to the no-op publisher. Call before the first document lands — the pipeline reads the field without a lock (same discipline the LSP shell followed when it assigned the field directly at construction time).
func (*Workspace) SetRuntimeViolations ¶
func (s *Workspace) SetRuntimeViolations(ctx context.Context, docURI uri.URI, violations []RuntimeViolation)
SetRuntimeViolations replaces the stored runtime-violation overlay for docURI and, when the document is open, republishes its diagnostics immediately so the editor reflects the new runtime state without waiting for the next edit. Also the embedder-facing programmatic entry point (the dispatch wrapper is protocol glue).
func (*Workspace) SetSeededFromInitOptions ¶
func (*Workspace) SetWatchedFilesWindow ¶
SetWatchedFilesWindow sets the watched-files coalescing window. Tests set 0 to keep dispatch synchronous; production keeps the default (200ms).
func (*Workspace) SnapshotChain ¶
func (s *Workspace) SnapshotChain() *chain.ActiveChain
func (*Workspace) SnapshotEditorConfig ¶
func (s *Workspace) SnapshotEditorConfig() EditorConfig
SnapshotEditorConfig / SwapEditorConfig / SnapshotSeededFromInitOptions / SetSeededFromInitOptions are thin shims over the ConfigState concern (T1 PR B). Callers continue to use Server methods so the dispatcher surface stays stable; the actual state + synchronization live in ConfigState.
func (*Workspace) SnapshotFileConfig ¶
func (s *Workspace) SnapshotFileConfig() *workspaceconfig.Config
func (*Workspace) SnapshotProtoIndex ¶
func (s *Workspace) SnapshotProtoIndex() *protoindex.Index
SnapshotProtoIndex returns the currently-installed index, or nil when LoadProtoIndex hasn't run yet. The returned pointer is safe to use without re-locking — the index itself is internally concurrent-safe, and we never mutate an installed Index (LoadProtoIndex swaps in a freshly built one).
func (*Workspace) SnapshotSectionsLocked ¶
func (s *Workspace) SnapshotSectionsLocked(sections []string) map[string]ConfigValue
SnapshotSectionsLocked returns the effective config for the given sections, reading the override tier from s.overrides directly. Caller MUST hold overridesMu.
Tier sources OTHER than override (settings, file, default) take their own mutexes (stateMu) internally; that's safe because stateMu and overridesMu are independent locks and neither is acquired by the other's holders.
func (*Workspace) SnapshotSeededFromInitOptions ¶
func (*Workspace) SourceContent ¶
SourceContent fetches the source bytes behind a registry:// URI against the ROOT lookup: parse the namespace, route to the right lookup (compiled-in internal vs root user-bound, per Workspace.LookupForNamespace), and GetSource the file. The composed recipe behind MethodSourceContent and the RPC sidecar's GetSourceContent; exported so in-process embedders share it. Multi-root callers use Workspace.SourceContentForWorkspace to resolve against a sub-workspace's own registry.
Errors wrap ErrNotRegistryURI (malformed URI — caller mistake), ErrNoSchemaLookup (nothing configured), or the underlying GetSource failure verbatim.
func (*Workspace) SourceContentForWorkspace ¶
func (s *Workspace) SourceContentForWorkspace(ctx context.Context, u uri.URI, workspaceDir string) (SourceContentResult, error)
SourceContentForWorkspace is Workspace.SourceContent scoped to a sub-workspace: workspaceDir is the absolute directory of the sub-workspace the preview was opened from, so a registry:// source fetched from a sub-workspace's own registry resolves against THAT registry rather than the root's. An empty workspaceDir selects the root lookup, making SourceContent the back-compatible root-scoped entry point.
func (*Workspace) SubWorkspaceByDir ¶
func (s *Workspace) SubWorkspaceByDir(dir string) (*WorkspaceState, bool)
SubWorkspaceByDir returns the loaded sub-workspace for a given directory if one exists. Used by the watcher event classifier to route .protolsp.pxf events to known sub-workspaces; we don't surface previously-unknown dirs to avoid loading every .protolsp.pxf in the workspace tree just because the editor watched its glob pattern. New sub-workspaces enter the map via EnsureWorkspaceForDoc when the first doc inside them opens.
func (*Workspace) SubWorkspaceCount ¶
SubWorkspaceCount returns the number of lazily-loaded sub-workspaces. Concurrent-safe. Pairs with SubWorkspaceByDir as the sanctioned view of the sub-workspace map.
func (*Workspace) SubWorkspaceForDoc ¶
func (s *Workspace) SubWorkspaceForDoc(doc *Document) *WorkspaceState
SubWorkspaceForDoc returns the loaded sub-workspace state for doc, or nil when doc belongs to the root workspace (or has no workspace mapping at all). Callers use the accessors fileConfigForDoc / chainForDoc / resolvedChainSpecPathForDoc rather than this helper directly.
func (*Workspace) SwapChain ¶
func (s *Workspace) SwapChain(c *chain.ActiveChain) *chain.ActiveChain
func (*Workspace) SwapEditorConfig ¶
func (s *Workspace) SwapEditorConfig(cfg EditorConfig) EditorConfig
func (*Workspace) SwapFileConfig ¶
func (s *Workspace) SwapFileConfig(cfg *workspaceconfig.Config) *workspaceconfig.Config
func (*Workspace) SwapSubWorkspaceLookup ¶
func (s *Workspace) SwapSubWorkspaceLookup(ws *WorkspaceState, newLookup schema.Lookup, newCloser io.Closer) io.Closer
SwapSubWorkspaceLookup installs new lookup state on ws and returns the prior closer for the caller to close outside the lock. Mirrors the server-wide swapLookup, including the LookupChanged fire — sub-workspace slots don't route through LookupManager, so the seam is fired here.
func (*Workspace) WatchedFilesDebounce ¶
WatchedFilesDebounce reports whether the watched-files debounce timer is armed and how many file events are buffered behind it. Test surface: teardown asserts both go to zero after Close.
func (*Workspace) Workspaces ¶
func (s *Workspace) Workspaces() *WorkspaceManager
Workspaces exposes the workspace manager: the root workspace's fileConfig + chain plus the sub-workspace map.
type WorkspaceManager ¶
type WorkspaceManager struct {
// contains filtered or unexported fields
}
WorkspaceManager owns the per-server workspace state. The zero value is NOT usable — use newWorkspaceManager.
Concurrency:
- stateMu (RWMutex) guards rootFileConfig + rootChain. They get written from the main goroutine (initialize, watcher events) and the analyze-debounce goroutine (live-reload); read from every handler plus the async rebuild's reanalyzeOpenDocs.
- workspacesMu (Mutex) guards the subWorkspaces map. The WorkspaceState values themselves have their own per-workspace locks (lookupMu, rebuildMu).
- workspaceRoot is set once at initialize before any concurrent handler can race with it; no mutex needed.
Lock-order between the two: never both held at once today. If a composite read ever needs them, take stateMu before workspacesMu (alphabetical; document the choice).
func (*WorkspaceManager) SetWorkspaceRoot ¶
func (w *WorkspaceManager) SetWorkspaceRoot(u uri.URI)
SetWorkspaceRoot installs the workspace root. Called once from dispatchInitialize before the connection loop begins accepting other handlers; no synchronization needed.
func (*WorkspaceManager) SnapshotChain ¶
func (w *WorkspaceManager) SnapshotChain() *chain.ActiveChain
SnapshotChain returns the root workspace's loaded chain spec (may be nil). Concurrent-safe.
func (*WorkspaceManager) SnapshotFileConfig ¶
func (w *WorkspaceManager) SnapshotFileConfig() *workspaceconfig.Config
SnapshotFileConfig returns the root workspace's parsed fileConfig (may be nil). Concurrent-safe.
func (*WorkspaceManager) SwapChain ¶
func (w *WorkspaceManager) SwapChain(c *chain.ActiveChain) *chain.ActiveChain
func (*WorkspaceManager) SwapFileConfig ¶
func (w *WorkspaceManager) SwapFileConfig(cfg *workspaceconfig.Config) *workspaceconfig.Config
SwapFileConfig replaces the root fileConfig pointer atomically and returns the prior value. The pointer is treated as immutable post-publish (writers swap the whole struct rather than mutating in place), so readers can hold the returned snapshot across multiple field accesses without further locking.
func (*WorkspaceManager) WorkspaceRoot ¶
func (w *WorkspaceManager) WorkspaceRoot() uri.URI
WorkspaceRoot returns the LSP-reported workspace root URI. Set once at initialize; safe to read concurrently afterward.
type WorkspaceState ¶
type WorkspaceState struct {
// Dir is the absolute path of the directory containing this
// workspace's `.protolsp.pxf`. Used as the map key in
// Server.subWorkspaces and stored on Document.WorkspaceDir
// so subsequent operations route to the right workspace.
Dir string
// FileConfig is the parsed workspace config. Loaded lazily
// the first time a doc maps to this dir. Nil when the
// `.protolsp.pxf` was unparseable or empty.
FileConfig *workspaceconfig.Config
// Chain is the loaded chameleon chain spec when FileConfig
// declares a chameleon block. Nil otherwise / on load failure.
Chain *chain.ActiveChain
// Lookup is the user-registry-backed schema.Lookup for this
// sub-workspace (W4b of workspace-config). Mirrors the
// machinery on Server for the root workspace; lets sub-
// workspaces dial DIFFERENT registries than the root when
// their `.protolsp.pxf` declares its own schema_sources.
// Nil when the sub-workspace doesn't declare a registry —
// callers fall through to the root lookup in that case.
Lookup schema.Lookup
LookupCloser io.Closer
// ProtoFiles is the W2 proto_files-backed schema.Lookup for
// this sub-workspace, populated when the sub's `.protolsp.pxf`
// declares one or more `proto_files { ... }` blocks. Sits
// alongside Lookup the same way LookupManager.protoFiles does
// on the root; W3 will compose the two via WithFallback.
ProtoFiles schema.Lookup
ProtoFilesCloser io.Closer
// CompileErrors captures any protocompile errors raised while
// building ProtoFiles. Surfaced as diagnostics on the
// sub-workspace's `.protolsp.pxf` by config_diagnostics.go.
CompileErrors []schema.CompileError
// contains filtered or unexported fields
}
WorkspaceState bundles the per-workspace state W4 splits out of Server. The root workspace's state lives on Server directly (s.ws.rootFileConfig / s.chain) — this type holds the same shape for each sub-workspace discovered via `.protolsp.pxf` ancestry.
func (*WorkspaceState) LastRebuiltConfig ¶
func (ws *WorkspaceState) LastRebuiltConfig() schema.Config
LastRebuiltConfig returns the effective registry config this sub-workspace's lookup was last rebuilt against (zero value when no rebuild has completed yet). Concurrent-safe.
func (*WorkspaceState) RebuildInFlight ¶
func (ws *WorkspaceState) RebuildInFlight() bool
RebuildInFlight reports whether an async lookup rebuild is currently running for this sub-workspace. Concurrent-safe.
Source Files
¶
- chain_hover.go
- chain_required.go
- chain_status.go
- codeaction.go
- completion.go
- config_attrs.go
- config_diagnostics.go
- config_reload.go
- config_state.go
- dataset_hover.go
- dataset_regions.go
- dataset_regions_ast.go
- dataset_validation.go
- debounce.go
- declared_names.go
- definition.go
- diagnostics.go
- document.go
- document_symbol.go
- edit_apply.go
- editor_config.go
- effective_config.go
- engine.go
- engine_config.go
- env_source_hover.go
- facade.go
- field_defaults.go
- field_refs.go
- field_refs_completion.go
- field_refs_cycle.go
- field_refs_definition.go
- file_config.go
- folding_range.go
- formatting.go
- hover.go
- inline_proto.go
- keyed.go
- keyed_diagnostics.go
- keyed_rename.go
- layer_info.go
- list_messages.go
- lookup_manager.go
- lookup_rebuild.go
- lsp_values.go
- overrides.go
- path_search.go
- position.go
- proto_analyze.go
- proto_completion.go
- proto_cross_file.go
- proto_definition.go
- proto_format.go
- proto_hover.go
- proto_options_walk.go
- proto_position.go
- proto_registry_crossfile.go
- proto_rfc001_ir.go
- proto_rfc001_nav.go
- proto_rfc001_quickfix.go
- proto_rfc001_remote.go
- proto_semantic_tokens.go
- proto_sensitive.go
- proto_workspace.go
- protocheck_data.go
- protocheck_data_stub.go
- protocheck_lifecycle.go
- protocheck_runner_stub.go
- protocheck_schema_stub.go
- protovalidate_data.go
- protovalidate_schema.go
- publisher.go
- references.go
- registry_status.go
- rename.go
- runtime_violations.go
- secret_diagnostics.go
- secret_ranges.go
- secret_ranges_request.go
- semantic_tokens.go
- shadow_proto.go
- source_content.go
- state.go
- type_resolution.go
- watched_files.go
- workspace.go
- workspace_manager.go