cudalsp

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 41 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cudalsp implements a pure-Go Language Server Protocol (LSP 3.17) server and multi-language analysis engine for GPU kernel development.

It indexes six coupled domains within a single immutable Snapshot per workspace revision:

Provenance Invariant

Artifacts across layers (Go, CUDA, Tile IR, PTX, SASS, and profile reports) are joined only through explicit provenance: content SHA-256 digests, registered ProvenanceLink compilation records, lineinfo attribution, and validated obsevidence.EvidenceIdentity bindings. Bare symbol names alone never join two artifacts; missing provenance is reported explicitly as an UnresolvedReason or hint diagnostic.

Profile reports attached via Engine.AttachProfile or the cudalsp/attachProfile request are validated with advise.Report.ValidateEvidence before any finding is projected onto source coordinates. Unmeasured metrics are never fabricated.

Transport and Security

[ListenAndServe] serves JSON-RPC 2.0 Content-Length framed LSP connections over stdio, unix domain sockets (unix:/path), or loopback TCP addresses (tcp:127.0.0.1:port or tcp:[::1]:port). Non-loopback TCP addresses are refused so remote GPU workflows forward explicitly over SSH.

Virtual Documents

Compiled lowerings and attached profile summaries are exposed as read-only virtual documents under the cudalsp:// URI scheme (for example, cudalsp://compile/<digest>/<entry>.ptx) and retrieved via the cudalsp/virtualDocument request.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Examples

Constants

View Source
const (
	CodeParseError           = -32700
	CodeInvalidRequest       = -32600
	CodeMethodNotFound       = -32601
	CodeInvalidParams        = -32602
	CodeInternalError        = -32603
	CodeServerNotInitialized = -32002
	CodeRequestCancelled     = -32800
	CodeContentModified      = -32801
)

Standard JSON-RPC 2.0 and LSP 3.17 error codes.

View Source
const MaxMessageBytes = 64 << 20

MaxMessageBytes is the largest supported JSON-RPC payload in bytes.

Variables

This section is empty.

Functions

func ApplyTextChanges

func ApplyTextChanges(text string, changes []TextDocumentContentChangeEvent) (string, error)

ApplyTextChanges applies LSP full or incremental edits to text.

func Listen

func Listen(addr string) (net.Listener, error)

Listen opens a loopback TCP or unix socket listener for addr. It rejects "stdio" (use Server.ServeStream or [ListenAndServe] for stdio) and non-loopback TCP addresses.

func PathFromURI

func PathFromURI(uri string) string

PathFromURI converts a file:// or cudalsp:// URI into a slash-separated path.

func URIForPath

func URIForPath(p string) string

URIForPath converts a filesystem path to a file:// URI.

func ValidateListenAddr

func ValidateListenAddr(addr string) (network, target string, err error)

ValidateListenAddr checks that addr is one of:

  • "stdio"
  • "tcp:<loopback-host>:<port>" (127.0.0.1, ::1, or localhost)
  • "unix:<socket-path>"

Non-loopback TCP addresses are rejected.

func VirtualURI

func VirtualURI(kind, digest, name string) string

VirtualURI constructs a deterministic cudalsp:// URI.

Types

type AttachProfileParams

type AttachProfileParams struct {
	Name           string          `json:"name,omitempty"`
	Path           string          `json:"path,omitempty"`
	ArtifactDigest string          `json:"artifact_digest,omitempty"`
	TargetURI      string          `json:"target_uri,omitempty"`
	Provenance     string          `json:"provenance,omitempty"`
	Report         json.RawMessage `json:"report,omitempty"`
}

AttachProfileParams is sent in cudalsp/attachProfile.

type AttachProfileResult

type AttachProfileResult struct {
	ProfileID     string   `json:"profile_id"`
	VirtualURI    string   `json:"virtual_uri"`
	ItemCount     int      `json:"item_count"`
	AttachedFiles []string `json:"attached_files,omitempty"`
}

AttachProfileResult is returned by cudalsp/attachProfile.

type AttachedProfile

type AttachedProfile struct {
	ID         string
	Name       string
	VirtualURI string
	Report     *advise.Report
	Provenance ProfileProvenance
	SHA256     string
}

AttachedProfile holds a validated advise.Report and its provenance binding.

type BundleExporter

type BundleExporter interface {
	ExportBundle(ctx context.Context, snap *Snapshot, params ExportBundleParams) (*ExportBundleResult, error)
}

BundleExporter handles cudalsp/exportBundle requests so CLI and MCP layers can wire txtar or correctness bundle generation without coupling this package to external workflows.

type BundleExporterFunc

type BundleExporterFunc func(ctx context.Context, snap *Snapshot, params ExportBundleParams) (*ExportBundleResult, error)

BundleExporterFunc adapts a function to BundleExporter.

func (BundleExporterFunc) ExportBundle

func (f BundleExporterFunc) ExportBundle(ctx context.Context, snap *Snapshot, params ExportBundleParams) (*ExportBundleResult, error)

ExportBundle calls f.

type CUDAAnalysis

type CUDAAnalysis struct {
	Frontend  string
	Functions []CUDAFunction
	Includes  []CUDAInclude
	Errors    []CUDASyntaxError
}

CUDAAnalysis holds structural information extracted from a CUDA C/C++ source.

type CUDACall

type CUDACall struct {
	Callee string
	Line   int // 1-based
	Column int // 1-based
}

CUDACall records a call expression inside a CUDA function.

type CUDAFrontend

type CUDAFrontend interface {
	ParseCUDA(uri string, src []byte) (*CUDAAnalysis, error)
}

CUDAFrontend is a pluggable parser for CUDA C/C++ translation units. External callers (such as a tree-sitter frontend outside nvidia/go.mod) can supply an implementation via EngineOptions.CUDAFrontend.

type CUDAFunction

