%{
#define yyerror printf
#define YYDEBUG 0

#include <cstdlib>
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

map<string,string> variables;

#define YYSTYPE std::string

int yyparse();
int yylex();

%}

%token  NUM STR VAR STRING PRINT REVERSE
%left '='
%left '+'
%left '*'
%left PJ
%nonassoc '['

%%
statements : 
        statements statement
    |   statement
    ;

statement : 
        STRING vars ';'
    |   PRINT '(' expr ')' ';'
        {   cout<<$3<<endl;  }
    |   REVERSE '(' VAR ')' ';'
        {   reverse(variables[$3].begin(), variables[$3].end());   }
    |   expr ';'
    ;
    
vars : 
        vars ',' var
    |   var
    ;

var :   
        VAR
    |   VAR '=' expr 
        {   variables[$1] = $3;   }
    ;
    
expr :
        expr '+' expr
        {   $$ = $1 + $3;   }
    |   VAR '=' expr
        {   $$ = variables[$1] = $3; }
    |   VAR PJ expr
        {   $$ = variables[$1] += $3;  }
    |   expr '*' NUM
        {   int num = atoi($3.c_str());
            $$ = "";            
            for (int i=0; i<num; i++)
                $$ += $1;
        }
    |   '(' expr ')'
        {   $$ = $2;    }
    |   expr '[' NUM ',' NUM ']'
        {   $$ = $1.substr(atoi($3.c_str()),atoi($5.c_str()));  }
    |   VAR
        {   $$ = variables[$1]; }
    |   STR 
        {   $$ = $1; }
    ;
%%
int main()
{
    yydebug=1;
    yyparse();
    return 0;
}
