/* SI 413 Fall 2021
 * Lab 4
 * Bison file specifying the calculator program parser
 * YOUR NAME(S) HERE
 */

  /* Everything in this block goes in the header file calc.tab.hpp. */
%code requires {
#include <cstdlib> // for atoi
#include <iostream>
#include <string>
#include <map>
#include "colorout.hpp"
using namespace std;

//-- Lexer prototype required by bison
int yylex();

// Global variables for printing in pretty colors
extern colorout resout;
extern colorout errout;
}

  /* Everything in this block only goes in the bison file. */
%code {

// Error function that bison will call
void yyerror(const char *description) {
  errout << description << endl;
}

// Global variable to indicate done-ness
bool keepgoing = true;

// For Ex 2
// prints n as a signed binary number
void printbin(int n);

}

  /* Tell bison to give descriptive error messages. */
%define parse.error verbose

  /* These are the different "semantic values" that a token can have. */
%union {
  int val;
  char sym;
};

  /* These are the basic token types, organized by what kind
   * of semantic value they can have. */
%token <val> NUM
%token <sym> OPA OPM
%token LP RP STOP

  /* These are the non-terminal names that have values. */
%type <val> exp term sfactor factor

//-- GRAMMAR RULES ---------------------------------------
%%
  /* Note: YYACCEPT is a macro that tells bison to stop parsing. */
S: stmt { YYACCEPT; }
|       { keepgoing = false; }

stmt: exp STOP { resout << $1 << endl; }

exp: exp OPA term      { $$ = ($2 == '+' ? $1 + $3 : $1 - $3); }
| term                 { $$ = $1; }

term: term OPM sfactor { $$ = ($2 == '*' ? $1 * $3 : $1 / $3); }
| sfactor              { $$ = $1; }

sfactor: OPA factor    { $$ = ($1 == '+' ? $2 : -$2); }
| factor               { $$ = $1; }

factor: NUM            { $$ = $1; }
| LP exp RP            { $$ = $2; }

%%
// These are the colored output streams to make things all pretty.
colorout resout(1, 'u');
colorout errout(2, 'r');

//-- FUNCTION DEFINITIONS ---------------------------------
int main()
{
  // This checks whether the output is a terminal.
  bool tty = isatty(0) && isatty(2);

  while (keepgoing) {
    if (tty) cerr << "> " << flush;
    yyparse();
  }
  if (tty) cerr << "Goodbye" << endl;
  return 0;
}

void printbin(int n) {
  if (n < 0) {
    resout << '-';
    n = -n;
  }
  int bit = 1;
  while (bit > 0 && bit*2 <= n) bit *= 2;
  while (bit > 0) {
    if (bit <= n) {
      n -= bit;
      resout << '1';
    }
    else resout << '0';
    bit /= 2;
  }
  return;
}