/*
 * Copyright (c) 2014-2017 Christian Schoenebeck and Andreas Persson
 * Copyright (c) 2018-2025 Christian Schoenebeck
 *
 * http://www.linuxsampler.org
 *
 * This file is part of LinuxSampler and released under the same terms.
 * See README file for details.
 */
 
/* Parser for NKSP real-time instrument script language. */

%{
    #define YYERROR_VERBOSE 1
    #include "parser_shared.h"
    #include <string>
    #include <map>
    using namespace LinuxSampler;

    void InstrScript_error(YYLTYPE* locp, LinuxSampler::ParserContext* context, const char* err);
    void InstrScript_warning(YYLTYPE* locp, LinuxSampler::ParserContext* context, const char* txt);
    int InstrScript_tnamerr(char* yyres, const char* yystr);
    int InstrScript_lex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner);
    #define scanner context->scanner
    #define PARSE_ERR(loc,txt)  yyerror(&loc, context, txt)
    #define PARSE_WRN(loc,txt)  InstrScript_warning(&loc, context, txt)
    #define PARSE_DROP(loc) \
        context->addPreprocessorComment( \
            loc.first_line, loc.last_line, loc.first_column+1, \
            loc.last_column+1, loc.first_byte, loc.length_bytes \
        );
    #define CODE_BLOCK(loc) { \
        .firstLine = loc.first_line, .lastLine = loc.last_line, \
        .firstColumn = loc.first_column+1, .lastColumn = loc.last_column+1, \
        .firstByte = loc.first_byte, .lengthBytes = loc.length_bytes \
    }
    #define ASSIGNED_EXPR_BLOCK(loc) { \
        .firstLine = loc.first_line, .lastLine = loc.last_line, \
        .firstColumn = loc.first_column+3, .lastColumn = loc.last_column+1, \
        .firstByte = loc.first_byte+2, .lengthBytes = loc.length_bytes-2 \
    }
    #define yytnamerr(res,str)  InstrScript_tnamerr(res, str)
%}

// generate reentrant safe parser
%pure-parser
%parse-param { LinuxSampler::ParserContext* context }
%lex-param { void* scanner }
// avoid symbol collision with other (i.e. future) auto generated (f)lex scanners
// (NOTE: "=" is deprecated here with Bison 3.x, however removing it would cause an error with Bison 2.x)
%name-prefix="InstrScript_"
%locations
%defines
%error-verbose

%token <iValue> INTEGER "integer literal"
%token <fValue> REAL "real number literal"
%token <iUnitValue> INTEGER_UNIT "integer literal with unit"
%token <fUnitValue> REAL_UNIT "real number literal with unit"
%token <sValue> STRING "string literal"
%token <sValue> IDENTIFIER "function name"
%token <sValue> VARIABLE "variable name"
%token ON "keyword 'on'"
%token END "keyword 'end'"
%token INIT "keyword 'init'"
%token NOTE "keyword 'note'"
%token RELEASE "keyword 'release'"
%token CONTROLLER "keyword 'controller'"
%token RPN "keyword 'rpn'"
%token NRPN "keyword 'nrpn'"
%token DECLARE "keyword 'declare'"
%token ASSIGNMENT "operator ':='"
%token CONST_ "keyword 'const'"
%token POLYPHONIC "keyword 'polyphonic'"
%token PATCH "keyword 'patch'"
%token LOCAL "keyword 'local'"
%token WHILE "keyword 'while'"
%token SYNCHRONIZED "keyword 'synchronized'"
%token IF "keyword 'if'"
%token ELSE "keyword 'else'"
%token SELECT "keyword 'select'"
%token CASE "keyword 'case'"
%token TO "keyword 'to'"
%token OR "operator 'or'"
%token AND "operator 'and'"
%token NOT "operator 'not'"
%token BITWISE_OR "bitwise operator '.or.'"
%token BITWISE_AND "bitwise operator '.and.'"
%token BITWISE_NOT "bitwise operator '.not.'"
%token FUNCTION "keyword 'function'"
%token CALL "keyword 'call'"
%token MOD "operator 'mod'"
%token LE "operator '<='"
%token GE "operator '>='"
%token RIGHT_ARROW "return type indicator '->'"
%token END_OF_FILE 0 "end of file"
%token UNKNOWN_CHAR "unknown character"

%type <nEventHandlers> script sections
%type <nEventHandler> section eventhandler
%type <nStatements> statements opt_statements
%type <nStatement> statement assignment variable_declaration global_variable_declaration
%type <nFunctionCall> functioncall
%type <nArgs> args opt_args opt_args_assignment
%type <nExpression> arg expr logical_or_expr logical_and_expr bitwise_or_expr bitwise_and_expr rel_expr add_expr mul_expr unary_expr concat_expr opt_expr_assignment opt_expr userfunctioncall opt_arr_size
%type <nCaseBranch> caseclause
%type <nCaseBranches> caseclauses
%type <varQualifier> opt_qualifiers qualifiers qualifier
%type <sValue> opt_result param
%type <nParams> opt_params params

%start script

%%

script:
    sections  {
        $$ = context->handlers = $1;
    }

sections:
    section  {
        $$ = new EventHandlers();
        if ($1) $$->add($1);
    }
    | sections section  {
        $$ = $1;
        if ($2) $$->add($2);
    }

section:
    global_variable_declaration  {
        if (!isNoOperation($1)) {
            if (!context->globalStatements)
                context->globalStatements = new Statements();
            context->globalStatements->add($1);
        }
        $$ = EventHandlerRef();
    }
    | function_declaration  {
        $$ = EventHandlerRef();
        context->dropLocalVariables();
    }
    | eventhandler  {
        $$ = $1;
        $$->assignLocalVariables(context);
        context->dropLocalVariables();
    }

global_variable_declaration:
    { context->globalScope = true; }  variable_declaration  {
        $$ = $2;
        context->globalScope = false;
    }

eventhandler:
    ON NOTE opt_statements END ON  {
        if (context->onNote)
            PARSE_ERR(@2, "Redeclaration of 'note' event handler.");
        context->onNote = new OnNote(context, $3);
        $$ = context->onNote;
    }
    | ON INIT opt_statements END ON  {
        if (context->onInit)
            PARSE_ERR(@2, "Redeclaration of 'init' event handler.");
        context->onInit =
            (context->globalStatements) ?
                new OnInit(context, context->globalStatements, $3) :
                new OnInit(context, $3);
        $$ = context->onInit;
    }
    | ON RELEASE opt_statements END ON  {
        if (context->onRelease)
            PARSE_ERR(@2, "Redeclaration of 'release' event handler.");
        context->onRelease = new OnRelease(context, $3);
        $$ = context->onRelease;
    }
    | ON CONTROLLER opt_statements END ON  {
        if (context->onController)
            PARSE_ERR(@2, "Redeclaration of 'controller' event handler.");
        context->onController = new OnController(context, $3);
        $$ = context->onController;
    }
    | ON RPN opt_statements END ON  {
        if (context->onRpn)
            PARSE_ERR(@2, "Redeclaration of 'rpn' event handler.");
        context->onRpn = new OnRpn(context, $3);
        $$ = context->onRpn;
    }
    | ON NRPN opt_statements END ON  {
        if (context->onNrpn)
            PARSE_ERR(@2, "Redeclaration of 'nrpn' event handler.");
        context->onNrpn = new OnNrpn(context, $3);
        $$ = context->onNrpn;
    }

function_declaration:
    FUNCTION IDENTIFIER opt_params opt_result opt_statements END FUNCTION  {
        const char* name = $2;
        const char* resultName = $4;
        ParamsRef params = $3;
        if (context->functionProvider->functionByName(name)) {
            PARSE_ERR(@2, (String("There is already a built-in function with name '") + name + "'.").c_str());
        } else if (context->userFunctionByName(name)) {
            PARSE_ERR(@2, (String("There is already a user defined function with name '") + name + "'.").c_str());
        } else {
            UserFunctionRef fn = new UserFunction(context, $5);
            context->userFnTable[name] = fn;
            if (resultName) {
                VariableRef resultVar = context->localVar(resultName);
                assert(resultVar);
                fn->assignResultVar(resultVar);
            }
            fn->assignParams(params);
            fn->assignLocalVariables(context);
        }
    }

