diff --git a/.agents/skills/dml/SKILL.md b/.agents/skills/dml/SKILL.md index f3c9dbe..dab963f 100644 --- a/.agents/skills/dml/SKILL.md +++ b/.agents/skills/dml/SKILL.md @@ -3,7 +3,7 @@ name: dml description: >- Reference and guide for understanding Device Modeling Language (DML 1.4 & 1.2) syntax, formal grammar, object model, templates, and standard library specifications. Use whenever - analyzing, writing, parsing, or formatting DML code, modifying pkg/dmlex/dml.g4, or implementing + analyzing, writing, parsing, or formatting DML code, modifying grammar/dml/dml.g4, or implementing AST and printer features in dmlint. --- diff --git a/.agents/skills/dml_printer_feature_bootstrap/SKILL.md b/.agents/skills/dml_printer_feature_bootstrap/SKILL.md index 2142a85..195fb50 100644 --- a/.agents/skills/dml_printer_feature_bootstrap/SKILL.md +++ b/.agents/skills/dml_printer_feature_bootstrap/SKILL.md @@ -8,11 +8,11 @@ description: A workflow for scaffolding new DML printer features from grammar ru This skill outlines a systematic, scalable approach to adding new formatting structures to the `dmlint` printer package after a grammar update in `dml.g4`. It enforces test-driven development, strict mapping to ANTLR contexts, and proactive error suppression. ## 1. Plan & Research -- **Analyze Grammar:** Inspect `pkg/dmlex/dml.g4` to identify the new rules to be implemented. Trace down dependencies and nested structures (e.g., initializers, statements, expressions). +- **Analyze Grammar:** Inspect `grammar/dml/dml.g4` to identify the new rules to be implemented. Trace down dependencies and nested structures (e.g., initializers, statements, expressions). - User may provide some pseudo g4 code with annotation: - \n - means force wrap - \r - optional wrap - - Check potential optimization of the `pkg/dmlex/dml.g4` file (Group similar rules). Any changes to the file has to be appoved by user. + - Check potential optimization of the `grammar/dml/dml.g4` file (Group similar rules). Any changes to the file has to be appoved by user. - **Propose Implementation:** Draft a plan that clarifies any formatting ambiguity with the user. Specifically ask about: - Line wrapping strategies (e.g. keeping elements on a single line if they fit post-wrap). - Trailing comma or specific grammar symbol handling (e.g., `...`). diff --git a/.goreleaser.yaml b/.goreleaser.yaml index a72113f..8a8ccc9 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -53,6 +53,19 @@ builds: - -X main.GitCommit={{.Commit}} - -X main.BuildDate={{.Date}} + - id: dmlsp-debug + dir: . + main: ./cmd/dmlsp + binary: dmlsp + targets: + - linux_amd64 + env: + - CGO_ENABLED=0 + ldflags: + - -X main.Version={{.Version}} + - -X main.GitCommit={{.Commit}} + - -X main.BuildDate={{.Date}} + - id: dml-web-format dir: . main: ./cmd/dml-web-format @@ -88,6 +101,7 @@ archives: ids: - dmlfmt-debug - dmlast-debug + - dmlsp-debug formats: - tar.gz name_template: "dmltools-debug_{{ .Version }}_{{ .Os }}_{{ .Arch }}" diff --git a/AGENTS.md b/AGENTS.md index 57013a3..eba994a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,77 +1,85 @@ -# dmlint Agent Instructions +# AGENTS.md -## Architecture & Boundaries -- **Module Name:** The Go module is `github.com/timoschenko/dmltools` (not `dmlint`). Internal imports must use `github.com/timoschenko/dmltools/pkg/...` or `github.com/timoschenko/dmltools/cmd/...`. -- **Primary Branch:** `master`. -- **Entrypoints (`cmd/`):** - - `cmd/dmlfmt`: Main DML formatter CLI (`dmlfmt [options] [src]...`). - - `cmd/dmlast`: AST dump tool emitting JSON. - - `cmd/dml-web-format`: WebAssembly formatter demo (`make build-wasm`, `make web` on port 8080). -- **Core Packages (`pkg/`):** - - `pkg/dmlex`: Lexer/parser generated from ANTLR4 grammar (`grammar/dml/dml.g4`), decomposed via `tools/baker` into per-rule context files (`dml_parser_*_context.go`). - - `pkg/printer`: Formatter visitor traversing DML AST nodes (`// g4-tag: `). - - `pkg/printer/layout`: Line wrapping, indentation, conflict resolution, token buffering (`layout.Engine`). - - `pkg/printer/format`: Unified Formatting Flags (`format.FormatFlag`), break priorities, separators, `TokenMap`. - - `pkg/printer/dml_defaults`: Default token format maps (cdecl, expression, tokens). - - `pkg/fs` & `pkg/fs/stream`: File system abstraction, caching (`FsCache`), and streaming. -- **Package Documentation:** Every package under `pkg/` must include a `doc.go` or package comment starting with `Package `. `test/doc_test.go` and `make doc` enforce this. +## Build, Test & Verification Commands -## Developer Commands +- **Default verification before finishing a task**: + 1. `go test -timeout 60s ./test/... ./cmd/... ./pkg/...` (debug assertions enabled) + 2. `go test -tags dmltools.ndebug -timeout 60s ./test/... ./cmd/... ./pkg/...` (release mode / `NDEBUG`) + 3. `golangci-lint run` + 4. `make license-check` +- **Do NOT run `go test ./...` from the repo root**: It scans `./venv` and standalone sub-modules under `./tools/`. Always pass `./test/... ./cmd/... ./pkg/...`. +- **Single test / package iteration**: + - `go test -v ./test/printer -run TestAssertStatement` + - Most unit and integration suites live under `./test/{dmlex,printer,lsp,fs}`, not alongside `./pkg/`. +- **Standalone tool modules**: `tools/baker` and `tools/licensecheck` have their own `go.mod` files. Test them via `make test-tools`. +- **`make` & ANTLR gotcha (`SKIP_ANTLR=1`)**: + - Makefile build/test targets (`make test`, `make release`, `make debug`) depend on `build-gocache`, which triggers `make generate` (requiring Java 11+, `curl`, and `stringer`) whenever `build/env/*.flag` files are missing or older than `grammar/dml/dml.g4`. + - Use `go test` directly or pass `SKIP_ANTLR=1` (e.g., `make test SKIP_ANTLR=1`, `make build/bin/dmlfmt SKIP_ANTLR=1`) to avoid triggering ANTLR codegen. + - Makefile also overrides `GOCACHE` to `build/cache/golang` unless `GOCACHE` is already set in the environment. +- **Full CI pipeline order** (`.github/workflows/pre-commit.yml`): + `make test-tools` -> `make generate` -> `make release` -> `make test` -> `make test-ndebug` -> `pre-commit run --all-files` (`golangci-lint`) -> `make license-check`. -```bash -# Full test suite (builds gocache, runs tests across all valid packages) -make test +## Grammar & Codegen Pipeline (`grammar/dml/dml.g4` -> `pkg/dmlex/`) -# Fast focused testing (bypasses ANTLR codegen) -go test ./test/printer/... -go test -v ./test/printer -run TestAssertStatement -go test ./test/... ./cmd/... ./pkg/... # Never run 'go test ./...' from root (scans ./venv) +- **Approval required**: **Never** modify `grammar/dml/dml.g4` or run `make generate` without explicit user approval. +- **What `make generate` does** (when approved): + 1. Formats `grammar/dml/dml.g4` using the cached ANTLR formatter JAR (`make format`). + 2. Runs ANTLR 4.13.2 to produce intermediate Go parser/lexer files in `grammar/dml/`. + 3. Runs `tools/baker` to split monolithic `dml_parser.go` into per-rule context files (`pkg/dmlex/dml_parser_*_context.go`) and removes `grammar/dml/dml_*.go`. + 4. Runs `go generate ./pkg/dmlex/...` (`stringer -type=TokenType` -> `pkg/dmlex/tokentype_string.go`). +- **Generated vs. hand-written files in `pkg/dmlex/`**: + - **Generated (never edit manually)**: `dml_parser_*.go`, `dml_lexer.go`, `dml_listener.go`, `dml_base_listener.go`, `tokentype_string.go`. + - **Hand-written (safe to edit)**: `file.go`, `porting.go`, `expression.go`, `cdecl.go`, `method.go`, `imports.go`, `synthetic_token.go`, `error_listener.go`, `version.go`, `doc.go`. -# Build binaries (outputs to build/bin/dmlfmt, build/bin/dmlast) -make build/bin/dmlfmt -make release +## Architecture & Package Map -# Build/test without Java/ANTLR runtime (uses committed parser sources) -make test SKIP_ANTLR=1 -make build/bin/dmlfmt SKIP_ANTLR=1 +- **Entrypoints (`cmd/`)**: + - `cmd/dmlfmt`: CLI code formatter (`build/bin/dmlfmt`). Note: sets `antlr.CommonTokenFactoryDEFAULT = antlr.NewCommonTokenFactory(true)` in `init()` so tokens retain zero-copy string slices backed by `stream.HashedBuffer`. + - `cmd/dmlast`: AST dumper CLI (`build/bin/dmlast`). + - `cmd/dmlsp`: LSP 3.17 server over stdio (`build/bin/dmlsp`). + - `cmd/dml-web-format`: WebAssembly formatter playground (`make build-wasm` -> `cmd/dml-web-format/main.wasm`). +- **Core Packages (`pkg/`)**: + - `pkg/dmlex`: ANTLR4 lexer/parser wrapper, AST rule contexts, `TokenType` enum, import resolution helpers (`imports.go`), and DML version detection (`version.go`). + - `pkg/printer`: AST traversal (`dml_*.go`), scoped `PrintContext` hierarchy, and Unified Formatting Flags (`pkg/printer/format`, 32-bit `FormatFlag`), backed by default token maps (`pkg/printer/dml_defaults`) and the line-wrapping engine (`pkg/printer/layout`). + - `pkg/lsp`: LSP server (`Server`), in-memory overlay/AST/symbol cache (`FsCache`), syntax diagnostics, and go-to-definition (`definition.go`, `symbols.go`). + - **UTF-16 vs. byte offset gotcha**: LSP `protocol.Position.Character` is in UTF-16 code units, whereas ANTLR and Go strings use UTF-8 byte/rune offsets. Always convert positions via `LineAndByteCol` / `utf16ColToByteCol` (`pkg/lsp/cache.go`). + - `pkg/fs`: Atomic file replacement (`ReplaceFileAtomically`), path normalization, `pkg/fs/stream` (`HashedBuffer` lazy UTF-8 `antlr.CharStream` + 192-bit composite hash), and `pkg/fs/lookup` (stat-validated file discovery, `.gitignore`/`.editorconfig` chain lookup). -# Linting and formatting Go code -golangci-lint run # Enforces gofmt and golines (max-len: 80, tab-len: 4) -golangci-lint fmt # Automatically format Go code +## Printer Constraints (`pkg/printer`) -# Grammar & codegen -make format # Format grammar/dml/dml.g4 -make generate # Format grammar + ANTLR codegen + baker split + go generate -make doc # Verify package doc coverage across pkg/ -make clean # Clear Go build, test, fuzz, and coverage caches -``` +- **Delegate all layout to `layout.Engine`**: AST visitor methods in `pkg/printer/dml_*.go` **must not** perform manual string length math, manual spacing, or manual line wrapping. Push tokens via `processToken`, `pushTokenRange`, `pushTokenRangeFromRightiest`, or `pushTokenWithCustomFormat` inside scoped `PrintContext` overrides (`p.newContext(...)` / `defer p.freeContext()`). +- **Sole newline exception**: Blank lines between top-level/block statements are emitted via `writeNewLines()` at statement boundaries (`pkg/printer/statement_spacing.go`). +- **Rule annotations & passthrough**: + - Prefix every grammar rule visitor method with `// g4-tag: `. + - Unimplemented grammar rules must call `p.printUnimplemented(node)` for raw source passthrough. +- **No unauthorized workarounds**: **Never** add new AST/token workarounds to `pkg/printer/workarounds.go` without explicit user approval. Fix the root cause in `pkg/printer` or `pkg/printer/layout`, or ask first. +- **Debug assertions**: `assert()` and `assertLazy()` in `pkg/printer/debug.go` panic during normal tests (`!dmltools.ndebug`) and compile to no-ops under `-tags dmltools.ndebug`. -## Codegen & Grammar Changes -- **Generated Code:** Never manually edit `pkg/dmlex/dml_*.go`, `pkg/dmlex/*_string.go`, `cmd/dml-web-format/wasm_exec.js`, `*.tokens`, or `*.interp`. -- **Regeneration Requirements:** `make generate` requires: - - Java runtime 11+ (Temurin 21 recommended) to execute ANTLR 4.13.2. - - `stringer` tool: `go install golang.org/x/tools/cmd/stringer@latest`. - - Virtualenv `./venv` (automatically provisioned by Makefile for whitespace/EOF fixers). -- **CI Enforcement:** When `CI=true`, `make generate` verifies generated files match committed files in git and fails if there is any diff. Always run `make generate` and commit all generated files after modifying `grammar/dml/dml.g4`. +## Testing Quirks (`test/printer`) -## Printer Architecture & Constraints -- **Layout Engine Delegation:** AST visitor methods in `pkg/printer/` push `PrintContext` overrides with `FormatFlag`s. Formatting, spacing, and line wrapping decisions must be delegated entirely to `layout.Engine`. -- **No Manual Wrapping:** AST methods must not perform manual string length calculations or manually inject spacing/newlines for line wrapping within statements. -- **Statement Boundary Exception:** `writeNewLines()` is permitted only between top-level statements, as `layout.Engine` operates within statements. -- **Grammar Tagging:** Every AST print method must be tagged with its grammar rule: `// g4-tag: `. -- **Synthetic Tokens (Epic 006):** Do not manually inject synthetic tokens. Use `task006Skip: true` in test cases requiring synthetic parens. +- **Backtick quote substitution**: In `printerTestCase` (`test/printer/testlib_test.go`), all backticks (`` ` ``) in `code`, `expected`, and `masked` strings are automatically converted to double quotes (`"`) before parsing and comparison. +- **Implicit headers & method wrapping**: + - `runPrinterTestCase` auto-prepends `"dml 1.4;\n\n\n"` and strips it from the formatted result unless `expected` already contains a `dml` header. + - `runPrinterMethodTestCase` wraps snippets in `method foo() { ... }` indented by 4 spaces and adds `+4` to `lineCap` (standard test `lineCap` is `40`). +- **Test masking policy (`test/printer/mask_test.go`)**: + - **Never** add new `masked: Mask...` entries or `task006Skip: true` flags to silence failing tests without explicit user approval. + - When fixing a bug covered by an existing mask, remove the mask—if a masked test produces `expected`, the runner fails with `"test case passed but it is still masked"`. -## Testing Harness & Masking (`test/printer/testlib_test.go`) -- **DML Header Preprocessing:** If test input lacks a `dml` header, `dml 1.4;\n\n\n` is automatically prepended and stripped from output. -- **Backtick Normalization:** Backticks (`` ` ``) in test code and expected strings are normalized to double quotes (`"`), allowing raw Go string literals to express DML double quotes cleanly. -- **Masked Tests (`test/printer/mask_test.go`):** Known issues and WIP formatting use typed masks (`MaskIncorrectFormatting`, `MaskSkip`, `MaskSyntaxError`). -- **Mask Removal Gotcha:** When a bugfix causes a masked test to output the correct expected string, the test harness triggers `t.Errorf("test case passed but it is still masked. Consider removing the mask")`. You **must** remove the mask once the test passes. +## Enforced Repo Conventions -## Code Conventions & Workarounds -- **AI Workarounds:** Every temporary fix or workaround must strictly follow the format: - `// TODO: AI WA: ` and `// Deprecated: This is workaround`. -- **Workaround Isolation:** Isolate non-trivial workaround logic into dedicated helper functions in `pkg/printer/workarounds.go` or `pkg/printer/layout/workarounds.go`. +- **SPDX License Header (`make license-check`)**: Every non-generated `.go` file and `grammar/dml/dml.g4` must start with: + ```go + // SPDX-License-Identifier: GPL-2.0-only + // Copyright (C) 2026 Sergei Timoshchenko + ``` + (`GPL-2.0-or-later` is explicitly rejected by `tools/licensecheck`). If local untracked directories with third-party `LICENSE` files cause `make license-check` to fail, pass explicit file paths: `(cd tools/licensecheck && go run . -root ../.. )`. +- **Package documentation (`test/doc_test.go` & `make doc`)**: Every package under `pkg/` containing non-test `.go` files must have a package doc comment (`doc.go`) starting with `"Package ..."`. When adding a new subpackage under `pkg/`, also add it to `TestGoDocCommand` in `test/doc_test.go`. +- **Go formatting & linting (`.golangci.yaml`)**: Formatted with `gofmt` and `golines` (`max-len: 80`). +- **Commit messages (`.goreleaser.yaml`)**: Follow Conventional Commits (`(): `) using types `feat`, `fix`, `perf`, `docs`, `refactor`, `chore`, `test`, `ci`, `infra`. -## Key Skills & References -- **DML 1.4 / 1.2 Syntax Spec:** Cached in `.docs-cache/dml.wiki` (fetch via `.agents/skills/dml/scripts/fetch_wiki.sh`); guide in `.agents/skills/dml/SKILL.md`. -- **Scaffolding New Printer Rules:** Workflow and checklist in `.agents/skills/dml_printer_feature_bootstrap/SKILL.md`. +## Existing Instruction & Reference Files + +- `.agents/skills/dml/SKILL.md`: DML 1.4/1.2 syntax and formal grammar lookup guide (queries `.docs-cache/dml.wiki`, fetched via `./.agents/skills/dml/scripts/fetch_wiki.sh`). +- `.agents/skills/dml_printer_feature_bootstrap/SKILL.md`: TDD workflow for scaffolding new printer rules and tests. +- `doc/format/README.md`, `doc/format/line_wrapping.md`, `doc/format/comments.md`: DML formatter style, wrap-group explosion, and sticky comment rules. +- `doc/lsp/README.md`, `doc/lsp/features.md`, `doc/lsp/compatibility.md`: `dmlsp` capabilities, import resolution, and LSP 3.17 support. diff --git a/Makefile b/Makefile index 5ae10b2..8e8ab71 100644 --- a/Makefile +++ b/Makefile @@ -65,6 +65,7 @@ $(ANTLR_FORMAT_JAR): | $(BUILD_DEPS_DIR) BUILD_APPS:= BUILD_APPS+=dmlast BUILD_APPS+=dmlfmt +BUILD_APPS+=dmlsp # Intermediate ANTLR generated files in grammar/dml G4_GENERATED_FILES:= diff --git a/cmd/dmlast/dmlast.go b/cmd/dmlast/dmlast.go index 7a32ba5..1140dd9 100644 --- a/cmd/dmlast/dmlast.go +++ b/cmd/dmlast/dmlast.go @@ -16,6 +16,9 @@ import ( "github.com/timoschenko/dmltools/pkg/dmlex" ) +const previewWarning = "WARNING: dmlast is a preview tool; " + + "features and behavior may change without notice." + var ( Version = "dev" GitCommit = "none" @@ -144,56 +147,87 @@ func printVersion(w io.Writer) { w, "There is NO WARRANTY, to the extent permitted by law.", ) + _, _ = fmt.Fprintln(w) + _, _ = fmt.Fprintln(w, previewWarning) } -func main() { - filePathPtr := flag.String("file", "", "The path to the DML file to parse.") - versionPtr := flag.Bool("version", false, "Show the version and exit.") - vPtr := flag.Bool("v", false, "Show the version and exit.") - VPtr := flag.Bool("V", false, "Show the version and exit.") - flag.Parse() // Parse the command-line arguments - - if *versionPtr || *vPtr || *VPtr { - printVersion(os.Stdout) - return +func printUsage(out io.Writer, fs *flag.FlagSet) { + _, _ = fmt.Fprintf(out, "Usage: dmlast -file \n\n") + _, _ = fmt.Fprintf(out, "%s\n\n", previewWarning) + _, _ = fmt.Fprintf(out, "Options:\n") + fs.SetOutput(out) + fs.PrintDefaults() +} + +func run(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("dmlast", flag.ContinueOnError) + fs.SetOutput(stderr) + + var filePath string + var showVersion bool + var showHelp bool + + fs.StringVar(&filePath, "file", "", "The path to the DML file to parse.") + fs.BoolVar(&showVersion, "version", false, "Show the version and exit.") + fs.BoolVar(&showVersion, "v", false, "Show the version and exit.") + fs.BoolVar(&showVersion, "V", false, "Show the version and exit.") + fs.BoolVar(&showHelp, "help", false, "Show help usage and exit.") + fs.BoolVar(&showHelp, "h", false, "Show help usage and exit.") + fs.Usage = func() { + printUsage(stderr, fs) } - // Check if the file path was provided - if *filePathPtr == "" { - fmt.Fprintf(os.Stderr, "Error: No file path provided.\n") - fmt.Fprintf( - os.Stderr, - "Usage: %s -file \n", - os.Args[0], - ) - os.Exit(1) + if err := fs.Parse(args); err != nil { + return 2 + } + + if showHelp { + printUsage(stdout, fs) + return 0 + } + + if showVersion { + printVersion(stdout) + return 0 + } + + if filePath == "" { + _, _ = fmt.Fprintf(stderr, "Error: No file path provided.\n") + printUsage(stderr, fs) + return 1 } - filename := *filePathPtr - errorListener := dmlex.NewErrorListener(filename, 0) + _, _ = fmt.Fprintln(stderr, previewWarning) + + errorListener := dmlex.NewErrorListener(filePath, 0) errorListener.Handler = func(e dmlex.SyntaxErrorInfo) { - fmt.Fprintf( - os.Stderr, + _, _ = fmt.Fprintf( + stderr, "ERROR %s:%d column %d: Syntax error - %s\n", - filename, e.Line, e.Column, e.Msg, + filePath, e.Line, e.Column, e.Msg, ) } - file, err := dmlex.ParseFile(filename, errorListener) + file, err := dmlex.ParseFile(filePath, errorListener) if err != nil { - fmt.Fprintf(os.Stderr, "Error reading file %s: %v\n", filename, err) - os.Exit(1) + _, _ = fmt.Fprintf( + stderr, + "Error reading file %s: %v\n", + filePath, + err, + ) + return 1 } p := file.Parser // alias tree := p.Dml() if errorCount := len(errorListener.Errors); errorCount > 0 { - fmt.Fprintf( - os.Stderr, + _, _ = fmt.Fprintf( + stderr, "Parsing failed with %d syntax error(s).\n", errorCount, ) - os.Exit(1) + return 1 } jsonTree := buildJsonTree(tree, p.GetRuleNames(), p.GetSymbolicNames()) @@ -201,13 +235,19 @@ func main() { // Marshal to JSON with pretty-printing jsonData, err := json.MarshalIndent(jsonTree, "", " ") if err != nil { - fmt.Fprintf(os.Stderr, "Error serializing tree to JSON: %v\n", err) - os.Exit(1) + _, _ = fmt.Fprintf(stderr, "Error serializing tree to JSON: %v\n", err) + return 1 } // Write to standard output - if _, err := fmt.Println(string(jsonData)); err != nil { - fmt.Fprintf(os.Stderr, "Error writing JSON to stdout: %v\n", err) - os.Exit(1) + if _, err := fmt.Fprintln(stdout, string(jsonData)); err != nil { + _, _ = fmt.Fprintf(stderr, "Error writing JSON to stdout: %v\n", err) + return 1 } + + return 0 +} + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) } diff --git a/cmd/dmlast/dmlast_test.go b/cmd/dmlast/dmlast_test.go index 0805a33..c587a24 100644 --- a/cmd/dmlast/dmlast_test.go +++ b/cmd/dmlast/dmlast_test.go @@ -5,6 +5,9 @@ package main import ( "bytes" + "encoding/json" + "os" + "path/filepath" "strings" "testing" ) @@ -24,4 +27,64 @@ func TestPrintVersion(t *testing.T) { !strings.Contains(out, "GPL-2.0-only") { t.Errorf("expected license information in version output, got: %q", out) } + if !strings.Contains(out, previewWarning) { + t.Errorf( + "expected preview warning in version output, got: %q", + out, + ) + } +} + +func TestHelpFlag(t *testing.T) { + for _, flag := range []string{"--help", "-h", "-help"} { + var stdout, stderr bytes.Buffer + code := run([]string{flag}, &stdout, &stderr) + if code != 0 { + t.Errorf("expected exit code 0 for %s, got %d", flag, code) + } + out := stdout.String() + if !strings.Contains(out, "Usage: dmlast") { + t.Errorf("expected usage output on stdout, got: %q", out) + } + if !strings.Contains(out, previewWarning) { + t.Errorf( + "expected preview warning in usage output, got: %q", + out, + ) + } + } +} + +func TestRunPreviewWarning(t *testing.T) { + tmpDir := t.TempDir() + dmlFile := filepath.Join(tmpDir, "test.dml") + if err := os.WriteFile( + dmlFile, + []byte("dml 1.4;\ndevice dev;\n"), + 0o600, + ); err != nil { + t.Fatalf("failed to write temp DML file: %v", err) + } + + var stdout, stderr bytes.Buffer + code := run([]string{"-file", dmlFile}, &stdout, &stderr) + if code != 0 { + t.Fatalf( + "expected exit code 0, got %d (stderr: %s)", + code, + stderr.String(), + ) + } + + if !strings.Contains(stderr.String(), previewWarning) { + t.Errorf( + "expected preview warning on stderr, got: %q", + stderr.String(), + ) + } + + var parsed JsonNode + if err := json.Unmarshal(stdout.Bytes(), &parsed); err != nil { + t.Errorf("expected valid JSON on stdout, got error: %v", err) + } } diff --git a/cmd/dmlfmt/device.go b/cmd/dmlfmt/device.go index 0eee1a4..6142f4d 100644 --- a/cmd/dmlfmt/device.go +++ b/cmd/dmlfmt/device.go @@ -6,7 +6,6 @@ package main import ( "fmt" "path/filepath" - "strconv" "strings" "github.com/antlr4-go/antlr/v4" @@ -31,11 +30,7 @@ var dmlcValueFlags = map[string]bool{ } // ImportRef describes an import statement location and target string. -type ImportRef struct { - Name string - Line int - Column int -} +type ImportRef = dmlex.ImportRef func nextDmlcArg( tail []string, @@ -114,102 +109,7 @@ func parseDmlcFlags(args []string) ([]string, string) { func extractDmlFileMeta( tree antlr.ParseTree, ) (bool, int, int, []ImportRef) { - dmlCtx, ok := tree.(dmlex.IDmlContext) - if !ok || dmlCtx == nil { - return false, 0, 0, nil - } - - codeCtx := dmlCtx.DmlCode() - if codeCtx == nil { - return false, 0, 0, nil - } - - var ( - hasDevice bool - devLine int - devCol int - ) - if devTag := codeCtx.DeviceTag(); devTag != nil { - hasDevice = true - if tok := devTag.GetStart(); tok != nil { - devLine = tok.GetLine() - devCol = tok.GetColumn() - } - } - - var imports []ImportRef - collectImportsFromStatements(codeCtx.DeviceStatements(), &imports) - - return hasDevice, devLine, devCol, imports -} - -func collectImportsFromStatements( - stmts dmlex.IDeviceStatementsContext, - out *[]ImportRef, -) { - if stmts == nil { - return - } - for _, stmt := range stmts.AllDeviceStatement() { - if stmt == nil { - continue - } - if imp := stmt.ImportStatement(); imp != nil { - if ref, ok := extractImportRef(imp); ok { - *out = append(*out, ref) - } - } - if ifCtx := stmt.ToplevelIf(); ifCtx != nil { - collectImportsFromToplevelIf(ifCtx, out) - } - } -} - -func collectImportsFromToplevelIf( - ifCtx dmlex.IToplevelIfContext, - out *[]ImportRef, -) { - if ifCtx == nil { - return - } - if ifStmt := ifCtx.ToplevelIfStatement(); ifStmt != nil { - collectImportsFromStatements(ifStmt.DeviceStatements(), out) - } - if elseStmt := ifCtx.ToplevelElseStatement(); elseStmt != nil { - collectImportsFromStatements(elseStmt.DeviceStatements(), out) - collectImportsFromToplevelIf(elseStmt.ToplevelIf(), out) - } -} - -func extractImportRef(imp dmlex.IImportStatementContext) (ImportRef, bool) { - lit := imp.STRING_LITERAL() - if lit == nil { - return ImportRef{}, false - } - raw := lit.GetText() - if raw == "" { - return ImportRef{}, false - } - var line, col int - if sym := lit.GetSymbol(); sym != nil { - line = sym.GetLine() - col = sym.GetColumn() - } - return ImportRef{ - Name: unquoteDmlString(raw), - Line: line, - Column: col, - }, true -} - -func unquoteDmlString(raw string) string { - if unquoted, err := strconv.Unquote(raw); err == nil { - return unquoted - } - if len(raw) >= 2 && raw[0] == '"' && raw[len(raw)-1] == '"' { - return raw[1 : len(raw)-1] - } - return raw + return dmlex.ExtractDmlFileMeta(tree) } // deviceImportResolver resolves imports and enforces workspace boundaries @@ -426,39 +326,15 @@ func (r *deviceImportResolver) resolveImportPath( importingPath, impName string, ) (string, bool) { importingDir := filepath.Dir(filepath.Clean(importingPath)) - nativeImp := filepath.FromSlash(impName) - - if strings.HasPrefix(impName, "./") { - candidate := filepath.Join(importingDir, nativeImp) - if r.isRegularFile(candidate) { - return candidate, true - } - return "", false - } - - if strings.HasPrefix(impName, "../") { - candidate := filepath.Join(importingDir, nativeImp) - if r.isRegularFile(candidate) { - return candidate, true - } - } - searchDirs := make([]string, 0, len(r.includeDirs)+2) searchDirs = append(searchDirs, r.includeDirs...) searchDirs = append(searchDirs, r.deviceDir, importingDir) - - for _, dir := range searchDirs { - verCandidate := filepath.Join(dir, dmlex.SupportedDmlVersion, nativeImp) - if r.isRegularFile(verCandidate) { - return verCandidate, true - } - directCandidate := filepath.Join(dir, nativeImp) - if r.isRegularFile(directCandidate) { - return directCandidate, true - } - } - - return "", false + return dmlex.ResolveImportPath( + importingPath, + impName, + searchDirs, + r.isRegularFile, + ) } func (r *deviceImportResolver) isRegularFile(path string) bool { diff --git a/cmd/dmlsp/main.go b/cmd/dmlsp/main.go new file mode 100644 index 0000000..b210bf6 --- /dev/null +++ b/cmd/dmlsp/main.go @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package main + +import ( + "context" + "flag" + "fmt" + "io" + "log/slog" + "os" + "path/filepath" + "runtime/debug" + + "github.com/timoschenko/dmltools/pkg/lsp" + + "go.lsp.dev/jsonrpc2" +) + +const previewWarning = "WARNING: dmlsp is a preview tool; " + + "features and behavior may change without notice." + +var ( + Version = "dev" + GitCommit = "none" + BuildDate = "unknown" + Debug = "false" +) + +type readWriteCloser struct { + io.Reader + io.Writer +} + +func (rwc *readWriteCloser) Close() error { + if c, ok := rwc.Reader.(io.Closer); ok && rwc.Reader != os.Stdin { + _ = c.Close() + } + if c, ok := rwc.Writer.(io.Closer); ok && + rwc.Writer != os.Stdout && + rwc.Writer != os.Stderr { + _ = c.Close() + } + return nil +} + +func printUsage(out io.Writer, fs *flag.FlagSet) { + _, _ = fmt.Fprintf(out, "Usage: dmlsp [options]\n\n") + _, _ = fmt.Fprintf( + out, + "Language Server Protocol (LSP) server for Device Modeling Language (DML).\n", + ) + _, _ = fmt.Fprintf( + out, + "Communicates with IDE/editor clients via standard I/O (stdin/stdout).\n\n", + ) + _, _ = fmt.Fprintf(out, "%s\n\n", previewWarning) + _, _ = fmt.Fprintf(out, "Options:\n") + fs.SetOutput(out) + fs.PrintDefaults() +} + +func printVersion(w io.Writer) { + ver := Version + commit := GitCommit + date := BuildDate + + if (ver == "dev" || ver == "") && commit == "none" { + if info, ok := debug.ReadBuildInfo(); ok { + if info.Main.Version != "" && info.Main.Version != "(devel)" { + ver = info.Main.Version + } + for _, setting := range info.Settings { + switch setting.Key { + case "vcs.revision": + if len(setting.Value) > 7 { + commit = setting.Value[:7] + } else { + commit = setting.Value + } + case "vcs.time": + date = setting.Value + } + } + } + } + + if commit != "none" || date != "unknown" { + _, _ = fmt.Fprintf( + w, + "dmlsp version %s (commit: %s, built: %s)\n", + ver, + commit, + date, + ) + } else { + _, _ = fmt.Fprintf(w, "dmlsp version %s\n\n", ver) + } + _, _ = fmt.Fprintln( + w, + "License: GNU General Public License v2.0 only (GPL-2.0-only)", + ) + _, _ = fmt.Fprintln( + w, + "This is free software: you are free to change and redistribute it.", + ) + _, _ = fmt.Fprintln( + w, + "There is NO WARRANTY, to the extent permitted by law.", + ) + _, _ = fmt.Fprintln(w) + _, _ = fmt.Fprintln(w, previewWarning) +} + +func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("dmlsp", flag.ContinueOnError) + fs.SetOutput(stderr) + + var logFile string + var verbose bool + var showVersion bool + var showHelp bool + + fs.StringVar( + &logFile, + "log-file", + "", + "Path to optional log file (logs to stderr by default)", + ) + fs.StringVar(&logFile, "logfile", "", "Alias for --log-file") + fs.BoolVar(&verbose, "v", false, "Enable verbose (debug) logging") + fs.BoolVar(&verbose, "verbose", false, "Alias for -v") + fs.BoolVar( + &showVersion, + "version", + false, + "Print version information and exit", + ) + fs.BoolVar(&showVersion, "V", false, "Alias for --version") + fs.BoolVar(&showHelp, "help", false, "Print help usage and exit") + fs.BoolVar(&showHelp, "h", false, "Alias for --help") + + if err := fs.Parse(args); err != nil { + return 2 + } + + if showHelp { + printUsage(stdout, fs) + return 0 + } + + if showVersion { + printVersion(stdout) + return 0 + } + + logWriter := stderr + if logFile != "" { + cleanPath := filepath.Clean(logFile) + f, err := os.OpenFile( //nolint:gosec // user-specified log destination via CLI flag + cleanPath, + os.O_CREATE|os.O_WRONLY|os.O_APPEND, + 0o600, + ) + if err != nil { + _, _ = fmt.Fprintf( + stderr, + "dmlsp: failed to open log file %q: %v\n", + logFile, + err, + ) + return 1 + } + defer func() { + _ = f.Close() + }() + logWriter = f + } + + logLevel := slog.LevelInfo + if verbose || Debug == "true" { + logLevel = slog.LevelDebug + } + + logger := slog.New(slog.NewTextHandler(logWriter, &slog.HandlerOptions{ + Level: logLevel, + })) + + logger.Info("starting dmlsp server", + slog.String("version", Version), + slog.String("commit", GitCommit), + ) + logger.Warn(previewWarning) + + rwc := &readWriteCloser{Reader: stdin, Writer: stdout} + stream := jsonrpc2.NewStream(rwc) + server := lsp.NewServer( + lsp.WithLogger(logger), + lsp.WithVersion(Version), + ) + + if err := server.Serve(context.Background(), stream); err != nil { + logger.Error("server error encountered", slog.Any("error", err)) + return server.ExitCode() + } + + return server.ExitCode() +} + +func main() { + os.Exit(run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) +} diff --git a/cmd/dmlsp/main_test.go b/cmd/dmlsp/main_test.go new file mode 100644 index 0000000..b29510b --- /dev/null +++ b/cmd/dmlsp/main_test.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package main + +import ( + "bytes" + "strings" + "testing" +) + +func TestHelpFlag(t *testing.T) { + for _, flag := range []string{"--help", "-h", "-help"} { + var stdout, stderr bytes.Buffer + stdin := strings.NewReader("") + + code := run([]string{flag}, stdin, &stdout, &stderr) + if code != 0 { + t.Errorf("expected exit code 0 for %s, got %d", flag, code) + } + + out := stdout.String() + if !strings.Contains(out, "Usage: dmlsp") { + t.Errorf("expected usage output on stdout, got: %s", out) + } + if !strings.Contains(out, previewWarning) { + t.Errorf( + "expected preview warning in usage output, got: %s", + out, + ) + } + } +} + +func TestVersionFlag(t *testing.T) { + for _, flag := range []string{"--version", "-version", "-V"} { + var stdout, stderr bytes.Buffer + stdin := strings.NewReader("") + + code := run([]string{flag}, stdin, &stdout, &stderr) + if code != 0 { + t.Errorf("expected exit code 0 for %s, got %d", flag, code) + } + + out := stdout.String() + if !strings.Contains(out, "dmlsp version") { + t.Errorf("expected version output on stdout, got: %s", out) + } + if !strings.Contains(out, "GPL-2.0-only") { + t.Errorf("expected license info on stdout, got: %s", out) + } + if !strings.Contains(out, previewWarning) { + t.Errorf( + "expected preview warning in version output, got: %s", + out, + ) + } + } +} + +func TestStartupPreviewWarning(t *testing.T) { + var stdout, stderr bytes.Buffer + stdin := strings.NewReader("") + + _ = run(nil, stdin, &stdout, &stderr) + if !strings.Contains(stderr.String(), previewWarning) { + t.Errorf( + "expected preview warning on stderr at startup, got: %q", + stderr.String(), + ) + } +} + +func TestInvalidFlag(t *testing.T) { + var stdout, stderr bytes.Buffer + stdin := strings.NewReader("") + + code := run( + []string{"--invalid-flag-that-does-not-exist"}, + stdin, + &stdout, + &stderr, + ) + if code != 2 { + t.Errorf("expected exit code 2 for invalid flag, got %d", code) + } +} diff --git a/doc/lsp/README.md b/doc/lsp/README.md new file mode 100644 index 0000000..a0d7376 --- /dev/null +++ b/doc/lsp/README.md @@ -0,0 +1,59 @@ +# 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. + +--- + +## Overview + +`dmlsp` runs as a background process managed by your code editor or IDE and +communicates using the **Language Server Protocol (LSP 3.17)** +over **JSON-RPC 2.0** via standard I/O (`stdin`/`stdout`). + +### Key Capabilities + +- **Real-Time Syntax Diagnostics**: Validates `.dml` files as you open, edit, and save them, reporting syntax errors and DML version warnings directly in your editor. +- **Go to Definition**: Navigates across symbols and files, including: + - `import` statements to the target `.dml` files + - `template` definitions and inherited template members (including multi-level template inheritance) + - Device object hierarchies (`device`, `bank`, `register`, `field`, `group`, `port`, `connect`, `interface`, `attribute`, `event`, `implement`, `subdevice`) + - 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 +- **Live Editor Synchronization**: Tracks unsaved edits in memory (supporting incremental updates) while automatically falling back to on-disk files when resolving unopened imported files. + +--- + +## Command-Line Usage + +`dmlsp` is normally launched automatically by your editor's LSP client rather than run manually in a terminal. + +```bash +dmlsp [options] +``` + +### Options + +| Flag | Description | +| :--- | :--- | +| `--log-file `, `--logfile ` | Write server logs to `` instead of `stderr` (created or appended with `0600` permissions). | +| `-v`, `--verbose` | Enable verbose (`DEBUG`-level) logging. By default, logs at `INFO` level. | +| `-V`, `--version` | Print version, commit, build date, and license information and exit. | +| `-h`, `--help` | Print command usage information and exit. | + +### Exit Codes + +| Exit Code | Meaning | +| :--- | :--- | +| `0` | Clean shutdown (`shutdown` request received before `exit`), or `--help` / `--version` completed. | +| `1` | Unclean exit (`exit` notification received without a prior `shutdown` request), or startup/log-file error. | +| `2` | Invalid command-line flag or argument. | + +--- + +## Documentation Guides + +- [**Installation & Editor Setup**](setup.md): How to install `dmlsp` and configure it in Neovim, VS Code, and Zed. +- [**Features & Navigation Guide**](features.md): Detailed examples of diagnostics, Go to Definition, import path resolution, and user-visible limitations. +- [**LSP API Compatibility & Limitations**](compatibility.md): Complete reference of supported LSP 3.17 API commands, their limitations, and unsupported methods. diff --git a/doc/lsp/compatibility.md b/doc/lsp/compatibility.md new file mode 100644 index 0000000..474c232 --- /dev/null +++ b/doc/lsp/compatibility.md @@ -0,0 +1,219 @@ +# LSP API Compatibility & Limitations + +This document provides the **Language Server Protocol (LSP 3.17)** +compatibility matrix for `dmlsp`, listing all supported LSP commands, +their specific limitations, and unsupported LSP commands. + +--- + +## 1. Protocol Overview + +| Property | Value | +| :--- | :--- | +| **LSP Specification** | 3.17 | +| **Transport** | JSON-RPC 2.0 over `stdin` / `stdout` | +| **Position Encoding** | `utf-16` (UTF-16 code units, including full surrogate-pair support) | +| **Document Sync Mode** | Incremental (`openClose: true`, `change: 2`, `save: {}`) | + +--- + +## 2. Supported LSP API Commands + +| Method | Direction | Type | Support Level | Summary | +| :--- | :--- | :--- | :--- | :--- | +| `initialize` | Client -> Server | Request | Supported (with limitations) | Negotiates capabilities and sets primary workspace root. | +| `initialized` | Client -> Server | Notification | Supported | Completes initialization handshake. | +| `shutdown` | Client -> Server | Request | Supported | Transitions server to shut-down state prior to `exit`. | +| `exit` | Client -> Server | Notification | Supported | Terminates server process (`0` after `shutdown`, `1` otherwise). | +| `textDocument/didOpen` | Client -> Server | Notification | Supported | Registers in-memory buffer and runs immediate diagnostics. | +| `textDocument/didChange` | Client -> Server | Notification | Supported (with limitations) | Applies incremental or full edits and schedules debounced diagnostics. | +| `textDocument/didSave` | Client -> Server | Notification | Supported (with limitations) | Updates buffer if text is provided and runs immediate diagnostics. | +| `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. | + +--- + +### Detailed Behavior & Limitations + +#### Lifecycle + +- **`initialize`** *(Request, Client -> Server)* + - **Behavior**: Records client info, determines the workspace root, transitions the server to the initialized state, and advertises: + - `positionEncoding`: `"utf-16"` + - `textDocumentSync`: `{ openClose: true, change: 2 (Incremental), save: {} }` + - `definitionProvider`: `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. + - **Single Initialization**: Calling `initialize` more than once returns an `already initialized` error. + +- **`initialized`** *(Notification, Client -> Server)* + - **Behavior**: Logs completion of the initialization handshake. + - **Limitations**: Does not perform dynamic capability registration (`client/registerCapability`) or workspace configuration queries. + +- **`shutdown`** *(Request, Client -> Server)* + - **Behavior**: Transitions the server to the shut-down state so the subsequent `exit` notification exits cleanly. + - **Limitations**: Calling `shutdown` before `initialize` returns a `server not initialized` error. + +- **`exit`** *(Notification, Client -> Server)* + - **Behavior**: Closes the JSON-RPC connection and terminates the process with exit code `0` if `shutdown` was previously received, or exit code `1` if `exit` was sent without a prior `shutdown`. + - **Limitations**: None. + +--- + +#### Document Synchronization + +- **`textDocument/didOpen`** *(Notification, Client -> Server)* + - **Behavior**: Stores the opened document content in the server's in-memory overlay (taking precedence over the on-disk file) and immediately publishes syntax diagnostics. + - **Limitations**: None. + +- **`textDocument/didChange`** *(Notification, Client -> Server)* + - **Behavior**: Supports both incremental range-based edits (`range` + `text`) and full-document replacements (`text`). Invalidates stale cached state for the modified file and schedules syntax diagnostics after a **150 ms** debounce delay. + - **Limitations**: The 150 ms debounce interval is fixed and cannot be customized via client settings. + +- **`textDocument/didSave`** *(Notification, Client -> Server)* + - **Behavior**: Cancels any pending diagnostic debounce timer, refreshes the in-memory buffer if `params.text` is included in the notification, and immediately publishes diagnostics. + - **Limitations**: Does not instruct the client to always include full text on save (`save.includeText` is omitted). + +- **`textDocument/didClose`** *(Notification, Client -> Server)* + - **Behavior**: Cancels any pending diagnostic debounce timer, publishes an empty diagnostics list (`[]`) to clear editor markers for the document, and removes the file from the in-memory overlay so subsequent cross-file lookups read from disk. + - **Limitations**: Because diagnostics are cleared on close, syntax errors in closed files do not persist in workspace-wide Problems panels. + +--- + +#### Diagnostics + +- **`textDocument/publishDiagnostics`** *(Notification, Server -> Client)* + - **Behavior**: Pushes parser and lexical errors (`Severity: Error`, `Source: "dml"`) and DML version compatibility warnings (`Severity: Warning`, `Code: "EUNIMPL"`, `Source: "dml"` for non-1.4 version headers such as `dml 1.2;`). + - **Limitations**: + - **Syntax Only**: Reports grammar and lexical errors only; does not perform semantic analysis (such as type checking, undeclared symbol detection, or duplicate definition checks). + - **DML 1.4 Target**: Files starting with `dml 1.2;` emit an `EUNIMPL` warning and skip further parsing of the file body. + - **No Import Validation**: Unresolved or missing `import` file paths do not generate diagnostic errors or warnings. + - **Opaque C Blocks**: Embedded C code inside `header %{ ... %}` and `footer %{ ... %}` blocks is not parsed or checked for C syntax errors. + +--- + +#### Language Features + +- **`textDocument/definition`** *(Request, Client -> Server)* + - **Behavior**: Resolves DML identifiers, dotted member access chains (`a.b.c`), hierarchy keywords (`this`, `parent`, `dev`), `template` references (`is ...`), and `import "..."` targets across open buffers and on-disk imported files. + - **Limitations**: + - **Single Location Result**: Returns a single `Location` object rather than `Location[]` or `LocationLink[]`. When a `param` or `default method` is declared in a template and overridden in an object, only the highest-precedence match in scope resolution order is returned. + - **Import Search Scope**: Searches only the importing file's directory and the primary workspace root (plus their `1.4/` subdirectories); external include directories (`-I` paths) outside the workspace are not supported. + - **`in each` Blocks**: Template applications and declarations inside `in each` statements are not indexed or resolved. + - **Embedded C Blocks**: Symbols defined inside `header %{ ... %}` and `footer %{ ... %}` C blocks are not indexed. + - **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. + +--- + +## 3. Unsupported LSP API Commands + +Any LSP 3.17 request or notification not listed in Section 2 is **unsupported** (`dmlsp` does not advertise capabilities for these features and returns method-not-found or empty responses if invoked). + +### Formatting + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `textDocument/formatting` | Client -> Server | Unsupported in `dmlsp`. Use the standalone `dmlfmt` CLI tool for DML code formatting (see the [DML Code Formatting Guide](../format/README.md)). | +| `textDocument/rangeFormatting` | Client -> Server | Unsupported in `dmlsp`. | +| `textDocument/onTypeFormatting` | Client -> Server | Unsupported in `dmlsp`. | + +### Code Navigation + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `textDocument/declaration` | Client -> Server | Unsupported. | +| `textDocument/typeDefinition` | Client -> Server | Unsupported. | +| `textDocument/implementation` | Client -> Server | Unsupported. | +| `textDocument/references` | Client -> Server | Unsupported (Find All References is not available). | + +### Coding Assistance & Intelligence + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `textDocument/hover` | Client -> Server | Unsupported (no hover documentation or type tooltips). | +| `textDocument/completion` | Client -> Server | Unsupported (no autocomplete suggestions). | +| `completionItem/resolve` | Client -> Server | Unsupported. | +| `textDocument/signatureHelp` | Client -> Server | Unsupported (no parameter hints while typing method calls). | +| `textDocument/inlayHint` | Client -> Server | Unsupported. | +| `inlayHint/resolve` | Client -> Server | Unsupported. | +| `textDocument/inlineValue` | Client -> Server | Unsupported. | +| `textDocument/moniker` | Client -> Server | Unsupported. | + +### Symbols & Document Outline + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `textDocument/documentSymbol` | Client -> Server | Unsupported (no editor Outline / Breadcrumbs tree). | +| `workspace/symbol` | Client -> Server | Unsupported (no workspace-wide symbol search). | +| `workspaceSymbol/resolve` | Client -> Server | Unsupported. | + +### Refactoring & Code Actions + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `textDocument/rename` | Client -> Server | Unsupported (no symbol renaming). | +| `textDocument/prepareRename` | Client -> Server | Unsupported. | +| `textDocument/codeAction` | Client -> Server | Unsupported (no quick fixes or refactorings). | +| `codeAction/resolve` | Client -> Server | Unsupported. | +| `textDocument/codeLens` | Client -> Server | Unsupported. | +| `codeLens/resolve` | Client -> Server | Unsupported. | + +### Highlighting, Folding & Selection + +| 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/foldingRange` | Client -> Server | Unsupported (folding relies on editor indentation/grammar). | +| `textDocument/selectionRange` | Client -> Server | Unsupported. | +| `textDocument/linkedEditingRange` | Client -> Server | Unsupported. | +| `textDocument/documentLink` | Client -> Server | Unsupported (use `textDocument/definition` on `import` statements instead). | +| `documentLink/resolve` | Client -> Server | Unsupported. | +| `textDocument/documentColor` | Client -> Server | Unsupported. | +| `textDocument/colorPresentation` | Client -> Server | Unsupported. | + +### Call & Type Hierarchy + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `textDocument/prepareCallHierarchy` | Client -> Server | Unsupported. | +| `callHierarchy/incomingCalls` | Client -> Server | Unsupported. | +| `callHierarchy/outgoingCalls` | Client -> Server | Unsupported. | +| `textDocument/prepareTypeHierarchy` | Client -> Server | Unsupported. | +| `typeHierarchy/supertypes` | Client -> Server | Unsupported. | +| `typeHierarchy/subtypes` | Client -> Server | Unsupported. | + +### Pull Diagnostics + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `textDocument/diagnostic` | Client -> Server | Unsupported (`dmlsp` uses push-based `textDocument/publishDiagnostics`). | +| `workspace/diagnostic` | Client -> Server | Unsupported. | + +### Document Sync (Will-Save) + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `textDocument/willSave` | Client -> Server | Unsupported. | +| `textDocument/willSaveWaitUntil` | Client -> Server | Unsupported. | + +### Workspace & File Operations + +| Method | Direction | Notes | +| :--- | :--- | :--- | +| `workspace/didChangeWorkspaceFolders` | Client -> Server | Unsupported (restart server or reopen workspace to change workspace root). | +| `workspace/didChangeConfiguration` | Client -> Server | Unsupported. | +| `workspace/didChangeWatchedFiles` | Client -> Server | Unsupported. | +| `workspace/executeCommand` | Client -> Server | Unsupported. | +| `workspace/applyEdit` | Server -> Client | Unsupported. | +| `workspace/willCreateFiles` | Client -> Server | Unsupported. | +| `workspace/didCreateFiles` | Client -> Server | Unsupported. | +| `workspace/willRenameFiles` | Client -> Server | Unsupported. | +| `workspace/didRenameFiles` | Client -> Server | Unsupported. | +| `workspace/willDeleteFiles` | Client -> Server | Unsupported. | +| `workspace/didDeleteFiles` | Client -> Server | Unsupported. | diff --git a/doc/lsp/features.md b/doc/lsp/features.md new file mode 100644 index 0000000..42c7726 --- /dev/null +++ b/doc/lsp/features.md @@ -0,0 +1,183 @@ +# DML Language Server Features + +This guide describes the editing and navigation features provided by `dmlsp` +and how they behave in day-to-day DML development. + +--- + +## 1. Real-Time Syntax Diagnostics + +`dmlsp` validates DML source syntax automatically as you work +and pushes diagnostics directly to your editor's Problems/Diagnostics view. + +### When Diagnostics Run + +| Editor Action | Behavior | +| :--- | :--- | +| **Open file** | Validates the file immediately and publishes diagnostics. | +| **Edit file** | Debounces validation for **150 ms** after the last keystroke so rapid typing does not flood the editor with transient errors. | +| **Save file** | Cancels any pending debounce timer and validates immediately. | +| **Close file** | Clears diagnostics for the closed file in your editor. | + +### Syntax & Lexical Errors + +Syntax and tokenization errors are reported with `Error` severity (source: `dml`) +highlighting the offending token or position: + +```dml +dml 1.4; +device my_device; // Valid + +bank regs { + register ctrl size 4 @ 0x00 // Missing ';' -> reported as an Error diagnostic +} +``` + +As soon as you fix the syntax error, the diagnostic clears automatically. + +### DML 1.2 Version Warning (`EUNIMPL`) + +`dmlsp` targets **DML 1.4**. Opening a file with an earlier language tag (such as `dml 1.2;`) produces a `Warning` diagnostic with code `EUNIMPL` on the version number: + +```dml +dml 1.2; // Warning [EUNIMPL]: Error Unimplemented: dml 1.2 syntax is not supported yet +device legacy_dev; +``` + +### Diagnostic Scope + +`dmlsp` performs **syntax and lexical validation only**. It does not currently emit diagnostics for: +- Type mismatches, undeclared identifiers, or semantic errors checked by `dmlc` +- Unresolved `import` paths (missing imported files) +- C syntax or compiler errors inside `header %{ ... %}` and `footer %{ ... %}` blocks + +--- + +## 2. Go to Definition + +Triggering **Go to Definition** in your editor resolves DML identifiers, +dotted member paths, hierarchy keywords, templates, +and `import` statements across the current file and imported files. + +### Navigating `import` Statements + +Placing the cursor anywhere on an `import` statement +jumps to line 1, column 1 of the imported file: + +```dml +dml 1.4; +device my_device; + +import "common/helpers.dml"; // Go to Definition opens common/helpers.dml +``` + +#### Import Search Path Order + +`dmlsp` resolves imported file paths using the following precedence: + +1. **`./` paths** (e.g., `import "./local.dml";`): Resolved strictly relative to the directory of the file containing the `import`. +2. **`../` paths** (e.g., `import "../shared.dml";`): Checked relative to the importing file's directory first; if not found, falls back to the search order below. +3. **Bare paths** (e.g., `import "dml-builtins.dml";` or `import "sub/defs.dml";`): Searched in order across the importing file's directory and the primary workspace root: + - `/1.4/` + - `/` + - `/1.4/` + - `/` + +### Templates & Template Inheritance (`template`, `is`) + +You can jump to a template definition either from the template name itself +or from the `is` keyword in an `is