Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion doc/lsp/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# DML Language Server (`dmlsp`)

`dmlsp` is the Language Server Protocol (LSP) server for Device Modeling Language.
It provides IDE and editor integrations with real-time syntax feedback and code navigation.
It provides IDE and editor integrations with real-time syntax feedback, semantic highlighting, and code navigation.

---

Expand All @@ -21,6 +21,7 @@ over **JSON-RPC 2.0** via standard I/O (`stdin`/`stdout`).
- Dotted member chains (such as `regs.r1.f1`) and hierarchy keywords (`this`, `parent`, `dev`)
- `method` declarations and definitions, input parameters, and named return parameters
- `local`, `session`, and `saved` variables, `param`, `constant`, `hook`, `loggroup`, `typedef`, and `extern` declarations
- **Semantic Tokens Highlighting**: Computes semantic tokens for full files (`textDocument/semanticTokens/full`) and viewport ranges (`textDocument/semanticTokens/range`) using a hybrid lexer-baseline and local AST/symbol pass that handles DML keywords used as identifiers, templates, objects, types, modifiers, and graceful fallback on syntax errors or `dml 1.2;` files.
- **Live Editor Synchronization**: Tracks unsaved edits in memory (supporting incremental updates) while automatically falling back to on-disk files when resolving unopened imported files.

---
Expand Down
16 changes: 13 additions & 3 deletions doc/lsp/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ their specific limitations, and unsupported LSP commands.
| `textDocument/didClose` | Client -> Server | Notification | Supported (with limitations) | Clears diagnostics for the file and drops the in-memory buffer. |
| `textDocument/publishDiagnostics` | Server -> Client | Notification | Supported (with limitations) | Pushes syntax errors and DML 1.2 `EUNIMPL` warnings. |
| `textDocument/definition` | Client -> Server | Request | Supported (with limitations) | Resolves symbols, hierarchies, templates, and `import` paths. |
| `textDocument/semanticTokens/full` | Client -> Server | Request | Supported (with limitations) | Computes semantic highlighting tokens for an entire document. |
| `textDocument/semanticTokens/range` | Client -> Server | Request | Supported (with limitations) | Computes semantic highlighting tokens overlapping a requested range. |

---

Expand All @@ -43,6 +45,7 @@ their specific limitations, and unsupported LSP commands.
- `positionEncoding`: `"utf-16"`
- `textDocumentSync`: `{ openClose: true, change: 2 (Incremental), save: {} }`
- `definitionProvider`: `true`
- `semanticTokensProvider`: `{ legend: { tokenTypes: [...], tokenModifiers: [...] }, full: true, range: true }`
- **Limitations**:
- **Single Workspace Root**: Only `workspaceFolders[0].uri` (or `rootUri` if `workspaceFolders` is empty) is used as the workspace root for `import` path lookup. Additional folders in multi-root workspaces are ignored.
- **No `initializationOptions`**: Custom initialization options (such as extra import include directories or custom diagnostic debounce settings) are not supported.
Expand Down Expand Up @@ -106,6 +109,15 @@ their specific limitations, and unsupported LSP commands.
- **Flat Method Scope**: Local variables inside nested `{ ... }` blocks within the same method share a flat method-level scope; shadowed names inside separate nested blocks resolve to the last declaration in that method.
- **Files with Syntax Errors**: When a buffer contains syntax errors, resolution relies on a best-effort partial parse of the current buffer, so symbols located after a parse failure may not resolve.

- **`textDocument/semanticTokens/full`** & **`textDocument/semanticTokens/range`** *(Requests, Client -> Server)*
- **Behavior**: Returns UTF-16 delta-encoded `SemanticTokens` for the full document or overlapping `Range` using a hybrid lexer-baseline and local AST/symbol pass (`18` token types, `6` token modifiers). Multi-line comments are split per line with trailing horizontal whitespace stripped.
- **Limitations**:
- **Same-File Resolution Only**: Does not follow cross-file `import` statements; symbols defined only in imported files rely on syntactic call/member heuristics (`function` for bare calls, `method` for member calls, `property` for member accesses) or remain untokenized for bare identifiers.
- **No Delta Updates**: `textDocument/semanticTokens/full/delta` is not implemented (`resultId` is omitted).
- **Embedded C Blocks**: `C_CODE_BLOCK` regions (`%{ ... %}`) are left untokenized.
- **DML 1.2 Fallback**: Documents with a `dml 1.2;` header use lexer-baseline tokens only.
- **Files with Syntax Errors**: Unparsed regions fall back cleanly to lexer-baseline tokens (`keyword`, `modifier`, `comment`, `string`, `number`, `operator`, built-in types).

