Allow function calls in expressions and add len() built-in
- Parse function calls in parse_term() so they work inside expressions (e.g. z = len(x), y = len(x) + 1) - Add len() built-in for string length in evaluator
This commit is contained in:
@@ -65,6 +65,8 @@ ASTNode *make_node(NodeType type) {
|
||||
|
||||
int pos = 0;
|
||||
|
||||
ASTNode *parse_expr(Token *tokens);
|
||||
|
||||
ASTNode *parse_term(Token *tokens) {
|
||||
if (tokens[pos].type == TOK_INT) {
|
||||
ASTNode *node = make_node(NODE_INT_LIT);
|
||||
@@ -77,8 +79,32 @@ ASTNode *parse_term(Token *tokens) {
|
||||
pos++;
|
||||
return node;
|
||||
} else if (tokens[pos].type == TOK_ID) {
|
||||
printf("Parsing token: %s\n", tokens[pos].value);
|
||||
if (tokens[pos +1].type == TOK_LPAREN) {
|
||||
// Function call
|
||||
char *name = tokens[pos].value;
|
||||
pos++; // consumir ID
|
||||
pos++; // consumir (
|
||||
|
||||
// Parsear argumentos
|
||||
ASTNode **args =
|
||||
(ASTNode **)malloc(sizeof(ASTNode *) * 16); // Max 16 parametros
|
||||
int arg_count = 0;
|
||||
|
||||
if (tokens[pos].type != TOK_RPAREN) {
|
||||
args[arg_count++] = parse_expr(tokens);
|
||||
while (tokens[pos].type == TOK_COMMA) {
|
||||
pos++; // Consumir ","
|
||||
args[arg_count++] = parse_expr(tokens);
|
||||
}
|
||||
}
|
||||
pos++; // consumir ")"
|
||||
ASTNode *node = make_node(NODE_CALL);
|
||||
node->data.call.name = name;
|
||||
node->data.call.args = args;
|
||||
node->data.call.arg_count = arg_count;
|
||||
return node;
|
||||
|
||||
}
|
||||
ASTNode *node = make_node(NODE_VAR);
|
||||
node->data.string_val = tokens[pos].value;
|
||||
pos++;
|
||||
|
||||
Reference in New Issue
Block a user