|
| 1 | +"""Scanner for parsing TOON input into lines with depth information. |
| 2 | +
|
| 3 | +This module implements the first stage of the TOON decoding pipeline: |
| 4 | +scanning the input text and converting it into structured line objects |
| 5 | +with depth and indentation metadata. |
| 6 | +""" |
| 7 | + |
| 8 | +from dataclasses import dataclass |
| 9 | +from typing import List, Optional, Tuple |
| 10 | + |
| 11 | +from .constants import SPACE, TAB |
| 12 | + |
| 13 | + |
| 14 | +@dataclass |
| 15 | +class ParsedLine: |
| 16 | + """A parsed line with metadata. |
| 17 | +
|
| 18 | + Attributes: |
| 19 | + raw: The original raw line content |
| 20 | + depth: The indentation depth (number of indent levels) |
| 21 | + indent: The number of leading spaces |
| 22 | + content: The line content after removing indentation |
| 23 | + line_num: The 1-based line number in the source |
| 24 | + """ |
| 25 | + |
| 26 | + raw: str |
| 27 | + depth: int |
| 28 | + indent: int |
| 29 | + content: str |
| 30 | + line_num: int |
| 31 | + |
| 32 | + |
| 33 | +@dataclass |
| 34 | +class BlankLineInfo: |
| 35 | + """Information about a blank line. |
| 36 | +
|
| 37 | + Attributes: |
| 38 | + line_num: The 1-based line number |
| 39 | + indent: The number of leading spaces |
| 40 | + depth: The computed indentation depth |
| 41 | + """ |
| 42 | + |
| 43 | + line_num: int |
| 44 | + indent: int |
| 45 | + depth: int |
| 46 | + |
| 47 | + |
| 48 | +class LineCursor: |
| 49 | + """Iterator-like class for traversing parsed lines. |
| 50 | +
|
| 51 | + Provides methods to peek at the current line, advance to the next line, |
| 52 | + and check for lines at specific depths. This abstraction makes the decoder |
| 53 | + logic cleaner and easier to test. |
| 54 | + """ |
| 55 | + |
| 56 | + def __init__( |
| 57 | + self, |
| 58 | + lines: List[ParsedLine], |
| 59 | + blank_lines: Optional[List[BlankLineInfo]] = None, |
| 60 | + ) -> None: |
| 61 | + """Initialize a line cursor. |
| 62 | +
|
| 63 | + Args: |
| 64 | + lines: The parsed lines to traverse |
| 65 | + blank_lines: Optional list of blank line information |
| 66 | + """ |
| 67 | + self._lines = lines |
| 68 | + self._index = 0 |
| 69 | + self._blank_lines = blank_lines or [] |
| 70 | + |
| 71 | + def get_blank_lines(self) -> List[BlankLineInfo]: |
| 72 | + """Get the list of blank lines.""" |
| 73 | + return self._blank_lines |
| 74 | + |
| 75 | + def peek(self) -> Optional[ParsedLine]: |
| 76 | + """Peek at the current line without advancing. |
| 77 | +
|
| 78 | + Returns: |
| 79 | + The current line, or None if at end |
| 80 | + """ |
| 81 | + if self._index >= len(self._lines): |
| 82 | + return None |
| 83 | + return self._lines[self._index] |
| 84 | + |
| 85 | + def next(self) -> Optional[ParsedLine]: |
| 86 | + """Get the current line and advance. |
| 87 | +
|
| 88 | + Returns: |
| 89 | + The current line, or None if at end |
| 90 | + """ |
| 91 | + if self._index >= len(self._lines): |
| 92 | + return None |
| 93 | + line = self._lines[self._index] |
| 94 | + self._index += 1 |
| 95 | + return line |
| 96 | + |
| 97 | + def current(self) -> Optional[ParsedLine]: |
| 98 | + """Get the most recently consumed line. |
| 99 | +
|
| 100 | + Returns: |
| 101 | + The previous line, or None if no line has been consumed |
| 102 | + """ |
| 103 | + if self._index > 0: |
| 104 | + return self._lines[self._index - 1] |
| 105 | + return None |
| 106 | + |
| 107 | + def advance(self) -> None: |
| 108 | + """Advance to the next line.""" |
| 109 | + self._index += 1 |
| 110 | + |
| 111 | + def at_end(self) -> bool: |
| 112 | + """Check if cursor is at the end of lines. |
| 113 | +
|
| 114 | + Returns: |
| 115 | + True if at end |
| 116 | + """ |
| 117 | + return self._index >= len(self._lines) |
| 118 | + |
| 119 | + @property |
| 120 | + def length(self) -> int: |
| 121 | + """Get the total number of lines.""" |
| 122 | + return len(self._lines) |
| 123 | + |
| 124 | + def peek_at_depth(self, target_depth: int) -> Optional[ParsedLine]: |
| 125 | + """Peek at the next line at a specific depth. |
| 126 | +
|
| 127 | + Args: |
| 128 | + target_depth: The target depth |
| 129 | +
|
| 130 | + Returns: |
| 131 | + The line if it matches the depth, None otherwise |
| 132 | + """ |
| 133 | + line = self.peek() |
| 134 | + if not line or line.depth < target_depth: |
| 135 | + return None |
| 136 | + if line.depth == target_depth: |
| 137 | + return line |
| 138 | + return None |
| 139 | + |
| 140 | + def has_more_at_depth(self, target_depth: int) -> bool: |
| 141 | + """Check if there are more lines at a specific depth. |
| 142 | +
|
| 143 | + Args: |
| 144 | + target_depth: The target depth |
| 145 | +
|
| 146 | + Returns: |
| 147 | + True if there are more lines at the target depth |
| 148 | + """ |
| 149 | + return self.peek_at_depth(target_depth) is not None |
| 150 | + |
| 151 | + |
| 152 | +def to_parsed_lines( |
| 153 | + source: str, |
| 154 | + indent_size: int, |
| 155 | + strict: bool, |
| 156 | +) -> Tuple[List[ParsedLine], List[BlankLineInfo]]: |
| 157 | + """Convert source string to parsed lines with depth information. |
| 158 | +
|
| 159 | + Per Section 12 of the TOON specification for indentation handling. |
| 160 | + This is the entry point for the scanning stage of the decoder pipeline. |
| 161 | +
|
| 162 | + Args: |
| 163 | + source: The source string to parse |
| 164 | + indent_size: The number of spaces per indentation level |
| 165 | + strict: Whether to enforce strict indentation validation |
| 166 | +
|
| 167 | + Returns: |
| 168 | + A tuple of (parsed_lines, blank_lines) |
| 169 | +
|
| 170 | + Raises: |
| 171 | + SyntaxError: If strict mode validation fails (tabs in indentation, invalid spacing) |
| 172 | +
|
| 173 | + Examples: |
| 174 | + >>> lines, blanks = to_parsed_lines("name: Alice\\n age: 30", 2, True) |
| 175 | + >>> lines[0].content |
| 176 | + 'name: Alice' |
| 177 | + >>> lines[1].depth |
| 178 | + 1 |
| 179 | + """ |
| 180 | + if not source.strip(): |
| 181 | + return [], [] |
| 182 | + |
| 183 | + lines = source.split("\n") |
| 184 | + parsed: List[ParsedLine] = [] |
| 185 | + blank_lines: List[BlankLineInfo] = [] |
| 186 | + |
| 187 | + for i, raw in enumerate(lines): |
| 188 | + line_num = i + 1 |
| 189 | + indent = 0 |
| 190 | + while indent < len(raw) and raw[indent] == SPACE: |
| 191 | + indent += 1 |
| 192 | + |
| 193 | + content = raw[indent:] |
| 194 | + |
| 195 | + # Track blank lines |
| 196 | + if not content.strip(): |
| 197 | + depth = _compute_depth_from_indent(indent, indent_size) |
| 198 | + blank_lines.append( |
| 199 | + BlankLineInfo( |
| 200 | + line_num=line_num, |
| 201 | + indent=indent, |
| 202 | + depth=depth, |
| 203 | + ) |
| 204 | + ) |
| 205 | + continue |
| 206 | + |
| 207 | + depth = _compute_depth_from_indent(indent, indent_size) |
| 208 | + |
| 209 | + # Strict mode validation |
| 210 | + if strict: |
| 211 | + # Find the full leading whitespace region (spaces and tabs) |
| 212 | + ws_end = 0 |
| 213 | + while ws_end < len(raw) and (raw[ws_end] == SPACE or raw[ws_end] == TAB): |
| 214 | + ws_end += 1 |
| 215 | + |
| 216 | + # Check for tabs in leading whitespace (before actual content) |
| 217 | + if TAB in raw[:ws_end]: |
| 218 | + raise SyntaxError( |
| 219 | + f"Line {line_num}: Tabs not allowed in indentation in strict mode" |
| 220 | + ) |
| 221 | + |
| 222 | + # Check for exact multiples of indent_size |
| 223 | + if indent > 0 and indent % indent_size != 0: |
| 224 | + raise SyntaxError( |
| 225 | + f"Line {line_num}: Indent must be exact multiple of {indent_size}, " |
| 226 | + f"but found {indent} spaces" |
| 227 | + ) |
| 228 | + |
| 229 | + parsed.append( |
| 230 | + ParsedLine( |
| 231 | + raw=raw, |
| 232 | + indent=indent, |
| 233 | + content=content, |
| 234 | + depth=depth, |
| 235 | + line_num=line_num, |
| 236 | + ) |
| 237 | + ) |
| 238 | + |
| 239 | + return parsed, blank_lines |
| 240 | + |
| 241 | + |
| 242 | +def _compute_depth_from_indent(indent_spaces: int, indent_size: int) -> int: |
| 243 | + """Compute depth from indentation spaces. |
| 244 | +
|
| 245 | + Args: |
| 246 | + indent_spaces: Number of leading spaces |
| 247 | + indent_size: Number of spaces per indentation level |
| 248 | +
|
| 249 | + Returns: |
| 250 | + The computed depth |
| 251 | +
|
| 252 | + Examples: |
| 253 | + >>> _compute_depth_from_indent(0, 2) |
| 254 | + 0 |
| 255 | + >>> _compute_depth_from_indent(4, 2) |
| 256 | + 2 |
| 257 | + >>> _compute_depth_from_indent(3, 2) # Lenient mode |
| 258 | + 1 |
| 259 | + """ |
| 260 | + return indent_spaces // indent_size |
0 commit comments