opt_result:
    /* epsilon (empty argument) */  {
        $$ = NULL;
    }
    | RIGHT_ARROW VARIABLE opt_arr_size opt_args_assignment  {
        $$ = NULL; // just as default result value
        const char* name = $2;
        IntExprRef sizeExpr = $3;
        vmint size =
            (sizeExpr && sizeExpr->isConstExpr()) ? sizeExpr->evalInt() : 0;
        ArgsRef initArgs = $4;
        ExpressionRef initScalar =
            (initArgs && initArgs->argsCount() == 1) ?
                initArgs->argRef(0) : ExpressionRef();
        const ExprType_t declType = exprTypeOfVarName(name);
        if (sizeExpr && sizeExpr->isFinal())
            PARSE_WRN(@3, "Final operator '!' is meaningless here.");
        if (context->localVarTable.count(name)) {
            PARSE_ERR(@2, (String("Redeclaration of function result variable '") + name + "'.").c_str());
        } else if ($3 && !$3->isConstExpr()) {
            PARSE_ERR(@3, (String("Function result array variable '") + name + "' must be declared with constant array size.").c_str());
        } else if ($3 && $3->exprType() != INT_EXPR) {
            PARSE_ERR(@3, (String("Size of result array variable '") + name + "' declared with non integer expression.").c_str());
        } else if (size == 0 && isArray(exprTypeOfVarName(name))) {
            PARSE_ERR(@3, (String("Function result array variable '") + name + "' declared with zero array size.").c_str());
        } else if (size < 0) {
            PARSE_ERR(@3, (String("Function result array variable '") + name + "' must not be declared with negative array size.").c_str());
        } else if (sizeExpr && (sizeExpr->unitType() || sizeExpr->hasUnitFactorNow())) {
            PARSE_ERR(@3, "Units are not allowed as array size.");
        } else if (initArgs && !isArray(declType) && initArgs->argsCount() > 1) {
            PARSE_ERR(@4, (String("Function result variable '") + name + "' declared as scalar type, assigned value is array type though.").c_str());
        } else if (initScalar && !isArray(declType) && initScalar->exprType() != declType) {
            PARSE_ERR(@4, (String("Function result variable '") + name + "' declared as " + typeStr(declType) + ", " + typeStr(initScalar->exprType()) + " expression assigned though.").c_str());
        } else if (initArgs && isArray(declType) && initArgs->argsCount() != size) {
            PARSE_ERR(@4, (String("Function result array variable '") + name +
                          "' was declared with size " + ToString(size) +
                          " but " + ToString(initArgs->argsCount()) +
                          " values were assigned." ).c_str());
        } else if (name[0] == '~') {
            context->localVarTable[name] = new RealVariable({
                .ctx = context,
                .isLocal = true,
                .unitType = initScalar ? initScalar->asNumber()->unitType() : VM_NO_UNIT,
                .isFinal  = initScalar ? initScalar->asNumber()->isFinal() : false,
                .initExpr = initScalar
            });
            $$ = $2;
        } else if (name[0] == '$') {
            context->localVarTable[name] = new IntVariable({
                .ctx = context,
                .isLocal = true,
                .unitType = initScalar ? initScalar->asNumber()->unitType() : VM_NO_UNIT,
                .isFinal  = initScalar ? initScalar->asNumber()->isFinal() : false,
                .initExpr = initScalar
            });
            $$ = $2;
        } else if (name[0] == '?' || name[0] == '%') {
            bool argsOK = true;
            if (initArgs) {
                for (vmint i = 0; i < initArgs->argsCount(); ++i) {
                    VMExpr* arg = initArgs->arg(i);
                    if (arg->exprType() != scalarTypeOfArray(declType)) {
                        PARSE_ERR(
                            @4,
                            (String("Function result array variable '") + name +
                            "' declared with invalid assignment values. Assigned element " +
                            ToString(i+1) + " is not a " +
                            typeStr(scalarTypeOfArray(declType)) +
                            " expression.").c_str()
                        );
                        argsOK = false;
                        break;
                    } else if (arg->asNumber()->unitType()) {
                        PARSE_ERR(
                            @4,
                            (String("Function result array variable '") + name +
                            "' declared with invalid assignment values. Assigned element " +
                            ToString(i+1) + " contains a unit type, only metric prefixes are allowed for arrays.").c_str()
                        );
                        argsOK = false;
                        break;
                    } else if (arg->asNumber()->isFinal()) {
                        PARSE_ERR(
                            @4,
                            (String("Function result array variable '") + name +
                            "' declared with invalid assignment values. Assigned element " +
                            ToString(i+1) + " declared as 'final' value.").c_str()
                        );
                        argsOK = false;
                        break;
                    }
                }
            }
            if (argsOK) {
                if (name[0] == '?') {
                    context->localVarTable[name] = new RealArrayVariable({
                        .ctx = context,
                        .isLocal = true,
                        .elements = size,
                        .values = initArgs
                    });
                    $$ = $2;
                } else if (name[0] == '%') {
                    context->localVarTable[name] = new IntArrayVariable({
                        .ctx = context,
                        .isLocal = true,
                        .elements = size,
                        .values = initArgs
                    });
                    $$ = $2;
                }
            }
        } else if (name[0] == '@') {
            context->localVarTable[name] = new LocalStringVariable(
                context, initScalar
            );
            $$ = $2;
        } else {
            PARSE_ERR(@2, (String("Function result variable '") + name + "' declared with unknown type.").c_str());
        }
    }

opt_params:
    /* epsilon (empty argument) */  {
        $$ = new Params();
    }
    | '(' ')'  {
        $$ = new Params();
    }
    | '(' params ')'  {
        $$ = $2;
    }

params:
    param  {
        $$ = new Params();
        if ($1) {
            VariableRef var = context->localVarTable[$1];
            $$->add($1, var);
        }
    }
    | params ',' param  {
        $$ = $1;
        const char* name = $3;
        if (name) {
            VariableRef var = context->localVarTable[name];
            if ($$->paramsCount() && $$->lastParam()->initializationExpr() &&
                !var->initializationExpr())
            {
                PARSE_ERR(@3, (String("Missing default value for function argument '") + name + "'.").c_str());
            }
            $$->add(name, var);
        }
    }

param:
    VARIABLE opt_args_assignment  {
        $$ = NULL; // just as default result value
        const char* name = $1;
        ArgsRef initArgs = $2;
        ExpressionRef initScalar =
            (initArgs && initArgs->argsCount() == 1) ?
                initArgs->argRef(0) : ExpressionRef();
        const ExprType_t declType = exprTypeOfVarName(name);
        if (context->localVarTable.count(name)) {
            PARSE_ERR(@1, (String("Redeclaration of function argument '") + name + "'.").c_str());
        } else if (initArgs && !isArray(declType) && initArgs->argsCount() > 1) {
            PARSE_ERR(@2, (String("Function argument '") + name + "' declared as scalar type, assigned value is array type though.").c_str());
        } else if (initScalar && !isArray(declType) && initScalar->exprType() != declType) {
            PARSE_ERR(@2, (String("Function argument '") + name + "' declared as " + typeStr(declType) + ", " + typeStr(initScalar->exprType()) + " expression assigned though.").c_str());
        } else if (name[0] == '~') {
            context->localVarTable[name] = new RealVariable({
                .ctx = context,
                .isLocal = true,
                .unitType = initScalar ? initScalar->asNumber()->unitType() : VM_NO_UNIT,
                .isFinal  = initScalar ? initScalar->asNumber()->isFinal() : false,
                .initExpr = initScalar
            });
            $$ = $1;
        } else if (name[0] == '$') {
            context->localVarTable[name] = new IntVariable({
                .ctx = context,
                .isLocal = true,
                .unitType = initScalar ? initScalar->asNumber()->unitType() : VM_NO_UNIT,
                .isFinal  = initScalar ? initScalar->asNumber()->isFinal() : false,
                .initExpr = initScalar
            });
            $$ = $1;
        } else if (name[0] == '?') {
            PARSE_ERR(@1, "Real array type is not allowed for arguments of user declared functions.");
        } else if (name[0] == '%') {
            PARSE_ERR(@1, "Integer array type is not allowed for arguments of user declared functions.");
        } else if (name[0] == '@') {
            context->localVarTable[name] = new LocalStringVariable(
                context, initScalar
            );
            $$ = $1;
        } else {
            PARSE_ERR(@1, (String("Function argument '") + name + "' declared with unknown type.").c_str());
        }
    }

