summaryrefslogtreecommitdiff
path: root/parse.c
blob: 7f11022dade630ef651163c0371d531546da23b2 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdlib.h>
#include <stdio.h>

#include "lex.h"
#include "parse.h"


typedef struct {
    TokenVec vec;
    size_t pos;
} TokStream;


Connector parse_connector(TokStream* toks) {
    Token tok = *get_from_TokenVec(&toks->vec, toks->pos);
    if (tok.kind != TOK_SPECIAL) exit(67);
    switch (tok.as.spec) {
        case PIPE: 
            toks->pos++;
            return CONN_PIPE;
        case EOL: 
            toks->pos++;
            return CONN_EOL;
        default: exit(76);
    }
}


Command parse_command(TokStream* toks) {
    TokenVec args = make_TokenVec(256);
    RedirectVec redirects = make_RedirectVec(256);
    while (true) {
        Token curr_tok = *get_from_TokenVec(&toks->vec, toks->pos);
        if (curr_tok.kind == TOK_SPECIAL &&(curr_tok.as.spec == PIPE || curr_tok.as.spec == EOL)) {
            break;
        }

        switch (curr_tok.kind) {
            case TOK_SPECIAL: 
                toks->pos++;
                Token name_tok = *get_from_TokenVec(&toks->vec, toks->pos);
                switch (curr_tok.as.spec) {
                    case WRITE_REDIR_TRUNC:
                        if(name_tok.kind != TOK_WORD) exit(1);
                        push_to_RedirectVec(&redirects, (Redirect){.kind = STDOUT_REDIR_TRUNC, .as.std_redir_filename = name_tok.as.word});
                        break;
                    case WRITE_REDIR_APPEND:
                        if(name_tok.kind != TOK_WORD) exit(1);
                        push_to_RedirectVec(&redirects, (Redirect){.kind = STDOUT_REDIR_APPEND, .as.std_redir_filename = name_tok.as.word});
                        break;
                    case READ_REDIR:
                        if(name_tok.kind != TOK_WORD) exit(1);
                        push_to_RedirectVec(&redirects, (Redirect){.kind = STDOUT_REDIR_APPEND, .as.std_redir_filename = name_tok.as.word});
                        break;
                    default:
                        exit(69);
                }
                break;
            default: 
                push_to_TokenVec(&args, curr_tok);
        }
        toks->pos++;
    }
    return (Command){.args = args, .redirects = redirects};
}


Pipeline parse_tokstream(TokenVec tok_vec) {
    TokStream tokstream = {.vec = tok_vec, .pos = 0};
    Pipeline result = make_Pipeline(256);
    while (true) {
        Command cmd = parse_command(&tokstream);
        Connector conn = parse_connector(&tokstream);
        push_to_Pipeline(&result, (PipelineElement){.cmd = cmd, .conn = conn});
        if (conn == CONN_EOL) break;
    }
    return result;
}