%{
#include <stdio.h>
#include "tree.h"
%}

%union {
	int	numval;
	char	*idval;
        tree    *tval;
}
%token tBEGIN
%token tEND
%token tIF
%token tTHEN
%token tELSE
%token tASSIGN
%token <idval> tIDENTIFIER
%token <numval> tNUMBER
%type  <tval> statement statements expression

%start pascal
%left '>'
%left '+'
%left '-'

%%

pascal:      statement { print_tree($1); }

statement:   tIDENTIFIER tASSIGN expression 
                            { $$ = mknode(t_assign, 0, mkid($1), $3); }
           | tIF expression tTHEN statement
                            { $$ = mknode(t_if, 0, $2, mknode(t_else, 0, $4, NULL)); }
           | tIF expression tTHEN statement tELSE statement
                            { $$ = mknode(t_if, 0, $2, mknode(t_else, 0, $4, $6)); }
           | tBEGIN statements tEND
                            { $$ = mknode(t_block, 0, $2, NULL); }
;

statements:  statement
                            { $$ = mknode(t_join, 0, $1, NULL); }
           | statement ';' statements
                            { $$ = mknode(t_join, 0, $1, $3); }
;

expression:  tNUMBER { $$ = mknum($1); }
           | tIDENTIFIER { $$ = mkid($1); }
           | expression '+' expression { $$ = mknode(t_op, '+', $1, $3); }
           | expression '-' expression { $$ = mknode(t_op, '-', $1, $3); }
           | expression '>' expression { $$ = mknode(t_op, '>', $1, $3); }
;

%%

int main()
{
  yyparse();
}

int yyerror(char *s)
{
  fprintf(stderr, "%s\n", s);
  return 0;
}

#include "lex.yy.c"