opt_arr_size:
    /* epsilon (empty argument) */  {
        $$ = NULL;
    }
    | '[' opt_expr ']'  {
        $$ = $2;
    }

opt_statements:
    /* epsilon (empty argument) */  {
        $$ = new Statements();
    }
    | statements  {
        $$ = $1;
    }

statements:
    statement  {
        $$ = new Statements();
        if ($1) {
            if (!isNoOperation($1)) $$->add($1); // filter out NoOperation statements
        } else 
            PARSE_WRN(@1, "Not a statement.");
    }
    | statements statement  {
        $$ = $1;
        if ($2) {
            if (!isNoOperation($2)) $$->add($2); // filter out NoOperation statements
        } else
            PARSE_WRN(@2, "Not a statement.");
    }

statement:
    functioncall  {
        $$ = $1;
    }
    | userfunctioncall  {
        $$ = $1;
    }
    | variable_declaration  {
        $$ = $1;
    }
    | assignment  {
        $$ = $1;
    }
    | WHILE '(' expr ')' opt_statements END WHILE  {
        if ($3->exprType() == INT_EXPR) {
            IntExprRef expr = $3;
            if (expr->asNumber()->unitType() ||
                expr->asNumber()->hasUnitFactorEver())
                PARSE_WRN(@3, "Condition for 'while' loops contains a unit.");
            else if (expr->isFinal() && expr->isConstExpr())
                PARSE_WRN(@3, "Final operator '!' is meaningless here.");
            $$ = new While(expr, $5);
        } else {
            PARSE_ERR(@3, "Condition for 'while' loops must be integer expression.");
            $$ = new While(new IntLiteral({ .value = 0 }), $5);
        }
    }
    | SYNCHRONIZED opt_statements END SYNCHRONIZED  {
        $$ = new SyncBlock($2);
    }
    | IF '(' expr ')' opt_statements ELSE opt_statements END IF  {
        if ($3->exprType() == INT_EXPR) {
            IntExprRef expr = $3;
            if (expr->asNumber()->unitType() ||
                expr->asNumber()->hasUnitFactorEver())
                PARSE_WRN(@3, "Condition for 'if' contains a unit.");
            else if (expr->isFinal() && expr->isConstExpr())
                PARSE_WRN(@3, "Final operator '!' is meaningless here.");
            $$ = new If($3, $5, $7);
        } else {
            PARSE_ERR(@3, "Condition for 'if' must be integer expression.");
            $$ = new If(new IntLiteral({ .value = 0 }), $5, $7);
        }
    }
    | IF '(' expr ')' opt_statements END IF  {
        if ($3->exprType() == INT_EXPR) {
            IntExprRef expr = $3;
            if (expr->asNumber()->unitType() ||
                expr->asNumber()->hasUnitFactorEver())
                PARSE_WRN(@3, "Condition for 'if' contains a unit.");
            else if (expr->isFinal() && expr->isConstExpr())
                PARSE_WRN(@3, "Final operator '!' is meaningless here.");
            $$ = new If($3, $5);
        } else {
            PARSE_ERR(@3, "Condition for 'if' must be integer expression.");
            $$ = new If(new IntLiteral({ .value = 0 }), $5);
        }
    }
    | SELECT expr caseclauses END SELECT  {
        if ($2->exprType() == INT_EXPR) {
            IntExprRef expr = $2;
            if (expr->unitType() || expr->hasUnitFactorEver()) {
                PARSE_ERR(@2, "Units are not allowed here.");
                $$ = new SelectCase(new IntLiteral({ .value = 0 }), $3);
            } else {
                if (expr->isFinal() && expr->isConstExpr())
                    PARSE_WRN(@2, "Final operator '!' is meaningless here.");
                $$ = new SelectCase(expr, $3);
            }
        } else {
            PARSE_ERR(@2, "Statement 'select' can only by applied to integer expressions.");
            $$ = new SelectCase(new IntLiteral({ .value = 0 }), $3);
        }
    }

caseclauses:
    caseclause  {
        $$ = CaseBranches();
        $$.push_back($1);
    }
    | caseclauses caseclause  {
        $$ = $1;
        $$.push_back($2);
    }

caseclause:
    CASE INTEGER opt_statements  {
        $$ = CaseBranch();
        $$.from = new IntLiteral({ .value = $2 });
        $$.statements = $3;
    }
    | CASE INTEGER TO INTEGER opt_statements  {
        $$ = CaseBranch();
        $$.from = new IntLiteral({ .value = $2 });
        $$.to   = new IntLiteral({ .value = $4 });
        $$.statements = $5;
    }

