Compare commits

..

41 commits
parser ... dev

Author SHA1 Message Date
cab8b0c51c doc: Update README 2026-04-24 21:17:10 +02:00
matteo
b12733cad4 feat(exec): export 2026-01-31 20:52:03 +01:00
matteo
08cc18bd21 Merge remote-tracking branch 'origin/exec-unset' into dev 2026-01-31 20:06:07 +01:00
william.valenduc
4bb3ee85cf fix: utils build error 2026-01-31 20:05:19 +01:00
matteo
c7822a2534 feat(main_loop): subshell start 2026-01-31 20:05:19 +01:00
Jean
c8d0285447 fix(while/until) 2026-01-31 20:04:48 +01:00
matteo
a7065a1d9f feat: subshell total support 2026-01-31 19:55:02 +01:00
matteo
3e42b6fd00 feat(parser): ast_subshell 2026-01-31 19:55:02 +01:00
william.valenduc
19addf8e6f fix: expand tests ast_create_command 2026-01-31 18:51:03 +00:00
william.valenduc
45d97fcc3f feat(utils): hash_map_free_ast 2026-01-31 18:30:28 +00:00
matteo
5eed5fa65f feat: ast_subshell 2026-01-31 19:25:42 +01:00
william.valenduc
bb7d4b772e feat(expansion): parse_subshell_str and tests 2026-01-31 17:31:55 +00:00
Gu://em_
2e7bcd7fa1 feat: Merge remote-tracking branch 'origin/exec-exit' into dev 2026-01-31 18:28:44 +01:00
Gu://em_
3b62c56756 feat: exit builtin 2026-01-31 18:27:48 +01:00
Jean
1f4742e17b feat(exec): Added the unset builtin 2026-01-31 18:17:43 +01:00
matteo
17f8b918c8 feat(testing): more loops tests 2026-01-31 17:29:21 +01:00
matteo
4d01199e21 fix(ast_function): ast_function_free does not free the ast data 2026-01-31 17:06:42 +01:00
Jean
16381f4f3e Merge branch 'dev' of gitlab.cri.epita.fr:guillem.george/42sh into dev 2026-01-31 16:47:16 +01:00
Jean
5df65f41c9 feat(execution): Implemented break and continue for while 2026-01-31 16:43:52 +01:00
Gu://em_
b6305c2453 fix: moved test scripts to functionnal testing 2026-01-31 16:35:34 +01:00
Jean
37e430a234 removed the warning 2026-01-31 15:47:23 +01:00
Jean
46dbc7ad6b Merge branch 'dev' of gitlab.cri.epita.fr:guillem.george/42sh into dev 2026-01-31 15:41:52 +01:00
Jean
182e31b42e fix(chaipa): Remove pretty print to avoid clang-tidy / added the options in echo 2026-01-31 15:40:46 +01:00
matteo
7a370b1dfa Merge branch 'parser' into dev 2026-01-31 13:26:14 +01:00
matteo
567bd44fce fix(parser): typo 2026-01-31 13:26:02 +01:00
matteo
132f4f3a53 feat(parser + ast): function parsing support 2026-01-31 13:24:44 +01:00
Matteo Flebus
3cd231f031 fix: build and .sh test file for functions 2026-01-31 12:53:23 +01:00
matteo
a63632005c Merge branch 'ast' into dev 2026-01-31 11:58:40 +01:00
matteo
a550f9747e feat(ast): ast_function 2026-01-31 11:57:51 +01:00
matteo
93f280f59d sh file to test loops 2026-01-31 11:34:24 +01:00
matteo
4289700e2e fix(lexer): destroy_lexer_context now fully functional 2026-01-31 11:09:08 +01:00
Matteo Flebus
5de6ef2bb5 fix: lexer_context also freed after normal execution... -_- 2026-01-31 11:02:19 +01:00
matteo
d95b0fd220 fix: lexer_context is now freed on errors 2026-01-31 10:59:45 +01:00
Matteo Flebus
64e3fb26c3 feat(tests): sh file for function testing 2026-01-31 10:48:58 +01:00
Gu://em_
f31fca4204 feat: full while/until loops support, important bug fixes and more tests 2026-01-30 23:43:49 +01:00
Gu://em_
9e522b2a68 feat: lexer support for loops keywords 2026-01-30 22:55:07 +01:00
Gu://em_
d6e6bfacf2 feat: Merge branch 'parser' into dev 2026-01-30 21:32:57 +01:00
Matteo Flebus
828b0e8be3 fix: coverage tests and hash_map_free on NULL 2026-01-30 20:28:38 +01:00
Matteo Flebus
834b6585c5 merge unit_tests in dev 2026-01-30 20:21:07 +01:00
Matteo Flebus
4870caa459 fix(lexer): and is now detected properly 2026-01-30 20:18:10 +01:00
william.valenduc
567192b771 feat(vars): unit tests 2026-01-29 11:18:33 +00:00
37 changed files with 1073 additions and 259 deletions

View file

@ -1,11 +1,12 @@
# 42sh - A POSIX shell with a bad name # 42sh - A POSIX shell with a bad name
42sh is a shcool project aiming to implement a POSIX compliant shell in C. 42sh is a project aiming to implement a POSIX-compliant shell written in C with only the standard library.
Source de is fully documented with the doxygen format so you can easily understand how the project works by exploring it.
> **Note** This is a school project, therefore it probably won't interest you if you are looking for something useful.
## Getting started ## Getting started
TODO
### Build ### Build
run this command: run this command:
`autoreconf --force --verbose --install` `autoreconf --force --verbose --install`
@ -16,27 +17,43 @@ run this command:
then: then:
`make` `make`
#### asan #### Build with ASan
run this command: run this command:
`./configure CFLAGS='-std=c99 -Werror -Wall -Wextra -Wvla -g -fsanitize=address'` `./configure CFLAGS='-std=c99 -Werror -Wall -Wextra -Wvla -g -fsanitize=address'`
or for MacOS (Jean Here): or for MacOS (Jean Here):
`./configure CFLAGS='-std=c99 -Werror -Wall -Wextra -Wvla -I/opt/homebrew/include' LDFLAGS='-L/opt/homebrew/lib'` `./configure CFLAGS='-std=c99 -Werror -Wall -Wextra -Wvla -I/opt/homebrew/include' LDFLAGS='-L/opt/homebrew/lib'`
then: then:
`make check` `make check`
## Project status
### Implemented features
* **Command Execution:** `$PATH` search and binary execution (via `fork` and `execvp`) with error return code handling.
* **Built-ins:** Native implementation of `echo`, `cd`, `exit`, `export`, `unset`, `set`, `.`, `true`, `false`, as well as loop management with `break` and `continue`.
* **Control Structures:** * Conditions: `if / then / elif / else / fi`.
* Loops: `while`, `until` and `for`.
* **Logical Operators:** Command chaining with `&&`, `||` and negation with `!`.
* **Pipelines and Redirections:** * Full management of pipes `|` to connect the output of one process to the input of another.
* Single and multiple redirections: `>`, `<`, `>>`, `>&`, `<&`, `<>`.
* **Variables Management:** Assignment, variable expansion, and special variables handling like `$?` (return code of the last command).
* **Command Grouping:** Execution blocks `{ ... }` and subshells creation `( ... )`.
* **Quoting:** Support for weak (`"`) and strong (`'`) quoting for special characters escaping.
## Architecture
The shell operates on a classic compilation/interpretation pipeline:
1. **Lexer (Lexical Analysis):** Reads standard input (or script) character by character and generates a stream of "Tokens" (Words, Operators, Redirections).
2. **Parser (Syntax Analysis):** Syntax analyzer that transforms the token stream into a complex Abstract Syntax Tree (AST). This module strictly manages the nesting of control structures and enforces the rigid grammar of the Shell Command Language.
3. **Execution (AST Traversal):** The tree is traversed recursively. Redirections modify file descriptors (`dup2`), child processes are created (`fork`), and commands are executed.
## Authors ## Authors
- Guillem George
- Matteo Flebus - Matteo Flebus
- Jean Herail - Jean Herail
- William Valenduc - William Valenduc
- Guillem George
## Project status
WIP
## TODO
# Autotools
implement functions in all .c files to see if everything compiles.

View file

@ -18,9 +18,9 @@ bin_PROGRAMS = 42sh
parser/libparser.a \ parser/libparser.a \
lexer/liblexer.a \ lexer/liblexer.a \
io_backend/libio_backend.a \ io_backend/libio_backend.a \
utils/libutils.a \
execution/libexecution.a \ execution/libexecution.a \
expansion/libexpansion.a \ expansion/libexpansion.a
utils/libutils.a
# ================ TESTS ================ # ================ TESTS ================
@ -36,13 +36,13 @@ check_PROGRAMS = testsuite
testsuite_SOURCES = ../tests/unit/utils/utils_tests.c \ testsuite_SOURCES = ../tests/unit/utils/utils_tests.c \
../tests/unit/expansion/parse_var.c \ ../tests/unit/expansion/parse_var.c \
../tests/unit/io_backend/io_backend.c \
../tests/unit/utils/args.c \ ../tests/unit/utils/args.c \
../tests/unit/utils/hash_map.c \ ../tests/unit/utils/hash_map.c \
../tests/unit/utils/insert_into.c ../tests/unit/utils/insert_into.c
# ../tests/unit/lexer/lexer_tests.c # ../tests/unit/lexer/lexer_tests.c
# ../tests/unit/expansion/expand.c # ../tests/unit/expansion/expand.c
# ../tests/unit/io_backend/io_backend.c
testsuite_CPPFLAGS = $(42sh_CPPFLAGS) testsuite_CPPFLAGS = $(42sh_CPPFLAGS)

