как исправить этот код? пожалуйста, помогите мне, я пытался создать язык программирования на основе санскрита для своего проекта. У меня здесь возникли некоторые проблемы, спасибо, я написал код лексера, но синтаксический анализатор выдает проблемы, я спросил в чате gpt, Gemini и черный ящик, но нигде не нашел помощи
import re
# Global variables to store defined variables and functions
variables = {}
functions = {}
# Lexer class (placeholder for the actual lexer implementation)
class Lexer:
# Define your lexer methods here
pass
# AST Node Classes
class PrintStatement:
def __init__(self, value):
self.value = value
class Assignment:
def __init__(self, variable, expression):
self.variable = variable
self.expression = expression
class IfStatement:
def __init__(self, condition, if_block, else_block=None):
self.condition = condition
self.if_block = if_block
self.else_block = else_block
class WhileStatement:
def __init__(self, condition, block):
self.condition = condition
self.block = block
class FunctionDefinition:
def __init__(self, name, parameters, body):
self.name = name
self.parameters = parameters
self.body = body
class FunctionCall:
def __init__(self, name, arguments):
self.name = name
self.arguments = arguments
def evaluate(expression):
global variables
if isinstance(expression, int):
return expression
elif isinstance(expression, str):
return variables.get(expression, 0)
elif isinstance(expression, list):
# Check if it's a binary operation
if len(expression) == 3:
left = evaluate(expression[0])
operator = expression[1] # Keep operator as string
right = evaluate(expression[2])
return evaluate_operation(left, operator, right)
elif expression[0] == 'list':
return [evaluate(e) for e in expression[1:]]
elif expression[0] == 'dict':
return {evaluate(expression): evaluate(expression[i + 1]) for i in range(1, len(expression), 2)}
elif len(expression) == 1: # Single value (like a variable)
return evaluate(expression[0])
elif isinstance(expression, FunctionCall):
function = functions.get(expression.name)
if not function:
raise ValueError(f"Function '{expression.name}' not defined")
# Prepare arguments
arguments = [evaluate(arg) for arg in expression.arguments]
if len(arguments) != len(function.parameters):
raise ValueError(f"Function '{expression.name}' expects {len(function.parameters)} arguments, got {len(arguments)}")
# Create a local scope for the function
local_variables = dict(zip(function.parameters, arguments))
saved_variables = variables.copy() # Save current state
variables.update(local_variables) # Update variables for the function call
execute(function.body) # Execute the function body
variables = saved_variables # Restore original variable state
return # Return None after function execution
raise ValueError(f"Unknown expression type: {expression}")
def execute(parsed_code):
for statement in parsed_code:
if isinstance(statement, PrintStatement):
value = evaluate(statement.value)
print(value)
elif isinstance(statement, Assignment):
variables[statement.variable] = evaluate(statement.expression)
elif isinstance(statement, IfStatement):
if evaluate(statement.condition):
execute(statement.if_block)
elif statement.else_block:
execute(statement.else_block)
elif isinstance(statement, WhileStatement):
while evaluate(statement.condition):
execute(statement.block)
elif isinstance(statement, FunctionDefinition):
functions[statement.name] = statement
elif isinstance(statement, FunctionCall):
evaluate(statement)
def evaluate_operation(left, operator, right):
if operator == '+':
return left + right
elif operator == '-':
return left - right
elif operator == '*':
return left * right
elif operator == '/':
return left / right
elif operator == '>':
return left > right
elif operator == '
Подробнее здесь: https://stackoverflow.com/questions/791 ... operator-a
Какая ошибка здесь, в этом коде, ошибка указывает на неизвестный оператор A? ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Объясните, как здесь, в этом Java-коде, работает приоритет операторов [дубликат]
Anonymous » » в форуме JAVA - 0 Ответы
- 19 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как использовать оператор FOR с continue/escape/break в этом коде Django?
Anonymous » » в форуме Python - 0 Ответы
- 25 Просмотры
-
Последнее сообщение Anonymous
-