variable_declaration:
    DECLARE opt_qualifiers VARIABLE opt_expr_assignment  {
        $$ = new NoOperation; // just as default result value
        const bool qConst      = $2 & QUALIFIER_CONST;
        const bool qPolyphonic = $2 & QUALIFIER_POLYPHONIC;
        const bool qPatch      = $2 & QUALIFIER_PATCH;
        const bool qLocal      = $2 & QUALIFIER_LOCAL;
        const char* name = $3;
        ExpressionRef expr = $4;
        //printf("declared var '%s'\n", name);
        const ExprType_t declType = exprTypeOfVarName(name);
        if (qPatch) {
            context->patchVars[name].nameBlock = CODE_BLOCK(@3);
            if (expr)
                context->patchVars[name].exprBlock = ASSIGNED_EXPR_BLOCK(@4);
        }
        if (qLocal && context->globalScope) {
            PARSE_ERR(@2, (String("Variable '") + name + "' cannot be declared as local variable in global scope.").c_str());
        } else if (qLocal && context->localVar(name)) {
            PARSE_ERR(@3, (String("Redeclaration of local variable '") + name + "'.").c_str());
        } else if (!qLocal && context->globalVar(name)) {
            PARSE_ERR(@3, (String("Redeclaration of global variable '") + name + "'.").c_str());
        } else if (qConst && !expr) {
            PARSE_ERR(@2, (String("Variable '") + name + "' declared const without value assignment.").c_str());
        } else if (qConst && !expr->isConstExpr()) {
            PARSE_ERR(@4, (String("Assignment to const variable '") + name + "' requires const expression.").c_str());
        } else if (qConst && qPolyphonic) {
            PARSE_ERR(@2, (String("Variable '") + name + "' must not be declared both const and polyphonic.").c_str());
        } else if (qLocal && qPolyphonic) {
            PARSE_ERR(@2, (String("Variable '") + name + "' must not be declared both local and polyphonic.").c_str());
        } else if (expr && expr->exprType() != declType) {
            PARSE_ERR(@3, (String("Variable '") + name + "' declared as " + typeStr(declType) + ", " + typeStr(expr->exprType()) + " expression assigned though.").c_str());
        } else if (qPolyphonic && !isNumber(declType)) {
            PARSE_ERR(@3, "Polyphonic variables must only be declared either as integer or real number type.");
        } else {
            VariableRef var;

            if (name[0] == '$') {
                IntExprRef intExpr = expr;
                if (qConst) {
                    var = new ConstIntVariable(
                        #if defined(__GNUC__) && !defined(__clang__)
                        (const IntVarDef&) // GCC 8.x requires this cast here (looks like a GCC bug to me); cast would cause an error with clang though
                        #endif
                    {
                        .value = intExpr->evalInt(),
                        .unitFactor = intExpr->unitFactor(),
                        .unitType = intExpr->unitType(),
                        .isFinal = intExpr->isFinal()
                    });
                } else {
                    var = new IntVariable({
                        .ctx = context,
                        .isPolyphonic = qPolyphonic,
                        .isLocal = qLocal,
                        .unitType = intExpr ? intExpr->unitType() : VM_NO_UNIT,
                        .isFinal = intExpr ? intExpr->isFinal() : false
                    });
                }
                if (intExpr) {
                    if (intExpr->isConstExpr()) {
                        $$ = new Assignment(var, new IntLiteral({
                            .value = intExpr->evalInt(),
                            .unitFactor = intExpr->unitFactor(),
                            .unitType = intExpr->unitType(),
                            .isFinal = intExpr->isFinal()
                        }));
                    } else {
                        $$ = new Assignment(var, intExpr);
                    }
                }
            } else if (name[0] == '~') {
                RealExprRef realExpr = expr;
                if (qConst) {
                    var = new ConstRealVariable(
                        #if defined(__GNUC__) && !defined(__clang__)
                        (const RealVarDef&) // GCC 8.x requires this cast here (looks like a GCC bug to me); cast would cause an error with clang though
                        #endif
                    {
                        .value = realExpr->evalReal(),
                        .unitFactor = realExpr->unitFactor(),
                        .unitType = realExpr->unitType(),
                        .isFinal = realExpr->isFinal()
                    });
                } else {
                    var = new RealVariable({
                        .ctx = context,
                        .isPolyphonic = qPolyphonic,
                        .isLocal = qLocal,
                        .unitType = realExpr ? realExpr->unitType() : VM_NO_UNIT,
                        .isFinal = realExpr ? realExpr->isFinal() : false
                    });
                }
                if (realExpr) {
                    if (realExpr->isConstExpr()) {
                        $$ = new Assignment(var, new RealLiteral({
                            .value = realExpr->evalReal(),
                            .unitFactor = realExpr->unitFactor(),
                            .unitType = realExpr->unitType(),
                            .isFinal = realExpr->isFinal()
                        }));
                    } else {
                        $$ = new Assignment(var, realExpr);
                    }
                }
            } else if (name[0] == '@') {
                StringExprRef strExpr = expr;
                if (qConst) {
                    var = new ConstStringVariable(context, strExpr->evalStr());
                } else {
                    var = (qLocal) ? new LocalStringVariable(context)
                                   : new StringVariable(context);
                }
                if (strExpr) {
                    if (strExpr->isConstExpr()) {
                        $$ = new Assignment(var, new StringLiteral(strExpr->evalStr()));
                    } else {
                        $$ = new Assignment(var, strExpr);
                    }
                }
            } else if (name[0] == '?') {
                PARSE_ERR(@3, (String("Real number array variable '") + name + "' declaration requires array size.").c_str());
            } else if (name[0] == '%') {
                PARSE_ERR(@3, (String("Integer array variable '") + name + "' declaration requires array size.").c_str());
            } else {
                PARSE_ERR(@3, (String("Variable '") + name + "' declared with unknown type.").c_str());
            }

            if (var) {
                if (qLocal)
                    context->localVarTable[name] = var;
                else
                    context->globalVarTable[name] = var;
            }
        }
    }
    | DECLARE opt_qualifiers VARIABLE '[' opt_expr ']' opt_args_assignment  {
        $$ = new NoOperation; // just as default result value
        const bool qConst      = $2 & QUALIFIER_CONST;
        const bool qPolyphonic = $2 & QUALIFIER_POLYPHONIC;
        const bool qPatch      = $2 & QUALIFIER_PATCH;
        const bool qLocal      = $2 & QUALIFIER_LOCAL;
        const char* name = $3;
        IntExprRef sizeExpr = $5;
        ArgsRef args = $7;
        const ExprType_t declType = exprTypeOfVarName(name);
        const vmint size =
            (sizeExpr && sizeExpr->isConstExpr()) ?
                sizeExpr->evalInt() : args ? args->argsCount() : 0;
        if (qPatch) {
            context->patchVars[name].nameBlock = CODE_BLOCK(@3);
            if (args)
                context->patchVars[name].exprBlock = ASSIGNED_EXPR_BLOCK(@7);
        }
        if (name[0] == '$') {
            PARSE_ERR(@3, (String("Variable '") + name + "' declaration ambiguous: Use '%' as name prefix for integer arrays instead of '$'.").c_str());
        } else if (name[0] == '~') {
            PARSE_ERR(@3, (String("Variable '") + name + "' declaration ambiguous: Use '?' as name prefix for real number arrays instead of '~'.").c_str());
        } else if (name[0] != '%' && name[0] != '?' ) {
            PARSE_ERR(@3, (String("Variable '") + name + "' declared as unknown array type: use either '%' or '?' instead of '" + String(name).substr(0,1) + "'.").c_str());
        } else if ($5 && !$5->isConstExpr()) {
            PARSE_ERR(@5, (String("Array variable '") + name + "' must be declared with constant array size.").c_str());
        } else if ($5 && $5->exprType() != INT_EXPR) {
            PARSE_ERR(@5, (String("Size of array variable '") + name + "' declared with non integer expression.").c_str());
        } else if (sizeExpr && (sizeExpr->unitType() || sizeExpr->hasUnitFactorNow())) {
            PARSE_ERR(@5, "Units are not allowed as array size.");
        } else if (qLocal && context->globalScope) {
            PARSE_ERR(@2, (String("Array variable '") + name + "' cannot be declared as local variable in global scope.").c_str());
        } else if (qLocal && context->localVar(name)) {
            PARSE_ERR(@3, (String("Redeclaration of local variable '") + name + "'.").c_str());
        } else if (!qLocal && context->globalVar(name)) {
            PARSE_ERR(@3, (String("Redeclaration of global variable '") + name + "'.").c_str());
        } else if (qConst && !$7) {
            PARSE_ERR(@2, (String("Array variable '") + name + "' declared const without value assignment.").c_str());
        } else if (qPolyphonic) {
            PARSE_ERR(@2, (String("Array variable '") + name + "' must not be declared polyphonic.").c_str());
        } else if (size < 0) {
            PARSE_ERR(@5, (String("Array variable '") + name + "' must not be declared with negative array size.").c_str());
        } else if (size == 0) {
            PARSE_ERR(@5, (String("Array variable '") + name + "' declared with zero array size.").c_str());
        } else if (args && args->argsCount() > size) {
            PARSE_ERR(@7, (String("Array variable '") + name +
                      "' was declared with size " + ToString(size) +
                      " but " + ToString(args->argsCount()) +
                      " values were assigned." ).c_str());
        } else {
            if (sizeExpr && sizeExpr->isFinal())
                PARSE_WRN(@5, "Final operator '!' is meaningless here.");
            if (args && args->argsCount() < size)
                PARSE_WRN(@5, (String("Array variable '") + name +
                          "' was declared with size " + ToString(size) +
                          " but only " + ToString(args->argsCount()) +
                          " values were assigned." ).c_str());
            bool argsOK = true;
            if (args) {
                for (vmint i = 0; i < args->argsCount(); ++i) {
                    if (args->arg(i)->exprType() != scalarTypeOfArray(declType)) {
                        PARSE_ERR(
                            @7,
                            (String("Array variable '") + name +
                            "' declared with invalid assignment values. Assigned element " +
                            ToString(i+1) + " is not an " + typeStr(declType) + " expression.").c_str()
                        );
                        argsOK = false;
                        break;
                    } else if (qConst && !args->arg(i)->isConstExpr()) {
                        PARSE_ERR(
                            @7,
                            (String("const array variable '") + name +
                            "' must be defined with const values. Assigned element " +
                            ToString(i+1) + " is not a const expression though.").c_str()
                        );
                        argsOK = false;
                        break;
                    } else if (args->arg(i)->asNumber()->unitType()) {
                        PARSE_ERR(
                            @7,
                            (String("Array variable '") + name +
                            "' declared with invalid assignment values. Assigned element " +
                            ToString(i+1) + " contains a unit type, only metric prefixes are allowed for arrays.").c_str()
                        );
                        argsOK = false;
                        break;
                    } else if (args->arg(i)->asNumber()->isFinal()) {
                        PARSE_ERR(
                            @7,
                            (String("Array variable '") + name +
                            "' declared with invalid assignment values. Assigned element " +
                            ToString(i+1) + " declared as 'final' value.").c_str()
                        );
                        argsOK = false;
                        break;
                    }
                }
            }
            if (argsOK) {
                VariableRef var;
                if (declType == REAL_ARR_EXPR)
                    var = new RealArrayVariable({
                        .ctx = context,
                        .isConst = qConst,
                        .isLocal = qLocal,
                        .elements = size,
                        .values = args,
                    });
                else
                    var = new IntArrayVariable({
                        .ctx = context,
                        .isConst = qConst,
                        .isLocal = qLocal,
                        .elements = size,
                        .values = args,
                    });
                if (qLocal) {
                    context->localVarTable[name] = var;
                    if (args)
                        $$ = new ArrayArgsAssignment(var, args);
                } else {
                    context->globalVarTable[name] = var;
                }
            }
        }
    }