---

## 3. Unsupported LSP API Commands
Expand Down Expand Up @@ -166,9 +178,7 @@ Any LSP 3.17 request or notification not listed in Section 2 is **unsupported**
| Method | Direction | Notes |
| :--- | :--- | :--- |
| `textDocument/documentHighlight` | Client -> Server | Unsupported. |
| `textDocument/semanticTokens/full` | Client -> Server | Unsupported (syntax highlighting relies on editor grammars). |
| `textDocument/semanticTokens/full/delta` | Client -> Server | Unsupported. |
| `textDocument/semanticTokens/range` | Client -> Server | Unsupported. |
| `textDocument/semanticTokens/full/delta` | Client -> Server | Unsupported (use `textDocument/semanticTokens/full` or `textDocument/semanticTokens/range`). |
| `textDocument/foldingRange` | Client -> Server | Unsupported (folding relies on editor indentation/grammar). |
| `textDocument/selectionRange` | Client -> Server | Unsupported. |
| `textDocument/linkedEditingRange` | Client -> Server | Unsupported. |
Expand Down
45 changes: 41 additions & 4 deletions doc/lsp/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,48 @@ The following DML declarations are indexed and navigable within their lexical, o

---

## 3. Known Limitations
## 3. Semantic Tokens Highlighting

`dmlsp` advertises `semanticTokensProvider` (`full: true`, `range: true`) and serves both `textDocument/semanticTokens/full` and `textDocument/semanticTokens/range` requests (incremental `full/delta` is not supported).

Highlighting uses a two-stage hybrid pipeline:
1. **Lexer Baseline**: Classifies comments (splitting multi-line block comments per line), string/char literals, numeric literals, operators, qualifiers, and keywords from the token stream, ensuring incomplete buffers mid-edit and `dml 1.2;` files continue to highlight reliably.
2. **AST & Same-File Symbol Refinement**: Walks the parse tree with same-file symbol resolution to reclassify keywords used as identifiers (e.g., `size`, `data`, `register`), declaration/definition sites, local/object/template members, `this`/`parent`/`dev`, method/function calls, types, and `struct`/`layout`/`bitfields` members.

### Supported Token Types & Modifiers

| Semantic Token Type | DML Constructs |
| :--- | :--- |
| `comment` | Line comments (`// ...`) and block comments (`/* ... */`, per-line spans) |
| `keyword` | Control/declaration keywords, `#if`/`#else`/`#foreach`/`#select`, `true`/`false`/`NULL`/`undefined`, `log` kind, time unit (`s`, etc.) |
| `modifier` | Method/storage/type qualifiers (`inline`, `shared`, `independent`, `startup`, `memoized`, `throws`, `const`, `static`, `vect`, `signed`, `unsigned`, etc.) |
| `string` | String and character literals |
| `number` | Integer, hex, binary, and float literals |
| `operator` | Arithmetic, bitwise, logical, relational, assignment, ternary (`?`, `#?`), `->`, `@`, `...` |
| `interface` | `template` definitions and `is` / `in each` / `each` / `sequence()` template references |
| `class` | `device`, `subdevice`, `bank`, `group`, `port`, `connect`, `implement`, `interface`, `register`, `field`, `attribute`, `event` |
| `property` | `param`, `struct`/`union`/`layout`/`bitfields` fields, `.field` designated initializers, unresolved member accesses |
| `method` | `method` declarations/definitions, resolved method references, unresolved member calls (`obj.m()`) |
| `function` | `extern` functions and unresolved bare calls (`fn()`) |
| `parameter` | Method input/output parameters and `after h -> (x, y)` message bindings |
| `variable` | `local`, `session`, `saved`, `static`, loop (`for`/`foreach`/`select`), and array-index variables; `this`, `parent`, `dev` |
| `enumMember` | `constant` and `loggroup` declarations/references |
| `event` | `hook` declarations and references |
| `type` | Primitive C/DML types (`int`, `uint32`, `bool`, standalone `unsigned`/`signed`, etc.) and `typedef`s |
| `struct` | `struct`, `union`, `layout`, `bitfields` tags and aliases |
| `label` | `goto` labels |

Token modifiers emitted in bitmask form: `declaration`, `definition`, `readonly` (`constant` and `const`-qualified variables/parameters), `static` (`static`/`session`/`saved`), `abstract` (`shared method ...;`), and `defaultLibrary` (`this`, `parent`, `dev`, and built-in primitive types).

---

## 4. Known Limitations

