My program is import json import re import sys token_patterns = [ (r'#[^\n]*', None),…
- User
My program is import json import re import sys
token_patterns = [ (r'#[^\n]', None),
(r'\s+', None), (r'[', 'LBRACKET'), (r']', 'RBRACKET'), (r'{', 'LBRACE'), (r'}', 'RBRACE'), (r'%{', 'LMAPBRACE'), (r'=>', 'ARROW'), (r',', 'COMMA'), (r'(true|false)', 'BOOLEAN'), (r'(0|[1-9][0-9_])', 'INTEGER'),
(r':[A-Za-z_]\w*', 'ATOM'),
(r'[A-Za-z_]\w*', 'KEY'),
(r':', 'COLON'), ]regex_parts = [f'(?P<{name}>{pattern})' if name else f'(?:{pattern})' for pattern, name in token_patterns] token_regex = '|'.join(regex_parts) token_re = re.compile(token_regex)
class TokenizerException(Exception): pass
class ParserException(Exception): pass
def tokenize(text): pos = 0 while pos < len(text): match = token_re.match(text, pos) if not match: raise TokenizerException(f'Illegal character {text[pos]!r} at index {pos}') pos = match.end() if match.lastgroup:
yield match.lastgroup, match.group(match.lastgroup)def make_hashable(value): """Recursively converts JSON-like objects to an immutable and hashable type.""" if isinstance(value, list): return tuple(make_hashable(x) for x in value) elif isinstance(value, dict): return tuple((make_hashable(k), make_hashable(v)) for k, v in value.items()) else: return value # Integers, strings, booleans, and None are already hashable
class Node: def init(self, kind, value): self.kind = kind self.value = value
def to_json(self): if self.kind == "map": # Corrected conditional to account for empty maps if not self.value: # self.value is empty return {"%k": self.kind, "%v": {}} # Return an empty dictionary instead of an empty list return {"%k": self.kind, "%v": {k.to_json()["%v"]: v.to_json() for k, v in self.value}} elif self.kind == "list": return {"%k": self.kind, "%v": [item.to_json() for item in self.value]} else: return {"%k": self.kind, "%v": self.value}class Parser: def init(self, tokens): self.tokens = iter(tokens) self.current_token = None self.next_token()
def next_token(self): try: self.current_token = next(self.tokens) except StopIteration: self.current_token = None def parse(self): result = self.parse_sentence() if self.current_token is not None: raise ParserException('Unexpected token at the end') return result def parse_sentence(self): nodes = [] while self.current_token is not None: node = self.parse_data_literal() nodes.append(node) if self.current_token and self.current_token[0] in {'COMMA', 'COLON', 'ARROW'}: self.next_token() return nodes def parse_data_literal(self): # Parse the correct type based on the current token if not self.current_token: raise ParserException("Unexpected end of input") token_type, token_value = self.current_token if token_type == 'LBRACKET': return self.parse_list() elif token_type == 'LBRACE': return self.parse_tuple() elif token_type == 'LMAPBRACE': return self.parse_map() elif token_type == 'INTEGER': self.next_token() # Move to the next token after parsing return Node('int', int(token_value)) # Convert string to integer elif token_type == 'ATOM': self.next_token() return Node('atom', token_value) elif token_type == 'BOOLEAN': self.next_token() # Convert string 'true' or 'false' to a boolean return Node('bool', token_value == 'true') elif token_type == 'KEY': self.next_token() return Node('key', token_value) else: raise ParserException(f"Unexpected token type {token_type}") def parse_list(self): self.next_token() items = [] while self.current_token and self.current_token[0] != 'RBRACKET': item = self.parse_data_literal() items.append(item) if self.current_token and self.current_token[0] == 'COMMA': self.next_token() if not self.current_token or self.current_token[0] != 'RBRACKET': raise ParserException('List not properly terminated with ]') self.next_token() # Consume 'RBRACKET' return Node('list', items) def parse_tuple(self): items = [] self.next_token() while self.current_token is not None and self.current_token[0] != 'RBRACE': items.append(self.parse_data_literal()) if self.current_token and self.current_token[0] == 'COMMA': self.next_token() if self.current_token is None or self.current_token[0] != 'RBRACE': raise ParserException('Tuple not properly terminated with }') self.next_token() return Node('tuple', [item.to_json() for item in items]) def parse_map(self): self.next_token() # Skip 'LMAPBRACE' map_items = [] while self.current_token and self.current_token[0] != 'RBRACE': key = self.parse_data_literal() if self.current_token[0] not in ['ARROW', 'COLON']: raise ParserException(f"Expected '=>' or ':', found {self.current_token} instead") self.next_token() # Skip 'ARROW' or 'COLON' value = self.parse_data_literal() # Serialize your key to a format that can be used in a JSON dictionary # This can be a string representation or a nested structure map_items[str(key)] = value if self.current_token and self.current_token[0] == 'COMMA': self.next_token() if not self.current_token or self.current_token[0] != 'RBRACE': raise ParserException('Map not properly terminated with "}"') self.next_token() # Skip 'RBRACE' return Node('map', map_items) - Assistant
- User
revise all the parts of the code that you think should be made to make my program just like ideal program
- Assistant
- User
- Assistant
- User
check the parse_tuple for same
- Assistant
The parse_tuple method should similarly check for unexpected end of input. Here's how you can update your parse_tuple method to raise an exception if the tuple is not properly terminated:
def parse_tuple(self): self.next_token() # Consume '{' items = [] while self.current_token and self.current_token[0] != 'RBRACE': if self.current_token[0] == 'EOF': raise ParserException('Tuple not properly terminated with }') items.append(self.parse_data_literal()) if self.current_token and self.current_token[0] == 'COMMA': self.next_token() if not self.current_token: # Add this check raise ParserException('Tuple not properly terminated with }') self.next_token() # Consume 'RBRACE' return Node('tuple', items)By adding this check for an 'EOF' token (indicating end of file/input) while parsing the tuple items, the parser will be able to catch cases where the input ends before the closing '}' of a tuple. If such a case is encountered, it will raise a ParserException stating that the tuple is not properly terminated.
With this improved error handling, your parser will be able to provide clear errors if the input ends unexpectedly in the middle of a list or tuple.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.