42sh/src/expansion/expansion.c

88 lines
2 KiB
C
Raw Normal View History

2026-01-09 13:46:37 +00:00
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2026-01-09 23:12:03 +00:00
#include "../utils/ast/ast.h"
2026-01-09 13:46:37 +00:00
2026-01-09 16:17:38 +00:00
// static size_t var_len(char *start)
// {
// char *iter = start;
// while (*iter != ' ' && *iter != 0)
// *iter++;
// return iter - start;
// }
2026-01-15 18:49:42 +01:00
struct ast_command *expand(struct ast_command *command)
2026-01-09 13:46:37 +00:00
{
2026-01-15 18:49:42 +01:00
if (command == NULL)
2026-01-09 13:46:37 +00:00
return NULL;
bool in_quotes = false;
char *str;
size_t len;
2026-01-15 18:49:42 +01:00
struct list *l = command->command;
2026-01-09 13:46:37 +00:00
while (l != NULL)
{
in_quotes = false;
str = (char *)l->data;
len = strlen(str);
for (size_t i = 0; str[i] != '\0'; i++)
{
if (in_quotes)
{
// do nothing
}
else if (str[i] == '\'')
{
in_quotes = !in_quotes;
memmove(&str[i], &str[i + 1], strlen(&str[i + 1]) + 1);
}
2026-01-09 16:17:38 +00:00
else if (str[i] == '$' && str[i + 1] != 0 && !isspace(str[i + 1]))
2026-01-09 13:46:37 +00:00
{
2026-01-09 16:17:38 +00:00
// size_t len = var_len(str + i + 1);
// char *end = str + i + len + 1;
// char c = *end;
// *end = 0;
// printf("var: %s\n", str + i + 1);
// *end = c;
2026-01-09 13:46:37 +00:00
}
}
if (in_quotes)
{
// error: quote not closed
}
if (len != strlen(str))
{
char *new_str = realloc(str, strlen(str) + 1);
if (new_str == NULL)
{
// error: realloc fail
}
l->data = new_str;
}
l = l->next;
}
2026-01-15 18:49:42 +01:00
return command;
2026-01-09 13:46:37 +00:00
}
2026-01-09 16:17:38 +00:00
// int main()
// {
// printf("Expansion module test\n");
2026-01-15 18:49:42 +01:00
// struct ast_command ast_command;
2026-01-09 16:17:38 +00:00
// // char str[] = "echo Hello $?";
// char str[] = "echo Hello $AE86";
2026-01-15 18:49:42 +01:00
// ast_command.command = list_append(NULL, str);
2026-01-09 16:17:38 +00:00
2026-01-15 18:49:42 +01:00
// struct ast_command *command2 = expand(&ast_command);
// printf("command2: %s\n", (char *)command2->command->data);
2026-01-09 16:17:38 +00:00
// return 0;
// }