- **Single Target Location**: Go to Definition returns at most one target location. When a `param` or `default method` is declared in a template and overridden in an object, navigating to it resolves to the highest-precedence definition in scope order rather than offering a list of all overrides.
- **Import Search Directories**: `dmlsp` searches only the importing file's directory and the primary workspace root (plus their `1.4/` subdirectories). Additional external include paths (such as custom `-I` directories outside the workspace) cannot currently be configured.
- **`in each` Statements**: Template applications (`in each ... is ...`) and declarations inside `in each` blocks are not indexed for member resolution.
- **Embedded C Blocks (`%{ ... %}`)**: Symbols defined inside `header %{ ... %}` and `footer %{ ... %}` C blocks are not indexed.
- **`in each` Statements**: Member declarations inside `in each` blocks are not indexed for member Go to Definition resolution (though `in each <template>` template names are highlighted semantically).
- **Embedded C Blocks (`%{ ... %}`)**: Symbols defined inside `header %{ ... %}` and `footer %{ ... %}` C blocks are not indexed for navigation and are left untokenized by semantic highlighting.
- **Same-File Scope for Semantic Tokens**: Semantic tokens resolve symbols and template inheritance within the current file only without following cross-file `import` statements; unresolved bare calls default to `function`, unresolved member calls to `method`, unresolved member accesses to `property`, and unresolved bare identifiers remain untokenized.
- **DML 1.2 Highlighting Fallback**: Files declaring `dml 1.2;` keep the lexer-baseline semantic tokens only without DML 1.4 AST refinement.
- **Flat Method Scope for Locals**: Local variables declared inside nested `{ ... }` blocks within the same method share a single method-level scope; if two nested blocks declare local variables with the same name, navigation resolves to the last declaration in that method.
- **Buffers with Active Syntax Errors**: When a file currently contains syntax errors, Go to Definition relies on a best-effort partial parse of the current buffer, so symbols after the syntax error may fail to resolve until the error is fixed.
- **Buffers with Active Syntax Errors**: When a file currently contains syntax errors, Go to Definition relies on a best-effort partial parse of the current buffer, so symbols after the syntax error may fail to resolve until the error is fixed, while Semantic Tokens retain lexer-baseline tokens across broken regions.
179 changes: 161 additions & 18 deletions pkg/lsp/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,16 @@ func LineAndByteCol(

// FileEntry represents an in-memory document buffer and its line metadata.
type FileEntry struct {
Path string
Version int32
Content string
Buffer *stream.HashedBuffer
AST antlr.ParseTree
Symbols *FileSymbols
modTime time.Time
lineOffsets []int
Path string
Version int32
Content string
Buffer *stream.HashedBuffer
AST antlr.ParseTree
Tokens *antlr.CommonTokenStream
Symbols *FileSymbols
semanticSpans []semanticSpan
modTime time.Time
lineOffsets []int
}

// Name returns the file's base name.
Expand Down Expand Up @@ -270,14 +272,18 @@ func (e *FileEntry) SetContent(newContent string) {
e.lineOffsets = computeLineOffsets(e.Content)
e.modTime = time.Now()
e.AST = nil
e.Tokens = nil
e.Symbols = nil
e.semanticSpans = nil
}

type diskCacheEntry struct {
hash stream.Hash
buf *stream.HashedBuffer
ast antlr.ParseTree
symbols *FileSymbols
hash stream.Hash
buf *stream.HashedBuffer
ast antlr.ParseTree
tokens *antlr.CommonTokenStream
symbols *FileSymbols
semanticSpans []semanticSpan
}

// FsCache is a thread-safe in-memory file overlay cache implementing
Expand Down Expand Up @@ -589,7 +595,9 @@ func (c *FsCache) SetAST(pathOrURI string, tree antlr.ParseTree) error {
}

entry.AST = tree
entry.Tokens = nil
entry.Symbols = nil
entry.semanticSpans = nil
return nil
}

Expand All @@ -614,7 +622,35 @@ func (c *FsCache) SetASTIfMatch(
}

entry.AST = tree
entry.Tokens = nil
entry.Symbols = nil
entry.semanticSpans = nil
return true
}

func (c *FsCache) setParsedIfMatch(
pathOrURI string,
expectedHash stream.Hash,
tokens *antlr.CommonTokenStream,
tree antlr.ParseTree,
) bool {
canonical, err := CanonicalPath(pathOrURI)
if err != nil {
return false
}

c.mu.Lock()
defer c.mu.Unlock()

entry, ok := c.overlay[canonical]
if !ok || entry.Buffer == nil || entry.Buffer.Hash() != expectedHash {
return false
}

entry.AST = tree
entry.Tokens = tokens
entry.Symbols = nil
entry.semanticSpans = nil
return true
}

