/* 
   Copyright (c) 1991-1999 Thomas T. Wetmore IV

   Permission is hereby granted, free of charge, to any person
   obtaining a copy of this software and associated documentation
   files (the "Software"), to deal in the Software without
   restriction, including without limitation the rights to use, copy,
   modify, merge, publish, distribute, sublicense, and/or sell copies
   of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be
   included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   SOFTWARE.
*/
/* modified 05 Jan 2000 by Paul B. McBride (pmcbride@tiac.net) */
/*==============================================================
 * eval.c -- Evaulate report program expressions
 * Copyright(c) 1991-95 by T. T. Wetmore IV; all rights reserved
 *   2.3.4 - 24 Jun 93    2.3.5 - 17 Aug 93
 *   3.0.0 - 29 Jun 94    3.0.2 - 22 Dec 94
 *   3.0.3 - 23 Nov 95
 *============================================================*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "llstdlib.h"
#include "table.h"
#include "translat.h"
#include "gedcom.h"
#include "cache.h"
#include "interp.h"
#include "liflines.h"
#include "feedback.h"
#include "lloptions.h"

extern BOOLEAN traceprogram, explicitvars;

/*=============================+
 * evaluate -- Generic evaluator
 *============================*/
PVALUE
evaluate (PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	if (prog_debug) {
		llwprintf("%d: ", iline(node));
		show_one_pnode(node);
		llwprintf("\n");
	}
	if (iistype(node, IIDENT))
		return evaluate_iden(node, stab, eflg);
	if (iistype(node, IBCALL))
		return evaluate_func(node, stab, eflg);
	if (iistype(node, IFCALL))
		return evaluate_ufunc(node, stab, eflg);
	*eflg = FALSE;
	if (iistype(node, IICONS))
		return copy_pvalue(ivalue(node));
	if (iistype(node, ISCONS))
		return copy_pvalue(ivalue(node));
	if (iistype(node, IFCONS))
		return copy_pvalue(ivalue(node));
	*eflg = TRUE;
	return NULL;
}
/*====================================+
 * evaluate_iden -- Evaluate identifier
 *===================================*/
PVALUE
evaluate_iden (PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	STRING iden = (STRING) iident(node);
#if 0
	if (prog_debug)
		llwprintf("evaluate_iden called: iden = %s\n", iden);
#endif
	*eflg = FALSE;
	return valueof_iden(node, stab, iden, eflg);
}
/*=======================================+
 * valueof_iden - Find value of identifier
 *======================================*/
PVALUE
valueof_iden (PNODE node, SYMTAB stab, STRING iden, BOOLEAN *eflg)
{
	BOOLEAN there;
	PVALUE val;

#ifdef DEBUG
	llwprintf("valueof_iden: iden, stab, globtab: %s, %d, %d\n",
	  	  iden, stab, globtab);
#endif

	*eflg = FALSE;
	val = symtab_valueofbool(stab, iden, &there);
	if (there) return copy_pvalue(val);
	val = symtab_valueofbool(globtab, iden, &there);
	if (there) return copy_pvalue(val);
	/* undeclared identifier */
	if (explicitvars) {
		*eflg = TRUE;
		prog_error(node, "Undeclared identifier: %s", iden);
	}
	return create_pvalue(PANY, NULL);
}
/*================================================+
 * evaluate_cond -- Evaluate conditional expression
 *===============================================*/
BOOLEAN
evaluate_cond (PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	PVALUE val;
	BOOLEAN rc;
	PNODE var = node, expr = inext(node);
	if (!expr) {
		expr = var;
		var = NULL;
	}
	if (var && !iistype(var, IIDENT)) {
		*eflg = TRUE;
		prog_error(node, "1st arg in conditional must be variable");
		return FALSE;
	}
	val = evaluate(expr, stab, eflg);
	if (*eflg || !val) {
		*eflg = TRUE;
		prog_error(node, "error in conditional expression");
		return FALSE;
	}
#ifdef DEBUG
	llwprintf("interp_if: cond = ");
	show_pvalue(val);
	wprintf("\n");
#endif
	if (var) assign_iden(stab, iident(node), copy_pvalue(val));
	coerce_pvalue(PBOOL, val, eflg);
	rc = (BOOLEAN) pvalue(val);
	delete_pvalue(val);
	return rc;
}
/*==========================================+
 * evaluate_func -- Evaluate builtin function
 *=========================================*/