userfunctioncall:
    CALL IDENTIFIER opt_args  {
        const char* name = $2;
        ArgsRef args = $3;
        UserFunctionRef fn = context->userFunctionByName(name);
        if (context->functionProvider->functionByName(name)) {
            PARSE_ERR(@1, (String("Keyword 'call' must only be used for user defined functions, not for any built-in function like '") + name + "'.").c_str());
            $$ = new UserFunctionCall("<invalid>", new UserFunction(context, new Statements()), new Args());
        } else if (!fn) {
            PARSE_ERR(@2, (String("No user defined function with name '") + name + "'.").c_str());
            $$ = new UserFunctionCall("<invalid>", new UserFunction(context, new Statements()), new Args());
        } else if (args->argsCount() < fn->params()->minRequiredArgs()) {
            PARSE_ERR(@3, (String("User declared function '") + name + "' requires " + ToString(fn->params()->minRequiredArgs()) + " arguments, " + ToString(args->argsCount()) + " were provided though.").c_str());
            $$ = new UserFunctionCall("<invalid>", new UserFunction(context, new Statements()), new Args());
        } else if (args->argsCount() > fn->params()->maxAllowedArgs()) {
            PARSE_ERR(@3, (String("User declared function '") + name + "' accepts not more than " + ToString(fn->params()->maxAllowedArgs()) + " arguments, " + ToString(args->argsCount()) + " were provided though.").c_str());
            $$ = new UserFunctionCall("<invalid>", new UserFunction(context, new Statements()), new Args());
        } else {
            bool argsOK = true;
            for (vmint i = 0; i < args->argsCount(); ++i) {
                VMExpr* arg = args->arg(i);
                Variable* param = fn->params()->param(i);
                NumberVariable* numParam = dynamic_cast<NumberVariable*>(param);
                String paramName = fn->params()->paramName(i);
                if (arg->exprType() != param->exprType()) {
                    PARSE_ERR(@3, (String("Argument '") + paramName + "' of user declared function '" + name + "' expects type " + typeStr(param->exprType()) + ", passed type is " + typeStr(arg->exprType()) + " though.").c_str());
                    argsOK = false;
                    break;
                } else if (isNumber(arg->exprType()) && arg->asNumber()->unitType() != numParam->unitType()) {
                    if (numParam->unitType()) {
                        PARSE_ERR(@3, (String("Argument '") + paramName + "' of user declared function '" + name + "' expects unit " + unitTypeStr(numParam->unitType()) + ", passed argument has unit type " + unitTypeStr(arg->asNumber()->unitType()) + " though.").c_str());
                    } else {
                        PARSE_ERR(@3, (String("Argument '") + paramName + "' of user declared function '" + name + "' does not expect any unit, passed argument has unit type " + unitTypeStr(arg->asNumber()->unitType()) + " though.").c_str());
                    }
                    argsOK = false;
                    break;
                } else if (isNumber(arg->exprType()) && arg->asNumber()->isFinal() != numParam->isFinal()) {
                    PARSE_ERR(@3, (String("Argument '") + paramName + "' of user declared function '" + name + "' was declared as " + String(numParam->isFinal() ? "final" : "not final") + ", passed argument is " + String(arg->asNumber()->isFinal() ? "final" : "not final") + " though.").c_str());
                    argsOK = false;
                    break;
                }
            }
            if (!argsOK) {
                $$ = new UserFunctionCall("<invalid>", new UserFunction(context, new Statements()), new Args());
            } else {
                UserFunctionCallRef fnCall = new UserFunctionCall(name, fn, args);
                //FIXME: get rid of this initUserFunctionCall() call
                fnCall->initUserFunctionCall(fnCall);
                $$ = fnCall;
            }
        }
    }

functioncall:
    IDENTIFIER opt_args  {
        const char* name = $1;
        //printf("function call of '%s'\n", name);
        ArgsRef args = $2;
        VMFunction* fn = context->functionProvider->functionByName(name);
        if (context->userFunctionByName(name)) {
            PARSE_ERR(@1, (String("Missing 'call' keyword before user defined function name '") + name + "'.").c_str());
            $$ = new FunctionCall(name, args, NULL);
        } else if (!fn) {
            PARSE_ERR(@1, (String("No built-in function with name '") + name + "'.").c_str());
            $$ = new FunctionCall(name, args, NULL);
        } else if (context->functionProvider->isFunctionDisabled(fn,context)) {
            PARSE_DROP(@$);
            $$ = new NoFunctionCall;
        } else if (args->argsCount() < fn->minRequiredArgs()) {
            PARSE_ERR(@2, (String("Built-in function '") + name + "' requires at least " + ToString(fn->minRequiredArgs()) + " arguments.").c_str());
            $$ = new FunctionCall(name, args, NULL);
        } else if (args->argsCount() > fn->maxAllowedArgs()) {
            PARSE_ERR(@2, (String("Built-in function '") + name + "' accepts max. " + ToString(fn->maxAllowedArgs()) + " arguments.").c_str());
            $$ = new FunctionCall(name, args, NULL);
        } else {
            bool argsOK = true;
            for (vmint i = 0; i < args->argsCount(); ++i) {
                if (!fn->acceptsArgType(i, args->arg(i)->exprType())) {
                    PARSE_ERR(@2, (String("Argument ") + ToString(i+1) + " of built-in function '" + name + "' expects " + acceptedArgTypesStr(fn, i) + " type, but type " + typeStr(args->arg(i)->exprType()) + " was given instead.").c_str());
                    argsOK = false;
                    break;
                } else if (fn->modifiesArg(i) && !args->arg(i)->isModifyable()) {
                    PARSE_ERR(@2, (String("Argument ") + ToString(i+1) + " of built-in function '" + name + "' expects an assignable variable.").c_str());
                    argsOK = false;
                    break;
                } else if (isNumber(args->arg(i)->exprType()) && !fn->acceptsArgUnitType(i, args->arg(i)->asNumber()->unitType())) {
                    if (args->arg(i)->asNumber()->unitType())
                        PARSE_ERR(@2, (String("Argument ") + ToString(i+1) + " of built-in function '" + name + "' does not expect unit " + unitTypeStr(args->arg(i)->asNumber()->unitType()) +  ".").c_str());
                    else
                        PARSE_ERR(@2, (String("Argument ") + ToString(i+1) + " of built-in function '" + name + "' expects a unit.").c_str());
                    argsOK = false;
                    break;
                } else if (isNumber(args->arg(i)->exprType()) && args->arg(i)->asNumber()->hasUnitFactorEver() && !fn->acceptsArgUnitPrefix(i, args->arg(i)->asNumber()->unitType())) {
                    if (args->arg(i)->asNumber()->unitType())
                        PARSE_ERR(@2, (String("Argument ") + ToString(i+1) + " of built-in function '" + name + "' does not expect a unit prefix for unit" + unitTypeStr(args->arg(i)->asNumber()->unitType()) + ".").c_str());
                    else
                        PARSE_ERR(@2, (String("Argument ") + ToString(i+1) + " of built-in function '" + name + "' does not expect a unit prefix.").c_str());
                    argsOK = false;
                    break;
                } else if (!fn->acceptsArgFinal(i) && isNumber(args->arg(i)->exprType()) && args->arg(i)->asNumber()->isFinal()) {
                    PARSE_ERR(@2, (String("Argument ") + ToString(i+1) + " of built-in function '" + name + "' does not expect a \"final\" value.").c_str());
                    argsOK = false;
                    break;
                }
            }
            if (args->argsCount() && argsOK) {
                // perform built-in function's own, custom arguments checks (if any)
                fn->checkArgs(&*args, [&](String err) {
                    PARSE_ERR(@2, (String("Built-in function '") + name + "()': " + err).c_str());
                    argsOK = false;
                }, [&](String wrn) {
                    PARSE_WRN(@2, (String("Built-in function '") + name + "()': " + wrn).c_str());
                });
            }
            $$ = new FunctionCall(name, args, argsOK ? fn : NULL);
        }
    }

