Metadata-Version: 2.4
Name: kompas3d-lsp
Version: 0.3.0
Summary: LSP server for KOMPAS-3D ksAPI
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: pygls>=2.1.0
Requires-Dist: lsprotocol>=2025.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Provides-Extra: pyinstaller
Requires-Dist: pyinstaller>=6.0; extra == "pyinstaller"

# KOMPAS-3D LSP

**Language Server Protocol** server for **KOMPAS-3D ksAPI**.

Auto-completion, hover docs, signature help and diagnostics for KOMPAS-3D scripting in Python, C++ and C#.

Powered by the official ksAPI documentation — 856 interfaces, 7104 methods with multi-language syntax (C++, Python pywin32, C# COM interop), 14106 enum member entries.

**v0.3.0**: AST-based diagnostics for Python, exact method name verification via `KOMPAS_BIN_DIR`, out-parameter handling in Python signatures.

---

## Features

| Feature | Status |
|---------|--------|
| `textDocument/completion` — interfaces, methods, enum constants, per-language syntax | ✅ |
| `textDocument/hover` — descriptions with syntax and examples per language | ✅ |
| `textDocument/signatureHelp` — method signatures on argument input | ✅ |
| `textDocument/publishDiagnostics` — common mistake warnings per language | ✅ |
| `--check` batch mode — file validation without LSP | ✅ |
| AST diagnostics for `.py` — unknown methods, arity, enum constants | ✅ (v0.3.0) |
| Exact name check via installed `ksapi.py` + `KsAPI.h` | ✅ (v0.3.0) |
| Python out-params as tuple return types | ✅ (v0.3.0) |

---

## Installation

### Windows / Linux / macOS (via pip)

```bash
pip install kompas3d-lsp
kompas3d-lsp --help
```

After installation, the executable `kompas3d-lsp` (or `kompas3d-lsp.exe` on Windows) is in Python's `Scripts/` directory — add it to your PATH.

### From source

**Windows (PowerShell):**

```powershell
uv venv .venv
.venv\Scripts\python.exe -m pip install -e ".[dev]"
.venv\Scripts\kompas3d-lsp --help
```

**Linux / macOS (bash):**

```bash
uv venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
kompas3d-lsp --help
```

### PyInstaller (.exe) — Windows only, standalone

For users without Python. **Windows only.**

```powershell
pip install pyinstaller
pyinstaller kompas3d-lsp.spec
dist\kompas3d-lsp\kompas3d-lsp.exe --help
```

The `.exe` runs on any Windows machine with no Python or packages required.

---

## OpenCode Integration

Put `opencode.json` in your project root:

```json
{
  "lsp": {
    "kompas3d-lsp": {
      "command": ["kompas3d-lsp", "--stdio"],
      "extensions": [".py", ".cpp", ".h", ".cs"]
    }
  }
}
```

---

## Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `KOMPAS_LSP_LANG` | `ru` | Knowledge base language (`ru` / `en`) |
| `KOMPAS_LSP_DATA_DIR` | — | Custom path to `{lang}/ksapi_knowledge.json` |
| `KOMPAS_BIN_DIR` | — | Path to KOMPAS-3D `Bin/` for exact method name lookup |

### `KOMPAS_BIN_DIR` (v0.3.0)

Points to the installed KOMPAS-3D build directory (`Bin/`). The server loads method names directly from `ksapi.py` (AST-parsed) and `KsAPI.h` (regex-parsed) — eliminates false positives from docs drift.

Without `KOMPAS_BIN_DIR`, the server falls back to the knowledge base with severity **hint** (not warning).

**Windows:**

```powershell
$env:KOMPAS_BIN_DIR = "C:\Program Files\KOMPAS-3D\Bin"
kompas3d-lsp --check myscript.py
```

**Linux (KOMPAS-3D via Wine or extracted SDK):**

```bash
export KOMPAS_BIN_DIR="/opt/kompas/bin"
kompas3d-lsp --check myscript.py
```

On Linux without KOMPAS-3D installed, just leave it unset — the server runs in hint mode using the knowledge base.

In `opencode.json`:

```json
{
  "lsp": {
    "kompas3d-lsp": {
      "command": ["kompas3d-lsp", "--stdio"],
      "env": {
        "KOMPAS_BIN_DIR": "/opt/kompas/bin"
      }
    }
  }
}
```

---

## CLI

```
kompas3d-lsp --stdio                  # stdio transport (default, for LSP clients)
kompas3d-lsp --tcp                    # TCP transport (127.0.0.1:2087, debugging)
kompas3d-lsp --lang en                # override knowledge base language
kompas3d-lsp --check file.py          # batch file check (exit code 1 on findings)
kompas3d-lsp --check file.py --json   # machine-readable JSON output
kompas3d-lsp --help
```

### Exit codes

- **0** — clean file (no findings)
- **1** — issues found

Use in pre-commit hooks or CI gates:

**Linux / macOS (bash):**

```bash
kompas3d-lsp --check myscript.py --json || echo "ksAPI issues found"
```

**Windows (PowerShell):**

```powershell
kompas3d-lsp --check myscript.py --json; if ($LASTEXITCODE) { throw "ksAPI issues found" }
```

### Output format

Default (human-readable): `file:line:col: severity: message`

```
myscript.py:3:5: hint: Method 'GetBodyParts' not found in SDK documentation.
myscript.py:7:12: warning: Method 'GetGabarit' called with 1 arguments; expected 4–8.
myscript.py:9:23: hint: Unknown enum constant: 'constants3d.o3d_facce'.
```

With `--json`: array `[{line, character, message, severity, source}]`.

---

## Diagnostics

### Language-agnostic

1. **Unknown ksAPI method** — checked against KB or `ksapi.py`/`KsAPI.h` (if `KOMPAS_BIN_DIR` set)
   - Without `KOMPAS_BIN_DIR` → hint
   - With `KOMPAS_BIN_DIR` → warning (exact against installed build)

### Python (AST-based)

2. `import win32com.client` without `try/except` — KOMPAS may be missing on CI
3. **Unknown ksAPI method** — hint/warning
4. **Method call chains** — both `a.GetModelContainer().GetObjects()` links are checked
5. **Arity** — `GetGabarit(True)` when expecting 4–8 arguments
6. **Enum constants** — `constants3d.o3d_facce` (typo)

### C++ (regex heuristic)

7. `->` call without null check
8. Unknown method (heuristic, false positives in comments possible)

### C# (regex heuristic)

9. `Marshal.GetActiveObject` / `Type.GetTypeFromProgID` without `try/catch`
10. Unknown method (heuristic, false positives in comments possible)

---

## Changelog

### v0.3.0

- Exact method name check: `KOMPAS_BIN_DIR` support, parses `ksapi.py` (AST) + `KsAPI.h` (regex) from installed build; fallback to KB with hint severity
- AST diagnostics for `.py`: call chains, arity (with kwargs + defaults), enum constants
- Python out-params in signatures: `GetGabarit(...) -> tuple[bool, float, ...]` (256 methods)
- Enum members in KB: 14106 entries, enum constant auto-completion
- `--check`: exit code 1 on findings; human-readable output by default, `--json` for JSON
- Performance: frozenset for O(1) method name lookup; mtime-cached build parsing
- 176 tests

### v0.2.0

- Multi-language pipeline (parser → transformer → dict format)
- `--check` batch mode
- pygls 2.x support, lazy KB loading

---

## Build & Publish

### Wheel

```bash
# Copy knowledge base into package
python tools/copy_data_to_package.py

# Build
python -m build
# → dist/kompas3d_lsp-0.3.0-py3-none-any.whl
# → dist/kompas3d_lsp-0.3.0.tar.gz
```

**Publish:**

```bash
pip install twine
twine upload dist/*
```

Or via GitHub Actions: `git tag v0.3.0 && git push origin v0.3.0`.

### PyInstaller (.exe)

Windows standalone executable:

```bash
pip install pyinstaller
pyinstaller kompas3d-lsp.spec
dist\kompas3d-lsp\kompas3d-lsp.exe --help
```

---

## Supported Languages

| Extension | Language | Syntax Style |
|-----------|----------|-------------|
| `.py`, `.pyw` | Python | `method(param: type) -> type` |
| `.cpp`, `.cxx`, `.cc`, `.h`, `.hpp`, `.hxx` | C++ | Native from documentation |
| `.cs` | C# | `Type method(params);` |

Language auto-detected by file extension. Server shows syntax, examples and diagnostics matching the file language.

---

## Client Configuration

### VS Code

```json
{
  "lsp.clients.kompas3d-lsp.command": ["kompas3d-lsp", "--stdio"]
}
```

### Neovim (vim.lsp)

```lua
vim.api.nvim_create_autocmd("FileType", {
  pattern = "python",
  callback = function()
    vim.lsp.start({
      name = "kompas3d-lsp",
      cmd = { "kompas3d-lsp", "--stdio" },
    })
  end,
})
```

---

## License

MIT.

---

## Links

- [KOMPAS-3D SDK Documentation](https://help.ascon.ru/KOMPAS_SDK/25/ru-RU/index.html)
- [LSP Specification](https://microsoft.github.io/language-server-protocol/)
- [pygls](https://github.com/openlawlibrary/pygls)