PVALUE
evaluate_func (PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	PVALUE val;
	char trace[20];

	*eflg = FALSE;
#if 0
	if (prog_debug)
		llwprintf("evaluate_func called: %d: %s\n",
		    iline(node), iname(node));
#endif
	if (traceprogram) {
		sprintf(trace, "%d: %s\n", iline(node), (char*)iname(node));
		poutput(trace, eflg);
	}
	val = (*(PFUNC)ifunc(node))(node, stab, eflg);
	return val;
}
/*================================================+
 * evaluate_ufunc -- Evaluate user defined function
 *  node:   [in] parsed node of function definition
 *  stab:   [in] function's symbol table
 *  eflg:   [out] error flag
 *===============================================*/
PVALUE
evaluate_ufunc (PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	STRING nam = (STRING) iname(node);
	PNODE func, arg, parm;
	SYMTAB newstab = null_symtab();
	PVALUE val=NULL;
	INTERPTYPE irc;

	*eflg = TRUE;
	if ((func = valueof_ptr(functab, nam)) == NULL) {
		prog_error(node, "undefined function %s()", nam);
		goto ufunc_leave;
	}
	create_symtab(&newstab);
	arg = (PNODE) iargs(node);
	parm = (PNODE) iargs(func);
	while (arg && parm) {
		BOOLEAN eflg=TRUE;
		PVALUE value = evaluate(arg, stab, &eflg);
		if (eflg) {
			if (getoptint("FullReportCallStack", 0) > 0)
				prog_error(node, "In user function %s()", iname(node));
			return INTERROR;
		}
		insert_symtab_pvalue(newstab, iident(parm), value);
		arg = inext(arg);
		parm = inext(parm);
	}
	if (arg || parm) {
		prog_error(node, "``%s'': mismatched args and params\n", iname(node));
		goto ufunc_leave;
	}
	irc = interpret((PNODE) ibody(func), newstab, &val);
	switch (irc) {
	case INTRETURN:
	case INTOKAY:
#ifdef DEBUG
	llwprintf("Successful ufunc call -- val returned was ");
	show_pvalue(val);
	llwprintf("\n");
#endif
		*eflg = FALSE;
		goto ufunc_leave;
	case INTBREAK:
	case INTCONTINUE:
	case INTERROR:
		break;
	}
	if (getoptint("FullReportCallStack", 0) > 0)
		prog_error(node, "In user function %s()", iname(node));
	*eflg = TRUE;
	delete_pvalue(val);
	val=NULL;

ufunc_leave:
	remove_symtab(&newstab);
	return val;
}
/*=====================================
 * iistype -- Check type of interp node
 *===================================*/
BOOLEAN
iistype (PNODE node,
         INT type)
{
	return itype(node) == type;
}
/*==============================================
 * num_params -- Return number of params in list
 *============================================*/
INT
num_params (PNODE node)
{
	INT np = 0;
	while (node) {
		np++;
		node = inext(node);
	}
	return np;
}
/*============================================
 * assign_iden -- Assign ident value in symtab
 *==========================================*/
void
assign_iden (SYMTAB stab, STRING id, PVALUE value)
{
	SYMTAB tab = stab;
	if (!in_symtab(stab, id) && in_symtab(globtab, id))
		tab = globtab;
	insert_symtab_pvalue(tab, id, value);
	return;
}
/*=================================================
 * eval_and_coerce -- Generic evaluator and coercer
 *  type:  [IN]  desired pvalue type
 *  node:  [IN]  node to coerce
 *  stab:  [IN]  symbol table
 *  eflg:  [OUT] error flag
 *===============================================*/
PVALUE
eval_and_coerce (INT type, PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	PVALUE val = eval_without_coerce(node, stab, eflg);
	if (*eflg) return NULL;
	coerce_pvalue(type, val, eflg);
	return val;
}
/*=================================================
 * eval_without_coerce -- Generic evaluator
 *  node:  [IN]  node to coerce
 *  stab:  [IN]  symbol table
 *  eflg:  [OUT] error flag
 * Created: 2001/12/24, Perry Rapp
 *===============================================*/
PVALUE
eval_without_coerce (PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	PVALUE val;
	if (*eflg) return NULL;
	val = evaluate(node, stab, eflg);
	if (*eflg || !val) {
		*eflg = TRUE;
		if (val) {
			delete_pvalue(val);
			val=NULL;
		}
		return NULL;
	}
	return val;
}
