#include "lexer.h" #include #include #include #include #include #include "io_backend/io_backend.h" #include "utils/string_utils/string_utils.h" static char *end_last_token; static ssize_t remaining_chars; /* @brief: saves state for the next call the the lexer. * */ static void save_state(char *stream, ssize_t i) { remaining_chars -= i; end_last_token = stream + i; return; } /* @return: true if a special character from the grammar was found, * false otherwise. * */ static bool is_special_char(char c) { return c == '\'' || c == '\n' || c == ';' || c == 'EOF'; } static void new_token_keyword(struct token *tok, char *begin, ssize_t size) { if (strncmp(begin, "if", size) == 0) { tok->type = TOKEN_IF; } if (strncmp(begin, "fi", size) == 0) { tok->type = TOKEN_FI; } if (strncmp(begin, "then", size) == 0) { tok->type = TOKEN_THEN; } if (strncmp(begin, "else", size) == 0) { tok->type = TOKEN_ELSE; } } struct token *new_token(char *begin, ssize_t size) { struct token *res = calloc(1, sizeof(struct token)); if (res == NULL) return NULL; // checks which type of token // is special char // is keyword // otherwise -> WORD char *token_data = calloc(size + 1, sizeof(char)); strncpy(res, begin, size); return res; } char *stream_init(void) { char *stream; if (remaining_chars == 0) { remaining_chars = stream_read(&stream); } else { stream = end_last_token; } char *trimed_stream = trim_blank_left(stream); remaining_chars -= trimed_stream - stream; stream = trimed_stream; return stream; } struct token *peek_token(void) { char *stream = stream_init(); ssize_t i = 0; while (i < remaining_chars) { if (is_special_char(stream[i])) { if (i == 0) // where we create spe_char token i++; break; } if (isblank(stream[i])) { break; } i++; } return new_token(stream, i); } struct token *pop_token(void) { char *stream = stream_init(); ssize_t i = 0; while (i < remaining_chars) { if (is_special_char(stream[i])) { if (i == 0) // where we create spe_char token i++; break; } if (isblank(stream[i])) { break; } i++; } save_state(stream, i); return new_token(stream, i); }