Coverage for fastblocks / adapters / templates / _syntax_support.py: 34%
227 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 syntax support and autocomplete system."""
3import re
4from contextlib import suppress
5from dataclasses import dataclass, field
6from pathlib import Path
7from typing import Any
8from uuid import UUID
10from oneiric.core.config import OneiricSettings
11from oneiric.core.resolution import Resolver
13# Migration from ACB to Oneiric
14depends = Resolver()
17class Settings(OneiricSettings):
18 """Base settings class for Oneiric compatibility."""
20 pass
23@dataclass
24class CompletionItem:
25 """Auto-completion item for FastBlocks syntax."""
27 label: str
28 kind: str # 'function', 'variable', 'filter', 'block', 'component'
29 detail: str = ""
30 documentation: str = ""
31 insert_text: str = ""
32 parameters: list[str] = field(default_factory=list)
33 category: str = "general"
34 priority: int = 0
37@dataclass
38class SyntaxError:
39 """FastBlocks syntax error."""
41 line: int
42 column: int
43 message: str
44 severity: str = "error" # 'error', 'warning', 'info'
45 code: str = ""
46 fix_suggestion: str = ""
49class FastBlocksSyntaxSettings(Settings):
50 """Settings for FastBlocks syntax support."""
52 # Required ACB 0.19.0+ metadata
53 MODULE_ID: UUID = UUID("01937d87-1234-5678-9abc-123456789def")
54 MODULE_STATUS: str = "stable"
56 # Completion settings
57 max_completions: int = 50
58 completion_timeout: float = 1.0
59 enable_snippets: bool = True
60 enable_parameter_hints: bool = True
62 # Syntax highlighting
63 enable_highlighting: bool = True
64 highlight_delimiters: bool = True
65 highlight_filters: bool = True
66 highlight_functions: bool = True
68 # Error checking
69 enable_error_checking: bool = True
70 check_template_syntax: bool = True
71 check_filter_existence: bool = True
72 check_function_calls: bool = True
74 # Template delimiters
75 variable_start: str = "[["
76 variable_end: str = "]]"
77 block_start: str = "[%"
78 block_end: str = "%]"
79 comment_start: str = "[#"
80 comment_end: str = "#]"
83class FastBlocksSyntaxSupport:
84 """FastBlocks syntax support and autocomplete provider."""
86 # Required ACB 0.19.0+ metadata
87 MODULE_ID: UUID = UUID("01937d87-1234-5678-9abc-123456789def")
88 MODULE_STATUS: str = "stable"
90 def __init__(self) -> None:
91 """Initialize syntax support."""
92 self.settings: FastBlocksSyntaxSettings | None = None
93 self._completions_cache: dict[str, list[CompletionItem]] = {}
94 self._syntax_patterns: dict[str, re.Pattern[str]] = {}
95 self._builtin_filters: set[str] = set()
96 self._builtin_functions: set[str] = set()
97 self._custom_components: set[str] = set()
99 # Register with ACB
100 with suppress(Exception):
101 depends.set(self)
103 self._initialize_patterns()
104 self._load_builtin_definitions()
106 def _initialize_patterns(self) -> None:
107 """Initialize regex patterns for syntax parsing."""
108 if not self.settings:
109 self.settings = FastBlocksSyntaxSettings()
111 # Escape delimiters for regex
112 var_start = re.escape(self.settings.variable_start)
113 var_end = re.escape(self.settings.variable_end)
114 block_start = re.escape(self.settings.block_start)
115 block_end = re.escape(self.settings.block_end)
116 comment_start = re.escape(self.settings.comment_start)
117 comment_end = re.escape(self.settings.comment_end)
119 self._syntax_patterns = {
120 "variable": re.compile(
121 rf"{var_start}\s*([^{var_end}]*?)\s*{var_end}"
122 ), # REGEX OK: template variable syntax
123 "block": re.compile(
124 rf"{block_start}\s*([^{block_end}]*?)\s*{block_end}"
125 ), # REGEX OK: template block syntax
126 "comment": re.compile( # REGEX OK: template comment syntax
127 rf"{comment_start}\s*([^{comment_end}]*?)\s*{comment_end}"
128 ),
129 "filter": re.compile(
130 r"\|\s*(\w+)(?:\([^)]*\))?"
131 ), # REGEX OK: template filter syntax
132 "function": re.compile(r"(\w+)\s*\("), # REGEX OK: template function calls
133 "component": re.compile(
134 r"render_component\s*\(\s*[\"']([^\"']+)[\"']"
135 ), # REGEX OK: component rendering syntax
136 "string": re.compile(
137 r'["\']([^"\']*)["\']'
138 ), # REGEX OK: string literals in templates
139 "identifier": re.compile(r"\b(\w+)\b"), # REGEX OK: variable identifiers
140 }
142 def _load_builtin_definitions(self) -> None:
143 """Load built-in Jinja2 filters and functions."""
144 self._builtin_filters = {
145 # Jinja2 built-in filters
146 "abs",
147 "attr",
148 "batch",
149 "capitalize",
150 "center",
151 "default",
152 "dictsort",
153 "escape",
154 "filesizeformat",
155 "first",
156 "float",
157 "forceescape",
158 "format",
159 "groupby",
160 "indent",
161 "int",
162 "join",
163 "last",
164 "length",
165 "list",
166 "lower",
167 "map",
168 "max",
169 "min",
170 "pprint",
171 "random",
172 "reject",
173 "rejectattr",
174 "replace",
175 "reverse",
176 "round",
177 "safe",
178 "select",
179 "selectattr",
180 "slice",
181 "sort",
182 "string",
183 "striptags",
184 "sum",
185 "title",
186 "tojson",
187 "trim",
188 "truncate",
189 "unique",
190 "upper",
191 "urlencode",
192 "urlize",
193 "wordcount",
194 "wordwrap",
195 "xmlattr",
196 # FastBlocks custom filters
197 "img",
198 "icon",
199 "stylesheet",
200 "component_class",
201 "duotone",
202 "interactive",
203 "button_icon",
204 "ph_icon",
205 "ph_class",
206 "hero_icon",
207 "remix_icon",
208 "material_icon",
209 "webawesome_class",
210 "kelp_class",
211 "cloudflare_img",
212 "twicpics_img",
213 }
215 self._builtin_functions = {
216 # Jinja2 built-in functions
217 "range",
218 "lipsum",
219 "dict",
220 "cycler",
221 "joiner",
222 "namespace",
223 # FastBlocks custom functions
224 "render_component",
225 "get_adapter",
226 "include_template",
227 "extend_template",
228 "load_static",
229 "url_for",
230 "csrf_token",
231 "flash_messages",
232 "get_config",
233 "phosphor_stylesheet_links",
234 "ph_duotone",
235 "ph_interactive",
236 "ph_button_icon",
237 "heroicons_stylesheet_links",
238 "remixicon_stylesheet_links",
239 "material_icons_links",
240 "webawesome_stylesheet_links",
241 "kelp_stylesheet_links",
242 }
244 def get_completions(
245 self, content: str, line: int, column: int, context: str = ""
246 ) -> list[CompletionItem]:
247 """Get auto-completion suggestions for given position."""
248 if not self.settings:
249 self.settings = FastBlocksSyntaxSettings()
251 # Find current context
252 current_line = (
253 content.split("\n")[line] if line < len(content.split("\n")) else ""
254 )
255 prefix = current_line[:column]
257 completions: list[CompletionItem] = []
259 # Determine completion context
260 if self._is_in_variable_context(prefix):
261 completions.extend(self._get_variable_completions(prefix))
262 elif self._is_in_block_context(prefix):
263 completions.extend(self._get_block_completions(prefix))
264 elif self._is_in_filter_context(prefix):
265 completions.extend(self._get_filter_completions(prefix))
266 elif self._is_in_function_context(prefix):
267 completions.extend(self._get_function_completions(prefix))
268 else:
269 # General completions
270 completions.extend(self._get_general_completions(prefix))
272 # Sort by priority and limit results
273 completions.sort(key=lambda x: (-x.priority, x.label))
274 return completions[: self.settings.max_completions]
276 def _is_in_variable_context(self, prefix: str) -> bool:
277 """Check if cursor is in variable context."""
278 if not self.settings:
279 return False
280 return (
281 self.settings.variable_start in prefix
282 and self.settings.variable_end
283 not in prefix.split(self.settings.variable_start)[-1]
284 )
286 def _is_in_block_context(self, prefix: str) -> bool:
287 """Check if cursor is in block context."""
288 if not self.settings:
289 return False
290 return (
291 self.settings.block_start in prefix
292 and self.settings.block_end
293 not in prefix.split(self.settings.block_start)[-1]
294 )
296 def _is_in_filter_context(self, prefix: str) -> bool:
297 """Check if cursor is after a pipe for filter completion."""
298 return "|" in prefix and not prefix.rstrip().endswith("|")
300 def _is_in_function_context(self, prefix: str) -> bool:
301 """Check if cursor is in function call context."""
302 return "(" in prefix and ")" not in prefix.split("(")[-1]
304 def _get_variable_completions(self, prefix: str) -> list[CompletionItem]:
305 """Get completions for variable context."""
306 return [
307 CompletionItem(
308 label="request",
309 kind="variable",
310 detail="Current request object",
311 documentation="The current HTTP request with all headers and data",
312 priority=10,
313 ),
314 CompletionItem(
315 label="user",
316 kind="variable",
317 detail="Current user object",
318 documentation="The authenticated user (if available)",
319 priority=9,
320 ),
321 CompletionItem(
322 label="config",
323 kind="variable",
324 detail="Application configuration",
325 documentation="FastBlocks configuration settings",
326 priority=8,
327 ),
328 CompletionItem(
329 label="now",
330 kind="variable",
331 detail="Current datetime",
332 documentation="Current datetime object",
333 priority=7,
334 ),
335 ]
337 def _get_block_completions(self, prefix: str) -> list[CompletionItem]:
338 """Get completions for block context."""
339 return [
340 CompletionItem(
341 label="if",
342 kind="block",
343 detail="Conditional block",
344 insert_text="if condition %]\n content\n[% endif",
345 documentation="Conditional rendering block",
346 priority=10,
347 ),
348 CompletionItem(
349 label="for",
350 kind="block",
351 detail="Loop block",
352 insert_text="for item in items %]\n [[ item ]]\n[% endfor",
353 documentation="Iteration loop block",
354 priority=10,
355 ),
356 CompletionItem(
357 label="block",
358 kind="block",
359 detail="Template inheritance block",
360 insert_text="block name %]\n content\n[% endblock",
361 documentation="Template inheritance block",
362 priority=9,
363 ),
364 CompletionItem(
365 label="extends",
366 kind="block",
367 detail="Template inheritance",
368 insert_text='extends "base.html"',
369 documentation="Extend a parent template",
370 priority=9,
371 ),
372 CompletionItem(
373 label="include",
374 kind="block",
375 detail="Include template",
376 insert_text='include "partial.html"',
377 documentation="Include another template",
378 priority=8,
379 ),
380 CompletionItem(
381 label="set",
382 kind="block",
383 detail="Variable assignment",
384 insert_text="set variable = value",
385 documentation="Set a template variable",
386 priority=8,
387 ),
388 ]
390 def _get_filter_completions(self, prefix: str) -> list[CompletionItem]:
391 """Get completions for filter context."""
392 completions = []
394 for filter_name in sorted(self._builtin_filters):
395 documentation = self._get_filter_documentation(filter_name)
396 completions.append(
397 CompletionItem(
398 label=filter_name,
399 kind="filter",
400 detail=f"Filter: {filter_name}",
401 documentation=documentation,
402 priority=8 if filter_name.startswith(("ph_", "img", "icon")) else 5,
403 )
404 )
406 return completions
408 def _get_function_completions(self, prefix: str) -> list[CompletionItem]:
409 """Get completions for function context."""
410 completions = []
412 for func_name in sorted(self._builtin_functions):
413 documentation = self._get_function_documentation(func_name)
414 parameters = self._get_function_parameters(func_name)
416 completions.append(
417 CompletionItem(
418 label=func_name,
419 kind="function",
420 detail=f"Function: {func_name}",
421 documentation=documentation,
422 parameters=parameters,
423 priority=8 if func_name.startswith("render_") else 5,
424 )
425 )
427 return completions
429 def _get_general_completions(self, prefix: str) -> list[CompletionItem]:
430 """Get general completions."""
431 if not self.settings:
432 self.settings = FastBlocksSyntaxSettings()
434 return [
435 CompletionItem(
436 label=f"{self.settings.variable_start} {self.settings.variable_end}",
437 kind="snippet",
438 detail="Variable output",
439 insert_text=f"{self.settings.variable_start} variable {self.settings.variable_end}",
440 documentation="Output a variable value",
441 priority=10,
442 ),
443 CompletionItem(
444 label=f"{self.settings.block_start} {self.settings.block_end}",
445 kind="snippet",
446 detail="Block statement",
447 insert_text=f"{self.settings.block_start} block {self.settings.block_end}",
448 documentation="Template logic block",
449 priority=10,
450 ),
451 CompletionItem(
452 label=f"{self.settings.comment_start} {self.settings.comment_end}",
453 kind="snippet",
454 detail="Comment",
455 insert_text=f"{self.settings.comment_start} comment {self.settings.comment_end}",
456 documentation="Template comment",
457 priority=5,
458 ),
459 ]
461 def _get_filter_documentation(self, filter_name: str) -> str:
462 """Get documentation for a filter."""
463 docs = {
464 "img": "Generate image tag with adapter support",
465 "icon": "Generate icon tag with variant support",
466 "ph_icon": "Generate Phosphor icon with customization",
467 "ph_class": "Get Phosphor icon CSS class",
468 "hero_icon": "Generate Heroicons icon",
469 "remix_icon": "Generate Remix icon",
470 "material_icon": "Generate Material Design icon",
471 "cloudflare_img": "Cloudflare Images optimization",
472 "twicpics_img": "TwicPics image transformation",
473 "default": "Provide default value if variable is undefined",
474 "length": "Get length of sequence or mapping",
475 "upper": "Convert string to uppercase",
476 "lower": "Convert string to lowercase",
477 "title": "Convert string to title case",
478 "capitalize": "Capitalize first letter",
479 "truncate": "Truncate string to specified length",
480 "join": "Join sequence elements with separator",
481 "replace": "Replace substring with another string",
482 "safe": "Mark string as safe HTML",
483 "escape": "Escape HTML characters",
484 "tojson": "Convert value to JSON string",
485 }
486 return docs.get(filter_name, f"Jinja2 {filter_name} filter")
488 def _get_function_documentation(self, func_name: str) -> str:
489 """Get documentation for a function."""
490 docs = {
491 "render_component": "Render HTMY component with context",
492 "get_adapter": "Get adapter instance by name",
493 "include_template": "Include template with context",
494 "url_for": "Generate URL for route",
495 "csrf_token": "Generate CSRF token",
496 "flash_messages": "Get flash messages",
497 "get_config": "Get configuration value",
498 "ph_duotone": "Generate duotone Phosphor icon",
499 "ph_interactive": "Generate interactive Phosphor icon",
500 "ph_button_icon": "Generate button with Phosphor icon",
501 "range": "Generate range of numbers",
502 "dict": "Create dictionary from arguments",
503 "lipsum": "Generate Lorem Ipsum text",
504 }
505 return docs.get(func_name, f"Jinja2 {func_name} function")
507 def _get_function_parameters(self, func_name: str) -> list[str]:
508 """Get function parameters."""
509 params = {
510 "render_component": ["component_name", "context={}"],
511 "get_adapter": ["adapter_name"],
512 "include_template": ["template_name", "**context"],
513 "url_for": ["route_name", "**params"],
514 "ph_duotone": ["icon_name", "primary_color=None", "secondary_color=None"],
515 "ph_interactive": ["icon_name", "variant='regular'", "action=None"],
516 "ph_button_icon": ["icon_name", "text=None", "variant='regular'"],
517 "range": ["start", "stop=None", "step=1"],
518 "dict": ["**items"],
519 }
520 return params.get(func_name, [])
522 def check_syntax(
523 self, content: str, template_path: Path | None = None
524 ) -> list[SyntaxError]:
525 """Check template syntax and return errors."""
526 if not self.settings or not self.settings.enable_error_checking:
527 return []
529 errors: list[SyntaxError] = []
530 lines = content.split("\n")
532 for line_num, line in enumerate(lines):
533 # Check delimiter balance
534 errors.extend(self._check_delimiter_balance(line, line_num))
536 # Check filter existence
537 if self.settings.check_filter_existence:
538 errors.extend(self._check_filter_existence(line, line_num))
540 # Check function calls
541 if self.settings.check_function_calls:
542 errors.extend(self._check_function_calls(line, line_num))
544 return errors
546 def _check_delimiter_balance(self, line: str, line_num: int) -> list[SyntaxError]:
547 """Check if delimiters are balanced."""
548 if not self.settings:
549 return []
551 errors = []
553 # Check variable delimiters
554 var_opens = line.count(self.settings.variable_start)
555 var_closes = line.count(self.settings.variable_end)
556 if var_opens != var_closes:
557 errors.append(
558 SyntaxError(
559 line=line_num,
560 column=0,
561 message=f"Unbalanced variable delimiters: {var_opens} opens, {var_closes} closes",
562 severity="error",
563 code="unbalanced_delimiters",
564 fix_suggestion=f"Add missing {self.settings.variable_end if var_opens > var_closes else self.settings.variable_start}",
565 )
566 )
568 # Check block delimiters
569 block_opens = line.count(self.settings.block_start)
570 block_closes = line.count(self.settings.block_end)
571 if block_opens != block_closes:
572 errors.append(
573 SyntaxError(
574 line=line_num,
575 column=0,
576 message=f"Unbalanced block delimiters: {block_opens} opens, {block_closes} closes",
577 severity="error",
578 code="unbalanced_delimiters",
579 fix_suggestion=f"Add missing {self.settings.block_end if block_opens > block_closes else self.settings.block_start}",
580 )
581 )
583 return errors
585 def _check_filter_existence(self, line: str, line_num: int) -> list[SyntaxError]:
586 """Check if filters exist."""
587 errors = []
589 if "filter" in self._syntax_patterns:
590 for match in self._syntax_patterns["filter"].finditer(line):
591 filter_name = match.group(1)
592 if filter_name not in self._builtin_filters:
593 errors.append(
594 SyntaxError(
595 line=line_num,
596 column=match.start(),
597 message=f"Unknown filter: {filter_name}",
598 severity="warning",
599 code="unknown_filter",
600 fix_suggestion="Check filter name or register custom filter",
601 )
602 )
604 return errors
606 def _check_function_calls(self, line: str, line_num: int) -> list[SyntaxError]:
607 """Check function calls."""
608 errors = []
610 if "function" in self._syntax_patterns:
611 for match in self._syntax_patterns["function"].finditer(line):
612 func_name = match.group(1)
613 if (
614 func_name not in self._builtin_functions
615 and not func_name.startswith("_")
616 ):
617 errors.append(
618 SyntaxError(
619 line=line_num,
620 column=match.start(),
621 message=f"Unknown function: {func_name}",
622 severity="warning",
623 code="unknown_function",
624 fix_suggestion="Check function name or import if custom",
625 )
626 )
628 return errors
630 def get_hover_info(self, content: str, line: int, column: int) -> str | None:
631 """Get hover information for symbol at position."""
632 lines = content.split("\n")
633 if line >= len(lines):
634 return None
636 current_line = lines[line]
638 # Find word at position
639 word_start = column
640 word_end = column
642 while word_start > 0 and current_line[word_start - 1].isalnum():
643 word_start -= 1
645 while word_end < len(current_line) and current_line[word_end].isalnum():
646 word_end += 1
648 word = current_line[word_start:word_end]
650 if word in self._builtin_filters:
651 return f"**Filter: {word}**\n\n{self._get_filter_documentation(word)}"
652 elif word in self._builtin_functions:
653 params = self._get_function_parameters(word)
654 param_str = ", ".join(params) if params else ""
655 return f"**Function: {word}({param_str})**\n\n{self._get_function_documentation(word)}"
657 return None
659 def format_template(self, content: str) -> str:
660 """Format template content."""
661 # Simple formatting - in a real implementation this would be more sophisticated
662 lines = content.split("\n")
663 formatted_lines = []
664 indent_level = 0
666 for line in lines:
667 stripped = line.strip()
669 # Decrease indent for end blocks
670 if stripped.startswith(("[% end", "[% else")):
671 indent_level = max(0, indent_level - 1)
673 # Add formatted line
674 if stripped:
675 formatted_lines.append(" " * indent_level + stripped)
676 else:
677 formatted_lines.append("")
679 # Increase indent for start blocks
680 if any(
681 stripped.startswith(f"[% {block}")
682 for block in ("if", "for", "block", "macro")
683 ):
684 indent_level += 1
685 elif stripped.startswith("[% else"):
686 indent_level += 1
688 return "\n".join(formatted_lines)
691# Template filter registration for FastBlocks
692def register_syntax_filters(env: Any) -> None:
693 """Register syntax support filters for Jinja2 templates."""
695 @env.filter("format_template") # type: ignore[misc]
696 def format_template_filter(content: str) -> str:
697 """Template filter for formatting FastBlocks templates."""
698 syntax_support = depends.get_sync("syntax_support")
699 if isinstance(syntax_support, FastBlocksSyntaxSupport):
700 return syntax_support.format_template(content)
701 return content
703 @env.global_("syntax_check") # type: ignore[misc]
704 def syntax_check_global(content: str) -> list[dict[str, Any]]:
705 """Global function for syntax checking."""
706 syntax_support = depends.get_sync("syntax_support")
707 if isinstance(syntax_support, FastBlocksSyntaxSupport):
708 errors = syntax_support.check_syntax(content)
709 return [
710 {
711 "line": error.line,
712 "column": error.column,
713 "message": error.message,
714 "severity": error.severity,
715 "code": error.code,
716 "fix": error.fix_suggestion,
717 }
718 for error in errors
719 ]
720 return []
723# ACB 0.19.0+ compatibility
724__all__ = [
725 "FastBlocksSyntaxSupport",
726 "FastBlocksSyntaxSettings",
727 "CompletionItem",
728 "SyntaxError",
729 "register_syntax_filters",
730]
733# Migration status indicator
734_using_oneiric = True