View file

@ -1,18 +1,15 @@
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
#include "execution.h" #include "execution.h"
#include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <unistd.h> #include <unistd.h>
#include "../expansion/expansion.h" #include "../expansion/expansion.h"
#include "../utils/ast/ast.h"
#include "../utils/hash_map/hash_map.h" #include "../utils/hash_map/hash_map.h"
#include "../utils/vars/vars.h"
// Refactored: delegates to helpers in execution_helpers.c // Refactored: delegates to helpers in execution_helpers.c
#include "execution_helpers.h" #include "execution_helpers.h"
@ -22,25 +19,55 @@ int execution(struct ast *ast, struct hash_map *vars)
if (!ast) if (!ast)
return 0; return 0;
int res;
switch (ast->type) switch (ast->type)
{ {
case AST_VOID: case AST_VOID:
case AST_END: case AST_END:
return 0; res = 0;
break;
case AST_CMD: { case AST_CMD: {
struct ast_command *command = ast_get_command(ast); struct ast_command *command = ast_get_command(ast);
if (!expand(command, vars)) if (!expand(command, vars))
fprintf(stderr, "Error: Variable expansion failed\n"); fprintf(stderr, "Error: Variable expansion failed\n");
return exec_ast_command(command, vars); res = exec_ast_command(command, vars);
break;
} }
case AST_IF: case AST_IF:
return exec_ast_if(ast_get_if(ast), vars); res = exec_ast_if(ast_get_if(ast), vars);
break;
case AST_LIST: case AST_LIST:
return exec_ast_list(ast_get_list(ast), vars); res = exec_ast_list(ast_get_list(ast), vars);
break;
case AST_AND_OR: case AST_AND_OR:
return exec_ast_and_or(ast_get_and_or(ast), vars); res = exec_ast_and_or(ast_get_and_or(ast), vars);
break;
case AST_LOOP:
res = exec_ast_loop(ast_get_loop(ast), vars);
break;
case AST_SUBSHELL:
res = exec_ast_subshell(ast_get_subshell(ast), vars);
break;
default: default:
return 127; res = 127;
break;
}
if (res == EXEC_SIGNAL_EXIT)
{
char *exit_val_str = get_var(vars, "EXIT_VALUE");
if (exit_val_str == NULL)
{
fprintf(
stderr,
"Internal error: could not retrieve return value from exit\n");
return 2;
}
return atoi(exit_val_str);
}
else
{
return res;
} }
} }

View file

