def visit_CallNode(self, node, context):
res = RTResult()
args = []
code
value_to_call = res.register(self.visit(node.node_to_call, context))
if res.error: return res
value_to_call = value_to_call.copy().set_pos(node.pos_start, node.pos_end)
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.error: return res
return_value = res.register(value_to_call.execute(args))
if res.error: return res
return_value = return_value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(return_value)
change this to accomodate arrays and procedures.
Assistant
code
def make_array(self):
pos_start = self.pos.copy()
self.advance() # Skip the '['
min_value = self.make_expr()
if not min_value:
return [], InvalidSyntaxError(pos_start, self.pos, "Expected a number or expression after '['")
if self.current_char != ':':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected ':' in array declaration")
self.advance() # Skip the ':'
max_value = self.make_expr()
if not max_value:
return [], InvalidSyntaxError(pos_start, self.pos, "Expected a number or expression after ':' in array declaration")
if self.current_char != ']':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected ']' in array declaration")
self.advance() # Skip the ']'
if self.current_char != 'OF':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected 'OF' in array declaration")
self.advance() # Skip 'OF'
array_type = self.make_identifier()
if array_type not in ALLOWED_ARRAY_TYPES:
return [], InvalidSyntaxError(pos_start, self.pos, f"Expected one of {ALLOWED_ARRAY_TYPES} in array declaration")
return [Token(TT_ARRAY, (min_value, max_value, array_type), pos_start, self.pos)], None
def make_tokens(self):
tokens = []
while self.current_char is not None:
if self.current_char in ' \t':
self.advance()
elif self.current_char in ['\n', ';']:
tokens.append(Token(TT_Newline, pos_start=self.pos))
self.advance()
elif self.current_char in LETTERS:
tokens.append(self.make_identifier())
elif self.current_char in DIGITS:
tokens.append(self.make_number())
elif self.current_char in ['"', "'"]:
tokens.append(self.make_string(self.current_char))
elif self.current_char == '[':
array_tokens, error = self.make_array()
if error:
return [], error
tokens += array_tokens
elif self.current_char == ']':
tokens.append(Token(TT_RSQUAREBRACKET, pos_start=self.pos))
self.advance()
elif self.current_char == '+':
tokens.append(Token(TT_PLUS, pos_start=self.pos))
self.advance()
elif self.current_char == '-':
tokens.append(Token(TT_MINUS, pos_start=self.pos))
self.advance()
elif self.current_char == ':':
tokens.append(Token(TT_Arrow, pos_start=self.pos))
self.advance()
elif self.current_char == '*':
tokens.append(Token(TT_MUL, pos_start=self.pos))
self.advance()
elif self.current_char == '/':
tokens.append(Token(TT_DIV, pos_start=self.pos))
self.advance()
elif self.current_char == '(':
tokens.append(Token(TT_LPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == ')':
tokens.append(Token(TT_RPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == '^':
tokens.append(Token(TT_POWER, pos_start=self.pos))
self.advance()
elif self.current_char == '<':
tok = self.make_not_lessThan_assign()
tokens.append(tok)
elif self.current_char == '>':
tokens.append(self.make_greater_than())
elif self.current_char == ',':
tokens.append(Token(TT_Comma, pos_start=self.pos))
self.advance()
elif self.current_char == 'P':
tok = self.make_keyword()
if tok.value == 'PROCEDURE':
tokens.append(Token(TT_PROCEDURE, pos_start=tok.pos_start, pos_end=tok.pos_end))
elif tok.value == 'ENDPROCEDURE':
tokens.append(Token(TT_END_PROCEDURE, pos_start=tok.pos_start, pos_end=tok.pos_end))
else:
return [], IllegalCharError(tok.pos_start, tok.pos_end, f"Unexpected character '{self.current_char}'")
else:
pos_start = self.pos.copy()
char = self.current_char
self.advance()
return [], IllegalCharError(pos_start, self.pos, "'" + char + "'")
tokens.append(Token(TT_EOF, pos_start=self.pos))
return tokens, None
def make_string(self,end):
string = ''
pos_start = self.pos.copy()
self.advance()
while self.current_char != None and self.current_char != end:
string += self.current_char
self.advance()
self.advance()
return Token(TT_STRING,string,pos_start,self.pos)
def make_number(self):
num_str = ''
dotCount = 0
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in DIGITS + '.':
if self.current_char == '.':
if dotCount == 1: break
num_str += '.'
dotCount += 1
else:
num_str += self.current_char
self.advance()
if dotCount == 0:
return Token(TT_INT,int(num_str),pos_start,self.pos)
else:
return Token(TT_REAL,float(num_str),pos_start,self.pos)
def make_identifier(self):
id_str = ''
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in LETTERS_DIGITS + '_':
id_str += self.current_char
self.advance()
tok_type = TT_KEYWORD if id_str in KEYWORDS else TT_IDENTIFIER
return Token(tok_type,id_str,pos_start,self.pos)
def make_greater_than(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
return Token(TT_GTE,pos_start=pos_start,pos_end=self.pos)
return Token(TT_GT,pos_start=pos_start,pos_end=self.pos)
def make_not_lessThan_assign(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '-':
self.advance()
return Token(TT_EQ,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '>':
self.advance()
return Token(TT_NE,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '=':
self.advance()
return Token(TT_LTE, pos_start=pos_start, pos_end=self.pos)
else:
return Token(TT_LT, pos_start=pos_start, pos_end=self.pos)
#Parser
#---------------------------------------
class Parser:
def init(self,tokens):
self.tokens = tokens
self.hasEq = 0
for q in tokens:
if q.type == TT_EQ:
self.hasEq += 1
self.tok_idx = -1
self.advance()
code
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def regress(self):
self.tok_idx -= 1
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def reverse(self,amount = 1):
self.tok_idx -= amount
self.update_current_tok()
return self.current_tok
def update_current_tok(self):
if self.tok_idx >= 0 and self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
def parse(self):
res = self.statements()
if not res.error and self.current_tok.type != TT_EOF:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '+', '-', '*' or '/'"
))
return res
def statements(self):
res = ParseResult()
statements = []
pos_start = self.current_tok.pos_start.copy()
n = 0
while self.current_tok.type == TT_Newline:
res.register(self.advance())
statement = res.register(self.expr())
if res.error: return res
statements.append(statement)
more_statements = True
while True:
newline_count = 0
while self.current_tok.type == TT_Newline:
res.register(self.advance())
newline_count +=1
if newline_count == 0: more_statements = False
if not more_statements: break
statement = res.try_register(self.expr())
if statement == None:
self.reverse(1)
more_statements = False
continue
statements.append(statement)
return res.success(ListNode(
statements,pos_start,self.current_tok.pos_end.copy()
))
def for_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,'FOR'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end,f"Expected 'FOR'"))
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected identifier"))
var_name = self.current_tok
res.register(self.advance())
if self.current_tok.type != TT_EQ:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, "Expected '<-'"))
res.register(self.advance())
start_value = res.register(self.expr())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'TO'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'TO'"))
res.register(self.advance())
end_value = res.register(self.expr())
if res.error: return res
if self.current_tok.matches(TT_KEYWORD,'STEP'):
res.register(self.advance())
step_value = res.register(self.expr())
if res.error:return res
else:
step_value = None
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
body = res.register(self.statements())
if res.error:
return res
if not self.current_tok.matches(TT_KEYWORD,'NEXT'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'NEXT'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Identifier"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected EOF or Newline"))
return res.success(ForNode(var_name,start_value,end_value,step_value,body))
def array_expr(self):
res = ParseResult()
pos_start = self.current_tok.pos_start.copy()
res.register(self.advance()) # Skip '['
index = res.register(self.expr()) # Parse array index expression
if res.error:
return res
if self.current_tok.type != TT_RSQUAREBRACKET:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ]"
))
res.register(self.advance()) # Skip ']'
return res.success(ArrayAccessNode(TT_ARRAY, index))
def while_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,"WHILE"):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'WHILE'"))
res.register(self.advance())
condition = res.register(self.expr())
if res.error: return res
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'DO'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'DO'"))
res.register(self.advance())
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'ENDWHILE'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'ENDWHILE'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline or EOF"))
return res.success(WhileNode(condition,body))
def repeat_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,"REPEAT"):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'REPEAT'"))
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'UNTIL'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'UNTIL'"))
res.register(self.advance())
condition = res.register(self.expr())
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected newline or EOF"))
return res.success(RepeatNode(body,condition))
def if_expr(self):
res = ParseResult()
cases = []
else_case = None
if not self.current_tok.matches(TT_KEYWORD,'IF'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'IF'"))
res.register(self.advance())
cond = res.register(self.expr())
if res.error: return res
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'THEN'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'THEN'"))
res.register(self.advance())
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
res.register(self.advance())
statements = res.register(self.statements())
if res.error: return res
cases.append((cond,statements))
if self.current_tok.matches(TT_KEYWORD,'ELSE'): #instead of making a separate else-expr I added it here
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
else_case = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'ENDIF'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'ENDIF'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected EOF or Newline"))
return res.success(IfNode(cases,else_case))
def call(self):
res = ParseResult()
atom = res.register(self.atom())
if res.error:
return res
if self.current_tok.type == TT_LPAREN:
res.register(self.advance())
arg_nodes = []
if self.current_tok.type == TT_RPAREN:
res.register(self.advance())
else:
tok = self.current_tok
arg_nodes.append(res.register(self.expr()))
if res.error: res.failure(InvalidSyntaxError(tok.pos_start,tok.pos_end,""))
while self.current_tok.type == TT_Comma:
res.register(self.advance())
arg_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RPAREN:
res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ')' or ','"))
res.register(self.advance())
return res.success(CallNode(atom,arg_nodes))
return res.success(atom)
def atom(self):
res = ParseResult()
tok = self.current_tok
if tok.type in [TT_INT,TT_REAL]:
res.register(self.advance())
return res.success(NumberNode(tok))
if tok.type == TT_STRING:
res.register(self.advance())
return res.success(StringNode(tok))
elif tok.type == TT_IDENTIFIER:
res.register(self.advance())
return res.success(VarAccessNode(tok))
elif tok.type == TT_LPAREN:
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
if self.current_tok.type == TT_RPAREN:
res.register(self.advance())
return res.success(expr)
else:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ')'"
))
elif tok.type == TT_LSQUAREBRACKET:
list_expr = res.register(self.list_expr())
if res.error:
return res
return res.success(list_expr)
elif tok.matches(TT_KEYWORD,'IF'):
if_expr = res.register(self.if_expr())
if res.error: return res
return res.success(if_expr)
elif tok.matches(TT_KEYWORD,'FOR'):
for_expr = res.register(self.for_expr())
if res.error:
return res
return res.success(for_expr)
elif tok.matches(TT_KEYWORD,'WHILE'):
while_expr = res.register(self.while_expr())
if res.error:return res
return res.success(while_expr)
elif tok.matches(TT_KEYWORD,"REPEAT"):
repeat_expr = res.register(self.repeat_expr())
if res.error:
return res
return res.success(repeat_expr)
elif tok.matches(TT_KEYWORD,"FUNCTION"):
function_def = res.register(self.func_def())
if res.error:
return res
return res.success(function_def)
else:
return res.failure(InvalidSyntaxError(tok.pos_start,tok.pos_end,"Expected int,real, '+', '-','(','IF','FOR','WHILE','REPEAT', or 'FUNCTION'"))
def power(self):
return self.bin_op(self.call,(TT_POWER,),self.factor)
def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (TT_PLUS,TT_MINUS):
res.register(self.advance())
factor = res.register(self.factor())
if res.error:
return res
return res.success(UnaryOpNode(tok,factor))
return self.power()
def term(self):
return self.bin_op(self.factor,(TT_DIV,TT_MUL))
def arith_expr(self):
return self.bin_op(self.term,(TT_PLUS,TT_MINUS))
def comp_expr(self):
res = ParseResult()
if self.current_tok.matches(TT_KEYWORD,'NOT'):
op_tok = self.current_tok
res.register(self.advance())
if res.error: return res
node = res.register(self.comp_expr())
if res.error:return res
return res.success(UnaryOpNode(op_tok,node))
node = res.register(self.bin_op(self.arith_expr,(TT_EE,TT_NE,TT_LT,TT_LTE,TT_GT,TT_GTE)))
tok = self.current_tok
if res.error:
return res
return res.success(node)
def expr(self):
res = ParseResult()
if self.current_tok.type == TT_IDENTIFIER:
var_name = self.current_tok
res.register(self.current_tok)
res.register(self.advance())
if self.current_tok.type == TT_EQ:
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
return res.success(VarAssignNode(var_name,expr))
if self.current_tok.type == TT_LSQUAREBRACKET:
index = res.register(self.array_expr())
if res.error:
return res
if self.current_tok.type != TT_EQ:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected <- for assignment"
))
res.register(self.advance())
value = res.register(self.expr())
if res.error: return res
return res.success(ArrayAssignmentNode(var_name, index, value))
self.regress()
return self.bin_op(self.comp_expr,((TT_KEYWORD,'AND'),(TT_KEYWORD,'OR')))
def proc_def(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD, 'PROCEDURE'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected 'PROCEDURE'"
))
res.register(self.advance()) # Advance past 'PROCEDURE'
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected an identifier"
))
procedure_name_tok = self.current_tok
res.register(self.advance()) # Advance past the procedure name
arg_name_toks = []
if self.current_tok.type != TT_LPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '(' after procedure name"
))
res.register(self.advance()) # Advance past '('
if self.current_tok.type == TT_IDENTIFIER:
arg_name_toks.append(self.current_tok)
res.register(self.advance()) # Advance past argument name
while self.current_tok.type == TT_Comma:
res.register(self.advance()) # Advance past ','
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected an identifier"
))
arg_name_toks.append(self.current_tok)
res.register(self.advance()) # Advance past argument name
if self.current_tok.type != TT_RPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ')' after procedure arguments"
))
res.register(self.advance()) # Advance past ')'
body = res.register(self.statements())
if res.error: return res
# Assuming ENDPROCEDURE marks the end of a procedure
if not self.current_tok.matches(TT_KEYWORD, "ENDPROCEDURE"):
return res.failure(InvalidSyntaxError(...))
res.register(self.advance()) # Advance past 'ENDPROCEDURE'
return res.success(ProcedureNode(procedure_name_tok, arg_name_toks, body))
def bin_op(self,func_a,ops,func_b = None):
if func_b == None:
func_b = func_a
res = ParseResult()
left = res.register(func_a())
while self.current_tok.type in ops or (self.current_tok.type, self.current_tok.value) in ops:
op_tok = self.current_tok
res.register(self.advance())
right = res.register(func_b())
if res.error:
return res
left = BinOpNode(left, op_tok, right)
return res.success(left)
def list_expr(self):
res = ParseResult()
element_nodes = []
pos_start = self.current_tok.pos_start.copy()
res.register(self.advance())
if self.current_tok.type == TT_RSQUAREBRACKET:
res.register(self.advance())
else:
tok = self.current_tok
element_nodes.append(res.register(self.expr()))
if res.error: res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ']', 'IF','FOR','WHILE','FUNCTION',variable,datatypoe"))
while self.current_tok.type == TT_Comma:
res.register(self.advance())
element_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RSQUAREBRACKET:
res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ']' or ','"))
res.register(self.advance())
return ListNode(element_nodes,pos_start,self.current_tok.pos_end.copy())
def func_def(self):
res = ParseResult()
tok = self.current_tok
if not self.current_tok.matches(TT_KEYWORD,'FUNCTION'):
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'FUNCTION'"))
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected indentifier"))
var_name_tok = self.current_tok
res.register(self.advance())
if self.current_tok.type != TT_LPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected '('"))
res.register(self.advance())
arg_name_toks = []
if self.current_tok.type == TT_IDENTIFIER:
arg_name_toks.append(self.current_tok)
res.register(self.advance())
if not self.current_tok.type == TT_Arrow:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ':'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER or self.current_tok.value not in ['REAL', 'INTEGER', 'CHAR','BOOLEAN', 'STRING']:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected datatype"))
res.register(self.advance())
while self.current_tok.type == TT_Comma:
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
tok = self.current_tok
return res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected identifier"))
name = self.current_tok
res.register(self.advance())
if not self.current_tok.type == TT_Arrow:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ':'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER or self.current_tok.value not in ['REAL', 'INTEGER', 'CHAR', 'BOOLEAN', 'STRING']:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected datatype"))
arg_name_toks.append(name)
res.register(self.advance())
if self.current_tok.type != TT_RPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ',' or ')'"))
else:
if self.current_tok.type != TT_RPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected identifier or ')'"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'RETURNS'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'RETURNS'"))
res.register(self.advance())
if self.current_tok.value not in ['INTEGER','REAL','BOOLEAN','STRING','CHAR']:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'INTEGER','REAL','BOOLEAN','STRING' or 'CHAR'"))
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected Newline'"))
node_to_return = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'RETURN'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'RETURN'"))
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'ENDFUNCTION'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'ENDFUNCTION'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected Newline or EOF'"))
return res.success(FuncDefNode(
var_name_tok,arg_name_toks,node_to_return,expr
))
#runtime result
#-------------------------------------------------
class RTResult:
def init(self):
self.value = None
self.error = None
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
# Create a new execution context for the procedure with a new symbol table
exec_ctx = self.generateNewContext()
# Populate the new context with arguments
res.register(self.check_and_populate_args(self.arg_names, args, exec_ctx))
if res.error: return res
# Execute the body of the procedure
value = res.register(interpreter.visit(self.body_node, exec_ctx))
if res.error: return res
# Normally, procedures do not return a value unless specified, return a “null” equivalent
return res.success(Number(0))
def copy(self):
# When copying a procedure, we copy the procedure’s name, body, and argument names
copy = Procedure(self.name, self.body_node, self.arg_names)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def repr(self):
return f"<procedure {self.name}>"
def get(self,name):
value = self.symbols.get(name, None)
if value == None and self.parent:
return self.parent.get(name)
return value
def set(self, name, value):
self.symbols[name] = value
def remove(self,name):
del self.symbols[name]
change the call node function to accomodate the arrays and the procedures.
It looks like you've pasted a substantial amount of Python code which seems to be part of an interpreter project for a custom language. This code includes definitions for various classes (like Token, Lexer, Parser, Interpreter, etc.) that are part of the language's front-end infrastructure (lexical analysis, parsing) and also the runtime infrastructure (execution).
However, the code is quite long and encompasses multiple functionalities, so I'll provide you with the rough idea about how to adjust the visit_CallNode method to accommodate arrays and procedures. Your visit_CallNode method in the Interpreter class will need to be able to distinguish between function calls, procedure calls, and array indexings. Here's a rough concept for how that method could be refactored:
python
def visit_CallNode(self, node, context):
res = RTResult()
# Visit the node that we are trying to call which could be a function, a procedure, or an array
callable_value = res.register(self.visit(node.node_to_call, context))
if res.error: return res
# Depending upon the type of callable_value, execute the call differently
if isinstance(callable_value, Function):
# If it's a function, prepare to call it by visiting the arguments
args = []
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.error: return res
# Perform the actual function call
return_value = res.register(callable_value.execute(args))
if res.error: return res
# Copy the function's position and context for error reporting
return_value = return_value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
elif isinstance(callable_value, Procedure):
# If it's a procedure, similarly visit its arguments and perform the call
# Note that procedures might not return a value, so handle that accordingly
elif isinstance(callable_value, List):
# If it's an array (List), we expect there to be a single argument which is the index
if len(node.arg_nodes) != 1:
# Throw an error because arrays expect only one index argument
return res.failure(...)
index_node = node.arg_nodes[0]
index_value = res.register(self.visit(index_node, context))
if res.error: return res
# Access the element at the given index in the array
# Make sure to handle the possibility of an index out of bounds error
# Similarly, make sure to copy the array's position and context for error reporting
else:
# If it's not a function, procedure, or array, we have an error (illegal operation)
return res.failure(...)
return res.success(return_value)
This is a high-level blueprint, and you will need to fill in the detailed logic for executing function calls, procedure calls, and array access.
The code you posted also contains the definition of a custom error RTError and other functionality that should be taken into account when you work on this interpreter.
Considering how complex and featureful this language interpreter is becoming, it might be good to consider adding proper error handling and testing to the code. This way, you can make more confident changes and ensure that your functionality works as expected.
Remember to keep the single-responsibility principle in mind: each part of your code should have one clear purpose, which will make your interpreter easier to read, maintain, and extend over time.
Based on your request to modify the visit_CallNode to accommodate arrays and procedures, it seems like you intend for the visit_CallNode method to be able to handle calls to functions, procedures, and access array elements using an index. Here is how you could refactor the method to handle these cases:
python
def visit_CallNode(self, node, context):
res = RTResult()
# First, evaluate the node that we're calling, which could be a function, procedure, or array
callable_value = res.register(self.visit(node.node_to_call, context))
if res.error: return res
if isinstance(callable_value, Function):
# Prepare to call the function by visiting all the argument nodes
args = []
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.error: return res
# Now execute the function with the prepared arguments
return_value = res.register(callable_value.execute(args))
if res.error: return res
# Set the context and position information for the return value
return_value = return_value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(return_value)
elif isinstance(callable_value, Procedure):
# Procedures should be called in a similar fashion to functions but may not return a value
args = []
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.error: return res
# Call the procedure, and we may not necessarily use the return value
res.register(callable_value.execute(args))
if res.error: return res
return res.success(Number(0)) # Usually, procedures do not return a value
elif isinstance(callable_value, List):
# For arrays (Lists), expect a single argument which is the index
if len(node.arg_nodes) != 1:
return res.failure(RTError(
node.pos_start,
node.pos_end,
"Array access must have a single index argument",
context
))
# Get the index value
index_node = node.arg_nodes[0]
index_value = res.register(self.visit(index_node, context))
if res.error: return res
# Access the element at the given index in the array
if index_value.value >= 0 and index_value.value < len(callable_value.elements):
return_value = callable_value.elements[index_value.value]
return res.success(return_value.set_pos(node.pos_start, node.pos_end))
else:
return res.failure(RTError(
index_node.pos_start,
index_node.pos_end,
"Array index out of bounds",
context
))
else:
return res.failure(RTError(
node.pos_start,
node.pos_end,
"Only functions, procedures and array indices can be called",
context
))
# Rest of your code...
What we're doing here is:
Identifying if the callable_value is a Function, Procedure, or List (array).
Handling the call as per the type of callable_value:
If it's a Function, we call it by preparing the arguments and executing it, just like before.
If it's a Procedure, we also prepare the arguments and call it, but we don't expect a return value. So we simply return a zero (Number(0)) to represent a 'void' return type which is a common convention for procedures that do not return a value.
If it's a List, we handle the single argument as an index (returning an error if more than one argument is given), and we return the element at the given index (or an error if the index is out of bounds).
Please merge this logic with the rest of your interpreter code, taking care to also handle any specific error messages or additional functionality that your particular interpreter needs. Remember that you may need to adapt this structure to fit your existing code structure or design choices.