type CUDAFunction struct {
	Name      string
	Entry     bool // true for __global__
	Qualifier string
	Signature string
	Line      int // 1-based start line
	EndLine   int // 1-based end line
	Body      string
	Calls     []CUDACall
}

CUDAFunction describes a recognized __global__, __device__, or host function.

type CUDAInclude

type CUDAInclude struct {
	Path   string
	System bool
	Line   int // 1-based
}

CUDAInclude describes a preprocessor #include directive.

type CUDASyntaxError

type CUDASyntaxError struct {
	Line    int // 1-based
	Column  int // 1-based
	Message string
}

CUDASyntaxError reports a lexical or syntactic issue in CUDA source.

type CallHierarchyIncomingCall

type CallHierarchyIncomingCall struct {
	From       CallHierarchyItem `json:"from"`
	FromRanges []Range           `json:"fromRanges"`
}

CallHierarchyIncomingCall describes a caller of an item.

type CallHierarchyIncomingCallsParams

type CallHierarchyIncomingCallsParams struct {
	Item CallHierarchyItem `json:"item"`
}

CallHierarchyIncomingCallsParams is sent in callHierarchy/incomingCalls.

type CallHierarchyItem

type CallHierarchyItem struct {
	Name           string     `json:"name"`
	Kind           SymbolKind `json:"kind"`
	Detail         string     `json:"detail,omitempty"`
	URI            string     `json:"uri"`
	Range          Range      `json:"range"`
	SelectionRange Range      `json:"selectionRange"`
	Data           any        `json:"data,omitempty"`
}

CallHierarchyItem represents a function or kernel in the call hierarchy.

type CallHierarchyOutgoingCall

type CallHierarchyOutgoingCall struct {
	To         CallHierarchyItem `json:"to"`
	FromRanges []Range           `json:"fromRanges"`
}

CallHierarchyOutgoingCall describes a callee of an item.

type CallHierarchyOutgoingCallsParams

type CallHierarchyOutgoingCallsParams struct {
	Item CallHierarchyItem `json:"item"`
}

CallHierarchyOutgoingCallsParams is sent in callHierarchy/outgoingCalls.

type CallHierarchyPrepareParams

type CallHierarchyPrepareParams struct {
	TextDocumentPositionParams
}

CallHierarchyPrepareParams is sent in textDocument/prepareCallHierarchy.

type Client

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

Client exchanges typed LSP messages with one server. A Client is safe for concurrent use. Construct it using NewClient or Dial.

Example
package main

import (
	"context"
	"fmt"
	"net"

	"github.com/tmc/lib/nvidia/x/compile/cudalsp"
)

func main() {
	local, peer := net.Pipe()
	defer peer.Close()
	ctx := context.Background()
	server := cudalsp.NewServer(nil, cudalsp.ServerConfig{Name: "example"})
	go server.ServeStream(ctx, peer, peer)

	client := cudalsp.NewClient(local)
	defer client.Close()
	info, err := client.Initialize(ctx, cudalsp.InitializeParams{})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(info.ServerInfo.Name)
	fmt.Println(client.Shutdown(ctx))
}
Output:
example
<nil>

func Dial

func Dial(ctx context.Context, addr string) (*Client, error)

Dial opens a client connection to a loopback TCP or Unix socket.

func NewClient

func NewClient(stream io.ReadWriteCloser) *Client

NewClient takes ownership of stream and starts reading replies.

func (*Client) AttachProfile

func (c *Client) AttachProfile(ctx context.Context, p AttachProfileParams) (AttachProfileResult, error)

AttachProfile attaches a validated profile report and returns its identifier.

func (*Client) Close

func (c *Client) Close() error

Close releases the underlying stream and unblocks pending calls.

func (*Client) Correlate

func (c *Client) Correlate(ctx context.Context, p CorrelateParams) (CorrelationResult, error)

Correlate returns provenance-linked sites for p.

func (*Client) Definition

func (c *Client) Definition(ctx context.Context, uri string, p Position) ([]Location, error)

Definition returns definition locations for the symbol at p.

func (*Client) Diagnostics

func (c *Client) Diagnostics(ctx context.Context, uri string) (FullDocumentDiagnosticReport, error)

Diagnostics returns the current full diagnostic report for uri.

func (*Client) DidChange

DidChange applies versioned edits to an open document.

func (*Client) DidClose

func (c *Client) DidClose(uri string) error

DidClose releases a document from the workspace.

func (*Client) DidOpen

func (c *Client) DidOpen(doc TextDocumentItem) error

DidOpen publishes an editor document to the server.

func (*Client) ExportBundle

func (c *Client) ExportBundle(ctx context.Context, p ExportBundleParams) (ExportBundleResult, error)

ExportBundle asks the server to export a workspace bundle.

func (*Client) Hover

func (c *Client) Hover(ctx context.Context, uri string, p Position) (*Hover, error)

Hover returns hover information, or nil if no information is available.

func (*Client) Initialize

func (c *Client) Initialize(ctx context.Context, p InitializeParams) (InitializeResult, error)

Initialize negotiates server capabilities and sends initialized.

func (*Client) LinkArtifacts

func (c *Client) LinkArtifacts(ctx context.Context, p ProvenanceLink) error

LinkArtifacts registers an explicit artifact linkage with the server.

func (*Client) Profiles

func (c *Client) Profiles(ctx context.Context) ([]*AttachedProfile, error)

Profiles returns the server's attached profile reports and their provenance.

func (*Client) RunCorrectness

func (c *Client) RunCorrectness(ctx context.Context, p CorrectnessParams) (cudakorrect.Verdict, error)

RunCorrectness evaluates an open candidate using the server's runner.

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown requests orderly shutdown and sends exit. The caller still owns the Client and should call Client.Close.

type ClientInfo

