frontend: compile: parse source files

This commit is contained in:
2024-11-26 13:10:36 +00:00
parent 25e65f2107
commit 886c0b49a4

View File

@@ -5,15 +5,19 @@
#include <blue/term.h>
#include <errno.h>
#include <ivy/file.h>
#include <ivy/lang/ast.h>
#include <ivy/lang/lex.h>
#include <stdio.h>
enum {
ARG_SOURCE_FILE,
ARG_SOURCE_FILE = 200,
OPT_LEX_ONLY,
};
static int compile_file(const char *path)
static int compile_file(const char *path, const b_arglist *args)
{
bool lex_only
= b_arglist_get_count(args, OPT_LEX_ONLY, B_COMMAND_INVALID_ID) > 0;
FILE *fp = fopen(path, "r");
if (!fp) {
@@ -23,7 +27,7 @@ static int compile_file(const char *path)
}
struct ivy_file *src = ivy_file_from_fp(fp);
struct ivy_lexer *lex;
struct ivy_lexer *lex = NULL;
if (ivy_lexer_create(&lex) != IVY_OK) {
b_err("failed to initialise Ivy lexer");
ivy_file_close(src);
@@ -33,6 +37,16 @@ static int compile_file(const char *path)
ivy_lexer_set_source(lex, &src->f_base);
enum ivy_status status = IVY_OK;
struct ivy_parser *parser = NULL;
status = ivy_parser_create(&parser);
if (status != IVY_OK) {
b_err("failed to initialise Ivy parser");
ivy_lexer_destroy(lex);
ivy_file_close(src);
return -1;
}
while (true) {
struct ivy_token *tok = ivy_lexer_read(lex);
status = ivy_lexer_get_status(lex);
@@ -47,12 +61,39 @@ static int compile_file(const char *path)
break;
}
if (lex_only) {
print_lex_token(tok);
ivy_token_destroy(tok);
continue;
}
status = ivy_parser_push_token(parser, tok);
if (status != IVY_OK) {
b_err("failed to parse '%s'", path);
b_i("reason: parse error (%s)",
ivy_status_to_string(status));
ivy_token_destroy(tok);
break;
}
}
int r = (status == IVY_OK || status == IVY_ERR_EOF) ? 0 : -1;
ivy_file_close(src);
if (!lex_only && r == 0) {
struct ivy_ast_node *root = ivy_parser_root_node(parser);
ivy_ast_node_print(root);
}
if (lex) {
ivy_lexer_destroy(lex);
}
if (parser) {
ivy_parser_destroy(parser);
}
return r;
}
@@ -67,7 +108,7 @@ static int compile(const b_command *cmd, const b_arglist *args, const b_array *_
}
printf("%s\n", path->val_str);
int r = compile_file(path->val_str);
int r = compile_file(path->val_str, args);
if (r != 0) {
return r;
}
@@ -85,6 +126,15 @@ B_COMMAND(CMD_COMPILE, CMD_ROOT)
B_COMMAND_FLAGS(B_COMMAND_SHOW_HELP_BY_DEFAULT);
B_COMMAND_FUNCTION(compile);
B_COMMAND_OPTION(OPT_LEX_ONLY)
{
B_OPTION_LONG_NAME("lex-only");
B_OPTION_SHORT_NAME('L');
B_OPTION_DESC(
"print the lexical tokens generated from the input "
"files.");
}
B_COMMAND_ARG(ARG_SOURCE_FILE)
{
B_ARG_NAME("source file");