/* SI 413 Fall 2018
 * Unit 5: Semantic Analysis
 * This is the parser for the "beefed up calculator" language.
 */

%{
#include <vector>
#include <string>
#include <iostream>
using namespace std;

#include "parsetree.hpp"

ParseTree* PT = NULL;

int yylex();
int yyerror(const char *p) { cerr << "Parse error!" << endl; return 0; }

%}


%token NUM OPA OPM LP RP STOP COMP BOP VAR ASN

%%
start: run { PT = $$; }

run: stmt run { $$ = new ParseTree("run",$1,$2); }
| stmt { $$ = new ParseTree("run",$1); }

stmt: ares STOP { $$ = new ParseTree("stmt",$1,$2); }

ares: VAR ASN bres { $$ = new ParseTree("ares",$1,$2,$3); }
| bres { $$ = new ParseTree("ares",$1); }

bres: res { $$ = new ParseTree("bres",$1); }
| bres BOP res { $$ = new ParseTree("bres",$1,$2,$3); }

res: exp { $$ = new ParseTree("res",$1); }
| res COMP exp { $$ = new ParseTree("res",$1,$2,$3); }

exp: exp OPA term { $$ = new ParseTree("exp",$1,$2,$3); }
| term { $$ = new ParseTree("exp",$1); }

term: term OPM factor { $$ = new ParseTree("term",$1,$2,$3); }
| factor { $$ = new ParseTree("term", $1); }

factor: NUM  { $$ = new ParseTree("factor",$1); }
| LP bres RP { $$ = new ParseTree("factor",$1,$2,$3); }
| VAR        { $$ = new ParseTree("factor",$1); }

%%
int main()
{
  yyparse();
  PT->writeDot("bcalc.dot");
  return 0;
}