@ -1,21 +1,21 @@
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
#include "execution_helpers.h" #include "execution_helpers.h"
#include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <unistd.h> #include <unistd.h>
#include "../expansion/expansion.h"
#include "../utils/ast/ast.h"
#include "../utils/hash_map/hash_map.h" #include "../utils/hash_map/hash_map.h"
#include "../utils/lists/lists.h" #include "../utils/lists/lists.h"
#include "../utils/vars/vars.h" #include "../utils/vars/vars.h"
#include "execution.h" #include "execution.h"
// === Static functions
static int open_redir_file(const struct ast_redir *redir, int *flags, int *mode) static int open_redir_file(const struct ast_redir *redir, int *flags, int *mode)
{ {
*mode = 0644; *mode = 0644;
@ -123,8 +123,36 @@ static char **list_to_argv(struct list *command_list)
return argv; return argv;
} }
/*
* @brief parses string and returns the represented (unsigned) number
* @return the number contained by the string or -1 if number is invalid
*/
static int atou(char *str)
{
if (str == NULL || *str == '\0')
return -1;
int result = 0;
size_t i = 0;
while (str[i] != '\0')
{
if (str[i] < '0' || str[i] > '9')
return -1;
result *= 10;
result += str[i] - '0';
i++;
}
return result;
}
static int try_builtin(char **argv, struct hash_map *vars); static int try_builtin(char **argv, struct hash_map *vars);
static int builtin_break(char **argv);
static int builtin_continue(char **argv);
static int builtin_unset(char **argv, struct hash_map *vars);
static int exec_assignment(struct list *assignment_list, struct hash_map *vars) static int exec_assignment(struct list *assignment_list, struct hash_map *vars)
{ {
while (assignment_list != NULL) while (assignment_list != NULL)
@ -137,12 +165,18 @@ static int exec_assignment(struct list *assignment_list, struct hash_map *vars)
struct ast_assignment *assignment = struct ast_assignment *assignment =
ast_get_assignment(assignment_list->data); ast_get_assignment(assignment_list->data);
if (assignment->global)
{
setenv(assignment->name, assignment->value, 1);
}
set_var_copy(vars, assignment->name, assignment->value); set_var_copy(vars, assignment->name, assignment->value);
assignment_list = assignment_list->next; assignment_list = assignment_list->next;
} }
return 0; return 0;
} }
// === Functions
int exec_ast_command(struct ast_command *command, struct hash_map *vars) int exec_ast_command(struct ast_command *command, struct hash_map *vars)
{ {
exec_assignment(command->assignments, vars); exec_assignment(command->assignments, vars);
@ -204,10 +238,46 @@ int exec_ast_if(struct ast_if *if_node, struct hash_map *vars)
if (if_node == NULL) if (if_node == NULL)
return 2; return 2;
int cond = execution(if_node->condition, vars); int cond = execution(if_node->condition, vars);
if (cond == EXEC_SIGNAL_BREAK || cond == EXEC_SIGNAL_CONTINUE
|| cond == EXEC_SIGNAL_EXIT)
return cond;
if (cond == 0) if (cond == 0)
return execution(if_node->then_clause, vars); {
int r = execution(if_node->then_clause, vars);
return r;
}
else else
return execution(if_node->else_clause, vars); {
int r = execution(if_node->else_clause, vars);
return r;
}
}
int exec_ast_subshell(struct ast_subshell *subshell_node,
struct hash_map *vars)
{
pid_t pid = fork();
if (pid < 0)
{
perror("fork");
return 1;
}
if (pid == 0)
{
int res = execution(subshell_node->child, vars);
_exit(res);
}
int status = 0;
waitpid(pid, &status, 0);
if (WIFEXITED(status))
{
return WEXITSTATUS(status);
}
return 1;
} }
int exec_ast_list(struct ast_list *list_node, struct hash_map *vars) int exec_ast_list(struct ast_list *list_node, struct hash_map *vars)
@ -218,7 +288,14 @@ int exec_ast_list(struct ast_list *list_node, struct hash_map *vars)
{ {
struct ast *child = (struct ast *)cur->data; struct ast *child = (struct ast *)cur->data;
if (!ast_is_void(child)) if (!ast_is_void(child))
ret = execution(child, vars); {
int child_ret = execution(child, vars);
if (child_ret == EXEC_SIGNAL_BREAK
|| child_ret == EXEC_SIGNAL_CONTINUE
|| child_ret == EXEC_SIGNAL_EXIT)
return child_ret;
ret = child_ret;
}
cur = cur->next; cur = cur->next;
} }
return ret; return ret;
@ -227,16 +304,25 @@ int exec_ast_list(struct ast_list *list_node, struct hash_map *vars)
int exec_ast_and_or(struct ast_and_or *ao_node, struct hash_map *vars) int exec_ast_and_or(struct ast_and_or *ao_node, struct hash_map *vars)
{ {
int left_ret = execution(ao_node->left, vars); int left_ret = execution(ao_node->left, vars);
if (left_ret == EXEC_SIGNAL_BREAK || left_ret == EXEC_SIGNAL_CONTINUE
|| left_ret == EXEC_SIGNAL_EXIT)
return left_ret;
if (ao_node->type == AST_AND_OR_TYPE_AND) if (ao_node->type == AST_AND_OR_TYPE_AND)
{ {
if (left_ret == 0) if (left_ret == 0)
return execution(ao_node->right, vars); {
int right_ret = execution(ao_node->right, vars);
return right_ret;
}
return left_ret; return left_ret;
} }
else else
{ {
if (left_ret != 0) if (left_ret != 0)
return execution(ao_node->right, vars); {
int right_ret = execution(ao_node->right, vars);
return right_ret;
}
return left_ret; return left_ret;
} }
} }
@ -275,21 +361,117 @@ void unset_all_redir(struct list *redir_list)
} }
} }
int exec_ast_loop(struct ast_loop *loop_node, struct hash_map *vars)
{
int res = 0;
while (execution(loop_node->condition, vars) == 0)
{
res = execution(loop_node->body, vars);
if (res == EXEC_SIGNAL_BREAK)
{
res = 0;
break;
}
else if (res == EXEC_SIGNAL_CONTINUE)
{
res = 0;
continue;
}
}
return res;
}
// --- Builtins --- // --- Builtins ---
static void print_with_escapes(const char *str)
{
while (*str)
{
if (*str == '\\')
{
str++;
if (*str == 'n')
putchar('\n');
else if (*str == 't')
putchar('\t');
else if (*str == '\\')
putchar('\\');
else if (*str == 'a')
putchar('\a');
else if (*str == 'b')
putchar('\b');
else if (*str == 'f')
putchar('\f');
else if (*str == 'r')
putchar('\r');
else if (*str == 'v')
putchar('\v');
else if (*str == 'c')
return; // stop printing
else
{
// unrecognized escape, print "\"" and the char
putchar('\\');
if (*str)
putchar(*str);
}
}
else
{
putchar(*str);
}
str++;
}
}
static int builtin_echo(char **argv) static int builtin_echo(char **argv)
{ {
bool newline = true; bool newline = true;
bool interpret_escapes = false;
int i = 1; int i = 1;
if (argv[1] && strcmp(argv[1], "-n") == 0) // Parse options
while (argv[i] && argv[i][0] == '-')
{
char *opt = argv[i] + 1; // skip "-"
bool valid_option = false;
while (*opt)
{
if (*opt == 'n')
{ {
newline = false; newline = false;
valid_option = true;
}
else if (*opt == 'e')
{
interpret_escapes = true;
valid_option = true;
}
else if (*opt == 'E')
{
interpret_escapes = false;
valid_option = true;
}
else
{
// invalid option so euh treat as regular argument
valid_option = false;
break;
}
opt++;
}
if (!valid_option)
break; // stop parsing options
i++; i++;
} }
// Print arguments
for (; argv[i]; i++) for (; argv[i]; i++)
{ {
if (interpret_escapes)
print_with_escapes(argv[i]);
else
printf("%s", argv[i]); printf("%s", argv[i]);
if (argv[i + 1]) if (argv[i + 1])
printf(" "); printf(" ");
@ -301,6 +483,18 @@ static int builtin_echo(char **argv)
return 0; return 0;
} }
static int builtin_break(char **argv)
{
(void)argv;
return EXEC_SIGNAL_BREAK;
}
static int builtin_continue(char **argv)
{
(void)argv;
return EXEC_SIGNAL_CONTINUE;
}
static int builtin_true(char **argv) static int builtin_true(char **argv)
{ {
(void)argv; (void)argv;
@ -313,13 +507,21 @@ static int builtin_false(char **argv)
return 1; return 1;
} }
static int builtin_exit(char **argv) static int builtin_exit(char **argv, struct hash_map *vars)
{ {
int exit_val = 0; int exit_val = 0;
if (argv[1]) if (argv[1])
exit_val = atoi(argv[1]); {
exit(exit_val); exit_val = atou(argv[1]);
return exit_val; if (exit_val == -1)
{
fprintf(stderr, "exit: Illegal number %s\n", argv[1]);
return 2;
}
}
set_var_int(vars, "EXIT_VALUE", exit_val);
return EXEC_SIGNAL_EXIT;
} }
static int builtin_cd(char **argv, struct hash_map *vars) static int builtin_cd(char **argv, struct hash_map *vars)
@ -346,6 +548,23 @@ static int builtin_cd(char **argv, struct hash_map *vars)
return 0; return 0;
} }
static int builtin_unset(char **argv, struct hash_map *vars)
{
if (!argv)
return 0;
for (int i = 1; argv[i]; i++)
{
const char *name = argv[i];
if (name == NULL || name[0] == '\0')
continue;
// remove from shell variables
hash_map_remove(vars, name);
// remove from environment variables
unsetenv(name);
}
return 0;
}
/** /**
* @brief Tries to execute a builtin command if the command matches a builtin * @brief Tries to execute a builtin command if the command matches a builtin
* *
@ -359,12 +578,18 @@ static int try_builtin(char **argv, struct hash_map *vars)
if (strcmp(argv[0], "echo") == 0) if (strcmp(argv[0], "echo") == 0)
return builtin_echo(argv); return builtin_echo(argv);
if (strcmp(argv[0], "unset") == 0)
return builtin_unset(argv, vars);
if (strcmp(argv[0], "true") == 0) if (strcmp(argv[0], "true") == 0)
return builtin_true(argv); return builtin_true(argv);
if (strcmp(argv[0], "false") == 0) if (strcmp(argv[0], "false") == 0)
return builtin_false(argv); return builtin_false(argv);
if (strcmp(argv[0], "break") == 0)
return builtin_break(argv);
if (strcmp(argv[0], "continue") == 0)
return builtin_continue(argv);
if (strcmp(argv[0], "exit") == 0) if (strcmp(argv[0], "exit") == 0)
return builtin_exit(argv); return builtin_exit(argv, vars);
if (strcmp(argv[0], "cd") == 0) if (strcmp(argv[0], "cd") == 0)
return builtin_cd(argv, vars); return builtin_cd(argv, vars);

View file

@ -4,10 +4,18 @@
#include "../utils/ast/ast.h" #include "../utils/ast/ast.h"
#include "../utils/hash_map/hash_map.h" #include "../utils/hash_map/hash_map.h"
// Special execution signals used internally to implement loop control
#define EXEC_SIGNAL_CONTINUE (-2)
#define EXEC_SIGNAL_BREAK (-3)
#define EXEC_SIGNAL_EXIT (-4)
int exec_ast_command(struct ast_command *command, struct hash_map *vars); int exec_ast_command(struct ast_command *command, struct hash_map *vars);
int exec_ast_if(struct ast_if *if_node, struct hash_map *vars); int exec_ast_if(struct ast_if *if_node, struct hash_map *vars);
int exec_ast_list(struct ast_list *list_node, struct hash_map *vars); int exec_ast_list(struct ast_list *list_node, struct hash_map *vars);
int exec_ast_and_or(struct ast_and_or *ao_node, struct hash_map *vars); int exec_ast_and_or(struct ast_and_or *ao_node, struct hash_map *vars);
int exec_ast_loop(struct ast_loop *loop_node, struct hash_map *vars);
int exec_ast_subshell(struct ast_subshell *subshell_node,
struct hash_map *vars);
void unset_all_redir(struct list *redir_list); void unset_all_redir(struct list *redir_list);
#endif // EXECUTION_HELPERS_H #endif // EXECUTION_HELPERS_H

View file

@ -1,4 +1,6 @@
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
#include "expansion.h"
#include <ctype.h> #include <ctype.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h> #include <stdio.h>
@ -115,6 +117,40 @@ static bool expand_var(char **str, size_t pos, const struct hash_map *vars)
return false; return false;
} }
size_t parse_subshell_str(char *str, char **res)
{
size_t i = 1; // skip the '('
int paren_count = 1;
if (str[i] == ')')
{
// empty subshell
*res = NULL;
return 0;
}
while (str[i] != 0)
{
if (str[i] == '(')
paren_count++;
else if (str[i] == ')')
{
paren_count--;
if (paren_count == 0)
{
*res = strndup(str + 1, i - 1);
return i + 1;
}
}
i++;
}
// error: parenthesis not closed
*res = NULL;
return 0;
}
bool expand(struct ast_command *command, const struct hash_map *vars) bool expand(struct ast_command *command, const struct hash_map *vars)
{ {
if (command == NULL) if (command == NULL)
@ -122,34 +158,42 @@ bool expand(struct ast_command *command, const struct hash_map *vars)
char *str; char *str;
size_t len; size_t len;
bool in_quotes; enum quote_state quotes;
struct list *l = command->command; struct list *l = command->command;
while (l != NULL) while (l != NULL)
{ {
in_quotes = false; quotes = NO_QUOTE;
str = (char *)l->data; str = (char *)l->data;
len = strlen(str); len = strlen(str);
for (size_t i = 0; str[i] != 0; i++) for (size_t i = 0; str[i] != 0; i++)
{ {
if (str[i] == '\'') if (str[i] == '\'' || str[i] == '\"')
{ {
// remove single quote if (quotes == NO_QUOTE)
in_quotes = !in_quotes; {
quotes = (str[i] == '\'') ? SINGLE_QUOTE : DOUBLE_QUOTE;
}
else if ((quotes == SINGLE_QUOTE && str[i] == '\'')
|| (quotes == DOUBLE_QUOTE && str[i] == '\"'))
{
quotes = NO_QUOTE;
}
else
{
// inside the other quote type, do nothing
continue;
}
// remove quote
memmove(str + i, str + i + 1, strlen(str + i + 1) + 1); memmove(str + i, str + i + 1, strlen(str + i + 1) + 1);
i--; i--;
} }
else if (in_quotes) else if (quotes == SINGLE_QUOTE)
{ {
continue; // do nothing continue; // do nothing
} }
else if (str[i] == '\"')
{
// remove double quote
memmove(str + i, str + i + 1, strlen(str + i + 1) + 1);
i--;
}
else if (str[i] == '$' && str[i + 1] != 0 && !isspace(str[i + 1])) else if (str[i] == '$' && str[i + 1] != 0 && !isspace(str[i + 1]))
{ {
// variable expansion // variable expansion
@ -161,21 +205,20 @@ bool expand(struct ast_command *command, const struct hash_map *vars)
} }
} }
if (in_quotes) // if (quotes != NO_QUOTE)
{ // {
// error: quote not closed // // error: quote not closed
fprintf(stderr, "Error: quote not closed in string: %s\n", str); // fprintf(stderr, "Error: quote not closed in string: %s\n", str);
return false; // return false;
} // }
if (len != strlen(str)) if (len != strlen(str))
{ {
char *new_str = realloc(str, strlen(str) + 1); char *new_str = realloc(str, strlen(str) + 1);
if (new_str == NULL) if (new_str == NULL)
{
// error: realloc fail // error: realloc fail
return false; return false;
}
l->data = new_str; l->data = new_str;
} }

View file

@ -7,6 +7,13 @@
#include "../utils/ast/ast.h" #include "../utils/ast/ast.h"
#include "../utils/hash_map/hash_map.h" #include "../utils/hash_map/hash_map.h"
enum quote_state
{
NO_QUOTE,
SINGLE_QUOTE,
DOUBLE_QUOTE
};
/** /**
* Parse a variable from a string starting with '$'. * Parse a variable from a string starting with '$'.
* @param str The input string starting with '$'. It must start with '$'. * @param str The input string starting with '$'. It must start with '$'.
@ -16,6 +23,15 @@
*/ */
size_t parse_var_name(char *str, char **res); size_t parse_var_name(char *str, char **res);
/**
* Parse a subshell string enclosed in parentheses.
* @param str The input string starting with '('. It must start with '('.
* @param res Pointer to a char pointer that will be set to the extracted
* subshell string.
* @return The number of characters processed in the input string.
*/
size_t parse_subshell_str(char *str, char **res);
/** /**
* Expand variables in an AST command using the provided variable map. * Expand variables in an AST command using the provided variable map.
* @param command The AST command to expand. * @param command The AST command to expand.

View file

@ -72,6 +72,16 @@ static void set_token_keyword(struct token *tok, char *begin, ssize_t size)
tok->type = TOKEN_ELSE; tok->type = TOKEN_ELSE;
else if (strncmp(begin, "elif", size) == 0 && size == 4) else if (strncmp(begin, "elif", size) == 0 && size == 4)
tok->type = TOKEN_ELIF; tok->type = TOKEN_ELIF;
else if (strncmp(begin, "for", size) == 0 && size == 3)
tok->type = TOKEN_FOR;
else if (strncmp(begin, "while", size) == 0 && size == 5)
tok->type = TOKEN_WHILE;
else if (strncmp(begin, "until", size) == 0 && size == 5)
tok->type = TOKEN_UNTIL;
else if (strncmp(begin, "do", size) == 0 && size == 2)
tok->type = TOKEN_DO;
else if (strncmp(begin, "done", size) == 0 && size == 4)
tok->type = TOKEN_DONE;
else if (strncmp(begin, "export", size) == 0 && size == 6) else if (strncmp(begin, "export", size) == 0 && size == 6)
tok->type = TOKEN_EXPORT; tok->type = TOKEN_EXPORT;
@ -247,16 +257,17 @@ struct token *new_token(char *begin, ssize_t size, struct token_info *info)
return tok; return tok;
} }
void destroy_lexer_context(struct lexer_context **ctx) void destroy_lexer_context(struct lexer_context *ctx)
{ {
if (ctx == NULL || *ctx == NULL) struct token *prev = ctx->previous_token;
struct token *cur = ctx->current_token;
if (ctx == NULL)
return; return;
if ((*ctx)->previous_token != NULL) if (prev != NULL)
free((*ctx)->previous_token); free_token(&prev);
if ((*ctx)->current_token != NULL) if (cur != NULL)
free((*ctx)->current_token); free_token(&cur);
free(*ctx); free(ctx);
*ctx = NULL;
} }
void free_token(struct token **tok) void free_token(struct token **tok)
@ -298,7 +309,7 @@ ssize_t len_op_sepchar(char *stream, ssize_t i)
return 2; return 2;
// AND // AND
if (stream[i] == '|' && stream[i + 1] == '|') if (stream[i] == '&' && stream[i + 1] == '&')
return 2; return 2;
// special chars // special chars

View file

@ -16,7 +16,7 @@ struct lexer_context
/* @brief: frees all fields of ctx and sets ctx to NULL. /* @brief: frees all fields of ctx and sets ctx to NULL.
*/ */
void destroy_lexer_context(struct lexer_context **ctx); void destroy_lexer_context(struct lexer_context *ctx);
enum lexing_mode enum lexing_mode
{ {

View file

@ -7,74 +7,9 @@
#include "lexer/lexer.h" #include "lexer/lexer.h"
#include "parser/parser.h" #include "parser/parser.h"
#include "utils/args/args.h" #include "utils/args/args.h"
#include "utils/main_loop/main_loop.h"
#include "utils/vars/vars.h" #include "utils/vars/vars.h"
// === Error codes
#define SUCCESS 0
#define ERR_INPUT_PROCESSING 2
#define ERR_MALLOC 3
#define ERR_GENERIC 4
// === Functions
/* @brief: frees the hash map.
* @return: always ERR_INPUT_PROCESSING.
*/
static int err_input(struct hash_map **vars)
{
hash_map_free(vars);
return ERR_INPUT_PROCESSING;
}
static int main_loop(struct lexer_context *ctx, struct args_options *options,
struct hash_map *vars)
{
int return_code = SUCCESS;
// init parser
if (!parser_init())
{
perror("parser initialization failed.");
}
// Retrieve and build first AST
struct ast *command_ast = get_ast(ctx);
if (options->pretty_print)
{
ast_print_dot(command_ast);
}
// Main parse-execute loop
while (command_ast != NULL && command_ast->type != AST_END)
{
if (command_ast->type != AST_VOID)
{
// Execute AST
return_code = execution(command_ast, vars);
// set $? variable
set_var_int(vars, "?", return_code);
}
ast_free(&command_ast);
// Retrieve and build next AST
command_ast = get_ast(ctx);
}
if (command_ast == NULL)
return err_input(&vars);
// === free
ast_free(&command_ast);
parser_close();
hash_map_free(&vars);
return return_code;
}
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -90,7 +25,7 @@ int main(int argc, char **argv)
if (return_code != 0) if (return_code != 0)
{ {
print_usage(stderr, argv[0]); print_usage(stderr, argv[0]);
return err_input(&vars); return err_input(&vars, NULL);
} }
// args_print(&options); // args_print(&options);
@ -105,7 +40,7 @@ int main(int argc, char **argv)
{ {
fprintf(stderr, fprintf(stderr,
"Error: Failed to configure IO Backend from arguments\n"); "Error: Failed to configure IO Backend from arguments\n");
return err_input(&vars); return err_input(&vars, NULL);
} }
// Init IO Backend (with the context struct) // Init IO Backend (with the context struct)
@ -115,13 +50,22 @@ int main(int argc, char **argv)
fprintf(stderr, fprintf(stderr,
"Error: IO Backend initialization failed with code %d\n", "Error: IO Backend initialization failed with code %d\n",
return_code); return_code);
return err_input(&vars); return err_input(&vars, NULL);
} }
// init lexer context // init lexer context
struct lexer_context ctx = { 0 }; struct lexer_context *ctx = calloc(1, sizeof(struct lexer_context));
return_code = main_loop(&ctx, &options, vars); // init parser
if (!parser_init())
{
perror("parser initialization failed.");
return err_input(&vars, ctx);
}
return_code = main_loop(ctx, vars);
parser_close();
return return_code; return return_code;
} }

