class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.position = 0
def parse(self):
parsed_data = []
while self.position < len(self.tokens):
parsed_data.append(self.parse_statement())
return parsed_data
def parse_statement(self):
variable = self.tokens[self.position]
if variable['type'] != 'identifier':
raise Exception('Ожидается идентификатор')
self.position += 1
if self.position >= len(self.tokens) or self.tokens[self.position]['value'] != '=':
raise Exception('Ожидается оператор присваивания')
self.position += 1
value_token = self.tokens[self.position]
if value_token['type'] == 'function_call':
function_name = value_token['value']
arguments = []
self.position += 1
while (
self.position < len(self.tokens)
and self.tokens[self.position]['type'] != 'paren'
and self.tokens[self.position]['value'] != ')'
):
argument = self.tokens[self.position]
arguments.append(argument)
self.position += 1
if (
self.position >= len(self.tokens)
or self.tokens[self.position]['value'] != ')'
):
raise Exception('Ожидается закрывающая скобка для вызова функции')
self.position += 1
return {
'type': 'assignment',
'variable': variable['value'],
'value': {
'type': 'function_call',
'function_name': function_name,
'arguments': arguments
}
}
elif value_token['type'] in ['string', 'number']:
assignment = {
'type': 'assignment',
'variable': variable['value'],
'value': value_token['value']
}
self.position += 1
return assignment
else:
raise Exception('Ожидается строка, число или вызов функции')
class Lexer:
def __init__(self, source_code):
self.source_code = source_code
self.position = 0
self.tokens = []
def tokenize(self):
while self.position < len(self.source_code):
current_char = self.source_code[self.position]
if current_char.isdigit():
self.tokens.append(self.parse_number())
elif current_char == '"':
self.tokens.append(self.parse_string())
elif current_char.isalpha() or current_char == '_':
self.tokens.append(self.parse_identifier())
elif current_char.isspace():
self.position += 1
continue
elif current_char == '(' or current_char == ')':
self.tokens.append({'type': 'paren', 'value': current_char})
elif current_char == '=':
self.tokens.append({'type': 'operator', 'value': current_char})
elif current_char == '+':
self.tokens.append({'type': 'operator', 'value': current_char})
else:
raise Exception(f'Недопустимый символ: {current_char}')
self.position += 1
return self.tokens
def parse_number(self):
start_position = self.position
while self.position < len(self.source_code) and self.source_code[self.position].isdigit():
self.position += 1
number = int(self.source_code[start_position:self.position])
return {'type': 'number', 'value': number}
def parse_string(self):
start_position = self.position
self.position += 1
while self.position < len(self.source_code) and self.source_code[self.position] != '"':
self.position += 1
if self.position >= len(self.source_code):
raise Exception('Неожиданный конец строки')
self.position += 1
string = self.source_code[start_position:self.position]
return {'type': 'string', 'value': string}
def parse_identifier(self):
start_position = self.position
while self.position < len(self.source_code) and (
self.source_code[self.position].isalpha() or self.source_code[self.position] == '_'):
self.position += 1
identifier = self.source_code[start_position:self.position]
return {'type': 'identifier', 'value': identifier}
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.position = 0
def parse(self):
parsed_data = []
while self.position < len(self.tokens):
parsed_data.append(self.parse_statement())
return parsed_data
def parse_statement(self):
variable = self.tokens[self.position]
if variable['type'] != 'identifier':
raise Exception('Ожидается идентификатор')
self.position += 1
if self.position >= len(self.tokens) or self.tokens[self.position]['value'] != '=':
raise Exception('Ожидается оператор присваивания')
self.position += 1
value_token = self.tokens[self.position]
if value_token['type'] == 'function_call':
function_name = value_token['value']
arguments = []
self.position += 1
while (
self.position < len(self.tokens)
and self.tokens[self.position]['type'] != 'paren'
and self.tokens[self.position]['value'] != ')'
):
argument = self.tokens[self.position]
arguments.append(argument)
self.position += 1
if (
self.position >= len(self.tokens)
or self.tokens[self.position]['value'] != ')'
):
raise Exception('Ожидается закрывающая скобка для вызова функции')
self.position += 1
return {
'type': 'assignment',
'variable': variable['value'],
'value': {
'type': 'function_call',
'function_name': function_name,
'arguments': arguments
}
}
elif value_token['type'] in ['string', 'number']:
assignment = {
'type': 'assignment',
'variable': variable['value'],
'value': value_token['value']
}
self.position += 1
return assignment
else:
raise Exception('Ожидается строка, число или вызов функции')
class SemanticAnalyzer:
def __init__(self, parsed_data):
self.parsed_data = parsed_data
def analyze(self):
semantic_data = []
for statement in self.parsed_data:
if statement['type'] == 'assignment':
variable = statement['variable']
value = self.evaluate_expression(statement['value'])
semantic_data.append({variable: value})
return semantic_data
def evaluate_expression(self, expression):
if expression['type'] == 'function_call':
function_name = expression['function_name']
arguments = expression['arguments']
if function_name == 'data_acquisition':
prompt = arguments[0]['value']
return self.data_acquisition(prompt)
else:
raise Exception(f'Неизвестная функция: {function_name}')
elif expression['type'] == 'string':
return expression['value']
elif expression['type'] == 'number':
return expression['value']
else:
raise Exception('Недопустимый тип выражения')
def data_acquisition(self, prompt):
return input(prompt)
class CodeGenerator:
def __init__(self, semantic_data):
self.semantic_data = semantic_data
def generate(self):
generated_code = ''
for statement in self.semantic_data:
variable = list(statement.keys())[0]
value = statement[variable]
generated_code += f"{variable} = {repr(value)}\n"
return generated_code
class Interpreter:
def __init__(self):
self.lexer = None
self.parser = None
self.semantic_analyzer = None
self.code_generator = None
def interpret(self, source_code):
self.lexer = Lexer(source_code)
tokens = self.lexer.tokenize()
self.parser = Parser(tokens)
parsed_data = self.parser.parse()
self.semantic_analyzer = SemanticAnalyzer(parsed_data)
semantic_data = self.semantic_analyzer.analyze()
self.code_generator = CodeGenerator(semantic_data)
generated_code = self.code_generator.generate()
self.execute_code(generated_code)
def execute_code(self, code):
exec(code, {'data_acquisition': self.semantic_analyzer.data_acquisition})
if __name__ == "__main__":
interpreter = Interpreter()
source_code = '''
name = data_acquisition("Enter your name: ")
print(name)
'''
interpreter.interpret(source_code)
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.position = 0
def parse(self):
parsed_data = []
while self.position < len(self.tokens):
parsed_data.append(self.parse_statement())
return parsed_data
def parse_statement(self):
variable = self.tokens[self.position]
if variable['type'] != 'identifier':
raise Exception('Ожидается идентификатор')
self.position += 1
if self.position >= len(self.tokens) or self.tokens[self.position]['value'] != '=':
raise Exception('Ожидается оператор присваивания')
self.position += 1
value_token = self.tokens[self.position]
if value_token['type'] == 'function_call':
function_name = value_token['value']
arguments = []
self.position += 1
while (
self.position < len(self.tokens)
and self.tokens[self.position]['type'] != 'paren'
and self.tokens[self.position]['value'] != ')'
):
argument = self.tokens[self.position]
arguments.append(argument)
self.position += 1
if (
self.position >= len(self.tokens)
or self.tokens[self.position]['value'] != ')'
):
raise Exception('Ожидается закрывающая скобка для вызова функции')
self.position += 1
return {
'type': 'assignment',
'variable': variable['value'],
'value': {
'type': 'function_call',
'function_name': function_name,
'arguments': arguments
}
}
elif value_token['type'] in ['string', 'number']:
assignment = {
'type': 'assignment',
'variable': variable['value'],
'value': value_token['value']
}
self.position += 1
return assignment
else:
raise Exception('Ожидается строка, число или вызов функции')
class Lexer:
def __init__(self, source_code):
self.source_code = source_code
self.position = 0
self.tokens = []
def tokenize(self):
while self.position < len(self.source_code):
current_char = self.source_code[self.position]
if current_char.isdigit():
self.tokens.append(self.parse_number())
elif current_char == '"':
self.tokens.append(self.parse_string())
elif current_char.isalpha() or current_char == '_':
self.tokens.append(self.parse_identifier())
elif current_char.isspace():
self.position += 1
continue
elif current_char == '(' or current_char == ')':
self.tokens.append({'type': 'paren', 'value': current_char})
elif current_char == '=':
self.tokens.append({'type': 'operator', 'value': current_char})
elif current_char == '+':
self.tokens.append({'type': 'operator', 'value': current_char})
else:
raise Exception(f'Недопустимый символ: {current_char}')
self.position += 1
return self.tokens
def parse_number(self):
start_position = self.position
while self.position < len(self.source_code) and self.source_code[self.position].isdigit():
self.position += 1
number = int(self.source_code[start_position:self.position])
return {'type': 'number', 'value': number}
def parse_string(self):
start_position = self.position
self.position += 1
while self.position < len(self.source_code) and self.source_code[self.position] != '"':
self.position += 1
if self.position >= len(self.source_code):
raise Exception('Неожиданный конец строки')
self.position += 1
string = self.source_code[start_position:self.position]
return {'type': 'string', 'value': string}
def parse_identifier(self):
start_position = self.position
while self.position < len(self.source_code) and (
self.source_code[self.position].isalpha() or self.source_code[self.position] == '_'):
self.position += 1
identifier = self.source_code[start_position:self.position]
return {'type': 'identifier', 'value': identifier}
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.position = 0
def parse(self):
parsed_data = []
while self.position < len(self.tokens):
parsed_data.append(self.parse_statement())
return parsed_data
def parse_statement(self):
variable = self.tokens[self.position]
if variable['type'] != 'identifier':
raise Exception('Ожидается идентификатор')
self.position += 1
if self.position >= len(self.tokens) or self.tokens[self.position]['value'] != '=':
raise Exception('Ожидается оператор присваивания')
self.position += 1
value_token = self.tokens[self.position]
if value_token['type'] == 'function_call':
function_name = value_token['value']
arguments = []
self.position += 1
while (
self.position < len(self.tokens)
and self.tokens[self.position]['type'] != 'paren'
and self.tokens[self.position]['value'] != ')'
):
argument = self.tokens[self.position]
arguments.append(argument)
self.position += 1
if (
self.position >= len(self.tokens)
or self.tokens[self.position]['value'] != ')'
):
raise Exception('Ожидается закрывающая скобка для вызова функции')
self.position += 1
return {
'type': 'assignment',
'variable': variable['value'],
'value': {
'type': 'function_call',
'function_name': function_name,
'arguments': arguments
}
}
elif value_token['type'] in ['string', 'number']:
assignment = {
'type': 'assignment',
'variable': variable['value'],
'value': value_token['value']
}
self.position += 1
return assignment
else:
raise Exception('Ожидается строка, число или вызов функции')
class SemanticAnalyzer:
def __init__(self, parsed_data):
self.parsed_data = parsed_data
def analyze(self):
semantic_data = []
for statement in self.parsed_data:
if statement['type'] == 'assignment':
variable = statement['variable']
value = self.evaluate_expression(statement['value'])
semantic_data.append({variable: value})
return semantic_data
def evaluate_expression(self, expression):
if expression['type'] == 'function_call':
function_name = expression['function_name']
arguments = expression['arguments']
if function_name == 'data_acquisition':
prompt = arguments[0]['value']
return self.data_acquisition(prompt)
else:
raise Exception(f'Неизвестная функция: {function_name}')
elif expression['type'] == 'string':
return expression['value']
elif expression['type'] == 'number':
return expression['value']
else:
raise Exception('Недопустимый тип выражения')
def data_acquisition(self, prompt):
return input(prompt)
class CodeGenerator:
def __init__(self, semantic_data):
self.semantic_data = semantic_data
def generate(self):
generated_code = ''
for statement in self.semantic_data:
variable = list(statement.keys())[0]
value = statement[variable]
generated_code += f"{variable} = {repr(value)}\n"
return generated_code
class Interpreter:
def __init__(self):
self.lexer = None
self.parser = None
self.semantic_analyzer = None
self.code_generator = None
def interpret(self, source_code):
self.lexer = Lexer(source_code)
tokens = self.lexer.tokenize()
self.parser = Parser(tokens)
parsed_data = self.parser.parse()
self.semantic_analyzer = SemanticAnalyzer(parsed_data)
semantic_data = self.semantic_analyzer.analyze()
self.code_generator = CodeGenerator(semantic_data)
generated_code = self.code_generator.generate()
self.execute_code(generated_code)
def execute_code(self, code):
exec(code, {'data_acquisition': self.semantic_analyzer.data_acquisition})
if __name__ == "__main__":
interpreter = Interpreter()
source_code = '''
name = data_acquisition("Enter your name: ")
print(name)
'''
interpreter.interpret(source_code)
[2023-05-20 12:30:53] [ERROR ] discord.ui.modal: Ignoring exception in modal <Form timeout=None children=4>:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 187, in _scheduled_task
await self.on_submit(interaction)
File "D:\wpg bot\cogs\command.py", line 64, in on_submit
channel = guild.get_channel(1108327539698585674)
NameError: name 'guild' is not defined
class MyBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('$'),
intents=discord.Intents.all(),
application_id=settings['app_id']
)