opt_args:
    /* epsilon (empty argument) */  {
        $$ = new Args();
    }
    | '(' ')'  {
        $$ = new Args();
    }
    | '(' args ')'  {
        $$ = $2;
    }

args:
    arg  {
        $$ = new Args();
        $$->add($1);
    }
    | args ',' arg  {
        $$ = $1;
        $$->add($3);
    }

arg:
    expr

opt_qualifiers:
    /* epsilon (empty argument) */  {
        $$ = QUALIFIER_NONE;
    }
    | qualifiers  {
        $$ = $1;
    }

qualifiers:
    qualifier  {
        $$ = $1;
    }
    | qualifiers qualifier  {
        if ($1 & $2)
            PARSE_ERR(@2, ("Qualifier '" + qualifierStr($2) + "' must only be listed once.").c_str());
        $$ = (Qualifier_t) ($1 | $2);
    }

qualifier:
    CONST_  {
        $$ = QUALIFIER_CONST;
    }
    | POLYPHONIC  {
        $$ = QUALIFIER_POLYPHONIC;
    }
    | PATCH  {
        $$ = QUALIFIER_PATCH;
    }
    | LOCAL  {
        $$ = QUALIFIER_LOCAL;
    }

opt_expr_assignment:
    /* epsilon (empty argument) */  {
        $$ = ExpressionRef();
    }
    | ASSIGNMENT expr  {
        $$ = $2;
    }

opt_args_assignment:
    /* epsilon (empty argument) */  {
        $$ = ArgsRef();
    }
    | ASSIGNMENT '(' args ',' arg ')'  {
        $$ = $3;
        $$->add($5);
    }
    | ASSIGNMENT arg  {
        $$ = new Args();
        $$->add($2);
    }

assignment:
    VARIABLE ASSIGNMENT expr  {
        //printf("variable lookup with name '%s' as assignment expr\n", $1);
        const char* name = $1;
        VariableRef var = context->variableByName(name);
        if (!var)
            PARSE_ERR(@1, (String("Variable assignment: No variable declared with name '") + name + "'.").c_str());
        else if (var->isConstExpr())
            PARSE_ERR(@2, (String("Variable assignment: Cannot modify const variable '") + name + "'.").c_str());
        else if (!var->isAssignable())
            PARSE_ERR(@2, (String("Variable assignment: Variable '") + name + "' is not assignable.").c_str());
        else if (var->exprType() != $3->exprType())
            PARSE_ERR(@3, (String("Variable assignment: Variable '") + name + "' is of type " + typeStr(var->exprType()) + ", assignment is of type " + typeStr($3->exprType()) + " though.").c_str());
        else if (isArray(var->exprType()))
            PARSE_ERR(@2, "Variable assignment: Cannot assign entire arrays; use array subscript operator [] for assigning individual array elements instead.");
        else if (isNumber(var->exprType())) {
            NumberVariableRef numberVar = var;
            NumberExprRef expr = $3;
            if (numberVar->unitType() != expr->unitType())
                PARSE_ERR(@3, (String("Variable assignment: Variable '") + name + "' has unit type " + unitTypeStr(numberVar->unitType()) + ", assignment has unit type " + unitTypeStr(expr->unitType()) + " though.").c_str());
            else if (numberVar->isFinal() != expr->isFinal())
                PARSE_ERR(@3, (String("Variable assignment: Variable '") + name + "' was declared as " + String(numberVar->isFinal() ? "final" : "not final") + ", assignment is " + String(expr->isFinal() ? "final" : "not final") + " though.").c_str());
        }

        if (var)
            $$ = new Assignment(var, $3);
        else
            $$ = new NoOperation;
    }
    | VARIABLE '[' expr ']' ASSIGNMENT expr  {
        const char* name = $1;
        VariableRef var = context->variableByName(name);
        if (!var)
            PARSE_ERR(@1, (String("No variable declared with name '") + name + "'.").c_str());
        else if (!isArray(var->exprType()))
            PARSE_ERR(@2, (String("Variable '") + name + "' is not an array variable.").c_str());
        else if (var->isConstExpr())
            PARSE_ERR(@5, (String("Variable assignment: Cannot modify const array variable '") + name + "'.").c_str());
        else if (!var->isAssignable())
            PARSE_ERR(@5, (String("Variable assignment: Array variable '") + name + "' is not assignable.").c_str());
        else if ($3->exprType() != INT_EXPR)
            PARSE_ERR(@3, (String("Array variable '") + name + "' accessed with non integer expression.").c_str());
        else if ($3->asInt()->unitType())
            PARSE_ERR(@3, "Unit types are not allowed as array index.");
        else if ($6->exprType() != scalarTypeOfArray(var->exprType()))
            PARSE_ERR(@5, (String("Variable '") + name + "' was declared as " + typeStr(var->exprType()) + ", assigned expression is " + typeStr($6->exprType()) + " though.").c_str());
        else if ($6->asNumber()->unitType())
            PARSE_ERR(@6, "Unit types are not allowed for array variables.");
        else if ($6->asNumber()->isFinal())
            PARSE_ERR(@6, "Final operator '!' not allowed for array variables.");
        else if ($3->isConstExpr() && $3->asInt()->evalInt() >= ((ArrayExprRef)var)->arraySize())
            PARSE_WRN(@3, (String("Index ") + ToString($3->asInt()->evalInt()) +
                          " exceeds size of array variable '" + name +
                          "' which was declared with size " +
                          ToString(((ArrayExprRef)var)->arraySize()) + ".").c_str());
        else if ($3->asInt()->isFinal())
            PARSE_WRN(@3, "Final operator '!' is meaningless here.");

        if (!var) {
            $$ = new NoOperation;
        } else if (var->exprType() == INT_ARR_EXPR) {
            IntArrayElementRef element = new IntArrayElement(var, $3);
            $$ = new Assignment(element, $6);
        } else if (var->exprType() == REAL_ARR_EXPR) {
            RealArrayElementRef element = new RealArrayElement(var, $3);
            $$ = new Assignment(element, $6);
        }
    }

