//#define msgx
#include "parser.ih"

SemVal pmv_callFunction(int funIdx, SemVal *args)
{
    msg("calling function 0x%x", funIdx);

    register unsigned nParams;

    if (funIdx == -1)                       // function name not found ? 
        return SVmove(args);          // nothing to do here        

    nParams = symtab_fun_nParams(funIdx);   // check correct # of args 

    if ((unsigned)svValue(args) != nParams)
        util_semantic(sem_argCount, symtab_funName(funIdx), nParams);
    else 
    {
        for (unsigned idx = 0; idx != nParams; ++idx)
            msg("arg. %d has type %x", idx, svType(svArg(args, idx)));

        if (! p_checkArgumentTypes(nParams, funIdx, svArg(args, 0)))
            return SVmove(args);
    }

    SemVal ret = SVzero();

    msg("Number of arguments: %d", svValue(args));
    svPushArgs(&ret, args);                 // push the args into ret

                                            // call function and clean stack 
    svAddCode(&ret, op_call, symtab_funAddress(funIdx));
    svAddCode(&ret, op_asp,  nParams);

    svSetType(&ret, symtab_funType(funIdx));

    return ret;
}