Expand Down Expand Up @@ -672,6 +708,7 @@ func (c *FsCache) GetOrParse(
buf := entry.Buffer
content := entry.Content
tree := entry.AST
tokens := entry.Tokens
syms := entry.Symbols
c.mu.RUnlock()

Expand All @@ -684,10 +721,8 @@ func (c *FsCache) GetOrParse(
return buf, tree, syms, nil
}
if tree == nil {
parseBuf := stream.NewHashedBufferFromString(canonical, content)
errListener := dmlex.NewErrorListener(canonical, 0)
file := dmlex.ParseStream(parseBuf, errListener)
tree = file.Parser.Dml()
tokens, tree = parseStreamAndTokens(canonical, content, errListener)
}
if syms == nil {
syms = ExtractFileSymbols(docURI, tree)
Expand All @@ -700,6 +735,9 @@ func (c *FsCache) GetOrParse(
}
if cur.Buffer.Hash() == targetHash {
cur.AST = tree
if tokens != nil {
cur.Tokens = tokens
}
cur.Symbols = syms
}
}
Expand All @@ -724,10 +762,8 @@ func (c *FsCache) GetOrParse(
return cached.buf, cached.ast, cached.symbols, nil
}

parseBuf := stream.NewHashedBufferFromString(canonical, content)
errListener := dmlex.NewErrorListener(canonical, 0)
file := dmlex.ParseStream(parseBuf, errListener)
tree := file.Parser.Dml()
tokens, tree := parseStreamAndTokens(canonical, content, errListener)
syms := ExtractFileSymbols(docURI, tree)

c.mu.Lock()
Expand All @@ -736,10 +772,117 @@ func (c *FsCache) GetOrParse(
hash: hash,
buf: buf,
ast: tree,
tokens: tokens,
symbols: syms,
}
}
c.mu.Unlock()

return buf, tree, syms, nil
}

func (c *FsCache) getOrComputeSemanticSpans(
pathOrURI string,
) ([]semanticSpan, error) {
canonical, err := CanonicalPath(pathOrURI)
if err != nil {
return nil, err
}
docURI := uri.File(canonical)

c.mu.RLock()
entry, inOverlay := c.overlay[canonical]
if inOverlay {
if entry.semanticSpans != nil {
spans := entry.semanticSpans
c.mu.RUnlock()
return spans, nil
}
buf := entry.Buffer
content := entry.Content
tree := entry.AST
tokens := entry.Tokens
syms := entry.Symbols
c.mu.RUnlock()

if buf == nil {
buf = stream.NewHashedBufferFromString(canonical, content)
}
targetHash := buf.Hash()

if tree == nil || tokens == nil {
errListener := dmlex.NewErrorListener(canonical, 0)
tokens, tree = parseStreamAndTokens(canonical, content, errListener)
syms = nil
}
if syms == nil {
syms = ExtractFileSymbols(docURI, tree)
}
spans := buildSemanticSpans(tokens, tree, syms)

c.mu.Lock()
if cur, ok := c.overlay[canonical]; ok {
if cur.Buffer == nil {
cur.Buffer = buf
}
if cur.Buffer.Hash() == targetHash {
cur.AST = tree
cur.Tokens = tokens
cur.Symbols = syms
cur.semanticSpans = spans
}
}
c.mu.Unlock()
return spans, nil
}
c.mu.RUnlock()

data, err := c.baseFS.ReadFile(canonical)
if err != nil {
return nil, err
}
content := string(data)
buf := stream.NewHashedBufferFromString(canonical, content)
hash := buf.Hash()

var tree antlr.ParseTree
var tokens *antlr.CommonTokenStream
var syms *FileSymbols

c.mu.RLock()
cached, ok := c.diskParsed[canonical]
c.mu.RUnlock()
if ok && cached.hash == hash {
if cached.semanticSpans != nil {
return cached.semanticSpans, nil
}
tree = cached.ast
tokens = cached.tokens
syms = cached.symbols
}

if tree == nil || tokens == nil {
errListener := dmlex.NewErrorListener(canonical, 0)
tokens, tree = parseStreamAndTokens(canonical, content, errListener)
syms = nil
}
if syms == nil {
syms = ExtractFileSymbols(docURI, tree)
}
spans := buildSemanticSpans(tokens, tree, syms)

c.mu.Lock()
if _, opened := c.overlay[canonical]; !opened {
c.diskParsed[canonical] = diskCacheEntry{
hash: hash,
buf: buf,
ast: tree,
tokens: tokens,
symbols: syms,
semanticSpans: spans,
}
}
c.mu.Unlock()

return spans, nil
}
Loading
Loading