Coverage for fastblocks / adapters / templates / _language_server.py: 34%
154 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""FastBlocks Language Server Protocol implementation."""
3import asyncio
4import typing as t
5from contextlib import suppress
6from typing import Any
7from uuid import UUID
9from oneiric.core.config import OneiricSettings
10from oneiric.core.resolution import Resolver
12# Oneiric resolver for dependency injection
13depends = Resolver()
15from ._syntax_support import FastBlocksSyntaxSupport
18class LanguageServerSettings(OneiricSettings):
19 """Settings for FastBlocks Language Server."""
21 # Required ACB 0.19.0+ metadata
22 MODULE_ID: UUID = UUID("01937d87-2345-6789-abcd-123456789def")
23 MODULE_STATUS: str = "stable"
25 # Server settings
26 port: int = 7777
27 host: str = "localhost"
28 enable_tcp: bool = False
29 enable_stdio: bool = True
31 # Feature flags
32 enable_completions: bool = True
33 enable_hover: bool = True
34 enable_diagnostics: bool = True
35 enable_formatting: bool = True
36 enable_signature_help: bool = True
38 # Performance settings
39 completion_trigger_characters: list[str] = ["[", "|", ".", "("]
40 signature_trigger_characters: list[str] = ["(", ","]
41 diagnostic_delay_ms: int = 500
42 completion_timeout_ms: int = 1000
45class FastBlocksLanguageServer:
46 """Language Server Protocol implementation for FastBlocks templates."""
48 # Required ACB 0.19.0+ metadata
49 MODULE_ID: UUID = UUID("01937d87-2345-6789-abcd-123456789def")
50 MODULE_STATUS: str = "stable"
52 def __init__(self) -> None:
53 """Initialize language server."""
54 self.settings: LanguageServerSettings | None = None
55 self.syntax_support: FastBlocksSyntaxSupport | None = None
56 self._documents: dict[str, str] = {}
57 self._diagnostics: dict[str, list[dict[str, Any]]] = {}
59 # Register with ACB
60 with suppress(Exception):
61 depends.set(self)
63 # Initialize syntax support
64 self.syntax_support = FastBlocksSyntaxSupport()
66 async def initialize(self, params: dict[str, Any]) -> dict[str, Any]:
67 """Handle LSP initialize request."""
68 if not self.settings:
69 self.settings = LanguageServerSettings()
71 capabilities: dict[str, Any] = {
72 "textDocumentSync": {
73 "openClose": True,
74 "change": 1, # Full document sync
75 "save": {"includeText": True},
76 }
77 }
79 if self.settings.enable_completions:
80 capabilities["completionProvider"] = {
81 "triggerCharacters": self.settings.completion_trigger_characters,
82 "resolveProvider": True,
83 }
85 if self.settings.enable_hover:
86 capabilities["hoverProvider"] = True
88 if self.settings.enable_formatting:
89 capabilities["documentFormattingProvider"] = True
91 if self.settings.enable_signature_help:
92 capabilities["signatureHelpProvider"] = {
93 "triggerCharacters": self.settings.signature_trigger_characters
94 }
96 return {
97 "capabilities": capabilities,
98 "serverInfo": {"name": "FastBlocks Language Server", "version": "1.0.0"},
99 }
101 async def text_document_did_open(self, params: dict[str, Any]) -> None:
102 """Handle document open event."""
103 doc = params["textDocument"]
104 uri = doc["uri"]
105 content = doc["text"]
107 self._documents[uri] = content
109 # Run diagnostics
110 if self.settings and self.settings.enable_diagnostics:
111 await self._run_diagnostics(uri, content)
113 async def text_document_did_change(self, params: dict[str, Any]) -> None:
114 """Handle document change event."""
115 uri = params["textDocument"]["uri"]
116 changes = params["contentChanges"]
118 # For full document sync
119 if changes:
120 self._documents[uri] = changes[0]["text"]
122 # Delayed diagnostics
123 if self.settings and self.settings.enable_diagnostics:
124 await asyncio.sleep(self.settings.diagnostic_delay_ms / 1000)
125 await self._run_diagnostics(uri, self._documents[uri])
127 async def text_document_completion(self, params: dict[str, Any]) -> dict[str, Any]:
128 """Handle completion request."""
129 if not self.settings or not self.settings.enable_completions:
130 return {"items": []}
132 uri = params["textDocument"]["uri"]
133 position = params["position"]
134 content = self._documents.get(uri, "")
136 if not self.syntax_support:
137 return {"items": []}
139 # Get completions
140 completions = self.syntax_support.get_completions(
141 content, position["line"], position["character"]
142 )
144 items = []
145 for completion in completions:
146 item = {
147 "label": completion.label,
148 "kind": self._completion_kind_to_lsp(completion.kind),
149 "detail": completion.detail,
150 "documentation": completion.documentation,
151 "insertText": completion.insert_text or completion.label,
152 "sortText": f"{100 - completion.priority:03d}_{completion.label}",
153 }
155 # Add snippet support
156 if completion.insert_text and "$" in completion.insert_text:
157 item["insertTextFormat"] = 2 # Snippet
159 items.append(item)
161 return {"items": items}
163 async def text_document_hover(
164 self, params: dict[str, Any]
165 ) -> dict[str, Any] | None:
166 """Handle hover request."""
167 if not self.settings or not self.settings.enable_hover:
168 return None
170 uri = params["textDocument"]["uri"]
171 position = params["position"]
172 content = self._documents.get(uri, "")
174 if not self.syntax_support:
175 return None
177 hover_info = self.syntax_support.get_hover_info(
178 content, position["line"], position["character"]
179 )
181 if hover_info:
182 return {"contents": {"kind": "markdown", "value": hover_info}}
184 return None
186 async def text_document_formatting(
187 self, params: dict[str, Any]
188 ) -> list[dict[str, Any]]:
189 """Handle formatting request."""
190 if not self.settings or not self.settings.enable_formatting:
191 return []
193 uri = params["textDocument"]["uri"]
194 content = self._documents.get(uri, "")
196 if not self.syntax_support:
197 return []
199 formatted = self.syntax_support.format_template(content)
201 if formatted != content:
202 lines = content.split("\n")
203 return [
204 {
205 "range": {
206 "start": {"line": 0, "character": 0},
207 "end": {"line": len(lines), "character": 0},
208 },
209 "newText": formatted,
210 }
211 ]
213 return []
215 async def _run_diagnostics(self, uri: str, content: str) -> None:
216 """Run diagnostics on document."""
217 if not self.syntax_support:
218 return
220 errors = self.syntax_support.check_syntax(content)
221 diagnostics = []
223 for error in errors:
224 diagnostic = {
225 "range": {
226 "start": {"line": error.line, "character": error.column},
227 "end": {"line": error.line, "character": error.column + 10},
228 },
229 "severity": self._severity_to_lsp(error.severity),
230 "code": error.code,
231 "source": "FastBlocks",
232 "message": error.message,
233 }
235 if error.fix_suggestion:
236 t.cast(dict[str, t.Any], diagnostic)["data"] = {
237 "fix": error.fix_suggestion
238 }
240 diagnostics.append(diagnostic)
242 self._diagnostics[uri] = diagnostics
244 # In a real LSP implementation, you would send this to the client
245 # self.send_notification("textDocument/publishDiagnostics", {
246 # "uri": uri,
247 # "diagnostics": diagnostics
248 # })
250 def _completion_kind_to_lsp(self, kind: str) -> int:
251 """Convert completion kind to LSP constants."""
252 mapping = {
253 "function": 3, # Function
254 "variable": 6, # Variable
255 "filter": 12, # Value
256 "block": 14, # Keyword
257 "component": 9, # Module
258 "snippet": 15, # Snippet
259 }
260 return mapping.get(kind, 1) # Text
262 def _severity_to_lsp(self, severity: str) -> int:
263 """Convert severity to LSP constants."""
264 mapping = {"error": 1, "warning": 2, "info": 3, "hint": 4}
265 return mapping.get(severity, 1)
267 def get_current_diagnostics(self, uri: str) -> list[dict[str, Any]]:
268 """Get current diagnostics for a document."""
269 return self._diagnostics.get(uri, [])
271 async def shutdown(self) -> None:
272 """Handle server shutdown."""
273 self._documents.clear()
274 self._diagnostics.clear()
277class FastBlocksLanguageClient:
278 """Simple language client for testing and integration."""
280 def __init__(self) -> None:
281 """Initialize language client."""
282 self.server = FastBlocksLanguageServer()
283 self._initialized = False
285 async def initialize(self) -> None:
286 """Initialize the language server."""
287 if self._initialized:
288 return
290 await self.server.initialize(
291 {
292 "processId": None,
293 "clientInfo": {"name": "FastBlocks Client", "version": "1.0.0"},
294 "capabilities": {},
295 }
296 )
297 self._initialized = True
299 async def open_document(self, uri: str, content: str) -> None:
300 """Open a document."""
301 await self.initialize()
302 await self.server.text_document_did_open(
303 {
304 "textDocument": {
305 "uri": uri,
306 "languageId": "fastblocks",
307 "version": 1,
308 "text": content,
309 }
310 }
311 )
313 async def change_document(self, uri: str, content: str) -> None:
314 """Change document content."""
315 await self.server.text_document_did_change(
316 {
317 "textDocument": {"uri": uri, "version": 2},
318 "contentChanges": [{"text": content}],
319 }
320 )
322 async def get_completions(
323 self, uri: str, line: int, character: int
324 ) -> list[dict[str, Any]]:
325 """Get completions at position."""
326 result = await self.server.text_document_completion(
327 {
328 "textDocument": {"uri": uri},
329 "position": {"line": line, "character": character},
330 }
331 )
332 return t.cast(list[dict[str, Any]], result.get("items", []))
334 async def get_hover(
335 self, uri: str, line: int, character: int
336 ) -> dict[str, Any] | None:
337 """Get hover information."""
338 return await self.server.text_document_hover(
339 {
340 "textDocument": {"uri": uri},
341 "position": {"line": line, "character": character},
342 }
343 )
345 async def format_document(self, uri: str) -> list[dict[str, Any]]:
346 """Format document."""
347 return await self.server.text_document_formatting(
348 {"textDocument": {"uri": uri}}
349 )
351 def get_diagnostics(self, uri: str) -> list[dict[str, Any]]:
352 """Get current diagnostics."""
353 return self.server.get_current_diagnostics(uri)
356# VS Code extension configuration generator
357def generate_vscode_extension() -> dict[str, Any]:
358 """Generate VS Code extension configuration for FastBlocks."""
359 return {
360 "name": "fastblocks-language-support",
361 "displayName": "FastBlocks Language Support",
362 "description": "Language support for FastBlocks templates",
363 "version": "1.0.0",
364 "publisher": "fastblocks",
365 "engines": {"vscode": "^1.74.0"},
366 "categories": ["Programming Languages"],
367 "activationEvents": ["onLanguage:fastblocks"],
368 "main": "./out/extension.js",
369 "contributes": {
370 "languages": [
371 {
372 "id": "fastblocks",
373 "aliases": ["FastBlocks", "fastblocks"],
374 "extensions": [".fb.html", ".fastblocks"],
375 "configuration": "./language-configuration.json",
376 }
377 ],
378 "grammars": [
379 {
380 "language": "fastblocks",
381 "scopeName": "text.html.fastblocks",
382 "path": "./syntaxes/fastblocks.tmLanguage.json",
383 }
384 ],
385 "configuration": {
386 "type": "object",
387 "title": "FastBlocks",
388 "properties": {
389 "fastblocks.languageServer.enabled": {
390 "type": "boolean",
391 "default": True,
392 "description": "Enable FastBlocks language server",
393 },
394 "fastblocks.languageServer.port": {
395 "type": "number",
396 "default": 7777,
397 "description": "Language server port",
398 },
399 "fastblocks.completion.enabled": {
400 "type": "boolean",
401 "default": True,
402 "description": "Enable auto-completion",
403 },
404 "fastblocks.diagnostics.enabled": {
405 "type": "boolean",
406 "default": True,
407 "description": "Enable error checking",
408 },
409 },
410 },
411 },
412 "scripts": {
413 "vscode:prepublish": "npm run compile",
414 "compile": "tsc -p ./",
415 "watch": "tsc -watch -p ./",
416 },
417 "devDependencies": {
418 "@types/vscode": "^1.74.0",
419 "@typescript-eslint/eslint-plugin": "^5.45.0",
420 "@typescript-eslint/parser": "^5.45.0",
421 "eslint": "^8.28.0",
422 "typescript": "^4.9.4",
423 },
424 "dependencies": {"vscode-languageclient": "^8.1.0"},
425 }
428# TextMate grammar for syntax highlighting
429def generate_textmate_grammar() -> dict[str, Any]:
430 """Generate TextMate grammar for FastBlocks syntax highlighting."""
431 return {
432 "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
433 "name": "FastBlocks",
434 "scopeName": "text.html.fastblocks",
435 "patterns": [
436 {"include": "#fastblocks-variable"},
437 {"include": "#fastblocks-block"},
438 {"include": "#fastblocks-comment"},
439 {"include": "text.html.basic"},
440 ],
441 "repository": {
442 "fastblocks-variable": {
443 "name": "meta.tag.template.value.fastblocks",
444 "begin": r"\[\[",
445 "end": r"\]\]",
446 "beginCaptures": {
447 "0": {"name": "punctuation.definition.tag.begin.fastblocks"}
448 },
449 "endCaptures": {
450 "0": {"name": "punctuation.definition.tag.end.fastblocks"}
451 },
452 "patterns": [
453 {"include": "#fastblocks-filter"},
454 {"include": "#fastblocks-string"},
455 {"include": "#fastblocks-identifier"},
456 ],
457 },
458 "fastblocks-block": {
459 "name": "meta.tag.template.block.fastblocks",
460 "begin": r"\[%",
461 "end": r"%\]",
462 "beginCaptures": {
463 "0": {"name": "punctuation.definition.tag.begin.fastblocks"}
464 },
465 "endCaptures": {
466 "0": {"name": "punctuation.definition.tag.end.fastblocks"}
467 },
468 "patterns": [
469 {
470 "name": "keyword.control.fastblocks",
471 "match": r"\b(if|else|elif|endif|for|endfor|block|endblock|extends|include|set|macro|endmacro)\b",
472 },
473 {"include": "#fastblocks-string"},
474 {"include": "#fastblocks-identifier"},
475 ],
476 },
477 "fastblocks-comment": {
478 "name": "comment.block.fastblocks",
479 "begin": r"\[#",
480 "end": r"#\]",
481 "beginCaptures": {
482 "0": {"name": "punctuation.definition.comment.begin.fastblocks"}
483 },
484 "endCaptures": {
485 "0": {"name": "punctuation.definition.comment.end.fastblocks"}
486 },
487 },
488 "fastblocks-filter": {
489 "name": "support.function.filter.fastblocks",
490 "match": r"\|\s*(\w+)",
491 "captures": {"1": {"name": "entity.name.function.filter.fastblocks"}},
492 },
493 "fastblocks-string": {
494 "name": "string.quoted.double.fastblocks",
495 "begin": r'"',
496 "end": r'"',
497 "patterns": [
498 {"name": "constant.character.escape.fastblocks", "match": r"\\."}
499 ],
500 },
501 "fastblocks-identifier": {
502 "name": "variable.other.fastblocks",
503 "match": r"\b[a-zA-Z_][a-zA-Z0-9_]*\b",
504 },
505 },
506 }
509# ACB 0.19.0+ compatibility
510__all__ = [
511 "FastBlocksLanguageServer",
512 "FastBlocksLanguageClient",
513 "LanguageServerSettings",
514 "generate_vscode_extension",
515 "generate_textmate_grammar",
516]