unary_expr:
    INTEGER  {
        $$ = new IntLiteral({ .value = $1 });
    }
    | REAL  {
        $$ = new RealLiteral({ .value = $1 });
    }
    | INTEGER_UNIT  {
        IntLiteralRef literal = new IntLiteral({
            .value = $1.iValue,
            .unitFactor = VMUnit::unitFactor($1.prefix),
            .unitType = $1.unit
        });
        $$ = literal;
    }
    | REAL_UNIT  {
        RealLiteralRef literal = new RealLiteral({
            .value = $1.fValue,
            .unitFactor = VMUnit::unitFactor($1.prefix),
            .unitType = $1.unit
        });
        $$ = literal;
    }
    | STRING    {
        $$ = new StringLiteral($1);
    }
    | VARIABLE  {
        //printf("variable lookup with name '%s' as unary expr\n", $1);
        VariableRef var = context->variableByName($1);
        if (var)
            $$ = var;
        else {
            PARSE_ERR(@1, (String("No variable declared with name '") + $1 + "'.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        }
    }
    | VARIABLE '[' expr ']'  {
        const char* name = $1;
        VariableRef var = context->variableByName(name);
        if (!var) {
            PARSE_ERR(@1, (String("No variable declared with name '") + name + "'.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isArray(var->exprType())) {
            PARSE_ERR(@2, (String("Variable '") + name + "' is not an array variable.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if ($3->exprType() != INT_EXPR) {
            PARSE_ERR(@3, (String("Array variable '") + name + "' accessed with non integer expression.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if ($3->asInt()->unitType() || $3->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@3, "Units are not allowed as array index.");
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if ($3->isConstExpr() && $3->asInt()->evalInt() >= ((ArrayExprRef)var)->arraySize())
                PARSE_WRN(@3, (String("Index ") + ToString($3->asInt()->evalInt()) +
                               " exceeds size of array variable '" + name +
                               "' which was declared with size " +
                               ToString(((ArrayExprRef)var)->arraySize()) + ".").c_str());
            else if ($3->asInt()->isFinal())
                PARSE_WRN(@3, "Final operator '!' is meaningless here.");
            if (var->exprType() == REAL_ARR_EXPR) {
                $$ = new RealArrayElement(var, $3);
            } else {
                $$ = new IntArrayElement(var, $3);
            }
        }
    }
    | '(' expr ')'  {
        $$ = $2;
    }
    | functioncall  {
        $$ = $1;
    }
    | userfunctioncall  {
        $$ = $1;
    }
    | userfunctioncall '[' expr ']'  {
        UserFunctionCallRef fn = $1;
        if (!isArray(fn->exprType())) {
            PARSE_ERR(@2, ("User function '" + fn->functionName() + "' does not return an array.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if ($3->exprType() != INT_EXPR) {
            PARSE_ERR(@3, ("Array result of user function '" + fn->functionName() + "' accessed with non integer expression.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if ($3->asInt()->unitType() || $3->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@3, "Units are not allowed as array index.");
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if ($3->isConstExpr() &&
                $3->asInt()->evalInt() >= fn->arraySize())
                PARSE_WRN(@3, ("Index " + ToString($3->asInt()->evalInt()) +
                               " exceeds size of result of user function '" + fn->functionName() +
                               "' which was declared to return an array of size " +
                               ToString(fn->arraySize()) + ".").c_str());
            if (fn->exprType() == REAL_ARR_EXPR) {
                $$ = new RealArrayElement(fn, $3);
            } else {
                $$ = new IntArrayElement(fn, $3);
            }
        }
    }
    | '+' unary_expr  {
        if (isNumber($2->exprType())) {
            $$ = $2;
        } else {
            PARSE_ERR(@2, (String("Unary '+' operator requires number, is ") + typeStr($2->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        }
    }
    | '-' unary_expr  {
        if (isNumber($2->exprType())) {
            $$ = new Neg($2);
        } else {
            PARSE_ERR(@2, (String("Unary '-' operator requires number, is ") + typeStr($2->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        }
    }
    | BITWISE_NOT unary_expr  {
        if ($2->exprType() != INT_EXPR) {
            PARSE_ERR(@2, (String("Right operand of bitwise operator '.not.' must be an integer expression, is ") + typeStr($2->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if ($2->asInt()->unitType() || $2->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@2, "Units are not allowed for operands of bitwise operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else {
            $$ = new BitwiseNot($2);
        }
    }
    | NOT unary_expr  {
        if ($2->exprType() != INT_EXPR) {
            PARSE_ERR(@2, (String("Right operand of operator 'not' must be an integer expression, is ") + typeStr($2->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if ($2->asInt()->unitType() || $2->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@2, "Units are not allowed for operands of logical operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else {
            $$ = new Not($2);
        }
    }
    | '!' unary_expr  {
        if (!isNumber($2->exprType())) {
            PARSE_ERR(@2, (String("Right operand of \"final\" operator '!' must be a scalar number expression, is ") + typeStr($2->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            $$ = new Final($2);
        }
    }

opt_expr:
    /* epsilon (empty argument) */  {
        $$ = NULL;
    }
    | expr  {
        $$ = $1;
    }

expr:
    concat_expr

concat_expr:
    logical_or_expr
    | concat_expr '&' logical_or_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (lhs->isConstExpr() && rhs->isConstExpr()) {
            $$ = new StringLiteral(
                lhs->evalCastToStr() + rhs->evalCastToStr()
            );
        } else {
            $$ = new ConcatString(lhs, rhs);
        }
    }

logical_or_expr:
    logical_and_expr
    | logical_or_expr OR logical_and_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (lhs->exprType() != INT_EXPR) {
            PARSE_ERR(@1, (String("Left operand of operator 'or' must be an integer expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->exprType() != INT_EXPR) {
            PARSE_ERR(@3, (String("Right operand of operator 'or' must be an integer expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asInt()->unitType() || lhs->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@1, "Units are not allowed for operands of logical operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->asInt()->unitType() || rhs->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@3, "Units are not allowed for operands of logical operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asInt()->isFinal() && !rhs->asInt()->isFinal())
                PARSE_WRN(@3, "Right operand of 'or' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asInt()->isFinal() && rhs->asInt()->isFinal())
                PARSE_WRN(@1, "Left operand of 'or' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new Or(lhs, rhs);
        }
    }

logical_and_expr:
    bitwise_or_expr  {
        $$ = $1;
    }
    | logical_and_expr AND bitwise_or_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (lhs->exprType() != INT_EXPR) {
            PARSE_ERR(@1, (String("Left operand of operator 'and' must be an integer expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->exprType() != INT_EXPR) {
            PARSE_ERR(@3, (String("Right operand of operator 'and' must be an integer expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asInt()->unitType() || lhs->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@1, "Units are not allowed for operands of logical operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->asInt()->unitType() || rhs->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@3, "Units are not allowed for operands of logical operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asInt()->isFinal() && !rhs->asInt()->isFinal())
                PARSE_WRN(@3, "Right operand of 'and' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asInt()->isFinal() && rhs->asInt()->isFinal())
                PARSE_WRN(@1, "Left operand of 'and' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new And(lhs, rhs);
        }
    }

bitwise_or_expr:
    bitwise_and_expr
    | bitwise_or_expr BITWISE_OR bitwise_and_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (lhs->exprType() != INT_EXPR) {
            PARSE_ERR(@1, (String("Left operand of bitwise operator '.or.' must be an integer expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->exprType() != INT_EXPR) {
            PARSE_ERR(@3, (String("Right operand of bitwise operator '.or.' must be an integer expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asInt()->unitType() || lhs->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@1, "Units are not allowed for operands of bitwise operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->asInt()->unitType() || rhs->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@3, "Units are not allowed for operands of bitwise operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asInt()->isFinal() && !rhs->asInt()->isFinal())
                PARSE_WRN(@3, "Right operand of '.or.' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asInt()->isFinal() && rhs->asInt()->isFinal())
                PARSE_WRN(@1, "Left operand of '.or.' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new BitwiseOr(lhs, rhs);
        }
    }

bitwise_and_expr:
    rel_expr  {
        $$ = $1;
    }
    | bitwise_and_expr BITWISE_AND rel_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (lhs->exprType() != INT_EXPR) {
            PARSE_ERR(@1, (String("Left operand of bitwise operator '.and.' must be an integer expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->exprType() != INT_EXPR) {
            PARSE_ERR(@3, (String("Right operand of bitwise operator '.and.' must be an integer expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asInt()->unitType() || lhs->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@1, "Units are not allowed for operands of bitwise operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->asInt()->unitType() || rhs->asInt()->hasUnitFactorEver()) {
            PARSE_ERR(@3, "Units are not allowed for operands of bitwise operations.");
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asInt()->isFinal() && !rhs->asInt()->isFinal())
                PARSE_WRN(@3, "Right operand of '.and.' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asInt()->isFinal() && rhs->asInt()->isFinal())
                PARSE_WRN(@1, "Left operand of '.and.' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new BitwiseAnd(lhs, rhs);
        }
    }

rel_expr:
      add_expr
    | rel_expr '<' add_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '<' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@3, (String("Right operand of operator '<' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() != rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Operands of relative operations must have same unit, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '<' comparison is not 'final', left operand is 'final' though.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '<' comparison is not 'final', right operand is 'final' though.");
            $$ = new Relation(lhs, Relation::LESS_THAN, rhs);
        }
    }
    | rel_expr '>' add_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '>' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@3, (String("Right operand of operator '>' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() != rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Operands of relative operations must have same unit, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '>' comparison is not 'final', left operand is 'final' though.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '>' comparison is not 'final', right operand is 'final' though.");
            $$ = new Relation(lhs, Relation::GREATER_THAN, rhs);
        }
    }
    | rel_expr LE add_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '<=' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@3, (String("Right operand of operator '<=' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() != rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Operands of relative operations must have same unit, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '<=' comparison is not 'final', left operand is 'final' though.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '<=' comparison is not 'final', right operand is 'final' though.");
            $$ = new Relation(lhs, Relation::LESS_OR_EQUAL, rhs);
        }
    }
    | rel_expr GE add_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '>=' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@3, (String("Right operand of operator '>=' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() != rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Operands of relative operations must have same unit, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '>=' comparison is not 'final', left operand is 'final' though.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '>=' comparison is not 'final', right operand is 'final' though.");
            $$ = new Relation(lhs, Relation::GREATER_OR_EQUAL, rhs);
        }
    }
    | rel_expr '=' add_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '=' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@3, (String("Right operand of operator '=' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() != rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Operands of relative operations must have same unit, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '=' comparison is not 'final', left operand is 'final' though.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '=' comparison is not 'final', right operand is 'final' though.");
            $$ = new Relation(lhs, Relation::EQUAL, rhs);
        }
    }
    | rel_expr '#' add_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '#' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@3, (String("Right operand of operator '#' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() != rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Operands of relative operations must have same unit, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '#' comparison is not 'final', left operand is 'final' though.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '#' comparison is not 'final', right operand is 'final' though.");
            $$ = new Relation(lhs, Relation::NOT_EQUAL, rhs);
        }
    }

add_expr:
      mul_expr
    | add_expr '+' mul_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '+' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@1, (String("Right operand of operator '+' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->exprType() != rhs->exprType()) {
            PARSE_ERR(@2, (String("Operands of operator '+' must have same type; left operand is ") +
                      typeStr(lhs->exprType()) + " and right operand is " + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() != rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Operands of '+' operations must have same unit, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '+' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '+' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new Add(lhs,rhs);
        }
    }
    | add_expr '-' mul_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '-' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@1, (String("Right operand of operator '-' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->exprType() != rhs->exprType()) {
            PARSE_ERR(@2, (String("Operands of operator '-' must have same type; left operand is ") +
                      typeStr(lhs->exprType()) + " and right operand is " + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() != rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Operands of '-' operations must have same unit, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '-' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '-' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new Sub(lhs,rhs);
        }
    }

mul_expr:
    unary_expr
    | mul_expr '*' unary_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '*' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@1, (String("Right operand of operator '*' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() && rhs->asNumber()->unitType()) {
            PARSE_ERR(@2, (String("Only one operand of operator '*' may have a unit type, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->exprType() != rhs->exprType()) {
            PARSE_ERR(@2, (String("Operands of operator '*' must have same type; left operand is ") +
                      typeStr(lhs->exprType()) + " and right operand is " + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '*' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '*' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new Mul(lhs,rhs);
        }
    }
    | mul_expr '/' unary_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (!isNumber(lhs->exprType())) {
            PARSE_ERR(@1, (String("Left operand of operator '/' must be a scalar number expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!isNumber(rhs->exprType())) {
            PARSE_ERR(@1, (String("Right operand of operator '/' must be a scalar number expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->asNumber()->unitType() && rhs->asNumber()->unitType() &&
                   lhs->asNumber()->unitType() != rhs->asNumber()->unitType())
        {
            PARSE_ERR(@2, (String("Operands of operator '/' with two different unit types, left operand is ") +
                unitTypeStr(lhs->asNumber()->unitType()) + " and right operand is " +
                unitTypeStr(rhs->asNumber()->unitType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (!lhs->asNumber()->unitType() && rhs->asNumber()->unitType()) {
            PARSE_ERR(@3, ("Dividing left operand without any unit type by right operand with unit type (" +
                unitTypeStr(rhs->asNumber()->unitType()) + ") is not possible.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (lhs->exprType() != rhs->exprType()) {
            PARSE_ERR(@2, (String("Operands of operator '/' must have same type; left operand is ") +
                      typeStr(lhs->exprType()) + " and right operand is " + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asNumber()->isFinal() && !rhs->asNumber()->isFinal())
                PARSE_WRN(@3, "Right operand of '/' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asNumber()->isFinal() && rhs->asNumber()->isFinal())
                PARSE_WRN(@1, "Left operand of '/' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new Div(lhs,rhs);
        }
    }
    | mul_expr MOD unary_expr  {
        ExpressionRef lhs = $1;
        ExpressionRef rhs = $3;
        if (lhs->exprType() != INT_EXPR) {
            PARSE_ERR(@1, (String("Left operand of modulo operator must be an integer expression, is ") + typeStr(lhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else if (rhs->exprType() != INT_EXPR) {
            PARSE_ERR(@3, (String("Right operand of modulo operator must be an integer expression, is ") + typeStr(rhs->exprType()) + " though.").c_str());
            $$ = new IntLiteral({ .value = 0 });
        } else {
            if (lhs->asInt()->unitType() || lhs->asInt()->hasUnitFactorEver())
                PARSE_ERR(@1, "Operands of modulo operator must not use any unit.");
            if (rhs->asInt()->unitType() || rhs->asInt()->hasUnitFactorEver())
                PARSE_ERR(@3, "Operands of modulo operator must not use any unit.");
            if (lhs->asInt()->isFinal() && !rhs->asInt()->isFinal())
                PARSE_WRN(@3, "Right operand of 'mod' operation is not 'final', result will be 'final' though since left operand is 'final'.");
            else if (!lhs->asInt()->isFinal() && rhs->asInt()->isFinal())
                PARSE_WRN(@1, "Left operand of 'mod' operation is not 'final', result will be 'final' though since right operand is 'final'.");
            $$ = new Mod(lhs,rhs);
        }
    }

%%

void InstrScript_error(YYLTYPE* locp, LinuxSampler::ParserContext* context, const char* err) {
    //fprintf(stderr, "%d: %s\n", locp->first_line, err);
    context->addErr(locp->first_line, locp->last_line, locp->first_column+1,
                    locp->last_column+1, locp->first_byte, locp->length_bytes,
                    err);
}

void InstrScript_warning(YYLTYPE* locp, LinuxSampler::ParserContext* context, const char* txt) {
    //fprintf(stderr, "WRN %d: %s\n", locp->first_line, txt);
    context->addWrn(locp->first_line, locp->last_line, locp->first_column+1,
                    locp->last_column+1, locp->first_byte, locp->length_bytes,
                    txt);
}

/// Custom implementation of yytnamerr() to ensure quotation is always stripped from token names before printing them to error messages.
int InstrScript_tnamerr(char* yyres, const char* yystr) {
  if (*yystr == '"') {
      int yyn = 0;
      char const *yyp = yystr;
      for (;;)
        switch (*++yyp)
          {
/*
          case '\'':
          case ',':
            goto do_not_strip_quotes;

          case '\\':
            if (*++yyp != '\\')
              goto do_not_strip_quotes;
*/
            /* Fall through.  */
          default:
            if (yyres)
              yyres[yyn] = *yyp;
            yyn++;
            break;

          case '"':
            if (yyres)
              yyres[yyn] = '\0';
            return yyn;
          }
/*
    do_not_strip_quotes: ;
*/
    }

  if (! yyres)
    return (int) yystrlen (yystr);

  return int( yystpcpy (yyres, yystr) - yyres );
}
