From 21efb0563b74d5c29909e8c83f8c9b7fca88c5c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=20Luis=20Monta=C3=B1es=20Ojados?= Date: Mon, 16 Feb 2026 18:31:39 +0100 Subject: [PATCH] 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 --- projects/functions.j | 13 ++----------- src/frontend/parser.h | 28 +++++++++++++++++++++++++++- src/vm/eval.h | 11 +++++++++++ 3 files changed, 40 insertions(+), 12 deletions(-) diff --git a/projects/functions.j b/projects/functions.j index 07fc53f..4013919 100644 --- a/projects/functions.j +++ b/projects/functions.j @@ -1,11 +1,2 @@ -x = "Hello world!" -y = 21 -println() -println(x) -print("y=") -println(y) - -dummy() - -if y > 1: - println("OK!") \ No newline at end of file +x = "Hello" +println(len(x) + 3) \ No newline at end of file diff --git a/src/frontend/parser.h b/src/frontend/parser.h index 0ff71bf..0df9701 100644 --- a/src/frontend/parser.h +++ b/src/frontend/parser.h @@ -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++; diff --git a/src/vm/eval.h b/src/vm/eval.h index aee01f5..5d8f113 100644 --- a/src/vm/eval.h +++ b/src/vm/eval.h @@ -168,6 +168,17 @@ size_t eval(ASTNode *node, Environment *env, void *allocator, int debug, printf("\n"); return 0; } + if (strcmp(node->data.call.name, "len") == 0) { + if (node->data.call.arg_count == 1) { + size_t val = eval(node->data.call.args[0], env, allocator, debug, gc); + Object *obj = (Object *) JLANG_RESOLVE(allocator, val); + + if (obj->type == OBJ_STRING) { + return obj_new_int(allocator, obj->data.string_val.length); + } + } + return 0; + } printf("ERROR: funcion '%s' no definida\n", node->data.call.name); exit(1); }