View file

@ -101,17 +101,13 @@ static void add_first_redir(void)
add_first(RULE_REDIRECTION, TOKEN_REDIR_RIGHT_PIPE); add_first(RULE_REDIRECTION, TOKEN_REDIR_RIGHT_PIPE);
} }
// === Functions // Adds only direct tokens to rules firsts into the firsts map
static void add_firsts_tokens(void)
int grammar_init(void)
{ {
// Initialize the firsts map // Redirection
bool success = init_firsts_map(); add_first_redir();
if (success != true) // %RIP Matteo 30/01/2026
return false; // %RAX Guillem 30/01/2026 hehe
// Populate the firsts map
// TODO CHECK ORDER
// If // If
add_first(RULE_IF, TOKEN_IF); add_first(RULE_IF, TOKEN_IF);
@ -127,7 +123,7 @@ int grammar_init(void)
add_first(RULE_WHILE, TOKEN_WHILE); add_first(RULE_WHILE, TOKEN_WHILE);
// Until // Until
add_first(RULE_WHILE, TOKEN_UNTIL); add_first(RULE_UNTIL, TOKEN_UNTIL);
// Case // Case
add_first(RULE_CASE, TOKEN_CASE); add_first(RULE_CASE, TOKEN_CASE);
@ -136,33 +132,57 @@ int grammar_init(void)
add_first(RULE_CASE_ITEM, TOKEN_LEFT_PAREN); add_first(RULE_CASE_ITEM, TOKEN_LEFT_PAREN);
add_first(RULE_CASE_ITEM, TOKEN_WORD); add_first(RULE_CASE_ITEM, TOKEN_WORD);
// Case clause // Shell command
add_firsts(RULE_CASE_CLAUSE, first(RULE_CASE_ITEM)); add_first(RULE_SHELL_COMMAND, TOKEN_LEFT_BRACKET);
add_first(RULE_SHELL_COMMAND, TOKEN_LEFT_PAREN);
// Redirection // Simple command
add_first_redir(); add_first(RULE_SIMPLE_COMMAND, TOKEN_WORD);
// %RIP Matteo 30/01/2026 add_first(RULE_SIMPLE_COMMAND, TOKEN_EXPORT);
// %RAX Guillem 30/01/2026 hehe
// Element // Element
add_first(RULE_ELEMENT, TOKEN_WORD); add_first(RULE_ELEMENT, TOKEN_WORD);
add_first(RULE_ELEMENT, TOKEN_ASSIGNMENT_WORD); add_first(RULE_ELEMENT, TOKEN_ASSIGNMENT_WORD);
add_firsts(RULE_ELEMENT, first(RULE_REDIRECTION));
// Prefix // Prefix
add_first(RULE_PREFIX, TOKEN_ASSIGNMENT_WORD); add_first(RULE_PREFIX, TOKEN_ASSIGNMENT_WORD);
// Pipeline
add_first(RULE_PIPELINE, TOKEN_WORD);
// Compound list
add_first(RULE_COMPOUND_LIST, TOKEN_NEWLINE);
// Input
add_first(RULE_INPUT, TOKEN_NEWLINE);
add_first(RULE_INPUT, TOKEN_EOF);
// Funcdec
add_first(RULE_FUNCDEC, TOKEN_WORD);
}
// Adds only firsts that depend on other rules to the firsts map
// WARNING order matters
static void add_firsts_rec(void)
{
// Case clause
add_firsts(RULE_CASE_CLAUSE, first(RULE_CASE_ITEM));
// Element
add_firsts(RULE_ELEMENT, first(RULE_REDIRECTION));
// Prefix
add_firsts(RULE_PREFIX, first(RULE_REDIRECTION)); add_firsts(RULE_PREFIX, first(RULE_REDIRECTION));
// Shell command // Shell command
add_firsts(RULE_SHELL_COMMAND, first(RULE_IF)); add_firsts(RULE_SHELL_COMMAND, first(RULE_IF));
add_firsts(RULE_SHELL_COMMAND, first(RULE_FOR));
add_firsts(RULE_SHELL_COMMAND, first(RULE_WHILE));
add_firsts(RULE_SHELL_COMMAND, first(RULE_UNTIL));
add_firsts(RULE_SHELL_COMMAND, first(RULE_CASE));
// Simple command // Simple command
add_firsts(RULE_SIMPLE_COMMAND, first(RULE_PREFIX)); add_firsts(RULE_SIMPLE_COMMAND, first(RULE_PREFIX));
add_first(RULE_SIMPLE_COMMAND, TOKEN_WORD);
add_first(RULE_SIMPLE_COMMAND, TOKEN_EXPORT);
// Funcdec
add_first(RULE_FUNCDEC, TOKEN_WORD);
// Command // Command
add_firsts(RULE_COMMAND, first(RULE_SIMPLE_COMMAND)); add_firsts(RULE_COMMAND, first(RULE_SIMPLE_COMMAND));
@ -170,23 +190,33 @@ int grammar_init(void)
add_firsts(RULE_COMMAND, first(RULE_FUNCDEC)); add_firsts(RULE_COMMAND, first(RULE_FUNCDEC));
// Pipeline // Pipeline
add_first(RULE_PIPELINE, TOKEN_WORD);
add_firsts(RULE_PIPELINE, first(RULE_COMMAND)); add_firsts(RULE_PIPELINE, first(RULE_COMMAND));
// And Or // And Or
add_firsts(RULE_AND_OR, first(RULE_PIPELINE)); add_firsts(RULE_AND_OR, first(RULE_PIPELINE));
// Compound list // Compound list
add_first(RULE_COMPOUND_LIST, TOKEN_NEWLINE);
add_firsts(RULE_COMPOUND_LIST, first(RULE_AND_OR)); add_firsts(RULE_COMPOUND_LIST, first(RULE_AND_OR));
// List // List
add_firsts(RULE_LIST, first(RULE_AND_OR)); add_firsts(RULE_LIST, first(RULE_AND_OR));
// Input // Input
add_first(RULE_INPUT, TOKEN_NEWLINE);
add_first(RULE_INPUT, TOKEN_EOF);
add_firsts(RULE_INPUT, first(RULE_LIST)); add_firsts(RULE_INPUT, first(RULE_LIST));
}
// === Functions
int grammar_init(void)
{
// Initialize the firsts map
bool success = init_firsts_map();
if (success != true)
return false;
// Populate the firsts map
add_firsts_tokens();
add_firsts_rec();
return true; return true;
} }

