summaryrefslogtreecommitdiff
path: root/21sh/ll-expr/src/eval/ast_print.c
blob: 9d7cbb858fab779a1e9c02439b67d08d42268cb2 (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
#include <stdio.h>

#include "lexer.h"
#include "parser.h"

char tab[] = { [AST_PLUS] = '+',
               [AST_MINUS] = '-',
               [AST_MUL] = '*',
               [AST_DIV] = '/' };

void print_ast(struct ast *ast)
{
    if (ast == NULL)
        return;

    if (ast->type == AST_NUMBER)
        printf("%zu", ast->value);
    else if (ast->type == AST_NEG)
        printf("-%zu", (ast->left)->value);
    else
    {
        printf("(");

        print_ast(ast->left);

        printf("%c", tab[ast->type]);

        print_ast(ast->right);

        printf(")");
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
        return 1;

    struct lexer *lexer = lexer_new(argv[1]);

    struct ast *ast;
    enum parser_status status = PARSER_OK;
    ast = parse(&status, lexer);
    if (status != PARSER_OK)
    {
        lexer_free(lexer);
        return 1;
    }

    print_ast(ast);
    printf("\n");

    ast_free(ast);
    lexer_free(lexer);

    return 0;
}