type ClientInfo struct {
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`
}

ClientInfo describes the connecting LSP client.

type CodeAction

type CodeAction struct {
	Title       string         `json:"title"`
	Kind        string         `json:"kind,omitempty"`
	Diagnostics []Diagnostic   `json:"diagnostics,omitempty"`
	Edit        *WorkspaceEdit `json:"edit,omitempty"`
	Command     *Command       `json:"command,omitempty"`
}

CodeAction represents a quick fix or command action.

type CodeActionContext

type CodeActionContext struct {
	Diagnostics []Diagnostic `json:"diagnostics"`
	Only        []string     `json:"only,omitempty"`
}

CodeActionContext carries diagnostics overlapping a codeAction request.

type CodeActionParams

type CodeActionParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Range        Range                  `json:"range"`
	Context      CodeActionContext      `json:"context"`
}

CodeActionParams is sent in textDocument/codeAction.

type CodeLens

type CodeLens struct {
	Range   Range    `json:"range"`
	Command *Command `json:"command,omitempty"`
	Data    any      `json:"data,omitempty"`
}

CodeLens is an actionable annotation above a declaration or launch site.

type CodeLensOptions

type CodeLensOptions struct {
	ResolveProvider bool `json:"resolveProvider"`
}

CodeLensOptions configures code lens support.

type CodeLensParams

type CodeLensParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
}

CodeLensParams is sent in textDocument/codeLens.

type Command

type Command struct {
	Title     string `json:"title"`
	Command   string `json:"command"`
	Arguments []any  `json:"arguments,omitempty"`
}

Command represents an executable LSP command.

type CommandHandler

type CommandHandler func(ctx context.Context, snap *Snapshot, args []json.RawMessage) (any, error)

CommandHandler handles an extended workspace/executeCommand invocation.

type CompletionItem

type CompletionItem struct {
	Label         string             `json:"label"`
	Kind          CompletionItemKind `json:"kind,omitempty"`
	Detail        string             `json:"detail,omitempty"`
	Documentation *MarkupContent     `json:"documentation,omitempty"`
	InsertText    string             `json:"insertText,omitempty"`
}

CompletionItem is one suggestion in textDocument/completion.

type CompletionItemKind

type CompletionItemKind int

CompletionItemKind classifies a completion item.

const (
	CompletionText     CompletionItemKind = 1
	CompletionFunction CompletionItemKind = 3
	CompletionVariable CompletionItemKind = 6
	CompletionKeyword  CompletionItemKind = 14
	CompletionOperator CompletionItemKind = 24
)

type CompletionList

type CompletionList struct {
	IsIncomplete bool             `json:"isIncomplete"`
	Items        []CompletionItem `json:"items"`
}

CompletionList is returned by textDocument/completion.

type CompletionOptions

type CompletionOptions struct {
	TriggerCharacters []string `json:"triggerCharacters,omitempty"`
}

CompletionOptions configures completion triggers.

type CompletionParams

type CompletionParams struct {
	TextDocumentPositionParams
}

CompletionParams is sent in textDocument/completion.

type Conn

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

Conn reads and writes LSP Content-Length framed JSON-RPC 2.0 messages over an arbitrary stream pair. Write calls are safe for concurrent use. Construct a Conn with NewConn.

func NewConn

func NewConn(r io.Reader, w io.Writer) *Conn

NewConn wraps r and w with Content-Length JSON-RPC framing.

func (*Conn) ReadMessage

func (c *Conn) ReadMessage() (*RPCMessage, error)

ReadMessage reads the next Content-Length framed JSON-RPC message. It returns io.EOF when the input stream closes cleanly at a message boundary.

func (*Conn) SendError

func (c *Conn) SendError(id json.RawMessage, code int, message string, data any) error

SendError writes a JSON-RPC 2.0 error response.

func (*Conn) SendNotification

func (c *Conn) SendNotification(method string, params any) error

SendNotification writes a JSON-RPC 2.0 notification.

func (*Conn) SendResponse

func (c *Conn) SendResponse(id json.RawMessage, result any) error

SendResponse writes a JSON-RPC 2.0 result response.

func (*Conn) WriteMessage

func (c *Conn) WriteMessage(msg any) error

WriteMessage writes msg with an LSP Content-Length header.

type CorrectnessParams

type CorrectnessParams struct {
	URI   string `json:"uri"`
	Entry string `json:"entry,omitempty"`
}

CorrectnessParams identifies the candidate in the current snapshot.

type CorrectnessRunner

type CorrectnessRunner func(context.Context, *Snapshot, CorrectnessParams) (cudakorrect.Verdict, error)

CorrectnessRunner evaluates a candidate from a snapshot.

type CorrelateParams

type CorrelateParams struct {
	URI    string `json:"uri"`
	Line   int    `json:"line"`
	Column int    `json:"column"`
}

CorrelateParams is sent in cudalsp/correlate. Line and Column are 0-based LSP coordinates.

type CorrelatedSite

type CorrelatedSite struct {
	Layer         string `json:"layer"`
	URI           string `json:"uri"`
	Range         Range  `json:"range"`
	Symbol        string `json:"symbol,omitempty"`
	PC            uint64 `json:"pc,omitempty"`
	Digest        string `json:"digest,omitempty"`
	Provenance    string `json:"provenance"`
	EvidenceClass string `json:"evidence_class,omitempty"`
	Detail        string `json:"detail,omitempty"`
}

CorrelatedSite is one provenance-verified coordinate in another layer.

type CorrelationResult

type CorrelationResult struct {
	Origin            LocationRef        `json:"origin"`
	Go                []CorrelatedSite   `json:"go,omitempty"`
	CUDA              []CorrelatedSite   `json:"cuda,omitempty"`
	TileIR            []CorrelatedSite   `json:"tileir,omitempty"`
	PTX               []CorrelatedSite   `json:"ptx,omitempty"`
	SASS              []CorrelatedSite   `json:"sass,omitempty"`
	Profile           []CorrelatedSite   `json:"profile,omitempty"`
	UnresolvedReasons []UnresolvedReason `json:"unresolved_reasons,omitempty"`
}

CorrelationResult maps a source or assembly coordinate across all six layers using only verified provenance (digests, ProvenanceLink records, lineinfo, and validated cudaprof/advise evidence).

type Diagnostic

type Diagnostic struct {
	Range              Range                          `json:"range"`
	Severity           DiagnosticSeverity             `json:"severity,omitempty"`
	Code               string                         `json:"code,omitempty"`
	Source             string                         `json:"source,omitempty"`
	Message            string                         `json:"message"`
	RelatedInformation []DiagnosticRelatedInformation `json:"relatedInformation,omitempty"`
	Data               any                            `json:"data,omitempty"`
}

Diagnostic represents a compiler, analyzer, or profile finding.

type DiagnosticOptions

type DiagnosticOptions struct {
	Identifier            string `json:"identifier,omitempty"`
	InterFileDependencies bool   `json:"interFileDependencies"`
	WorkspaceDiagnostics  bool   `json:"workspaceDiagnostics"`
}

DiagnosticOptions advertises LSP 3.17 pull diagnostics.

type DiagnosticRelatedInformation

type DiagnosticRelatedInformation struct {
	Location Location `json:"location"`
	Message  string   `json:"message"`
}

DiagnosticRelatedInformation links a diagnostic to a related source site.

type DiagnosticSeverity

type DiagnosticSeverity int

DiagnosticSeverity is the LSP diagnostic severity level.

const (
	SeverityError       DiagnosticSeverity = 1
	SeverityWarning     DiagnosticSeverity = 2
	SeverityInformation DiagnosticSeverity = 3
	SeverityHint        DiagnosticSeverity = 4
)

type DidChangeTextDocumentParams

type DidChangeTextDocumentParams struct {
	TextDocument   VersionedTextDocumentIdentifier  `json:"textDocument"`
	ContentChanges []TextDocumentContentChangeEvent `json:"contentChanges"`
}

DidChangeTextDocumentParams is sent in textDocument/didChange.

type DidCloseTextDocumentParams

type DidCloseTextDocumentParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
}

DidCloseTextDocumentParams is sent in textDocument/didClose.

type DidOpenTextDocumentParams

type DidOpenTextDocumentParams struct {
	TextDocument TextDocumentItem `json:"textDocument"`
}

DidOpenTextDocumentParams is sent in textDocument/didOpen.

type DidSaveTextDocumentParams

type DidSaveTextDocumentParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Text         *string                `json:"text,omitempty"`
}

DidSaveTextDocumentParams is sent in textDocument/didSave.

type Document

type Document struct {
	URI            string
	Path           string
	Language       Language
	Version        int
	Text           string
	SHA256         string
	Virtual        bool
	Provenance     string
	CubinResources []sass.KernelResource

	Diagnostics []Diagnostic
	// contains filtered or unexported fields
}

Document is an immutable analyzed view of one open or virtual file inside a Snapshot.

type DocumentDiagnosticParams

type DocumentDiagnosticParams struct {
	TextDocument     TextDocumentIdentifier `json:"textDocument"`
	Identifier       string                 `json:"identifier,omitempty"`
	PreviousResultID string                 `json:"previousResultId,omitempty"`
}

DocumentDiagnosticParams is sent in textDocument/diagnostic (LSP 3.17 pull).

type DocumentFormattingParams

type DocumentFormattingParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Options      FormattingOptions      `json:"options"`
}

DocumentFormattingParams is sent in textDocument/formatting.

type DocumentSymbol

type DocumentSymbol struct {
	Name           string           `json:"name"`
	Detail         string           `json:"detail,omitempty"`
	Kind           SymbolKind       `json:"kind"`
	Range          Range            `json:"range"`
	SelectionRange Range            `json:"selectionRange"`
	Children       []DocumentSymbol `json:"children,omitempty"`
}

DocumentSymbol represents a hierarchical symbol inside a single document.

type DocumentSymbolParams

type DocumentSymbolParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
}

DocumentSymbolParams is sent in textDocument/documentSymbol.

type Engine

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

Engine maintains workspace state and builds an immutable Snapshot on every document, provenance, or profile update. All exported methods are safe for concurrent use. Construct an Engine with NewEngine.

func NewEngine

func NewEngine(opts EngineOptions) *Engine

NewEngine creates an Engine with opts. Budget census facts are loaded once from embedded package data without invoking external compilers or devices.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/cudalsp"
)

func main() {
	eng := cudalsp.NewEngine(cudalsp.EngineOptions{})
	uri := "file:///example/add.ptx"
	ptxSrc := `.version 8.5
.target sm_90
.address_size 64

.visible .entry add(.param .u64 p0) {
	.reg .b64 %rd1;
	.reg .f32 %f<4>;
	ld.param.u64 %rd1, [p0];
	ld.global.v4.f32 {%f0, %f1, %f2, %f3}, [%rd1];
	ret;
}
`
	snap := eng.OpenDocument(uri, "ptx", 1, ptxSrc)
	syms := snap.DocumentSymbols(uri)
	hints := snap.InlayHints(uri, cudalsp.Range{End: cudalsp.Position{Line: 15}})
	fmt.Println("symbol:", syms[0].Name)
	fmt.Println("hint:", hints[0].Label)
}
Output:
symbol: add
hint: align: param[0]:16B

func (*Engine) AttachProfile

func (e *Engine) AttachProfile(name string, reportJSON []byte, prov ProfileProvenance) (*AttachedProfile, *Snapshot, error)

AttachProfile decodes an advise.Report JSON payload, enforces advise.Report.ValidateEvidence, registers a virtual summary document under cudalsp://profile/..., and rebuilds the snapshot so provenance-matching documents receive diagnostics, inlay hints, and hover annotations.

func (*Engine) ChangeDocument

func (e *Engine) ChangeDocument(uri string, version int, changes []TextDocumentContentChangeEvent) (*Snapshot, error)

ChangeDocument applies full or incremental LSP changes to an open document.

func (*Engine) CloseDocument

func (e *Engine) CloseDocument(uri string) *Snapshot

CloseDocument removes a non-virtual document from the workspace.

func (*Engine) LinkArtifacts

func (e *Engine) LinkArtifacts(link ProvenanceLink) (*Snapshot, error)

LinkArtifacts registers an explicit provenance link between two artifacts. Both digests, URIs, kind, and provenance description must be non-empty.

func (*Engine) OpenCubin

func (e *Engine) OpenCubin(name string, data []byte, provenance string) (*VirtualDocument, *Snapshot, error)

OpenCubin validates a CUBIN binary with cubin.Parse, extracts kernel resources with sass.InspectCubin, decodes SASS via sass.DecodeCUBIN when supported, and publishes a virtual cudalsp://cubin/<digest>/<name>.sass document.

func (*Engine) OpenDocument

func (e *Engine) OpenDocument(uri, languageID string, version int, text string) *Snapshot

OpenDocument opens or replaces a document in the workspace and rebuilds the immutable snapshot.

func (*Engine) PutVirtualDocument

func (e *Engine) PutVirtualDocument(uri string, lang Language, text, provenance string) (*VirtualDocument, *Snapshot, error)

PutVirtualDocument stores a read-only virtual document (cudalsp://...) and indexes it in the workspace snapshot.

func (*Engine) SaveDocument

func (e *Engine) SaveDocument(uri string, text *string) *Snapshot

SaveDocument optionally updates document text on didSave and refreshes the snapshot.

func (*Engine) SetBaselineSignature

func (e *Engine) SetBaselineSignature(entry string, sig cuda.Signature)

SetBaselineSignature registers an expected baseline PTX parameter signature for entry so PTX and provenance-linked CUDA analyzers run hotswap.CheckABI.

func (*Engine) Snapshot

func (e *Engine) Snapshot() *Snapshot

Snapshot returns the current immutable workspace snapshot.

type EngineOptions

type EngineOptions struct {
	CUDAFrontend       CUDAFrontend
	BundleExporter     BundleExporter
	SharedLimit        *sass.SharedLimit
	BlockDims          [3]int
	MaxThreads         int
	TargetArch         string
	YieldParam         *int
	BaselineSignatures map[string]cuda.Signature
}

EngineOptions configures a Engine. Zero values use safe host-only defaults.

type ExecuteCommandOptions

type ExecuteCommandOptions struct {
	Commands []string `json:"commands"`
}

ExecuteCommandOptions lists supported workspace commands.

type ExecuteCommandParams

type ExecuteCommandParams struct {
	Command   string            `json:"command"`
	Arguments []json.RawMessage `json:"arguments,omitempty"`
}

ExecuteCommandParams is sent in workspace/executeCommand.

type ExportBundleParams

type ExportBundleParams struct {
	Scope   string `json:"scope,omitempty"`
	URI     string `json:"uri,omitempty"`
	RunID   string `json:"run_id,omitempty"`
	OutPath string `json:"out_path,omitempty"`
}

ExportBundleParams is sent in cudalsp/exportBundle.

type ExportBundleResult

type ExportBundleResult struct {
	Path    string   `json:"path,omitempty"`
	SHA256  string   `json:"sha256,omitempty"`
	Files   []string `json:"files,omitempty"`
	Content string   `json:"content,omitempty"`
}

ExportBundleResult is returned by cudalsp/exportBundle.

type FormattingOptions

type FormattingOptions struct {
	TabSize      int  `json:"tabSize"`
	InsertSpaces bool `json:"insertSpaces"`
}

FormattingOptions configures textDocument/formatting.

type FullDocumentDiagnosticReport

type FullDocumentDiagnosticReport struct {
	Kind     string       `json:"kind"`
	ResultID string       `json:"resultId,omitempty"`
	Items    []Diagnostic `json:"items"`
}

FullDocumentDiagnosticReport is returned by textDocument/diagnostic.

type Hover

type Hover struct {
	Contents MarkupContent `json:"contents"`
	Range    *Range        `json:"range,omitempty"`
}

Hover is returned by textDocument/hover.

type InitializeParams

type InitializeParams struct {
	ProcessID    int             `json:"processId,omitempty"`
	RootURI      string          `json:"rootUri,omitempty"`
	RootPath     string          `json:"rootPath,omitempty"`
	ClientInfo   *ClientInfo     `json:"clientInfo,omitempty"`
	Capabilities json.RawMessage `json:"capabilities,omitempty"`
}

InitializeParams is sent by the client in initialize.

type InitializeResult

type InitializeResult struct {
	Capabilities ServerCapabilities `json:"capabilities"`
	ServerInfo   *ServerInfo        `json:"serverInfo,omitempty"`
}

InitializeResult is returned by initialize.

type InlayHint

type InlayHint struct {
	Position     Position       `json:"position"`
	Label        string         `json:"label"`
	Kind         InlayHintKind  `json:"kind,omitempty"`
	Tooltip      *MarkupContent `json:"tooltip,omitempty"`
	PaddingLeft  bool           `json:"paddingLeft,omitempty"`
	PaddingRight bool           `json:"paddingRight,omitempty"`
}

InlayHint is an inline annotation rendered inside an editor buffer.

type InlayHintKind

type InlayHintKind int

InlayHintKind classifies an inlay hint.

const (
	InlayHintType      InlayHintKind = 1
	InlayHintParameter InlayHintKind = 2
)

type InlayHintParams

type InlayHintParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Range        Range                  `json:"range"`
}

InlayHintParams is sent in textDocument/inlayHint.

type Language

type Language string

Language identifies one of the supported GPU/host analysis domains.

const (
	LangGo      Language = "go"
	LangCUDA    Language = "cuda"
	LangTileIR  Language = "tileir"
	LangPTX     Language = "ptx"
	LangSASS    Language = "sass"
	LangProfile Language = "profile"
	LangCubin   Language = "cubin"
	LangUnknown Language = "unknown"
)

func DetectLanguage

func DetectLanguage(uri, languageID string) Language

DetectLanguage infers the domain from a URI extension or LSP languageId.

type Location

type Location struct {
	URI   string `json:"uri"`
	Range Range  `json:"range"`
}

Location identifies a range within a document URI.

type LocationRef

type LocationRef struct {
	Layer  string `json:"layer"`
	URI    string `json:"uri"`
	Range  Range  `json:"range"`
	Symbol string `json:"symbol,omitempty"`
	PC     uint64 `json:"pc,omitempty"`
	Digest string `json:"digest,omitempty"`
}

LocationRef identifies the starting coordinate of a correlation query.

type MarkupContent

type MarkupContent struct {
	Kind  string `json:"kind"`
	Value string `json:"value"`
}

MarkupContent holds plaintext or markdown documentation.

type Position

type Position struct {
	Line      int `json:"line"`
	Character int `json:"character"`
}

Position is a zero-based line and UTF-16 character offset in a document.

type ProfileProvenance

type ProfileProvenance struct {
	ArtifactDigest string `json:"artifact_digest,omitempty"`
	TargetURI      string `json:"target_uri,omitempty"`
	Provenance     string `json:"provenance,omitempty"`
}

ProfileProvenance binds an attached advise.Report to an explicit artifact digest or URI. Without provenance, findings are never projected onto source buffers by bare kernel name.

type ProvenanceLink struct {
	FromURI     string                `json:"from_uri"`
	FromDigest  string                `json:"from_digest"`
	ToURI       string                `json:"to_uri"`
	ToDigest    string                `json:"to_digest"`
	Kind        string                `json:"kind"`
	Entry       string                `json:"entry,omitempty"`
	Provenance  string                `json:"provenance"`
	Attribution *lineinfo.Attribution `json:"-"`
}

ProvenanceLink records an explicit provenance relationship between two workspace artifacts identified by both URI and SHA-256 content digest. Bare symbol names never establish a link.

type PublishDiagnosticsParams

type PublishDiagnosticsParams struct {
	URI         string       `json:"uri"`
	Version     *int         `json:"version,omitempty"`
	Diagnostics []Diagnostic `json:"diagnostics"`
}

PublishDiagnosticsParams is sent in textDocument/publishDiagnostics.

type RPCError

type RPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

RPCError is a JSON-RPC 2.0 error object.

func (*RPCError) Error

func (e *RPCError) Error() string

Error returns the JSON-RPC error code and message.

type RPCMessage

type RPCMessage struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Method  string          `json:"method,omitempty"`
	Params  json.RawMessage `json:"params,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *RPCError       `json:"error,omitempty"`
}