View file

@ -149,14 +149,57 @@ struct ast *parse_prefix(struct lexer_context *ctx)
} }
} }
// TODO NOT IMPLEMENTED
struct ast *parse_funcdec(struct lexer_context *ctx) struct ast *parse_funcdec(struct lexer_context *ctx)
{ {
(void)ctx; struct token *token = PEEK_TOKEN();
perror("Error: usage of a not implemented function (parse_funcdec)"); struct ast *value = NULL;
char *func_name = NULL;
if (token->type != TOKEN_WORD)
{
return NULL; return NULL;
} }
// word -> func name
POP_TOKEN();
func_name = strdup(token->data);
// (
token = PEEK_TOKEN();
if (token->type != TOKEN_LEFT_PAREN)
{
free(func_name);
return NULL;
}
POP_TOKEN();
// )
token = PEEK_TOKEN();
if (token->type != TOKEN_RIGHT_PAREN)
{
free(func_name);
return NULL;
}
POP_TOKEN();
token = PEEK_TOKEN();
// { \n }
while (token->type == TOKEN_NEWLINE)
{
POP_TOKEN();
token = PEEK_TOKEN();
}
// shell_command -> value
value = parse_shell_command(ctx);
if (value == NULL)
{
free(func_name);
return NULL;
}
return ast_create_function(func_name, value);
}
struct ast *parse_for(struct lexer_context *ctx) struct ast *parse_for(struct lexer_context *ctx)
{ {
(void)ctx; (void)ctx;
@ -177,18 +220,18 @@ struct ast *parse_while(struct lexer_context *ctx)
} }
POP_TOKEN(); POP_TOKEN();
return parse_loop(ctx, true); return parse_loop(ctx, false);
} }
struct ast *parse_until(struct lexer_context *ctx) struct ast *parse_until(struct lexer_context *ctx)
{ {
struct token *token = PEEK_TOKEN(); struct token *token = PEEK_TOKEN();
// 'while' // 'until'
if (token->type != TOKEN_UNTIL) if (token->type != TOKEN_UNTIL)
{ {
perror( perror(
"Internal error: expected a TOKEN_WHILE but got a different type"); "Internal error: expected a TOKEN_UNTIL but got a different type");
return NULL; return NULL;
} }
POP_TOKEN(); POP_TOKEN();

View file

@ -26,7 +26,7 @@ struct ast *parse_prefix(struct lexer_context *ctx);
/* /*
* @brief parses a funcdec rule * @brief parses a funcdec rule
* @warning NOT IMPLEMENTED * @warning Work in progress
* *
* @code funcdec = WORD '(' ')' {'\n'} shell_command ; * @code funcdec = WORD '(' ')' {'\n'} shell_command ;
* *
@ -36,7 +36,6 @@ struct ast *parse_funcdec(struct lexer_context *ctx);
/* /*
* @brief parses a for rule * @brief parses a for rule
* @warning NOT IMPLEMENTED
* *
* @code rule_for = 'for' WORD * @code rule_for = 'for' WORD
* ( [';'] | [ {'\n'} 'in' { WORD } ( ';' | '\n' ) ] ) * ( [';'] | [ {'\n'} 'in' { WORD } ( ';' | '\n' ) ] )

View file

@ -223,7 +223,6 @@ struct ast *parse_command(struct lexer_context *ctx)
{ {
result = parse_shell_command(ctx); result = parse_shell_command(ctx);
} }
// WARNING funcdec seems to require a LL(2) parser
else if (is_first(*token, RULE_FUNCDEC)) else if (is_first(*token, RULE_FUNCDEC))
{ {
result = parse_funcdec(ctx); result = parse_funcdec(ctx);
@ -373,28 +372,45 @@ struct ast *parse_shell_command(struct lexer_context *ctx)
struct token *token = PEEK_TOKEN(); struct token *token = PEEK_TOKEN();
struct ast *result = NULL; struct ast *result = NULL;
// Grouping // '{'
// '(' or '{' if (token->type == TOKEN_LEFT_BRACKET)
if (token->type == TOKEN_LEFT_BRACKET || token->type == TOKEN_LEFT_PAREN)
{ {
POP_TOKEN(); POP_TOKEN();
result = parse_compound_list(ctx); result = parse_compound_list(ctx);
if (result == NULL) if (result == NULL)
return NULL; return NULL;
// ')' or '}' // '}'
token = PEEK_TOKEN(); token = PEEK_TOKEN();
if (token->type == TOKEN_LEFT_BRACKET if (token->type == TOKEN_LEFT_BRACKET)
|| token->type == TOKEN_LEFT_PAREN)
{ {
ast_free(&result); ast_free(&result);
perror("Syntax error: bracket/parenthesis mismatch"); perror("Syntax error: bracket mismatch");
return NULL; return NULL;
} }
POP_TOKEN(); POP_TOKEN();
return result; return result;
} }
// '('
else if (token->type == TOKEN_LEFT_PAREN)
{
POP_TOKEN();
result = parse_compound_list(ctx);
if (result == NULL)
return NULL;
// ')'
token = PEEK_TOKEN();
if (token->type == TOKEN_LEFT_PAREN)
{
ast_free(&result);
perror("Syntax error: parenthesis mismatch");
return NULL;
}
POP_TOKEN();
return ast_create_subshell(result);
}
else if (is_first(*token, RULE_IF)) else if (is_first(*token, RULE_IF))
{ {
return parse_if_rule(ctx); return parse_if_rule(ctx);

View file

@ -20,7 +20,10 @@ libutils_a_SOURCES = \
ast/ast_loop.c \ ast/ast_loop.c \
args/args.c \ args/args.c \
vars/vars.c \ vars/vars.c \
ast/ast_assignment.c main_loop/main_loop.c \
ast/ast_assignment.c \
ast/ast_subshell.c \
ast/ast_function.c
libutils_a_CPPFLAGS = -I$(top_srcdir)/src libutils_a_CPPFLAGS = -I$(top_srcdir)/src

View file

@ -67,7 +67,7 @@ int args_handler(int argc, char **argv, struct args_options *options,
{ {
options->type = INPUT_UNDEFINED; options->type = INPUT_UNDEFINED;
options->input_source = NULL; options->input_source = NULL;
options->pretty_print = false; // options->pretty_print = false;
options->verbose = false; options->verbose = false;
struct list *args_list = NULL; struct list *args_list = NULL;
@ -76,11 +76,11 @@ int args_handler(int argc, char **argv, struct args_options *options,
for (int i = 1; i < argc; i++) for (int i = 1; i < argc; i++)
{ {
if (strcmp(argv[i], "--pretty-print") == 0) /* if (strcmp(argv[i], "--pretty-print") == 0)
{ {
options->pretty_print = true; options->pretty_print = true;
} } */
else if (strcmp(argv[i], "--verbose") == 0) if (strcmp(argv[i], "--verbose") == 0)
{ {
options->verbose = true; options->verbose = true;
} }
@ -138,7 +138,7 @@ void args_print(struct args_options *options)
: "UNDEFINED"); : "UNDEFINED");
printf("Input source: %s\n", printf("Input source: %s\n",
options->input_source ? options->input_source : "NULL"); options->input_source ? options->input_source : "NULL");
printf("Pretty print: %s\n", options->pretty_print ? "true" : "false"); // printf("Pretty print: %s\n", options->pretty_print ? "true" : "false");
printf("Verbose: %s\n", options->verbose ? "true" : "false"); printf("Verbose: %s\n", options->verbose ? "true" : "false");
} }
@ -147,7 +147,8 @@ void print_usage(FILE *std, const char *program_name)
fprintf(std, "Usage: %s [OPTIONS] [SCRIPT] [ARGUMENTS...]\n", program_name); fprintf(std, "Usage: %s [OPTIONS] [SCRIPT] [ARGUMENTS...]\n", program_name);
fprintf(std, "Options:\n"); fprintf(std, "Options:\n");
fprintf(std, " -c [SCRIPT] Execute the given command string.\n"); fprintf(std, " -c [SCRIPT] Execute the given command string.\n");
fprintf(std, " --pretty-print Enable pretty printing of outputs.\n"); // fprintf(std, " --pretty-print Enable pretty printing of
// outputs.\n");
fprintf(std, " --verbose Enable verbose mode.\n"); fprintf(std, " --verbose Enable verbose mode.\n");
fprintf(std, fprintf(std,
"If no SCRIPT is provided, input is read from standard input.\n"); "If no SCRIPT is provided, input is read from standard input.\n");

