feat: parser

This commit is contained in:
Ahurac 2024-10-01 22:00:40 +02:00
parent a3d156eb1f
commit 6672cb3bf8
4 changed files with 80 additions and 0 deletions

View file

@ -1,6 +1,7 @@
#include <stdio.h>
#include <stdlib.h>
#include "parse.h"
#include "reader.h"
int main() {
@ -15,6 +16,17 @@ int main() {
printf("command: '%s'\n", input_line);
struct Args args = parse(input_line);
unsigned int i = 0;
while (i < args.argc) {
if (i != 0) {
printf(" ");
}
printf("%s", args.argv[i]);
i++;
}
printf("\n");
free(input_line);
}
}

51
src/parse.c Normal file
View file

@ -0,0 +1,51 @@
#include "parse.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define ARGV_INIT_SIZE 4
void add_arg(struct Args *args, char *arg_ptr, unsigned int arg_length) {
if (args->argv_size == 0) {
args->argv_size = ARGV_INIT_SIZE;
args->argv = malloc(args->argv_size * sizeof(char *));
}
if (args->argc == args->argv_size) {
args->argv_size *= 2;
args->argv = realloc(args->argv, sizeof(char *) * args->argv_size);
}
char *arg = malloc(arg_length + 1);
strncpy(arg, arg_ptr, arg_length);
args->argv[args->argc] = arg;
args->argc++;
}
void parse_worker(struct Args *args, char *arg_position,
unsigned int arg_length, char *line) {
if (line[0] == '\n') {
add_arg(args, arg_position, arg_length);
return;
} else if (isspace(line[0])) {
add_arg(args, arg_position, arg_length);
while (line[0] != '\n' && isspace(line[0])) {
line++;
}
parse_worker(args, line, 0, line);
} else {
parse_worker(args, arg_position, arg_length + 1, line + 1);
}
}
struct Args parse(char *line) {
struct Args args;
args.argc = 0;
args.argv_size = 0;
parse_worker(&args, line, 0, line);
return args;
}

16
src/parse.h Normal file
View file

@ -0,0 +1,16 @@
#ifndef PARSE_H
#define PARSE_H
#include <sys/types.h>
struct Args {
unsigned int argc;
size_t argv_size;
char **argv;
};
void add_arg(struct Args *args, char *arg_ptr, unsigned int arg_length);
void parse_worker(struct Args *args, char *arg_position, unsigned int arg_length, char *line);
struct Args parse(char *line);
#endif /* PARSE_H */

View file

@ -28,6 +28,7 @@ char *read_a_line(FILE *file_to_read) {
if (!feof(file_to_read)) {
return input_buffer;
} else {
free(input_buffer);
return NULL;
}
}