summaryrefslogtreecommitdiff
path: root/42sh/src/parser/parser_fundec.c
blob: 08d48164a0a5820e149fb28acfc5165a9b47efd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "parser/parser_functions.h"
#include "parser/parser_utils.h"

struct ast *parse_funcdec(struct lexer *lexer, enum parser_state *state,
                          struct string *txt)
{
    struct ast *function = ast_create(AST_FUNCTION);
    if (function == NULL)
    {
        QUICK_CLEANUP
    }

    struct token next = lexer_peek(lexer);

    if (txt == NULL && next.type != TOKEN_WORD)
    {
        cleanup(function, state);
        return NULL;
    }
    else if (txt == NULL)
    {
        ((struct ast_function *)function)->name = next.value;
        lexer_pop(lexer);
        next = lexer_peek(lexer);
    }
    else
    {
        // If we used the word in the txt variable, no need to peek
        ((struct ast_function *)function)->name = txt;
    }

    if (next.type != TOKEN_PAR_LEFT)
    {
        cleanup(function, state);
        return NULL;
    }

    lexer_pop(lexer);
    next = lexer_peek(lexer);

    if (next.type != TOKEN_PAR_RIGHT)
    {
        cleanup(function, state);
        return NULL;
    }

    lexer_pop(lexer);
    next = lexer_peek(lexer);

    clean_cons_tokens(TOKEN_NEWLINE, lexer);

    struct ast *body = parse_shell_command(lexer, state);
    next = lexer_peek(lexer);

    if (error_check(function, state, next))
    {
        return NULL;
    }

    set_left(function, body);

    return function;
}