View file

@ -22,7 +22,7 @@ struct args_options
/** Type of the input source */ /** Type of the input source */
enum input_type type; enum input_type type;
/** Enable or disable pretty printing of outputs */ /** Enable or disable pretty printing of outputs */
bool pretty_print; // bool pretty_print;
/** Enable or disable verbose mode */ /** Enable or disable verbose mode */
bool verbose; bool verbose;
}; };

View file

@ -11,7 +11,7 @@ void ast_free(struct ast **node)
{ {
if (node == NULL || *node == NULL) if (node == NULL || *node == NULL)
{ {
perror( fprintf(stderr,
"WARNING: Internal error: failed to free AST node (NULL argument)"); "WARNING: Internal error: failed to free AST node (NULL argument)");
return; return;
} }
@ -42,13 +42,25 @@ void ast_free(struct ast **node)
case AST_ASSIGNMENT: case AST_ASSIGNMENT:
ast_free_assignment(ast_get_assignment(*node)); ast_free_assignment(ast_get_assignment(*node));
break; break;
case AST_NEG:
ast_free_neg(ast_get_neg(*node));
break;
case AST_LOOP:
ast_free_loop(ast_get_loop(*node));
break;
case AST_FUNCTION:
ast_free_function(ast_get_function(*node));
break;
case AST_SUBSHELL:
ast_free_subshell(ast_get_subshell(*node));
break;
case AST_VOID: case AST_VOID:
case AST_END: case AST_END:
break; break;
default: default:
perror("WARNING: Internal error: failed to free an AST node (Unknown " fprintf(stderr, "WARNING: Internal error:"
"type)"); " failed to free an AST node (Unknown type)");
return; return;
} }
@ -68,7 +80,7 @@ struct ast *ast_create(enum ast_type type, void *data)
return node; return node;
} }
// TODO handle new types (AST_WORD, AST_PIPE, etc.) /* // TODO handle new types (AST_WORD, AST_PIPE, etc.)
static void ast_print_dot_recursive(struct ast *node, FILE *out) static void ast_print_dot_recursive(struct ast *node, FILE *out)
{ {
if (!node) if (!node)
@ -159,3 +171,4 @@ void ast_print_dot(struct ast *ast)
fprintf(dot_pipe, "}\n"); fprintf(dot_pipe, "}\n");
pclose(dot_pipe); pclose(dot_pipe);
} }
*/

View file

@ -6,6 +6,7 @@
#include "ast_base.h" #include "ast_base.h"
#include "ast_command.h" #include "ast_command.h"
#include "ast_end.h" #include "ast_end.h"
#include "ast_function.h"
#include "ast_if.h" #include "ast_if.h"
#include "ast_list.h" #include "ast_list.h"
#include "ast_loop.h" #include "ast_loop.h"
@ -14,10 +15,6 @@
#include "ast_redir.h" #include "ast_redir.h"
#include "ast_void.h" #include "ast_void.h"
#include "ast_word.h" #include "ast_word.h"
#include "ast_subshell.h"
/**
* Prints the Graphviz DOT representation of the given AST to stdout.
*/
void ast_print_dot(struct ast *ast);
#endif /* ! AST_H */ #endif /* ! AST_H */

View file

@ -17,7 +17,9 @@ enum ast_type
AST_PIPE, AST_PIPE,
AST_NEG, AST_NEG,
AST_LOOP, AST_LOOP,
AST_ASSIGNMENT AST_ASSIGNMENT,
AST_FUNCTION,
AST_SUBSHELL
}; };
struct ast struct ast

View file

@ -0,0 +1,42 @@
#include "ast_function.h"
#include <stdlib.h>
#include <string.h>
#include "ast_base.h"
bool ast_is_function(struct ast *node)
{
return node != NULL && node->type == AST_FUNCTION;
}
struct ast_function *ast_get_function(struct ast *node)
{
if (!ast_is_function(node))
return NULL;
return (struct ast_function *)node->data;
}
struct ast *ast_create_function(char *name, struct ast *value)
{
struct ast_function *function_data = malloc(sizeof(struct ast_function));
if (!function_data)
return NULL;
function_data->name = name;
function_data->value = value;
return ast_create(AST_FUNCTION, function_data);
}
void ast_free_function(struct ast_function *function_data)
{
if (function_data)
{
free(function_data->name);
// WARNING: this ast will be stored in the function hashmap.
// thus, it will be freed from the hashmap.
// ast_free(&function_data->value);
free(function_data);
}
}

View file

@ -0,0 +1,33 @@
#ifndef AST_FUNCTION_H
#define AST_FUNCTION_H
#include <stdbool.h>
struct ast_function
{
char *name;
struct ast *value;
};
/**
* @brief: Checks if the given AST node is an ast_function
*/
bool ast_is_function(struct ast *node);
/**
* @brief: Retrieves the function data from the given AST node.
* Assumes that the node is of type AST_function.
*/
struct ast_function *ast_get_function(struct ast *node);
/**
* @brief: Creates a new AST node representing an AST_function
* @warning: name must be already allocated.
*/
struct ast *ast_create_function(char *name, struct ast *value);
/*
* @brief: frees the given ast_function and sets the pointer to NULL.
*/
void ast_free_function(struct ast_function *function_data);
#endif /* AST_FUNCTION_H */

View file

@ -0,0 +1,31 @@
#include "ast_subshell.h"
bool ast_is_subshell(struct ast *node)
{
return node != NULL && node->type == AST_SUBSHELL;
}
struct ast_subshell *ast_get_subshell(struct ast *node)
{
if (ast_is_subshell(node))
return (struct ast_subshell *)node->data;
return NULL;
}
struct ast *ast_create_subshell(struct ast *child)
{
struct ast_subshell *subshell = calloc(1, sizeof(struct ast_subshell));
if (subshell == NULL)
return NULL;
subshell->child = child;
return ast_create(AST_SUBSHELL, subshell);
}
void ast_free_subshell(struct ast_subshell *subshell)
{
if (!subshell)
return;
ast_free(&subshell->child);
free(subshell);
}

View file

@ -0,0 +1,19 @@
#ifndef AST_SUBSHELL_H
#define AST_SUBSHELL_H
#include "ast_base.h"
struct ast_subshell
{
struct ast *child;
};
bool ast_is_subshell(struct ast *node);
struct ast_subshell *ast_get_subshell(struct ast *node);
struct ast *ast_create_subshell(struct ast *child);
void ast_free_subshell(struct ast_subshell *subshell);
#endif /* ! AST_SUBSHELL_H */

View file

