|
| 1 | +"""Semantic parser pipeline for routing input to semantic parsers. |
| 2 | +
|
| 3 | +This module provides SemanticParserPipeline, which routes input to semantic parsers |
| 4 | +that work with semantic types and contexts for enhanced type safety. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +from dataclasses import dataclass |
| 10 | +from typing import Callable, Optional, Protocol, runtime_checkable |
| 11 | + |
| 12 | +from cli_patterns.core.parser_types import CommandId |
| 13 | +from cli_patterns.ui.parser.semantic_context import SemanticContext |
| 14 | +from cli_patterns.ui.parser.semantic_errors import SemanticParseError |
| 15 | +from cli_patterns.ui.parser.semantic_result import SemanticParseResult |
| 16 | + |
| 17 | + |
| 18 | +@runtime_checkable |
| 19 | +class SemanticParser(Protocol): |
| 20 | + """Protocol defining the interface for semantic command parsers. |
| 21 | +
|
| 22 | + Semantic parsers work with semantic types and contexts to provide |
| 23 | + enhanced type safety for command parsing operations. |
| 24 | + """ |
| 25 | + |
| 26 | + def can_parse(self, input_str: str, context: SemanticContext) -> bool: |
| 27 | + """Determine if this parser can handle the given input. |
| 28 | +
|
| 29 | + Args: |
| 30 | + input_str: Raw input string to evaluate |
| 31 | + context: Current semantic parsing context |
| 32 | +
|
| 33 | + Returns: |
| 34 | + True if this parser can handle the input, False otherwise |
| 35 | + """ |
| 36 | + ... |
| 37 | + |
| 38 | + def parse(self, input_str: str, context: SemanticContext) -> SemanticParseResult: |
| 39 | + """Parse the input string into a structured SemanticParseResult. |
| 40 | +
|
| 41 | + Args: |
| 42 | + input_str: Raw input string to parse |
| 43 | + context: Current semantic parsing context |
| 44 | +
|
| 45 | + Returns: |
| 46 | + SemanticParseResult containing parsed command, args, flags, and options |
| 47 | +
|
| 48 | + Raises: |
| 49 | + SemanticParseError: If parsing fails or input is invalid |
| 50 | + """ |
| 51 | + ... |
| 52 | + |
| 53 | + def get_suggestions(self, partial: str) -> list[CommandId]: |
| 54 | + """Get completion suggestions for partial input. |
| 55 | +
|
| 56 | + Args: |
| 57 | + partial: Partial input string to complete |
| 58 | +
|
| 59 | + Returns: |
| 60 | + List of suggested semantic command completions |
| 61 | + """ |
| 62 | + ... |
| 63 | + |
| 64 | + |
| 65 | +@dataclass |
| 66 | +class _SemanticParserEntry: |
| 67 | + """Internal entry for storing semantic parser with metadata.""" |
| 68 | + |
| 69 | + parser: SemanticParser |
| 70 | + condition: Optional[Callable[[str, SemanticContext], bool]] |
| 71 | + priority: int |
| 72 | + |
| 73 | + |
| 74 | +class SemanticParserPipeline: |
| 75 | + """Pipeline for routing input to appropriate semantic parsers. |
| 76 | +
|
| 77 | + The pipeline maintains a list of semantic parsers with optional conditions and priorities. |
| 78 | + When parsing input, it tries each parser in order until one succeeds, maintaining |
| 79 | + semantic type safety throughout the process. |
| 80 | + """ |
| 81 | + |
| 82 | + def __init__(self) -> None: |
| 83 | + """Initialize empty semantic parser pipeline.""" |
| 84 | + self._parsers: list[_SemanticParserEntry] = [] |
| 85 | + |
| 86 | + def add_parser( |
| 87 | + self, |
| 88 | + parser: SemanticParser, |
| 89 | + condition: Optional[Callable[[str, SemanticContext], bool]] = None, |
| 90 | + priority: int = 0, |
| 91 | + ) -> None: |
| 92 | + """Add a semantic parser to the pipeline. |
| 93 | +
|
| 94 | + Args: |
| 95 | + parser: Semantic parser instance to add |
| 96 | + condition: Optional condition function that returns True if parser should handle input |
| 97 | + priority: Priority for ordering (higher numbers = higher priority, default 0) |
| 98 | + """ |
| 99 | + entry = _SemanticParserEntry( |
| 100 | + parser=parser, condition=condition, priority=priority |
| 101 | + ) |
| 102 | + self._parsers.append(entry) |
| 103 | + |
| 104 | + # Sort by priority (higher numbers first), maintaining insertion order for same priority |
| 105 | + self._parsers.sort( |
| 106 | + key=lambda x: ( |
| 107 | + -x.priority, |
| 108 | + ( |
| 109 | + self._parsers.index(x) |
| 110 | + if x in self._parsers[:-1] |
| 111 | + else len(self._parsers) |
| 112 | + ), |
| 113 | + ) |
| 114 | + ) |
| 115 | + |
| 116 | + def remove_parser(self, parser: SemanticParser) -> bool: |
| 117 | + """Remove a semantic parser from the pipeline. |
| 118 | +
|
| 119 | + Args: |
| 120 | + parser: Semantic parser instance to remove |
| 121 | +
|
| 122 | + Returns: |
| 123 | + True if parser was found and removed, False otherwise |
| 124 | + """ |
| 125 | + for i, entry in enumerate(self._parsers): |
| 126 | + if entry.parser is parser: |
| 127 | + self._parsers.pop(i) |
| 128 | + return True |
| 129 | + return False |
| 130 | + |
| 131 | + def parse(self, input_str: str, context: SemanticContext) -> SemanticParseResult: |
| 132 | + """Parse input using the first matching semantic parser in the pipeline. |
| 133 | +
|
| 134 | + Args: |
| 135 | + input_str: Input string to parse |
| 136 | + context: Semantic parsing context |
| 137 | +
|
| 138 | + Returns: |
| 139 | + SemanticParseResult from the first parser that can handle the input |
| 140 | +
|
| 141 | + Raises: |
| 142 | + SemanticParseError: If no parser can handle the input or parsing fails |
| 143 | + """ |
| 144 | + if not self._parsers: |
| 145 | + raise SemanticParseError( |
| 146 | + error_type="NO_PARSERS", |
| 147 | + message="No parsers available in pipeline", |
| 148 | + suggestions=[], |
| 149 | + ) |
| 150 | + |
| 151 | + matching_parsers = [] |
| 152 | + condition_errors = [] |
| 153 | + |
| 154 | + # Find all parsers that can handle the input |
| 155 | + for entry in self._parsers: |
| 156 | + try: |
| 157 | + # Check condition if provided |
| 158 | + if entry.condition is not None: |
| 159 | + if not entry.condition(input_str, context): |
| 160 | + continue |
| 161 | + |
| 162 | + # Check if parser can handle the input |
| 163 | + if hasattr(entry.parser, "can_parse"): |
| 164 | + if entry.parser.can_parse(input_str, context): |
| 165 | + matching_parsers.append(entry) |
| 166 | + else: |
| 167 | + # If no can_parse method, assume it can handle it |
| 168 | + matching_parsers.append(entry) |
| 169 | + |
| 170 | + except Exception as e: |
| 171 | + # Condition function failed, skip this parser |
| 172 | + condition_errors.append(f"Condition failed for parser: {e}") |
| 173 | + continue |
| 174 | + |
| 175 | + if not matching_parsers: |
| 176 | + error_msg = "No parser can handle the input" |
| 177 | + if condition_errors: |
| 178 | + error_msg += f". Condition errors: {'; '.join(condition_errors)}" |
| 179 | + |
| 180 | + raise SemanticParseError( |
| 181 | + error_type="NO_MATCHING_PARSER", |
| 182 | + message=error_msg, |
| 183 | + suggestions=[], |
| 184 | + ) |
| 185 | + |
| 186 | + # Try the first matching parser (highest priority) |
| 187 | + parser_entry = matching_parsers[0] |
| 188 | + |
| 189 | + try: |
| 190 | + return parser_entry.parser.parse(input_str, context) |
| 191 | + except SemanticParseError: |
| 192 | + # Re-raise semantic parse errors from the parser |
| 193 | + raise |
| 194 | + except Exception as e: |
| 195 | + # Convert other exceptions to SemanticParseError |
| 196 | + raise SemanticParseError( |
| 197 | + error_type="PARSER_ERROR", |
| 198 | + message=f"Parser failed: {str(e)}", |
| 199 | + suggestions=[], |
| 200 | + ) from e |
| 201 | + |
| 202 | + def clear(self) -> None: |
| 203 | + """Clear all parsers from the pipeline.""" |
| 204 | + self._parsers.clear() |
| 205 | + |
| 206 | + @property |
| 207 | + def parser_count(self) -> int: |
| 208 | + """Get the number of parsers in the pipeline.""" |
| 209 | + return len(self._parsers) |
0 commit comments