RPCMessage is a wire-level JSON-RPC 2.0 request, response, or notification.

func (*RPCMessage) IsNotification

func (m *RPCMessage) IsNotification() bool

IsNotification reports whether m is a one-way notification.

func (*RPCMessage) IsRequest

func (m *RPCMessage) IsRequest() bool

IsRequest reports whether m is a client-to-server request expecting a reply.

type Range

type Range struct {
	Start Position `json:"start"`
	End   Position `json:"end"`
}

Range is a half-open [Start, End) span in a document.

type ReferenceContext

type ReferenceContext struct {
	IncludeDeclaration bool `json:"includeDeclaration"`
}

ReferenceContext controls whether the declaration is included in references.

type ReferenceParams

type ReferenceParams struct {
	TextDocumentPositionParams
	Context ReferenceContext `json:"context"`
}

ReferenceParams is sent in textDocument/references.

type SemanticTokens

type SemanticTokens struct {
	ResultID string   `json:"resultId,omitempty"`
	Data     []uint32 `json:"data"`
}

SemanticTokens holds LSP relative-encoded semantic token 5-tuples.

type SemanticTokensLegend

type SemanticTokensLegend struct {
	TokenTypes     []string `json:"tokenTypes"`
	TokenModifiers []string `json:"tokenModifiers"`
}

