slr/lexer.c

67 lines
2.1 KiB
C
Raw Normal View History

2024-05-16 20:03:04 +02:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "lexer.h"
2024-05-18 20:07:13 +02:00
Token *lexer(char *buf)
{
2024-05-16 20:03:04 +02:00
char *current = strdup(buf);
int current_index = 0, tokens_index = 0;
Token *tokens = malloc(sizeof(Token) * 1024);
2024-05-18 20:07:13 +02:00
while(current[current_index] != '\0') {
2024-05-16 20:03:04 +02:00
Token *token = NULL;
2024-05-18 20:07:13 +02:00
if(current[current_index] == ';') {
2024-05-16 20:03:04 +02:00
token = malloc(sizeof(Token));
char *value = malloc(2 * sizeof(char));
value[0] = current[current_index];
value[1] = '\0';
token->value = value;
token->type = SEPARATOR;
tokens[tokens_index] = *token;
tokens_index++;
printf("FOUND SEMICOLON\n");
2024-05-18 20:07:13 +02:00
} else if(current[current_index] == '(') {
2024-05-16 20:03:04 +02:00
token = malloc(sizeof(Token));
char *value = malloc(2 * sizeof(char));
value[0] = current[current_index];
value[1] = '\0';
token->value = value;
token->type = SEPARATOR;
tokens[tokens_index] = *token;
tokens_index++;
printf("FOUND OPEN PAREN\n");
2024-05-18 20:07:13 +02:00
} else if(current[current_index] == ')') {
2024-05-16 20:03:04 +02:00
token = malloc(sizeof(Token));
char *value = malloc(2 * sizeof(char));
value[0] = current[current_index];
value[1] = '\0';
token->value = value;
token->type = SEPARATOR;
tokens[tokens_index] = *token;
tokens_index++;
printf("FOUND CLOSE PAREN\n");
2024-05-18 20:07:13 +02:00
} else if(isdigit(current[current_index])) {
2024-05-16 20:03:04 +02:00
token = generate_number(current, &current_index);
tokens[tokens_index] = *token;
tokens_index++;
current_index--;
2024-05-18 20:07:13 +02:00
} else if(isalpha(current[current_index])) {
2024-05-16 20:03:04 +02:00
token = generate_keyword(current, &current_index);
tokens[tokens_index] = *token;
tokens_index++;
current_index--;
}
if (token != NULL) {
print_token(*token);
}
current_index++;
}
tokens[tokens_index].type = END_OF_TOKENS;
tokens[tokens_index].value = '\0';
return tokens;
}