jitters: print: print on FILE instead of stdout

This commit is contained in:
Bruno BELANYI 2020-09-28 18:39:43 +02:00
parent 6aff66a4b6
commit fe05cff2c8
2 changed files with 31 additions and 21 deletions

View file

@ -2,65 +2,73 @@
#include <stdio.h> #include <stdio.h>
static void printer_binop(const struct binop_node *bin_op) static void printer_ast(const struct ast_node *ast, FILE *file);
static void printer_binop(const struct binop_node *bin_op, FILE *file)
{ {
putchar('('); fputc('(', file);
printer_ast(bin_op->lhs); printer_ast(bin_op->lhs, file);
switch (bin_op->op) switch (bin_op->op)
{ {
case PLUS: case PLUS:
printf(" + "); fputs(" + ", file);
break; break;
case MINUS: case MINUS:
printf(" - "); fputs(" - ", file);
break; break;
case TIMES: case TIMES:
printf(" * "); fputs(" * ", file);
break; break;
case DIVIDE: case DIVIDE:
printf(" / "); fputs(" / ", file);
break; break;
default: default:
break; break;
} }
printer_ast(bin_op->rhs); printer_ast(bin_op->rhs, file);
putchar(')'); fputc(')', file);
} }
static void printer_unop(const struct unop_node *un_op) static void printer_unop(const struct unop_node *un_op, FILE *file)
{ {
putchar('('); fputc('(', file);
switch (un_op->op) switch (un_op->op)
{ {
case NEGATE: case NEGATE:
printf("- "); fputs("- ", file);
case IDENTITY: case IDENTITY:
default: default:
break; break;
} }
printer_ast(un_op->rhs); printer_ast(un_op->rhs, file);
putchar(')'); fputc(')', file);
} }
static void printer_num(int num) static void printer_num(int num, FILE *file)
{ {
printf("%d", num); fprintf(file, "%d", num);
} }
void printer_ast(const struct ast_node *ast) static void printer_ast(const struct ast_node *ast, FILE *file)
{ {
switch (ast->kind) switch (ast->kind)
{ {
case BINOP: case BINOP:
printer_binop(&ast->val.bin_op); printer_binop(&ast->val.bin_op, file);
break; break;
case UNOP: case UNOP:
printer_unop(&ast->val.un_op); printer_unop(&ast->val.un_op, file);
break; break;
case NUM: case NUM:
printer_num(ast->val.num); printer_num(ast->val.num, file);
break; break;
default: default:
break; break;
} }
} }
void print_ast(const struct ast_node *ast, FILE *file)
{
printer_ast(ast, file);
fputc('\n', file);
}

View file

@ -1,8 +1,10 @@
#ifndef PRINTER_H #ifndef PRINTER_H
#define PRINTER_H #define PRINTER_H
#include <stdio.h>
#include "ast/ast.h" #include "ast/ast.h"
void printer_ast(const struct ast_node *ast); void print_ast(const struct ast_node *ast, FILE *file);
#endif /* !PRINTER_H */ #endif /* !PRINTER_H */