@ -7,6 +7,8 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "../ast/ast.h"
/* /*
** Hash the key using FNV-1a 32 bits hash algorithm. ** Hash the key using FNV-1a 32 bits hash algorithm.
*/ */
@ -36,6 +38,14 @@ static void destroy_pair_list(struct pair_list **p)
*p = NULL; *p = NULL;
} }
static void destroy_pair_list_ast(struct pair_list **p)
{
free((char *)(*p)->key);
ast_free((*p)->value);
free((*p));
*p = NULL;
}
struct hash_map *hash_map_init(size_t size) struct hash_map *hash_map_init(size_t size)
{ {
struct hash_map *p = malloc(sizeof(struct hash_map)); struct hash_map *p = malloc(sizeof(struct hash_map));
@ -116,9 +126,32 @@ void hash_map_free(struct hash_map **hash_map)
} }
free((*hash_map)->data); free((*hash_map)->data);
free(*hash_map); free(*hash_map);
}
*hash_map = NULL; *hash_map = NULL;
} }
}
void hash_map_free_ast(struct hash_map **hash_map)
{
struct pair_list *l;
struct pair_list *prev;
if (hash_map != NULL && *hash_map != NULL)
{
for (size_t i = 0; i < (*hash_map)->size; i++)
{
l = (*hash_map)->data[i];
while (l != NULL)
{
prev = l;
l = l->next;
destroy_pair_list_ast(&prev);
}
}
free((*hash_map)->data);
free(*hash_map);
*hash_map = NULL;
}
}
void hash_map_foreach(struct hash_map *hash_map, void hash_map_foreach(struct hash_map *hash_map,
void (*fn)(const char *, const void *)) void (*fn)(const char *, const void *))

View file

@ -0,0 +1,111 @@
#define _POSIX_C_SOURCE 200809L
#include "main_loop.h"
// === Includes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "../../execution/execution.h"
#include "../../io_backend/io_backend.h"
#include "../../lexer/lexer.h"
#include "../../parser/parser.h"
#include "../args/args.h"
#include "../vars/vars.h"
// === Functions
int err_input(struct hash_map **vars, struct lexer_context *ctx)
{
hash_map_free(vars);
destroy_lexer_context(ctx);
return ERR_INPUT_PROCESSING;
}
int main_loop(struct lexer_context *ctx, struct hash_map *vars)
{
int return_code = SUCCESS;
// Retrieve and build first AST
struct ast *command_ast = get_ast(ctx);
// Main parse-execute loop
while (command_ast != NULL && command_ast->type != AST_END)
{
if (command_ast->type != AST_VOID)
{
// Execute AST
return_code = execution(command_ast, vars);
// set $? variable
set_var_int(vars, "?", return_code);
}
ast_free(&command_ast);
// Retrieve and build next AST
command_ast = get_ast(ctx);
}
if (command_ast == NULL)
return err_input(&vars, ctx);
// === free
ast_free(&command_ast);
hash_map_free(&vars);
destroy_lexer_context(ctx);
return return_code;
}
/* @brief: initializes a lexer context from a command string.
* @return: pointer to the lexer context, or NULL on failure.
*/
static struct lexer_context *lexer_init_from_string(char *command)
{
// Create a lexer context from the command string
struct lexer_context *ctx = calloc(1, sizeof(struct lexer_context));
if (ctx == NULL)
return NULL;
ctx->end_previous_token = strdup(command);
if (ctx->end_previous_token == NULL)
{
free(ctx);
return NULL;
}
ctx->remaining_chars = strlen(command);
return ctx;
}
int start_subshell(struct hash_map **parent_vars, char *command)
{
int fd = fork();
if (fd < 0)
return ERR_GENERIC;
else if (fd == 0) // Child process
{
struct lexer_context *ctx = lexer_init_from_string(command);
if (ctx == NULL)
return ERR_MALLOC;
int return_code = main_loop(ctx, *parent_vars);
exit(return_code);
}
else // Parent process
{
int status;
if (waitpid(fd, &status, 0) == -1)
return ERR_GENERIC;
if (WIFEXITED(status))
return WEXITSTATUS(status);
else
return ERR_GENERIC;
}
}

View file

@ -0,0 +1,31 @@
#ifndef MAIN_LOOP_H
#define MAIN_LOOP_H
#include "../../utils/vars/vars.h"
#include "../../lexer/lexer.h"
// === Error codes
#define SUCCESS 0
#define ERR_INPUT_PROCESSING 2
#define ERR_MALLOC 3
#define ERR_GENERIC 4
/* @brief: main loop called from main.
* @return: exit code.
*/
int main_loop(struct lexer_context *ctx, struct hash_map *vars);
/*
* @brief: frees the hash map and lexer context.
* @return: ERR_INPUT_PROCESSING.
*/
int err_input(struct hash_map **vars, struct lexer_context *ctx);
/*
* @brief: starts a subshell and builds the intern lexer context
* from the string.
* @return: exit code of the subshell.
*/
int start_subshell(struct hash_map **parent_vars, char *command);
#endif /* MAIN_LOOP_H */

21
tests/functional/func.sh Executable file
View file

@ -0,0 +1,21 @@
func()
{
echo hello
}
arg_func()
{
echo first argument is "$1"
}
func_in_func()
{
func
}
func_one_line() { echo "this is on one line"; }
func
arg_func "HERE"
func_in_func
func_one_line

20
tests/functional/loops.sh Executable file
View file

@ -0,0 +1,20 @@
echo "starting tests"
while false;
do
echo "should NOT be printed"
done
a='yes'
while [ "$a" -eq "yes" ];
do
a="no"
echo "should be printed only once"
done;
while true;
do
echo "yes"
done;
echo "tests done"

View file

@ -269,9 +269,6 @@ echo -e "\n\n""===$BGreen TestsuitatorX Ultra Pro Max+ 365 Premium Gris Sidéral
#
echo -e "\n$BBlue=== Builtins ===$Color_Off" echo -e "\n$BBlue=== Builtins ===$Color_Off"
# echo # echo
test_str "Hello" "echo Hello" test_str "Hello" "echo Hello"
@ -377,9 +374,14 @@ test_str "If with negation" "if ! false; then echo Yes; fi"
test_str "If faut aller niquer sa mere" "if false; ! false; then echo Embrasse moi; fi" test_str "If faut aller niquer sa mere" "if false; ! false; then echo Embrasse moi; fi"
echo -e "\n$BBlue=== For/While ===$Color_Off" echo -e "\n$BBlue=== Loops ===$Color_Off"
test_str "While loop" "i=0; while [ \$i -lt 3 ]; do echo \$i; i=\$((i+1)); done" test_str "While false" "while false; do false; done"
test_str "Until loop" "i=0; until [ \$i -ge 3 ]; do echo \$i; i=\$((i+1)); done" test_str "While(false) true" "while false; do true; done"
test_str "Until(true) false" "until true; do false; done"
test_str "Until true" "until true; do true; done"
# test_str "While var" "a=2; while [ \$a -eq 2 ]; do \$a=3; done"
test_str "While arithmetic" "i=0; while [ \$i -lt 3 ]; do echo \$i; i=\$((i+1)); done"
test_str "Until arithmetic" "i=0; until [ \$i -ge 3 ]; do echo \$i; i=\$((i+1)); done"
test_str "While break" "while true; do echo break; break; done" test_str "While break" "while true; do echo break; break; done"
test_str "While continue" "i=0; while [ \$i -lt 3 ]; do i=\$((i+1)); if [ \$i -eq 2 ]; then continue; fi; echo \$i; done" test_str "While continue" "i=0; while [ \$i -lt 3 ]; do i=\$((i+1)); if [ \$i -eq 2 ]; then continue; fi; echo \$i; done"
test_str "For loop basic" "for i in a b c; do echo \$i; done" test_str "For loop basic" "for i in a b c; do echo \$i; done"

View file

