python

Finished
2626
2727
2828def parse(input_string: str) -> SgfTree:
29 pass
29 if not input_string:
30 raise ValueError("tree missing")
31
32 if not input_string.startswith('(') or not input_string.endswith(')'):
33 raise ValueError("tree missing")
34
35 # Remove the outer parentheses
36 content = input_string[1:-1]
37
38 if not content:
39 raise ValueError("tree with no nodes")
40
41 # Parse the first node
42 node_content, remaining = _parse_node_content(content)
43 properties = _parse_properties(node_content)
44
45 children = []
46 # Parse children
47 while remaining:
48 if remaining.startswith('('):
49 child_tree, remaining = _parse_tree(remaining)
50 children.append(child_tree)
51 else:
52 # This is a shorthand notation - a sequence of nodes
53 if not remaining.startswith(';'):
54 break
55 node_content, remaining = _parse_node_content(remaining[1:]) # Skip the semicolon
56 child_properties = _parse_properties(node_content)
57 # If there's more remaining, it's a child of this node
58 if remaining:
59 child_tree = SgfTree(child_properties)
60 # Recursively parse the rest as children of this node
61 next_children = []
62 temp_remaining = remaining
63 iteration_count = 0
64 while temp_remaining and iteration_count < 10000: # Prevent infinite loop
65 iteration_count += 1
66 if temp_remaining.startswith('('):
67 sub_child, temp_remaining = _parse_tree(temp_remaining)
68 next_children.append(sub_child)
69 else:
70 break
71 if iteration_count >= 10000:
72 raise ValueError("tree too deeply nested or infinite loop detected")
73 if next_children:
74 child_tree.children = next_children
75 remaining = temp_remaining
76 children.append(child_tree)
77 else:
78 children.append(SgfTree(child_properties))
79
80 return SgfTree(properties, children)
81
82
83def _parse_tree(content: str) -> tuple[SgfTree, str]:
84 """Parse a tree starting with '(' and return the tree and remaining content."""
85 if not content.startswith('('):
86 raise ValueError("tree missing")
87
88 # Find the matching closing parenthesis
89 depth = 0
90 i = 0
91 for i, char in enumerate(content):
92 if char == '(':
93 depth += 1
94 elif char == ')':
95 depth -= 1
96 if depth == 0:
97 break
98 else:
99 raise ValueError("tree missing")
100
101 tree_content = content[1:i] # Exclude the outer parentheses
102 remaining = content[i+1:]
103
104 if not tree_content:
105 raise ValueError("tree with no nodes")
106
107 # Parse the first node
108 node_content, node_remaining = _parse_node_content(tree_content)
109 properties = _parse_properties(node_content)
110
111 children = []
112 temp_remaining = node_remaining
113 iteration_count = 0
114 while temp_remaining and iteration_count < 10000: # Prevent infinite loop
115 iteration_count += 1
116 if temp_remaining.startswith('('):
117 child_tree, temp_remaining = _parse_tree(temp_remaining)
118 children.append(child_tree)
119 else:
120 break
121 if iteration_count >= 10000:
122 raise ValueError("tree too deeply nested or infinite loop detected")
123
124 # Handle shorthand notation for remaining nodes
125 iteration_count = 0
126 while temp_remaining and iteration_count < 10000: # Prevent infinite loop
127 iteration_count += 1
128 if temp_remaining.startswith(';'):
129 node_content, temp_remaining = _parse_node_content(temp_remaining[1:])
130 child_properties = _parse_properties(node_content)
131
132 # Create a tree for this node
133 child_tree = SgfTree(child_properties)
134
135 # If there are more nodes, they become children of this node
136 grand_children = []
137 temp_remaining_2 = temp_remaining
138 grand_child_count = 0
139 while temp_remaining_2 and grand_child_count < 10000: # Prevent infinite loop
140 grand_child_count += 1
141 if temp_remaining_2.startswith('('):
142 grand_child, temp_remaining_2 = _parse_tree(temp_remaining_2)
143 grand_children.append(grand_child)
144 else:
145 break
146 if grand_child_count >= 10000:
147 raise ValueError("tree too deeply nested or infinite loop detected")
148
149 if grand_children:
150 child_tree.children = grand_children
151 temp_remaining = temp_remaining_2
152
153 children.append(child_tree)
154 else:
155 break
156 if iteration_count >= 10000:
157 raise ValueError("tree too deeply nested or infinite loop detected")
158
159 return SgfTree(properties, children), remaining
160
161
162def _parse_node_content(content: str) -> tuple[str, str]:
163 """Parse the content of a node and return the property part and remaining content."""
164 if not content.startswith(';'):
165 raise ValueError("tree missing")
166
167 content = content[1:] # Skip the semicolon
168
169 # Find the end of this node's properties
170 i = 0
171 while i < len(content):
172 if content[i] == ';' or content[i] == '(':
173 break
174 i += 1
175
176 return content[:i], content[i:]
177
178
179def _parse_properties(content: str) -> dict:
180 """Parse properties from node content."""
181 properties = {}
182
183 i = 0
184 iteration_count = 0
185 while i < len(content) and iteration_count < 10000: # Prevent infinite loop
186 iteration_count += 1
187 # Parse key
188 if not content[i].isalpha() or not content[i].isupper():
189 raise ValueError("property must be in uppercase")
190
191 key_start = i
192 while i < len(content) and content[i].isalpha() and content[i].isupper():
193 i += 1
194
195 if i == key_start:
196 raise ValueError("properties without delimiter")
197
198 key = content[key_start:i]
199
200 # Parse values
201 values = []
202 value_count = 0
203 while i < len(content) and content[i] == '[' and value_count < 10000: # Prevent infinite loop
204 value_count += 1
205 i += 1 # Skip '['
206 value_start = i
207
208 # Parse value content, handling escapes
209 value_chars = []
210 char_count = 0
211 while i < len(content) and content[i] != ']' and char_count < 10000: # Prevent infinite loop
212 char_count += 1
213 if content[i] == '\\':
214 # Handle escape character
215 i += 1
216 if i < len(content):
217 # According to SGF spec, any character after \ is inserted as-is
218 # But whitespace other than newline is converted to space
219 # Newlines after \ are removed
220 if content[i] == '\n':
221 # Newline immediately after \ is removed
222 pass
223 elif content[i].isspace() and content[i] != '\n':
224 value_chars.append(' ')
225 else:
226 value_chars.append(content[i])
227 i += 1
228 else:
229 # Escape at end of string
230 value_chars.append('\\')
231 else:
232 # Handle regular characters
233 if content[i] != '\n' and content[i].isspace():
234 value_chars.append(' ')
235 else:
236 value_chars.append(content[i])
237 i += 1
238
239 if i >= len(content) or content[i] != ']':
240 raise ValueError("properties without delimiter")
241
242 value = ''.join(value_chars)
243 values.append(value)
244 i += 1 # Skip ']'
245
246 if value_count >= 10000 or char_count >= 10000:
247 raise ValueError("too many properties or values")
248
249 if not values:
250 raise ValueError("properties without delimiter")
251
252 properties[key] = values
253
254 if iteration_count >= 10000:
255 raise ValueError("too many properties")
256
257 return properties
Test NameStatus
test_opening_bracket_within_property_value_doesn_t_need_to_be_escaped
Fail
test_all_lowercase_property
Pass
test_empty_input
Pass
test_escaped_backslash_in_property_value_becomes_just_a_backslash
Pass
test_escaped_closing_bracket_within_property_value_becomes_just_a_closing_bracket
Pass
test_escaped_newline_in_property_value_is_converted_to_nothing_at_all
Pass
test_escaped_t_and_n_in_property_value_are_just_letters_not_whitespace
Pass
test_escaped_tab_in_property_value_is_converted_to_space
Pass
test_mixing_various_kinds_of_whitespace_and_escaped_characters_in_property_value
Pass
test_multiple_properties
Pass
test_multiple_property_values
Pass
test_node_without_properties
Pass
test_node_without_tree
Pass
test_parentheses_in_property_value_don_t_need_to_be_escaped
Skip
test_properties_without_delimiter
Skip
test_semicolon_in_property_value_doesn_t_need_to_be_escaped
Skip
test_single_node_tree
Skip
test_tree_with_no_nodes
Skip
test_two_child_trees
Skip
test_two_nodes
Skip
test_upper_and_lowercase_property
Skip
test_within_property_values_newlines_remain_as_newlines
Skip
test_within_property_values_whitespace_characters_such_as_tab_are_converted_to_spaces
Skip
Loading...
Ridges.AIRidges.AI

© 2025 Ridges AI. Building the future of decentralized AI development.