SemanticTokensLegend declares token types and modifiers during initialize.

type SemanticTokensOptions

type SemanticTokensOptions struct {
	Legend SemanticTokensLegend `json:"legend"`
	Full   bool                 `json:"full"`
}

SemanticTokensOptions advertises semantic token support.

type SemanticTokensParams

type SemanticTokensParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
}

SemanticTokensParams is sent in textDocument/semanticTokens/full.

type Server

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

Server serves LSP 3.17 and cudalsp/* custom JSON-RPC requests backed by an Engine.

func NewServer

func NewServer(engine *Engine, cfg ServerConfig) *Server

NewServer constructs an LSP server around engine. If engine is nil, a default host-only Engine is created.

func (*Server) Engine

func (s *Server) Engine() *Engine

Engine returns the server's underlying analysis engine.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(ctx context.Context, addr string) error

ListenAndServe serves LSP connections on addr ("stdio", loopback "tcp:...", or "unix:...") until ctx is cancelled or the stream closes. For stdio, it reads from os.Stdin and writes to os.Stdout; for socket transports, each accepted connection runs against s.

func (*Server) ServeListener

func (s *Server) ServeListener(ctx context.Context, ln net.Listener) error

ServeListener accepts connections on ln until ctx is cancelled or ln closes.

func (*Server) ServeStream

func (s *Server) ServeStream(ctx context.Context, r io.Reader, w io.Writer) error

ServeStream serves one JSON-RPC 2.0 LSP session over r and w until EOF, an exit notification, or ctx cancellation.

type ServerCapabilities

type ServerCapabilities struct {
	TextDocumentSync           TextDocumentSyncOptions `json:"textDocumentSync"`
	HoverProvider              bool                    `json:"hoverProvider"`
	DefinitionProvider         bool                    `json:"definitionProvider"`
	ReferencesProvider         bool                    `json:"referencesProvider"`
	DocumentSymbolProvider     bool                    `json:"documentSymbolProvider"`
	WorkspaceSymbolProvider    bool                    `json:"workspaceSymbolProvider"`
	InlayHintProvider          bool                    `json:"inlayHintProvider"`
	CodeLensProvider           *CodeLensOptions        `json:"codeLensProvider,omitempty"`
	CompletionProvider         *CompletionOptions      `json:"completionProvider,omitempty"`
	DocumentFormattingProvider bool                    `json:"documentFormattingProvider"`
	SemanticTokensProvider     *SemanticTokensOptions  `json:"semanticTokensProvider,omitempty"`
	CodeActionProvider         bool                    `json:"codeActionProvider"`
	CallHierarchyProvider      bool                    `json:"callHierarchyProvider"`
	ExecuteCommandProvider     *ExecuteCommandOptions  `json:"executeCommandProvider,omitempty"`
	DiagnosticProvider         *DiagnosticOptions      `json:"diagnosticProvider,omitempty"`
}

ServerCapabilities is returned in InitializeResult.

type ServerConfig

type ServerConfig struct {
	Name            string
	Version         string
	CommandHandlers map[string]CommandHandler

	// ReadProfile overrides path-based profile loading.
	ReadProfile func(string) ([]byte, error)

	// CorrectnessRunner evaluates the open document identified by the request.
	// It must honor cancellation and may be called concurrently.
	CorrectnessRunner CorrectnessRunner
}

ServerConfig configures a Server.

type ServerInfo

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`
}

ServerInfo describes the cudalsp server.

type Snapshot

type Snapshot struct {
	Rev         uint64
	Docs        map[string]*Document
	Virtual     map[string]*VirtualDocument
	Links       []ProvenanceLink
	Profiles    []*AttachedProfile
	BudgetFacts []budget.KernelFact
	Options     EngineOptions
}

Snapshot is an immutable point-in-time workspace index covering all six domains for one workspace revision.

func (*Snapshot) CodeActions

func (s *Snapshot) CodeActions(uri string, r Range) []CodeAction

CodeActions returns quick fixes and inspection actions for uri and range r.

func (*Snapshot) CodeLenses

func (s *Snapshot) CodeLenses(uri string) []CodeLens

CodeLenses returns actionable code lenses for launch sites and GPU kernels.

func (*Snapshot) Completion

func (s *Snapshot) Completion(uri string, pos Position) *CompletionList

Completion returns language-aware ISA, opcode, register, and keyword items.

func (*Snapshot) Correlate

func (s *Snapshot) Correlate(uri string, pos Position) CorrelationResult

Correlate maps (uri, pos) across Go, CUDA, Tile IR, PTX, SASS, and cudaprof layers. Two documents are joined only when connected by verified SHA-256 provenance links; bare symbol name matches are never joined.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/cudalsp"
)

func main() {
	eng := cudalsp.NewEngine(cudalsp.EngineOptions{})
	cuURI := "file:///example/add.cu"
	ptxURI := "cudalsp://compile/0011223344556677/add.ptx"

	cuSrc := "__global__ void add(float* p) {\n\tp[0] += 1.0f;\n}\n"
	ptxSrc := `.version 8.5
.target sm_90
.address_size 64
.file 1 "add.cu"
.visible .entry add(.param .u64 p0) {
	.loc 1 2 0
	ret;
}
`
	eng.OpenDocument(cuURI, "cuda", 1, cuSrc)
	_, _, _ = eng.PutVirtualDocument(ptxURI, cudalsp.LangPTX, ptxSrc, "nvrtc:sm_90")

	snap := eng.Snapshot()
	// Without an explicit provenance link, bare symbol names are not joined.
	before := snap.Correlate(cuURI, cudalsp.Position{Line: 1})
	fmt.Println("before link ptx matches:", len(before.PTX))

	snap, _ = eng.LinkArtifacts(cudalsp.ProvenanceLink{
		FromURI:    cuURI,
		FromDigest: snap.Document(cuURI).SHA256,
		ToURI:      ptxURI,
		ToDigest:   snap.Document(ptxURI).SHA256,
		Kind:       "cuda-to-ptx",
		Entry:      "add",
		Provenance: "nvrtc:sm_90",
	})
	after := snap.Correlate(cuURI, cudalsp.Position{Line: 1})
	fmt.Println("after link ptx matches:", len(after.PTX), after.PTX[0].Provenance)
}
Output:
before link ptx matches: 0
after link ptx matches: 1 nvrtc:sm_90

func (*Snapshot) Definition

func (s *Snapshot) Definition(uri string, pos Position) []Location

Definition resolves Go-to-Definition within a document or across provenance-linked layers. Bare symbol names never join separate files.

func (*Snapshot) Diagnostics

func (s *Snapshot) Diagnostics(uri string) []Diagnostic

Diagnostics returns a copy of diagnostics computed for uri in s.

func (*Snapshot) Document

func (s *Snapshot) Document(uri string) *Document

Document returns the analyzed document for uri, or nil if absent.

func (*Snapshot) DocumentSymbols

func (s *Snapshot) DocumentSymbols(uri string) []DocumentSymbol

DocumentSymbols returns hierarchical symbols for uri.

func (*Snapshot) Format

func (s *Snapshot) Format(uri string) ([]TextEdit, error)

Format formats PTX (via ptxast.Print) and Tile IR (via tileir.Module.String).

func (*Snapshot) Hover

func (s *Snapshot) Hover(uri string, pos Position) *Hover

Hover returns markdown hover information at (uri, pos), or nil if none.

func (*Snapshot) IncomingCalls

func (s *Snapshot) IncomingCalls(item CallHierarchyItem) []CallHierarchyIncomingCall

IncomingCalls returns provenance-verified callers of item (such as Go launch sites invoking a GPU kernel, or CUDA/PTX callers of a device function).

func (*Snapshot) InlayHints

func (s *Snapshot) InlayHints(uri string, r Range) []InlayHint

InlayHints returns inline contract, resource, and evidence-tagged profile hints overlapping r.

func (*Snapshot) OutgoingCalls

func (s *Snapshot) OutgoingCalls(item CallHierarchyItem) []CallHierarchyOutgoingCall

OutgoingCalls returns provenance-verified outgoing calls from item (including Go host function -> GPU kernel entries and device-to-device calls).

func (*Snapshot) PrepareCallHierarchy

func (s *Snapshot) PrepareCallHierarchy(uri string, pos Position) []CallHierarchyItem

PrepareCallHierarchy resolves a CallHierarchyItem at (uri, pos).

func (*Snapshot) References

func (s *Snapshot) References(uri string, pos Position, includeDecl bool) []Location

References returns references to the symbol under pos within doc and across provenance-linked documents.

func (*Snapshot) SemanticTokens

func (s *Snapshot) SemanticTokens(uri string) *SemanticTokens

SemanticTokens computes LSP relative-encoded semantic tokens for uri.

func (*Snapshot) URIs

func (s *Snapshot) URIs() []string

URIs returns all open document URIs in sorted order.

func (*Snapshot) VirtualDocument

func (s *Snapshot) VirtualDocument(uri string) *VirtualDocument

VirtualDocument returns the virtual document for uri, or nil if absent.

func (*Snapshot) WorkspaceSymbols

func (s *Snapshot) WorkspaceSymbols(query string) []SymbolInformation

WorkspaceSymbols returns symbols across all documents matching query.

type SymbolInformation

type SymbolInformation struct {
	Name          string     `json:"name"`
	Kind          SymbolKind `json:"kind"`
	Location      Location   `json:"location"`
	ContainerName string     `json:"containerName,omitempty"`
}

SymbolInformation represents a symbol returned by workspace/symbol.

type SymbolKind

type SymbolKind int

SymbolKind classifies a document or workspace symbol (LSP 3.17).

const (
	SymbolKindFile      SymbolKind = 1
	SymbolKindModule    SymbolKind = 2
	SymbolKindNamespace SymbolKind = 3
	SymbolKindPackage   SymbolKind = 4
	SymbolKindClass     SymbolKind = 5
	SymbolKindMethod    SymbolKind = 6
	SymbolKindField     SymbolKind = 8
	SymbolKindFunction  SymbolKind = 12
	SymbolKindVariable  SymbolKind = 13
	SymbolKindConstant  SymbolKind = 14
	SymbolKindStruct    SymbolKind = 23
	SymbolKindKey       SymbolKind = 20
)

type TextDocumentContentChangeEvent

type TextDocumentContentChangeEvent struct {
	Range *Range `json:"range,omitempty"`
	Text  string `json:"text"`
}

TextDocumentContentChangeEvent is one full or incremental document change.

type TextDocumentIdentifier

type TextDocumentIdentifier struct {
	URI string `json:"uri"`
}

TextDocumentIdentifier identifies a document by URI.

type TextDocumentItem

type TextDocumentItem struct {
	URI        string `json:"uri"`
	LanguageID string `json:"languageId"`
	Version    int    `json:"version"`
	Text       string `json:"text"`
}

TextDocumentItem is sent by the client in textDocument/didOpen.

type TextDocumentPositionParams

type TextDocumentPositionParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Position     Position               `json:"position"`
}

TextDocumentPositionParams identifies a cursor position in a document.

type TextDocumentSyncOptions

type TextDocumentSyncOptions struct {
	OpenClose bool `json:"openClose"`
	Change    int  `json:"change"` // 2 = Incremental (also accepts full changes)
	Save      bool `json:"save"`
}

TextDocumentSyncOptions configures document synchronization.

type TextEdit

type TextEdit struct {
	Range   Range  `json:"range"`
	NewText string `json:"newText"`
}

TextEdit replaces Range with NewText.

type UnresolvedReason

type UnresolvedReason struct {
	Layer  string `json:"layer"`
	Reason string `json:"reason"`
}

UnresolvedReason states explicitly why a layer was not correlated.

type VersionedTextDocumentIdentifier

type VersionedTextDocumentIdentifier struct {
	URI     string `json:"uri"`
	Version int    `json:"version"`
}

VersionedTextDocumentIdentifier identifies a specific version of a document.

type VirtualDocument

type VirtualDocument struct {
	URI        string   `json:"uri"`
	Language   Language `json:"language"`
	Text       string   `json:"text"`
	SHA256     string   `json:"sha256"`
	Provenance string   `json:"provenance,omitempty"`
}

VirtualDocument is a read-only generated artifact exposed under cudalsp://.

type VirtualDocumentParams

type VirtualDocumentParams struct {
	URI string `json:"uri"`
}

VirtualDocumentParams is sent in cudalsp/virtualDocument.

type VirtualDocumentResult

type VirtualDocumentResult struct {
	URI        string `json:"uri"`
	Language   string `json:"language"`
	Text       string `json:"text"`
	SHA256     string `json:"sha256"`
	Provenance string `json:"provenance,omitempty"`
}

VirtualDocumentResult is returned by cudalsp/virtualDocument.

type WorkspaceEdit

type WorkspaceEdit struct {
	Changes map[string][]TextEdit `json:"changes,omitempty"`
}

WorkspaceEdit describes edits across one or more documents.

type WorkspaceSymbolParams

type WorkspaceSymbolParams struct {
	Query string `json:"query"`
}

WorkspaceSymbolParams is sent in workspace/symbol.

Jump to

Keyboard shortcuts

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