#include "parse.h"
#include <stdio.h>
struct node_tag *ast_last_numbered_line;
static struct node_tag *ast_alloc(enum NODE_TYPE node_type) {
struct node_tag *new_node = malloc(sizeof(struct node_tag));
if (new_node == NULL) {
fprintf(stderr, "Memory allocation failed at %s:%d\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
new_node->type = node_type;
return new_node;
}
struct node_tag *ast_make_string(char *s) {
struct node_tag *new_node = ast_alloc(NODE_STRING);
new_node->data.string.str = s;
return new_node;
}
struct node_tag *ast_make_numbered_line(int line, struct node_tag *stmt) {
struct node_tag *new_node = ast_alloc(NODE_NUMBERED_LINE);
new_node->data.line.linum = line;
new_node->data.line.stmt = stmt;
ast_last_numbered_line = new_node;
return new_node;
}
struct node_tag *ast_make_print(struct node_tag *expr) {
struct node_tag *new_node = ast_alloc(NODE_PRINT);
new_node->data.print.expr = expr;
return new_node;
}
struct node_tag *ast_make_if(struct node_tag *pred, struct node_tag *stmt) {
struct node_tag *new_node = ast_alloc(NODE_IF);
new_node->data.iff.pred = pred;
new_node->data.iff.stmt = stmt;
return new_node;
}
struct node_tag *ast_make_id(char *name) {
struct node_tag *new_node = ast_alloc(NODE_ID);
new_node->data.id.name = name;
return new_node;
}
struct node_tag *ast_make_number_integer(int val) {
struct node_tag *new_node = ast_alloc(NODE_NUMBER_INTEGER);
new_node->data.number_integer.val = val;
return new_node;
}
struct node_tag *read_line(char *line) {
int yyparse_failed;
yy_scan_string(line);
yyparse_failed = yyparse();
yylex_destroy();
return yyparse_failed ? NULL : ast_last_numbered_line;
}
int set_initial_buffer() {
rl_replace_line("custom!", 1);
rl_redisplay();
return 0;
}
struct node_tag *read_line_stdin(char *prompt) {
char *line = NULL;
struct node_tag *read_node;
rl_startup_hook = set_initial_buffer;
line = readline(prompt);
if (strlen(line) == 0)
return NULL;
read_node = read_line(line);
if (read_node != NULL)
add_history(line);
free(line);
return read_node;
}