@ -1,7 +1,6 @@
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
#include <criterion/criterion.h> #include <criterion/criterion.h>
#include <criterion/new/assert.h> #include <criterion/new/assert.h>
#include <criterion/redirect.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
@ -17,7 +16,7 @@ Test(expand, no_expansion)
char str[] = "echo something"; char str[] = "echo something";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
bool ret = expand(ast_command, NULL); bool ret = expand(ast_command, NULL);
@ -32,7 +31,7 @@ Test(expand, single_quotes_no_expansion)
char str[] = "echo '$VAR'"; char str[] = "echo '$VAR'";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -51,7 +50,7 @@ Test(expand, single_dollar)
char str[] = "echo $ sign"; char str[] = "echo $ sign";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -70,7 +69,7 @@ Test(expand, empty_braces_no_expansion)
char str[] = "echo ${}"; char str[] = "echo ${}";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -87,7 +86,7 @@ Test(expand, basic_expansion)
char str[] = "echo $VAR"; char str[] = "echo $VAR";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -106,7 +105,7 @@ Test(expand, multiple_expansion)
char str[] = "echo $VAR1 $VAR2 ${VAR3}"; char str[] = "echo $VAR1 $VAR2 ${VAR3}";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -128,7 +127,7 @@ Test(expand, env_variable)
char str[] = "echo $MY_ENV_VAR"; char str[] = "echo $MY_ENV_VAR";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
setenv("MY_ENV_VAR", "environment", 0); setenv("MY_ENV_VAR", "environment", 0);
@ -145,7 +144,7 @@ Test(expand, undefined_variable)
char str[] = "echo $UNDEFINED"; char str[] = "echo $UNDEFINED";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -163,7 +162,7 @@ Test(expand, nested_expansion)
char str[] = "echo $B"; char str[] = "echo $B";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -178,34 +177,34 @@ Test(expand, nested_expansion)
hash_map_free(&vars); hash_map_free(&vars);
} }
Test(expand, mixed_quotes_expansion) // Test(expand, mixed_quotes_expansion)
{ // {
char str[] = "echo \"$VAR1 and '$VAR2'\""; // char str[] = "echo \"$VAR1 and '$VAR2'\"";
char *str_heap = strdup(str); // char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); // struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); // struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); // struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); // struct hash_map *vars = vars_init();
set_var_copy(vars, "VAR1", "expanded"); // set_var_copy(vars, "VAR1", "expanded");
set_var_copy(vars, "VAR2", "not_expanded"); // set_var_copy(vars, "VAR2", "not_expanded");
bool ret = expand(ast_command, vars); // bool ret = expand(ast_command, vars);
cr_expect(ret, "expansion failed with %s", str); // cr_expect(ret, "expansion failed with %s", str);
cr_expect_str_eq((char *)ast_command->command->data, // cr_expect_str_eq((char *)ast_command->command->data,
"echo \"expanded and $VAR2\"", // "echo \"expanded and $VAR2\"",
"Variable in double quotes should expand, while variable " // "Variable in double quotes should expand, while variable "
"in single quotes should not"); // "in single quotes should not");
ast_free(&ast); // ast_free(&ast);
hash_map_free(&vars); // hash_map_free(&vars);
} // }
Test(expand, adjacent_variables) Test(expand, adjacent_variables)
{ {
char str[] = "echo $VAR1$VAR2"; char str[] = "echo $VAR1$VAR2";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -225,7 +224,7 @@ Test(expand, random)
char str[] = "$RANDOM"; char str[] = "$RANDOM";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
bool ret = expand(ast_command, NULL); bool ret = expand(ast_command, NULL);
@ -241,7 +240,7 @@ Test(expand, pid)
char str[] = "$$"; char str[] = "$$";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
@ -259,7 +258,7 @@ Test(expand, default_last_exit_code)
char str[] = "$?"; char str[] = "$?";
char *str_heap = strdup(str); char *str_heap = strdup(str);
struct list *list = list_append(NULL, str_heap); struct list *list = list_append(NULL, str_heap);
struct ast *ast = ast_create_command(list); struct ast *ast = ast_create_command(list, NULL, NULL);
struct ast_command *ast_command = ast_get_command(ast); struct ast_command *ast_command = ast_get_command(ast);
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();

View file

@ -0,0 +1,72 @@
#include <criterion/criterion.h>
#include <criterion/new/assert.h>
#include "../../../src/expansion/expansion.h"
TestSuite(parse_subshell_str);
Test(parse_subshell_str, basic_subshell)
{
char *input = "(ls -l)";
char *extracted_var = NULL;
size_t r = parse_subshell_str(input, &extracted_var);
cr_expect(r == 7);
cr_expect_str_eq(extracted_var, "ls -l");
free(extracted_var);
}
Test(parse_subshell_str, multi_basic_subshell)
{
char *input = "(echo hello) and (echo world)";
char *extracted_var = NULL;
size_t r = parse_subshell_str(input, &extracted_var);
cr_expect(r == 12);
cr_expect_str_eq(extracted_var, "echo hello");
free(extracted_var);
input += r + 5; // skip " and "
r = parse_subshell_str(input, &extracted_var);
cr_expect(r == 12);
cr_expect_str_eq(extracted_var, "echo world");
free(extracted_var);
}
Test(parse_subshell_str, incomplete_braces)
{
char *input = "(echo hello";
char *extracted_var = NULL;
size_t r = parse_subshell_str(input, &extracted_var);
cr_expect(r == 0);
cr_expect(extracted_var == NULL);
}
Test(parse_subshell_str, empty_braces)
{
char *input = "()";
char *extracted_var = NULL;
size_t r = parse_subshell_str(input, &extracted_var);
cr_expect(r == 0);
cr_expect(extracted_var == NULL);
}
Test(parse_subshell_str, nested_subshell)
{
char *input = "(echo (nested))";
char *extracted_var = NULL;
size_t r = parse_subshell_str(input, &extracted_var);
cr_expect(r == 15);
cr_expect_str_eq(extracted_var, "echo (nested)");
free(extracted_var);
char *nested = input + 6; // point to the nested subshell
r = parse_subshell_str(nested, &extracted_var);
cr_expect(r == 8);
cr_expect_str_eq(extracted_var, "nested");
free(extracted_var);
}

View file

@ -1,6 +1,5 @@
#include <criterion/criterion.h> #include <criterion/criterion.h>
#include <criterion/new/assert.h> #include <criterion/new/assert.h>
#include <criterion/redirect.h>
#include "../../../src/expansion/expansion.h" #include "../../../src/expansion/expansion.h"

View file

@ -19,7 +19,7 @@ Test(utils_args, basic_command)
int r = args_handler(argc, input, &options, vars); int r = args_handler(argc, input, &options, vars);
cr_expect(r == 0); cr_expect(r == 0);
cr_expect(options.pretty_print == false); // cr_expect(options.pretty_print == false);
cr_expect(options.verbose == false); cr_expect(options.verbose == false);
cr_expect(options.type == INPUT_CMD); cr_expect(options.type == INPUT_CMD);
cr_expect(eq(options.input_source, "echo Hello, World!")); cr_expect(eq(options.input_source, "echo Hello, World!"));
@ -30,14 +30,16 @@ Test(utils_args, basic_command_with_flags)
{ {
int argc = 5; int argc = 5;
struct args_options options; struct args_options options;
char *input[] = { "program", "--pretty-print", "-c", "echo Hello, World!", /* char *input[] = { "program", "--pretty-print", "-c", "echo Hello,
"--verbose" }; World!",
"--verbose" };*/
char *input[] = { "program", "-c", "echo Hello, World!", "--verbose" };
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
int r = args_handler(argc, input, &options, vars); int r = args_handler(argc, input, &options, vars);
cr_expect(r == 0); cr_expect(r == 0);
cr_expect(options.pretty_print == true); // cr_expect(options.pretty_print == true);
cr_expect(options.verbose == true); cr_expect(options.verbose == true);
cr_expect(options.type == INPUT_CMD); cr_expect(options.type == INPUT_CMD);
cr_expect(eq(options.input_source, "echo Hello, World!")); cr_expect(eq(options.input_source, "echo Hello, World!"));
@ -54,7 +56,7 @@ Test(utils_args, basic_file_input)
int r = args_handler(argc, input, &options, vars); int r = args_handler(argc, input, &options, vars);
cr_expect(r == 0); cr_expect(r == 0);
cr_expect(options.pretty_print == false); // cr_expect(options.pretty_print == false);
cr_expect(options.verbose == false); cr_expect(options.verbose == false);
cr_expect(options.type == INPUT_FILE); cr_expect(options.type == INPUT_FILE);
cr_expect(eq(options.input_source, "input.txt")); cr_expect(eq(options.input_source, "input.txt"));
@ -65,13 +67,15 @@ Test(utils_args, basic_file_input_with_flags)
{ {
int argc = 4; int argc = 4;
struct args_options options; struct args_options options;
char *input[] = { "program", "--verbose", "input.txt", "--pretty-print" }; // char *input[] = { "program", "--verbose", "input.txt", "--pretty-print"
// };
char *input[] = { "program", "--verbose", "input.txt" };
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
int r = args_handler(argc, input, &options, vars); int r = args_handler(argc, input, &options, vars);
cr_expect(r == 0); cr_expect(r == 0);
cr_expect(options.pretty_print == true); // cr_expect(options.pretty_print == true);
cr_expect(options.verbose == true); cr_expect(options.verbose == true);
cr_expect(options.type == INPUT_FILE); cr_expect(options.type == INPUT_FILE);
cr_expect(eq(options.input_source, "input.txt")); cr_expect(eq(options.input_source, "input.txt"));
@ -88,7 +92,7 @@ Test(utils_args, basic_stdin_input)
int r = args_handler(argc, input, &options, vars); int r = args_handler(argc, input, &options, vars);
cr_expect(r == 0); cr_expect(r == 0);
cr_expect(options.pretty_print == false); // cr_expect(options.pretty_print == false);
cr_expect(options.verbose == false); cr_expect(options.verbose == false);
cr_expect(options.type == INPUT_STDIN); cr_expect(options.type == INPUT_STDIN);
cr_expect(options.input_source == NULL); cr_expect(options.input_source == NULL);
@ -99,13 +103,14 @@ Test(utils_args, pretty_print_and_verbose_flags)
{ {
int argc = 3; int argc = 3;
struct args_options options; struct args_options options;
char *input[] = { "program", "--pretty-print", "--verbose" }; // char *input[] = { "program", "--pretty-print", "--verbose" };
char *input[] = { "program", "--verbose" };
struct hash_map *vars = vars_init(); struct hash_map *vars = vars_init();
int r = args_handler(argc, input, &options, vars); int r = args_handler(argc, input, &options, vars);
cr_expect(r == 0); cr_expect(r == 0);
cr_expect(options.pretty_print == true); // cr_expect(options.pretty_print == true);
cr_expect(options.verbose == true); cr_expect(options.verbose == true);
cr_expect(options.type == INPUT_STDIN); cr_expect(options.type == INPUT_STDIN);
cr_expect(options.input_source == NULL); cr_expect(options.input_source == NULL);

View file

@ -3,6 +3,7 @@
#include <criterion/criterion.h> #include <criterion/criterion.h>
#include <criterion/new/assert.h> #include <criterion/new/assert.h>
#include <criterion/redirect.h>
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>