eval.c 182 KB
Newer Older
1
/*
2
 *  pqR : A pretty quick version of R
3
 *  Copyright (C) 2013, 2014, 2015, 2016, 2017, 2018 by Radford M. Neal
4 5
 *
 *  Based on R : A Computer Language for Statistical Data Analysis
Radford Neal's avatar
Radford Neal committed
6
 *  Copyright (C) 1995, 1996	Robert Gentleman and Ross Ihaka
7
 *  Copyright (C) 1998--2011	The R Core Team.
Radford Neal's avatar
Radford Neal committed
8
 *
9 10 11
 *  The changes in pqR from R-2.15.0 distributed by the R Core Team are
 *  documented in the NEWS and MODS files in the top-level source directory.
 *
Radford Neal's avatar
Radford Neal committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, a copy is available at
 *  http://www.r-project.org/Licenses/
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
Radford Neal's avatar
Radford Neal committed
30

31
#define USE_FAST_PROTECT_MACROS
Radford Neal's avatar
Radford Neal committed
32
#define R_USE_SIGNALS 1
Radford Neal's avatar
Radford Neal committed
33 34 35 36
#include <Defn.h>
#include <Rinterface.h>
#include <Fileio.h>

37
#include "scalar-stack.h"
38
#include <Rmath.h>
39 40
#include "arithmetic.h"

41 42
#include <helpers/helpers-app.h>

Radford Neal's avatar
Radford Neal committed
43

44
#ifndef SCALAR_STACK_DEBUG    /* can be overridden by compiler option */
45
#define SCALAR_STACK_DEBUG 0
46
#endif
47

Radford Neal's avatar
Radford Neal committed
48

49 50 51 52 53 54 55 56 57
attribute_hidden void SrcrefPrompt(const char * prefix, SEXP srcref)
{
    /* If we have a valid srcref, use it */
    if (srcref && srcref != R_NilValue) {
        if (TYPEOF(srcref) == VECSXP) srcref = VECTOR_ELT(srcref, 0);
	SEXP srcfile = getAttrib00(srcref, R_SrcfileSymbol);
	if (TYPEOF(srcfile) == ENVSXP) {
	    SEXP filename = findVar(install("filename"), srcfile);
	    if (isString(filename) && length(filename)) {
Radford Neal's avatar
Radford Neal committed
58 59
	    	Rprintf(_("%s at %s#%d: "),prefix,CHAR(STRING_ELT(filename,0)), 
	                                   asInteger(srcref));
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
	        return;
	    }
	}
    }
    /* default: */
    Rprintf("%s: ", prefix);
}


/* This function gets the srcref attribute from a statement block, 
   and confirms it's in the expected format */
   
static inline void getBlockSrcrefs(SEXP call, SEXP **refs, int *len)
{
    SEXP srcrefs = getAttrib00(call, R_SrcrefSymbol);
    if (TYPEOF(srcrefs) == VECSXP) {
        *refs = (SEXP *) DATAPTR(srcrefs);
        *len = LENGTH(srcrefs);
    }
    else
    {   *len = 0;
    }
}


/* This function extracts one srcref, and confirms the format.  It is 
   passed an index and the array and length from getBlockSrcrefs. */

static inline SEXP getSrcref(SEXP *refs, int len, int ind)
{
    if (ind < len) {
        SEXP result = refs[ind];
        if (TYPEOF(result) == INTSXP && LENGTH(result) >= 6)
            return result;
    }

    return R_NilValue;
}

static void start_browser (SEXP call, SEXP op, SEXP stmt, SEXP env)
{
    SrcrefPrompt("debug", R_Srcref);
    PrintValue(stmt);
    do_browser(call, op, R_NilValue, env);
}


static void printcall (SEXP call, SEXP rho)
{
    int old_bl = R_BrowseLines;
    int blines = asInteger(GetOption1(install("deparse.max.lines")));
    if (blines != NA_INTEGER && blines > 0) R_BrowseLines = blines;
    PrintValueRec(call,rho);
    R_BrowseLines = old_bl;
}


static SEXP VectorToPairListNamed(SEXP x)
{
    SEXP xptr, xnew, xnames;
    int i, len, len_x = length(x);

    PROTECT(x);
    PROTECT(xnames = getAttrib(x, R_NamesSymbol)); 
                       /* isn't this protected via x?  Or could be concocted? */

    len = 0;
    if (xnames != R_NilValue) {
	for (i = 0; i < len_x; i++)
	    if (CHAR(STRING_ELT(xnames,i))[0] != 0) len += 1;
    }

    PROTECT(xnew = allocList(len));

    if (len > 0) {
	xptr = xnew;
	for (i = 0; i < len_x; i++) {
	    if (CHAR(STRING_ELT(xnames,i))[0] != 0) {
		SETCAR (xptr, VECTOR_ELT(x,i));
139
		SET_TAG (xptr, install_translated (STRING_ELT(xnames,i)));
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
		xptr = CDR(xptr);
	    }
	}
    } 

    UNPROTECT(3);
    return xnew;
}

#define simple_as_environment(arg) (IS_S4_OBJECT(arg) && (TYPEOF(arg) == S4SXP) ? R_getS4DataSlot(arg, ENVSXP) : R_NilValue)

/* "eval" and "eval.with.vis" : Evaluate the first argument */
/* in the environment specified by the second argument. */

static SEXP do_eval (SEXP call, SEXP op, SEXP args, SEXP rho, int variant)
{
    SEXP encl, x, xptr;
    volatile SEXP expr, env, tmp;

    int frame;
    RCNTXT cntxt;

    checkArity(op, args);

    expr = CAR(args);
    env = CADR(args);
    encl = CADDR(args);
    if (isNull(encl)) {
	/* This is supposed to be defunct, but has been kept here
	   (and documented as such) */
	encl = R_BaseEnv;
    } else if ( !isEnvironment(encl) &&
		!isEnvironment((encl = simple_as_environment(encl))) )
	error(_("invalid '%s' argument"), "enclos");
    if(IS_S4_OBJECT(env) && (TYPEOF(env) == S4SXP))
	env = R_getS4DataSlot(env, ANYSXP); /* usually an ENVSXP */
    switch(TYPEOF(env)) {
    case NILSXP:
	env = encl;     /* so eval(expr, NULL, encl) works */
        break;
    case ENVSXP:
	break;
    case LISTSXP:
	/* This usage requires all the pairlist to be named */
	env = NewEnvironment(R_NilValue, duplicate(CADR(args)), encl);
        set_symbits_in_env(env);
	break;
    case VECSXP:
	/* PR#14035 */
	x = VectorToPairListNamed(CADR(args));
	for (xptr = x ; xptr != R_NilValue ; xptr = CDR(xptr))
	    SET_NAMEDCNT_MAX(CAR(xptr));
	env = NewEnvironment(R_NilValue, x, encl);
        set_symbits_in_env(env);
	break;
    case INTSXP:
    case REALSXP:
	if (length(env) != 1)
	    error(_("numeric 'envir' arg not of length one"));
	frame = asInteger(env);
	if (frame == NA_INTEGER)
	    error(_("invalid '%s' argument"), "envir");
	env = R_sysframe(frame, R_GlobalContext);
	break;
    default:
	error(_("invalid '%s' argument"), "envir");
    }

    PROTECT(env); /* may no longer be what was passed in arg */

    /* isLanguage includes NILSXP, and that does not need to be evaluated,
       so don't use isLanguage(expr) || isSymbol(expr) || isByteCode(expr) */
    if (TYPEOF(expr) == LANGSXP || TYPEOF(expr) == SYMSXP || isByteCode(expr)) {
	begincontext(&cntxt, CTXT_RETURN, call, env, rho, args, op);
	if (!SETJMP(cntxt.cjmpbuf))
	    expr = evalv (expr, env, VARIANT_PASS_ON(variant));
	else {
	    expr = R_ReturnedValue;
	    if (expr == R_RestartToken) {
		cntxt.callflag = CTXT_RETURN;  /* turn restart off */
		error(_("restarts not supported in 'eval'"));
	    }
            if ( ! (variant & VARIANT_PENDING_OK))
                WAIT_UNTIL_COMPUTED(R_ReturnedValue);
	}
	UNPROTECT(1);
	PROTECT(expr);
	endcontext(&cntxt);
    }
    else if (TYPEOF(expr) == EXPRSXP) {
	int i, n;
        int len;
        SEXP *srcrefs;
        getBlockSrcrefs(expr,&srcrefs,&len);
	n = LENGTH(expr);
	tmp = R_NilValue;
	begincontext(&cntxt, CTXT_RETURN, call, env, rho, args, op);
        SEXP savedsrcref = R_Srcref;
	if (!SETJMP(cntxt.cjmpbuf)) {
	    for (i = 0 ; i < n ; i++) {
                R_Srcref = getSrcref (srcrefs, len, i); 
		tmp = evalv (VECTOR_ELT(expr, i), env, 
                        i==n-1 ? VARIANT_PASS_ON(variant) 
                               : VARIANT_NULL | VARIANT_PENDING_OK);
            }
        }
	else {
	    tmp = R_ReturnedValue;
	    if (tmp == R_RestartToken) {
		cntxt.callflag = CTXT_RETURN;  /* turn restart off */
		error(_("restarts not supported in 'eval'"));
	    }
            if ( ! (variant & VARIANT_PENDING_OK))
                WAIT_UNTIL_COMPUTED(R_ReturnedValue);
	}
	UNPROTECT(1);
	PROTECT(tmp);
        R_Srcref = savedsrcref;
	endcontext(&cntxt);
	expr = tmp;
    }
    else if( TYPEOF(expr) == PROMSXP ) {
	expr = forcePromise(expr);
    } 
    else 
        ; /* expr is returned unchanged */

    if (PRIMVAL(op)) { /* eval.with.vis(*) : */
	PROTECT(expr);
	PROTECT(env = allocVector(VECSXP, 2));
	PROTECT(encl = allocVector(STRSXP, 2));
	SET_STRING_ELT(encl, 0, mkChar("value"));
	SET_STRING_ELT(encl, 1, mkChar("visible"));
	SET_VECTOR_ELT(env, 0, expr);
	SET_VECTOR_ELT(env, 1, ScalarLogicalMaybeConst(R_Visible));
	setAttrib(env, R_NamesSymbol, encl);
	expr = env;
	UNPROTECT(3);
    }

    UNPROTECT(1);
    return expr;
}

/* This is a special .Internal */
static SEXP do_withVisible(SEXP call, SEXP op, SEXP args, SEXP rho)
{
    SEXP x, nm, ret;

    checkArity(op, args);
    x = CAR(args);
    x = eval(x, rho);
    PROTECT(x);
    PROTECT(ret = allocVector(VECSXP, 2));
    PROTECT(nm = allocVector(STRSXP, 2));
    SET_STRING_ELT(nm, 0, mkChar("value"));
    SET_STRING_ELT(nm, 1, mkChar("visible"));
    SET_VECTOR_ELT(ret, 0, x);
    SET_VECTOR_ELT(ret, 1, ScalarLogicalMaybeConst(R_Visible));
    setAttrib(ret, R_NamesSymbol, nm);
    UNPROTECT(3);
    return ret;
}

/* This is a special .Internal */
static SEXP do_recall(SEXP call, SEXP op, SEXP args, SEXP rho)
{
    RCNTXT *cptr;
    SEXP s, ans ;
    cptr = R_GlobalContext;
    /* get the args supplied */
    while (cptr != NULL) {
	if (cptr->callflag == CTXT_RETURN && cptr->cloenv == rho)
	    break;
	cptr = cptr->nextcontext;
    }
    if (cptr != NULL) {
	args = cptr->promargs;
    }
    /* get the env recall was called from */
    s = R_GlobalContext->sysparent;
    while (cptr != NULL) {
	if (cptr->callflag == CTXT_RETURN && cptr->cloenv == s)
	    break;
	cptr = cptr->nextcontext;
    }
    if (cptr == NULL)
	error(_("'Recall' called from outside a closure"));

    /* If the function has been recorded in the context, use it
       otherwise search for it by name or evaluate the expression
       originally used to get it.
    */
    if (cptr->callfun != R_NilValue)
	PROTECT(s = cptr->callfun);
    else if( TYPEOF(CAR(cptr->call)) == SYMSXP)
	PROTECT(s = findFun(CAR(cptr->call), cptr->sysparent));
    else
	PROTECT(s = eval(CAR(cptr->call), cptr->sysparent));
    if (TYPEOF(s) != CLOSXP) 
    	error(_("'Recall' called from outside a closure"));
    ans = applyClosure_v(cptr->call, s, args, cptr->sysparent, NULL, 0);
    UNPROTECT(1);
    return ans;
}
345

346

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
/* -------------------------------------------------------------------------- */
/*                CONTEXT PROCEDURES - others are in context.c                */

void beginbuiltincontext (RCNTXT * cptr, SEXP syscall)
{ begincontext (cptr, CTXT_BUILTIN, syscall, R_BaseEnv, 
                      R_BaseEnv, R_NilValue, R_NilValue);
}

/* begincontext - begin an execution context

   begincontext and endcontext are used in dataentry.c and modules. */

void begincontext(RCNTXT * cptr, int flags,
		  SEXP syscall, SEXP env, SEXP sysp,
		  SEXP promargs, SEXP callfun)
{
    cptr->nextcontext = R_GlobalContext;  /* store in order in structure, */
    cptr->callflag = flags;               /*   since that may be faster   */
    cptr->cstacktop = R_PPStackTop;
    cptr->evaldepth = R_EvalDepth;
    cptr->promargs = promargs;
    cptr->callfun = callfun;
    cptr->sysparent = sysp;
    cptr->call = syscall;
    cptr->cloenv = env;
    cptr->conexit = R_NilValue;
    cptr->cend = NULL;
    cptr->vmax = VMAXGET();
    cptr->intsusp = R_interrupts_suspended;
    cptr->handlerstack = R_HandlerStack;
    cptr->restartstack = R_RestartStack;
    cptr->prstack = R_PendingPromises;
    cptr->nodestack = R_BCNodeStackTop;
#ifdef BC_INT_STACK
    cptr->intstack = R_BCIntStackTop;
#endif
    cptr->srcref = R_Srcref;
    cptr->local_pr = R_local_protect_start;
    cptr->scalar_stack = R_scalar_stack;
    R_GlobalContext = cptr;
}


/* endcontext - end an execution context. */

void endcontext(RCNTXT * cptr)
{
    R_HandlerStack = cptr->handlerstack;
    R_RestartStack = cptr->restartstack;
    if (cptr->cloenv != R_NilValue && cptr->conexit != R_NilValue ) {
	SEXP s = cptr->conexit;
	Rboolean savevis = R_Visible;
	cptr->conexit = R_NilValue; /* prevent recursion */
	PROTECT(s);
	eval(s, cptr->cloenv);
	UNPROTECT(1);
	R_Visible = savevis;
    }
    R_GlobalContext = cptr->nextcontext;
}


/* revisecontext - change environments in a context

   The revised context differs from the previous one only in env and sysp. */

413
static inline void revisecontext (SEXP env, SEXP sysp)
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
{
    R_GlobalContext->sysparent = sysp;
    R_GlobalContext->cloenv = env;
}


/* jumpfun - jump to the named context */

static R_NORETURN void jumpfun(RCNTXT * cptr, int mask, SEXP val)
{
    Rboolean savevis = R_Visible;

    if (ON_SCALAR_STACK(val))
        val = DUP_STACK_VALUE(val);

    /* run onexit/cend code for all contexts down to but not including
       the jump target */
    PROTECT(val);
    R_run_onexits(cptr);
    UNPROTECT(1);
    R_Visible = savevis;

    R_ReturnedValue = val;
    R_GlobalContext = cptr; /* this used to be set to
			       cptr->nextcontext for non-toplevel
			       jumps (with the context set back at the
			       SETJMP for restarts).  Changing this to
			       always using cptr as the new global
			       context should simplify some code and
			       perhaps allow loops to be handled with
			       fewer SETJMP's.  LT */
    R_restore_globals(R_GlobalContext);

    LONGJMP(cptr->cjmpbuf, mask);
}


/* findcontext - find the correct context */

void R_NORETURN attribute_hidden findcontext(int mask, SEXP env, SEXP val)
{
    RCNTXT *cptr;
    if (mask & CTXT_LOOP) {		/* break/next */
	for (cptr = R_GlobalContext;
	     cptr != NULL && cptr->callflag != CTXT_TOPLEVEL;
	     cptr = cptr->nextcontext)
460
	    if ((cptr->callflag & CTXT_LOOP) && cptr->cloenv == env )
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
		jumpfun(cptr, mask, val);
	error(_("no loop for break/next, jumping to top level"));
    }
    else {				/* return; or browser */
	for (cptr = R_GlobalContext;
	     cptr != NULL && cptr->callflag != CTXT_TOPLEVEL;
	     cptr = cptr->nextcontext)
	    if ((cptr->callflag & mask) && cptr->cloenv == env)
		jumpfun(cptr, mask, val);
	error(_("no function to return from, jumping to top level"));
    }
}

void R_NORETURN attribute_hidden R_JumpToContext (RCNTXT *target, int mask, 
                                                  SEXP val)
{
    RCNTXT *cptr;
    for (cptr = R_GlobalContext;
	 cptr != NULL && cptr->callflag != CTXT_TOPLEVEL;
	 cptr = cptr->nextcontext)
	if (cptr == target)
	    jumpfun(cptr, mask, val);
    error(_("target context is not on the stack"));
}


487 488 489 490
/* -------------------------------------------------------------------------- */
/*              CORE EVAL PROCEDURES - KEEP TOGETHER FOR LOCALITY             */


491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
/* Similar version used in bytecode.c */

extern void Rf_asLogicalNoNA_warning(SEXP s, SEXP call);
extern R_NORETURN void Rf_asLogicalNoNA_error(SEXP s, SEXP call);

/* Caller needn't protect the s arg below.  Value is popped off the
   scalar stack if it's there. */

static inline Rboolean asLogicalNoNA(SEXP s, SEXP call)
{
    int len, cond;

    /* Check the constants explicitly, since they should be the most
       common cases, and then no need to check for NA, or pop scalar stack. */

    if (s == R_ScalarLogicalTRUE)
        return TRUE;
    if (s == R_ScalarLogicalFALSE)
        return FALSE;

    switch(TYPEOF(s)) { /* common cases done here for efficiency */
    case INTSXP:  /* assume logical and integer are the same */
    case LGLSXP:
        len = LENGTH(s);
        if (len == 0) goto error;
        cond = LOGICAL(s)[0];
        break;
    case REALSXP:
    case CPLXSXP:
    case STRSXP:
    case RAWSXP:
        len = LENGTH(s);
        if (len == 0) goto error;
        cond = asLogical(s);
        break;
    default:
        goto error;
    }

    if (cond == NA_LOGICAL) goto error;

    POP_IF_TOP_OF_STACK(s);

    if (len > 1) Rf_asLogicalNoNA_warning (s, call);

    return cond;

  error:
    Rf_asLogicalNoNA_error (s, call);
}


543
/* Inline version of findVarPendingOK, for speed when symbol is found
544
   from LASTSYMBINDING. */
545 546 547 548 549 550 551

static inline SEXP FIND_VAR_PENDING_OK (SEXP sym, SEXP rho)
{
    rho = SKIP_USING_SYMBITS (rho, sym);

    if (LASTSYMENV(sym) == SEXP32_FROM_SEXP(rho)) {
        SEXP b = CAR(LASTSYMBINDING(sym));
552 553
        if (b != R_UnboundValue) {
            R_binding_cell = LASTSYMBINDING(sym);
554
            return b;
555
        }
556 557 558 559 560 561 562
        LASTSYMENV(sym) = R_NoObject32;
    }

    return findVarPendingOK(sym,rho);
}


Radford Neal's avatar
Radford Neal committed
563 564 565 566 567 568 569
/* Inline version of findFun.  It's meant to be very fast when a
   function is found in the base environmet.  It can delegate uncommon
   cases such as traced functions to the general-case procedure.

   Note that primitive functions in the base environment are directly
   stored as the bound values, while closures (including internals)
   are referenced via promises (for lazy loading). */
570 571 572 573 574 575 576

static inline SEXP FINDFUN (SEXP symbol, SEXP rho)
{
    rho = SKIP_USING_SYMBITS (rho, symbol);

    if (rho == R_GlobalEnv && BASE_CACHE(symbol)) {
        SEXP res = SYMVALUE(symbol);
Radford Neal's avatar
Radford Neal committed
577 578
        int type_etc = TYPE_ETC(res);
        if (type_etc == SPECIALSXP || type_etc == BUILTINSXP)
579
            return res;
Radford Neal's avatar
Radford Neal committed
580
        if (type_etc == PROMSXP + TYPE_ET_CETERA_VEC_DOTS_TR) { /* forced prom*/
Radford Neal's avatar
Radford Neal committed
581
            res = PRVALUE_PENDING_OK(res);
Radford Neal's avatar
Radford Neal committed
582
            type_etc = TYPE_ETC(res);
Radford Neal's avatar
Radford Neal committed
583
        }
Radford Neal's avatar
Radford Neal committed
584 585
        if (type_etc == CLOSXP)
            return res;
586 587 588 589 590 591 592 593 594 595
    }

    return findFun_nospecsym(symbol,rho);
}


#define CHECK_STACK_BALANCE(o,s) do { \
  if (s != R_PPStackTop) check_stack_balance(o,s); \
} while (0)

Radford Neal's avatar
Radford Neal committed
596

597 598 599 600 601 602 603 604
/* Wait until no value in an argument list is still being computed by a task.
   Macro version does preliminary check in-line for speed. */

#define WAIT_UNTIL_ARGUMENTS_COMPUTED(_args_) \
    do { \
        if (helpers_tasks > 0) { \
            SEXP _a_ = (_args_); \
            while (_a_ != R_NilValue) { \
605
                if (helpers_is_being_computed(CAR(_a_))) { \
606 607 608 609 610 611 612 613 614 615 616 617 618 619
                    wait_until_arguments_computed (_a_); \
                    break; \
                } \
                _a_ = CDR(_a_); \
            } \
        } \
    } while (0)

void attribute_hidden wait_until_arguments_computed (SEXP args)
{
    SEXP wait_for, a;

    if (helpers_tasks == 0) return;

620
    wait_for = R_NoObject;
621 622 623

    for (a = args; a != R_NilValue; a = CDR(a)) {
        SEXP this_arg = CAR(a);
624
        if (helpers_is_being_computed(this_arg)) {
625
            if (wait_for == R_NoObject)
626 627 628
                wait_for = this_arg;
            else {
                helpers_wait_until_not_being_computed2 (wait_for, this_arg);
629
                wait_for = R_NoObject;
630 631 632 633
            }
        }
    }

634
    if (wait_for != R_NoObject)
635 636 637
        helpers_wait_until_not_being_computed (wait_for);
}

Radford Neal's avatar
Radford Neal committed
638

639 640 641 642 643 644
/* Fast eval macros.  Do not set R_Visible properly, so should not be
   used if that is needed.  Do not check evaluation count, so should
   not be used if a loop without such a check might result.  Do not
   check expression depth or stack overflow, so should not be used if
   infinite recursion could result.  EVALV_NC is meant for use in
   contexts where a self-evaluating constant is not likely. */
Radford Neal's avatar
Radford Neal committed
645

646 647
static SEXP attribute_noinline evalv_sym   (SEXP, SEXP, int);
static SEXP attribute_noinline evalv_other (SEXP, SEXP, int);
Radford Neal's avatar
Radford Neal committed
648

649 650 651
#define EVALV(e, rho, variant) ( \
    R_variant_result = 0, \
    SELF_EVAL(TYPEOF(e)) ? \
Radford Neal's avatar
Radford Neal committed
652 653
       (NAMEDCNT_EQ_MAX(e) ? e \
         : (UPTR_FROM_SEXP(e)->sxpinfo.nmcnt |= MAX_NAMEDCNT, e)) \
654
    : TYPE_ETC(e) == SYMSXP /* not ..., ..1, etc */ ? \
655 656
       evalv_sym (e, rho, variant) \
    :  evalv_other (e, rho, variant) \
657
)
Radford Neal's avatar
Radford Neal committed
658

659 660 661 662 663 664 665
#define EVALV_NC(e, rho, variant) ( \
    R_variant_result = 0, \
    TYPE_ETC(e) == SYMSXP /* not ..., ..1, etc */ ? \
       evalv_sym (e, rho, variant) \
    :  evalv_other (e, rho, variant) \
)

666 667 668 669

/* The "evalv" function returns the value of "e" evaluated in "rho",
   with given variant.  The caller must ensure that both SEXP
   arguments are protected.  The "eval" function is just like "evalv"
670
   with 0 for the variant return argument. */
671

672 673 674
static SEXP attribute_noinline forcePromiseUnbound (SEXP e, int variant);
static SEXP attribute_noinline Rf_builtin_op_no_cntxt (SEXP op, SEXP e, 
                                                       SEXP rho, int variant);
Radford Neal's avatar
Radford Neal committed
675 676
SEXP attribute_hidden Rf_builtin_op (SEXP op, SEXP e, 
                                     SEXP rho, int variant);
677

678 679
#define evalcount R_high_frequency_globals.evalcount

680
SEXP eval (SEXP e, SEXP rho)
681
{
682
    return evalv (e, rho, 0);
683 684
}

685
SEXP evalv (SEXP e, SEXP rho, int variant)
Radford Neal's avatar
Radford Neal committed
686
{
Radford Neal's avatar
Radford Neal committed
687 688
    SEXP res;

689
    R_variant_result = 0;
690 691 692
    R_Visible = TRUE;
    
    /* Handle check for user interrupt. */
693

694
    if (--evalcount < 0) {
695 696 697
        R_CheckUserInterrupt();
        evalcount = 1000;
    }
Radford Neal's avatar
Radford Neal committed
698

699 700 701 702 703 704 705 706 707 708
    /* Quick return for self-evaluating constants. */

    if (SELF_EVAL(TYPEOF(e))) {
        SET_NAMEDCNT_MAX(e);
        return e;
    }

    /* Handle symbol lookup without stack overflow or expression depth check */

    if (TYPE_ETC(e) == SYMSXP /* symbol, but not ..., ..1, etc */) {
709 710
        res = evalv_sym (e, rho, variant);  /* may change R_Visible, but
                                               that seems to be desired... */
Radford Neal's avatar
Radford Neal committed
711
        return res;
712 713
    }

714
    /* Handle evaluations of other things (mostly language objects). */
715

Radford Neal's avatar
Radford Neal committed
716
    R_CHECKSTACK();  /* Check for stack overflow. */
717

718
    R_EvalDepth += 1;
Radford Neal's avatar
Radford Neal committed
719

720 721
    if (R_EvalDepth > R_Expressions)
        too_deep_error();
722

723
    res =  evalv_other (e, rho, variant);
Radford Neal's avatar
Radford Neal committed
724

725
    R_EvalDepth -= 1;
Radford Neal's avatar
Radford Neal committed
726

727 728 729 730 731 732 733
#   ifdef ENABLE_EVAL_DEBUG
    {
        sggc_cptr_t cptr = CPTR_FROM_SEXP(res);
        sggc_check_valid_cptr (cptr);
        if (SEXP_FROM_CPTR(cptr) != res) abort();
        if (res != R_NilValue && TYPEOF(res) == NILSXP) abort();
        if (TYPEOF(res) == FREESXP) abort();
Radford Neal's avatar
Radford Neal committed
734

735 736 737 738 739 740 741 742 743 744
#       ifdef ENABLE_SGGC_DEBUG
            if (sggc_trace_cptr_in_use) {
                sggc_check_valid_cptr (sggc_trace_cptr);
                SEXP trp = SEXP_FROM_CPTR (sggc_trace_cptr);
                if (trp != R_NilValue && TYPEOF(trp) == NILSXP) abort();
                if (TYPEOF(trp) == FREESXP) abort();
            }
#       endif
    }
#   endif
Radford Neal's avatar
Radford Neal committed
745

746 747
    return res;
}
748

749

Radford Neal's avatar
Radford Neal committed
750
static inline SEXP handle_symbol (SEXP res, SEXP e, SEXP rho, int variant)
751
{
752
    SEXP grad = R_NoObject;
753

754 755 756 757 758 759 760 761 762 763 764 765 766
    if (TYPEOF(res) == PROMSXP) {
        if (TYPE_ETC(res) == PROMSXP + TYPE_ET_CETERA_VEC_DOTS_TR) {
            /* forced promise, no gradient */
            res = PRVALUE_PENDING_OK(res);
        }
        else {
            SEXP prom = res;
            if (PRVALUE_PENDING_OK(prom) == R_UnboundValue)
                res = forcePromiseUnbound(prom,variant);
            else
                res = PRVALUE_PENDING_OK(prom);
            if ((variant & VARIANT_GRADIENT) && HAS_ATTRIB(prom))
                grad = ATTRIB(prom);
767
        }
768
    }
769 770 771 772 773 774 775 776 777
    else {
        if (TYPEOF(res) == SYMSXP) {
            if (res == R_MissingArg) {
                if ( ! (variant & VARIANT_MISSING_OK))
                    if (!DDVAL(e))  /* revert bug fix for the moment */
                        arg_missing_error(e);
            }
            else if (res == R_UnboundValue)
                unbound_var_error(e);
778
        }
779 780 781 782 783 784 785
        if ((variant & VARIANT_GRADIENT) && HAS_ATTRIB(R_binding_cell))
            grad = ATTRIB(R_binding_cell);
    }

    if (grad != R_NoObject) {
        R_variant_result = VARIANT_GRADIENT_FLAG;
        R_gradient = grad;
786
    }
787

788 789 790 791 792 793
    /* A NAMEDCNT of 0 might arise from an inadverently missing increment
       somewhere, or from a save/load sequence (since loaded values in
       promises have NAMEDCNT of 0), so fix up here... */

    SET_NAMEDCNT_NOT_0(res);

794 795 796
    if ( ! (variant & VARIANT_PENDING_OK))
        WAIT_UNTIL_COMPUTED(res);

797 798 799
    return res;
}

800

Radford Neal's avatar
Radford Neal committed
801 802 803 804 805 806 807 808
/* Evaluate an expression that is a symbol other than ..., ..1, ..2, etc. */

static SEXP attribute_noinline evalv_sym (SEXP e, SEXP rho, int variant)
{
    return handle_symbol (FIND_VAR_PENDING_OK (e, rho), e, rho, variant);
}


809 810 811
/* Evaluate an expression that is not a symbol (other than ..., ..1, ..2, etc.)
   such as language objects, promises, and self-evaluating expressions. 
   (Most often called with language objects.) */
812

813
static SEXP attribute_noinline evalv_other (SEXP e, SEXP rho, int variant)
814
{
815
    SEXP res;
816

817
    if (TYPE_ETC(e) == LANGSXP) {  /* parts other than type will be 0 */
818

819 820
        SEXP op;

821
#       if SCALAR_STACK_DEBUG
Radford Neal's avatar
Radford Neal committed
822
            SEXP sv_scalar_stack = R_scalar_stack;
823 824
#       endif

825
        SEXP fn = CAR(e);
826

827
        if (TYPE_ETC(fn) == SYMSXP)  /* symbol, and not ..., ..1, ..2, etc. */
828
            op = FINDFUN(fn,rho);
829
        else {
830
            op = eval(fn,rho);
831 832
            R_variant_result = 0;
        }
833

834
        int type_etc = TYPE_ETC(op);
835
        SEXP args = CDR(e);
836

837 838 839
      redo:  /* comes back here for traced functions, after clearing flag */

        if (type_etc == CLOSXP) {
840
            PROTECT(op);
841 842
            res = applyClosure_v (e, op, promiseArgs(args,rho,variant), 
                                  rho, NULL, variant);
843 844 845 846 847 848
            UNPROTECT(1);
        }
        else {
            int save = R_PPStackTop;
            const void *vmax = VMAXGET();

849 850 851 852 853
#           ifdef Win32
                /* Reset precision, rounding & exception modes of an ix86 fpu */
                __asm__ ( "fninit" );
#           endif

Radford Neal's avatar
Radford Neal committed
854
            /* Note: If called from evalv, R_Visible will've been set to TRUE */
855
            if (type_etc == SPECIALSXP) {
856 857 858
                /* Note:  Special primitives always take variant argument,
                   and are responsible for setting R_Visible as desired 
                   themselves, with default of TRUE. */
859
                res = PRIMFUNV(op) (e, op, args, rho, variant);
860
            }
861
            else if (type_etc == BUILTINSXP) {
862 863
                res = R_Profiling ? Rf_builtin_op(op, e, rho, variant)
                                  : Rf_builtin_op_no_cntxt(op, e, rho, variant);
864
                if (PRIMVISON(op))
Radford Neal's avatar
Radford Neal committed
865
                    R_Visible = TRUE;
866
            }
867
            else if (type_etc & TYPE_ET_CETERA_VEC_DOTS_TR) {
Radford Neal's avatar
Radford Neal committed
868
                PROTECT(op);
869
                R_trace_call(e,op);
Radford Neal's avatar
Radford Neal committed
870
                UNPROTECT(1);
871
                type_etc &= ~TYPE_ET_CETERA_VEC_DOTS_TR;
872 873
                goto redo;
            }
874 875 876 877 878 879 880 881 882
            else
                apply_non_function_error();

            CHECK_STACK_BALANCE(op, save);
            VMAXSET(vmax);
        }

#       if SCALAR_STACK_DEBUG
            if (variant & VARIANT_SCALAR_STACK_OK) {
Radford Neal's avatar
Radford Neal committed
883 884 885 886 887 888 889
                if (ON_SCALAR_STACK(res)) {
                    if (res != sv_scalar_stack) abort();
                    if (res != SCALAR_STACK_OFFSET(1)) abort();
                }
                else {
                    if (R_scalar_stack != sv_scalar_stack) abort();
                }
890 891
            }
            else {
Radford Neal's avatar
Radford Neal committed
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
                if (ON_SCALAR_STACK(res)) abort();
                if (R_scalar_stack != sv_scalar_stack) abort();
            }
#       endif

#       if SCALAR_STACK_DEBUG /* to get debug output, type SCALAR.STACK.DEBUG */
            if (installed_already("SCALAR.STACK.DEBUG") != R_NoObject) {
                if (ON_SCALAR_STACK(res)) {
                    REprintf(
                     "SCALAR STACK VALUE RETURNED: %llx %llx %llx %s %f\n",
                     (long long) R_scalar_stack_start,
                     (long long) res, 
                     (long long) R_scalar_stack,
                     TYPEOF(res)==INTSXP ? "int" : "real",
                     TYPEOF(res)==INTSXP ? (double)*INTEGER(res) : *REAL(res));
                }
#               if 0
                    REprintf("STACK:\n");
                    for (int i = 0; i < 6; i++) {
                        if (SCALAR_STACK_ENTRY(i)==R_scalar_stack)
                            REprintf("@@\n");
                        R_inspect(SCALAR_STACK_ENTRY(i));
                    }
                    REprintf("END\n");
#               endif
917 918
            }
#       endif
Radford Neal's avatar
Radford Neal committed
919

920
        return res;
Radford Neal's avatar
Radford Neal committed
921 922
    }

923 924
    if (TYPE_ETC(e) == PROMSXP + TYPE_ET_CETERA_VEC_DOTS_TR) {
        /* forced promise, no gradient */
Radford Neal's avatar
Radford Neal committed
925
        res = PRVALUE_PENDING_OK(e);
926
        if ( ! (variant & VARIANT_PENDING_OK))
927
            WAIT_UNTIL_COMPUTED(res);
928 929
        return res;
    }
930 931 932 933 934

    if (TYPE_ETC(e) == PROMSXP) {
        /* unforced promise, force here */
        res = forcePromiseUnbound(e,variant);
        if ((variant & VARIANT_GRADIENT) && HAS_ATTRIB(e)) {
935 936 937 938 939
            R_variant_result = VARIANT_GRADIENT_FLAG;
            R_gradient = ATTRIB(e);
        }
        if ( ! (variant & VARIANT_PENDING_OK))
            WAIT_UNTIL_COMPUTED(res);
940
        R_Visible = TRUE;
941 942
        return res;
    }
943 944 945 946 947 948
 
    if (TYPE_ETC(e) == 
           PROMSXP + TYPE_ET_CETERA_VEC_DOTS_TR + TYPE_ET_CETERA_HAS_ATTR) {
        /* forced promise, with gradient */
        res = PRVALUE_PENDING_OK(e);
        if (variant & VARIANT_GRADIENT) {
949 950 951
            R_variant_result = VARIANT_GRADIENT_FLAG;
            R_gradient = ATTRIB(e);
        }
952 953
        if ( ! (variant & VARIANT_PENDING_OK))
            WAIT_UNTIL_COMPUTED(res);
954 955 956 957 958 959
        return res;
    }

    if (SELF_EVAL(TYPEOF(e))) {
        SET_NAMEDCNT_MAX(e);
        return e;
960
    }
961

Radford Neal's avatar
Radford Neal committed
962 963
    if (TYPE_ETC(e )== SYMSXP+TYPE_ET_CETERA_VEC_DOTS_TR) /* ... or ..1, ..2 */
        return handle_symbol (ddfindVar(e,rho), e, rho, variant);
Radford Neal's avatar
Radford Neal committed
964

965 966 967
    if (TYPE_ETC(e) == BCODESXP) {  /* parts other than type will be 0 */
        return bcEval(e, rho, TRUE);
    }
968

969 970
    if (TYPEOF(e) == DOTSXP)
        dotdotdot_error();
971 972
    else
        UNIMPLEMENTED_TYPE("eval", e);
Radford Neal's avatar
Radford Neal committed
973
}
974

975

976
/* e is protected here */
977
static SEXP attribute_noinline forcePromiseUnbound (SEXP e, int variant)
978 979 980
{
    SEXP val;

981
    val = PRCODE(e);
982

983 984 985 986 987
    if (SELF_EVAL(TYPEOF(val)) ) {

        /* Just copy code to value - avoids old-to-new check. */

        SET_PRVALUE_TO_PRCODE (e);
988 989

        SET_NAMEDCNT_MAX (val);  /* mimic what would happen if eval'd */
990 991
    }
    else {
992

993
        RPRSTACK prstack;
994

995
        if (PRSEEN(e) == 1) PRSEEN_error(e);
996

997 998 999
        /* Mark the promise as under evaluation and push it on a stack
           that can be used to unmark pending promises if a jump out
           of the evaluation occurs. */
1000

1001 1002 1003
        prstack.promise = e;
        prstack.next = R_PendingPromises;
        R_PendingPromises = &prstack;
1004

1005
        SET_PRSEEN (e, 1);
1006

1007 1008
        PROTECT(e);

1009
        int vrnt = variant & VARIANT_PENDING_OK;
1010

1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        if (STORE_GRAD(e)) {
            vrnt |= VARIANT_MISSING_OK | VARIANT_GRADIENT;
            val = EVALV_NC (val, PRENV(e), vrnt);
            if (R_variant_result & VARIANT_GRADIENT_FLAG)
                SET_ATTRIB (e, R_gradient);
        }
        else {
            vrnt |= VARIANT_MISSING_OK;
            val = EVALV_NC (val, PRENV(e), vrnt);
        }
1021 1022 1023 1024

        /* Pop the stack, unmark the promise and set its value field. */

        R_PendingPromises = prstack.next;
1025
        SET_PRSEEN (e, 0);
1026

1027
        SET_PRVALUE_MACRO (e, val);
1028

1029
        if (val == R_MissingArg) {
1030

1031 1032 1033 1034
            /* Attempt to mimic past behaviour... */
            if ( ! (variant & VARIANT_MISSING_OK) && TYPEOF(PRCODE(e)) == SYMSXP
                      && R_isMissing (PRCODE(e), PRENV(e)))
                arg_missing_error(PRCODE(e));
1035

1036
            UNPROTECT(1);
1037 1038
            return val;
        }
1039

1040
        INC_NAMEDCNT(val);
1041
        UNPROTECT(1);
1042
    }
1043

1044 1045 1046 1047 1048 1049
    /* Set the environment to R_NilValue to allow GC to reclaim the
       promise environment (unless value is R_MissingArg); this is
       also useful for fancy games with delayedAssign() */

    SET_PRENV_NIL(e);

1050 1051 1052 1053 1054
    return val;
}

SEXP forcePromise (SEXP e) /* e protected here if necessary */
{
1055
    if (PRVALUE(e) == R_UnboundValue)
1056 1057 1058 1059 1060
        return forcePromiseUnbound(e,0);
    else
        return PRVALUE(e);
}

1061 1062
SEXP forcePromise_v (SEXP e, int variant) /* e protected here if necessary */
{
1063
    if (PRVALUE(e) == R_UnboundValue)
1064
        return forcePromiseUnbound(e,variant);
1065 1066 1067 1068 1069
    else {
        if ((variant & VARIANT_GRADIENT) && HAS_ATTRIB(e)) {
            R_variant_result = VARIANT_GRADIENT_FLAG;
            R_gradient = ATTRIB(e);
        }
1070 1071 1072 1073
        SEXP r = PRVALUE_PENDING_OK(e);
        if ( ! (variant & VARIANT_PENDING_OK))
            WAIT_UNTIL_COMPUTED(r);
        return r;
1074
    }
1075 1076
}

1077

Radford Neal's avatar
Radford Neal committed
1078
/* Like Rf_builtin_op (in builtin.c) except that no context is
1079 1080 1081 1082
   created.  Making this separate from Rf_builtin_op saves on stack
   space for the local context variable.  Since the somewhat
   time-consuming context creation is not done, there is no advantage
   to evaluating a single argument with pending OK. */
Radford Neal's avatar
Radford Neal committed
1083

1084 1085
static SEXP attribute_noinline Rf_builtin_op_no_cntxt(SEXP op, SEXP e, SEXP rho,
                                                      int variant)
Radford Neal's avatar
Radford Neal committed
1086 1087 1088 1089 1090 1091 1092
{
    SEXP args = CDR(e);
    SEXP arg1;
    SEXP res;

    /* See if this may be a fast primitive.  All fast primitives
       should be BUILTIN.  We do a fast call only if there is exactly
1093 1094 1095 1096
       one argument, with no tag, not missing or a ... argument; also
       must not be an object if the fast primitive dispatches, unless
       the argument was evaluated with VARIANT_UNCLASS and we got this
       variant result.  The argument is stored in arg1. */
Radford Neal's avatar
Radford Neal committed
1097 1098 1099 1100 1101 1102 1103 1104 1105

    if (args!=R_NilValue) {
        if (PRIMFUN_FAST(op) 
              && TAG(args)==R_NilValue && CDR(args)==R_NilValue
              && (arg1 = CAR(args))!=R_DotsSymbol 
              && arg1!=R_MissingArg && arg1!=R_MissingUnder) {

            PROTECT(arg1 = EVALV (arg1, rho, PRIMFUN_ARG1VAR(op)));

Radford Neal's avatar
Radford Neal committed
1106
            if (isObject(arg1) && PRIMFUN_DSPTCH1(op)) {
1107 1108 1109
                if ((PRIMFUN_ARG1VAR (op) & VARIANT_UNCLASS)
                       && (R_variant_result & VARIANT_UNCLASS_FLAG)) {
                    R_variant_result &= ~VARIANT_UNCLASS_FLAG;
Radford Neal's avatar
Radford Neal committed
1110 1111 1112 1113 1114 1115
                }
                else {
                    UNPROTECT(1);
                    PROTECT(args = CONS(arg1,R_NilValue));
                    goto not_fast;
                }
Radford Neal's avatar
Radford Neal committed
1116 1117
            }

Radford Neal's avatar
Radford Neal committed
1118
            R_Visible = TRUE;
Radford Neal's avatar
Radford Neal committed
1119 1120 1121
            res = ((SEXP(*)(SEXP,SEXP,SEXP,SEXP,int)) PRIMFUN_FAST(op)) 
                     (e, op, arg1, rho, variant);

1122
            UNPROTECT(1); /* arg1 */
Radford Neal's avatar
Radford Neal committed
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
            return res;
        }

        args = evalList (args, rho);
    }

    PROTECT(args);

    /* Handle a non-fast op.  We may get here after starting to handle a
       fast op, but if so, args has been set to the evaluated argument list. */

  not_fast: 

1136
    R_variant_result = 0;
1137 1138
    R_Visible = TRUE;
    res = CALL_PRIMFUN(e, op, args, rho, variant);
Radford Neal's avatar
Radford Neal committed
1139

1140 1141
    UNPROTECT(1); /* args */
    return res;
1142 1143
}

1144

1145 1146 1147 1148
/* 'supplied' is an array of SEXP values, first a set of pairs of tag and
   value, then a pairlist of tagged values (or R_NilValue).  If NULL, no
   extras supplied. */

1149
SEXP attribute_hidden applyClosure_v(SEXP call, SEXP op, SEXP arglist, SEXP rho,
1150
                                     SEXP *supplied, int variant)
Radford Neal's avatar
Radford Neal committed
1151
{
1152
    int vrnt = VARIANT_PENDING_OK | VARIANT_DIRECT_RETURN | VARIANT_WHOLE_BODY
1153 1154
                 | VARIANT_PASS_ON(variant);

1155 1156 1157
    if (variant & VARIANT_NOT_WHOLE_BODY)
        vrnt &= ~VARIANT_WHOLE_BODY;

1158
    SEXP formals, actuals, savedrho, savedsrcref;
Radford Neal's avatar
Radford Neal committed
1159
    volatile SEXP body, newrho;
1160
    SEXP f, a;
Radford Neal's avatar
Radford Neal committed
1161 1162 1163 1164 1165 1166
    RCNTXT cntxt;

    formals = FORMALS(op);
    body = BODY(op);
    savedrho = CLOENV(op);

1167
    /*  Set up a context with the call in it for use if an error occurs below
1168 1169
        in matchArgs or from running out of memory (eg, in NewEnvironment). 
        Note that this also protects call, savedrho, rho, arglist, and op. */
Radford Neal's avatar
Radford Neal committed
1170 1171

    begincontext(&cntxt, CTXT_RETURN, call, savedrho, rho, arglist, op);
1172

1173
    savedsrcref = R_Srcref;  /* saved in context for longjmp, and protection */
Radford Neal's avatar
Radford Neal committed
1174 1175 1176

    /*  Build a list which matches the actual (unevaluated) arguments
	to the formal paramters.  Build a new environment which
1177 1178
	contains the matched pairs.  Note that actuals is protected via
        newrho. */
Radford Neal's avatar
Radford Neal committed
1179

1180
    actuals = matchArgs_pairlist (formals, arglist, call);
1181 1182
    PROTECT(newrho = NewEnvironment(R_NilValue, actuals, savedrho));
        /* no longer passes formals, since matchArg now puts tags in actuals */
Radford Neal's avatar
Radford Neal committed
1183 1184
    if (variant & VARIANT_GRADIENT)
        SET_STORE_GRAD (newrho, STORE_GRAD(rho));
Radford Neal's avatar
Radford Neal committed
1185 1186 1187 1188 1189 1190 1191 1192 1193

    /* This piece of code is destructively modifying the actuals list,
       which is now also the list of bindings in the frame of newrho.
       This is one place where internal structure of environment
       bindings leaks out of envir.c.  It should be rewritten
       eventually so as not to break encapsulation of the internal
       environment layout.  We can live with it for now since it only
       happens immediately after the environment creation.  LT */

1194 1195
    R_symbits_t bits = 0;

Radford Neal's avatar
Radford Neal committed
1196 1197
    f = formals;
    a = actuals;
1198 1199 1200
    while (a != R_NilValue) {
        SEXP t = TAG(a);
        bits |= SYMBITS(t);
1201 1202 1203 1204 1205 1206
        if (MISSING(a)) {
            if (CAR(f) != R_MissingArg) {
                SETCAR(a, mkPROMISE(CAR(f), newrho));
                SET_MISSING(a, 2);
            }
        }
1207 1208
        else { 
            /* optimize assuming non-missing arguments are usually referenced */
1209 1210
            LASTSYMENV(t) = SEXP32_FROM_SEXP(newrho);
            LASTSYMBINDING(t) = a;
1211
        }
Radford Neal's avatar
Radford Neal committed
1212
	a = CDR(a);
1213
	f = CDR(f);
Radford Neal's avatar
Radford Neal committed
1214 1215
    }

1216 1217 1218
    SET_ENVSYMBITS (newrho, bits);

    /* set_symbits_in_env (newrho); */  /* now done in loop above */
1219

Radford Neal's avatar
Radford Neal committed
1220 1221
    /*  Fix up any extras that were supplied by usemethod. */

1222 1223 1224 1225 1226 1227
    if (supplied != NULL) {
        while (TYPEOF(*supplied) == SYMSXP) {
            set_var_in_frame (*supplied, *(supplied+1), newrho, TRUE, 3);
            supplied += 2;
        }
	for (SEXP t = *supplied; t != R_NilValue; t = CDR(t)) {
Radford Neal's avatar
Radford Neal committed
1228
	    for (a = actuals; a != R_NilValue; a = CDR(a))
Radford Neal's avatar
Radford Neal committed
1229
		if (TAG(a) == TAG(t))
Radford Neal's avatar
Radford Neal committed
1230 1231
		    break;
	    if (a == R_NilValue)
Radford Neal's avatar
Radford Neal committed
1232
		set_var_in_frame (TAG(t), CAR(t), newrho, TRUE, 3);
Radford Neal's avatar
Radford Neal committed
1233 1234 1235
	}
    }

1236
    UNPROTECT(1); /* newrho, which will be protected below via revised context*/
Radford Neal's avatar
Radford Neal committed
1237

1238
    /*  Change the previously-set-up context to have the correct environment.
Radford Neal's avatar
Radford Neal committed
1239

1240
        If we have a generic function we need to use the sysparent of
Radford Neal's avatar
Radford Neal committed
1241
	the generic as the sysparent of the method because the method
1242
	is a straight substitution of the generic. */
Radford Neal's avatar
Radford Neal committed
1243

1244 1245
    if (R_GlobalContext->nextcontext->callflag == CTXT_GENERIC)
	revisecontext (newrho, R_GlobalContext->nextcontext->sysparent);
Radford Neal's avatar
Radford Neal committed
1246
    else
1247
	revisecontext (newrho, rho);
Radford Neal's avatar
Radford Neal committed
1248

1249 1250
    /* Get the srcref record from the closure object */
    
1251
    R_Srcref = getAttrib00(op, R_SrcrefSymbol);
Radford Neal's avatar
Radford Neal committed
1252 1253 1254

    /* Debugging */

1255 1256 1257 1258
    if (RDEBUG(op) | RSTEP(op)) {
        SET_RDEBUG(newrho, 1);
        if (RSTEP(op)) SET_RSTEP(op, 0);
	SEXP savesrcref; SEXP *srcrefs; int len;
Radford Neal's avatar
Radford Neal committed
1259 1260 1261
	/* switch to interpreted version when debugging compiled code */
	if (TYPEOF(body) == BCODESXP)
	    body = bytecodeExpr(body);
Radford Neal's avatar
Radford Neal committed
1262
	Rprintf("debugging in: ");
1263
        printcall(call,rho);
Radford Neal's avatar
Radford Neal committed
1264
	savesrcref = R_Srcref;
1265 1266 1267
	getBlockSrcrefs(body,&srcrefs,&len);
	PROTECT(R_Srcref = getSrcref(srcrefs,len,0));
        start_browser (call, op, body, newrho);
Radford Neal's avatar
Radford Neal committed
1268 1269
	R_Srcref = savesrcref;
	UNPROTECT(1);
Radford Neal's avatar
Radford Neal committed
1270 1271
    }

Radford Neal's avatar
Radford Neal committed
1272 1273
    /* Set a longjmp target which will catch any explicit returns from the
       function body that are not instead handled by VARIANT_DIRECT_RETURN.  */
1274 1275

    SEXP res;
Radford Neal's avatar
Radford Neal committed
1276 1277 1278 1279 1280

    if ((SETJMP(cntxt.cjmpbuf))) {
	if (R_ReturnedValue == R_RestartToken) {
	    cntxt.callflag = CTXT_RETURN;  /* turn restart off */
	    R_ReturnedValue = R_NilValue;  /* remove restart token */
1281
	    res = evalv (body, newrho, vrnt);
Radford Neal's avatar
Radford Neal committed
1282
	}
1283
	else {
1284
	    res = R_ReturnedValue;
1285
        }
Radford Neal's avatar
Radford Neal committed
1286 1287
    }
    else {
1288
	res = evalv (body, newrho, vrnt);
Radford Neal's avatar
Radford Neal committed
1289 1290
    }

1291 1292
    PROTECT(res);

Radford Neal's avatar
Radford Neal committed
1293 1294
    R_variant_result &= ~VARIANT_RTN_FLAG;

1295
    R_Srcref = savedsrcref;
Radford Neal's avatar
Radford Neal committed
1296 1297
    endcontext(&cntxt);

Radford Neal's avatar
Radford Neal committed
1298 1299 1300
    if ( ! (variant & VARIANT_PENDING_OK))
        WAIT_UNTIL_COMPUTED(res);

Radford Neal's avatar
Radford Neal committed
1301 1302
    if (RDEBUG(op)) {
	Rprintf("exiting from: ");
1303
        printcall(call,rho);
Radford Neal's avatar
Radford Neal committed
1304
    }
Radford Neal's avatar
Radford Neal committed
1305

1306
    UNPROTECT(1); /* res */
Radford Neal's avatar
Radford Neal committed
1307
    return res;
Radford Neal's avatar
Radford Neal committed
1308 1309
}

1310
SEXP applyClosure (SEXP call, SEXP op, SEXP arglist, SEXP rho, 
1311
                   SEXP *supplied)
1312
{
1313 1314
    if (supplied != NULL) error("Last argument to applyClosure must be NULL");
    return applyClosure_v (call, op, arglist, rho, NULL, 0);
1315 1316
}

Radford Neal's avatar
Radford Neal committed
1317 1318 1319 1320 1321 1322
/* **** FIXME: This code is factored out of applyClosure.  If we keep
   **** it we should change applyClosure to run through this routine
   **** to avoid code drift. */
static SEXP R_execClosure(SEXP call, SEXP op, SEXP arglist, SEXP rho,
			  SEXP newrho)
{
Radford Neal's avatar
Radford Neal committed
1323
    volatile SEXP body;
1324
    SEXP savedsrcref;
Radford Neal's avatar
Radford Neal committed
1325 1326 1327 1328 1329
    RCNTXT cntxt;

    body = BODY(op);

    begincontext(&cntxt, CTXT_RETURN, call, newrho, rho, arglist, op);
1330
    savedsrcref = R_Srcref;  /* saved in context for longjmp, and protection */
Radford Neal's avatar
Radford Neal committed
1331

1332 1333 1334
    /* Get the srcref record from the closure object.  Disable for now
       at least, since it's not clear that it's needed. */
    
1335
    R_Srcref = R_NilValue;  /* was: getAttrib(op, R_SrcrefSymbol); */
1336

Radford Neal's avatar
Radford Neal committed
1337 1338
    /* Debugging */

1339 1340 1341 1342
    if (RDEBUG(op) | RSTEP(op)) {
        SET_RDEBUG(newrho, 1);
        if (RSTEP(op)) SET_RSTEP(op, 0);
        SEXP savesrcref; SEXP *srcrefs; int len;
Radford Neal's avatar
Radford Neal committed
1343 1344 1345
	/* switch to interpreted version when debugging compiled code */
	if (TYPEOF(body) == BCODESXP)
	    body = bytecodeExpr(body);
Radford Neal's avatar
Radford Neal committed
1346
	Rprintf("debugging in: ");
1347
	printcall (call, rho);
Radford Neal's avatar
Radford Neal committed
1348
	savesrcref = R_Srcref;
1349 1350 1351
	getBlockSrcrefs(body,&srcrefs,&len);
	PROTECT(R_Srcref = getSrcref(srcrefs,len,0));
        start_browser (call, op, body, newrho);
Radford Neal's avatar
Radford Neal committed
1352 1353
	R_Srcref = savesrcref;
	UNPROTECT(1);
Radford Neal's avatar
Radford Neal committed
1354 1355 1356 1357 1358
    }

    /*  Set a longjmp target which will catch any explicit returns
	from the function body.  */

1359 1360
    SEXP res;

Radford Neal's avatar
Radford Neal committed
1361 1362 1363 1364
    if ((SETJMP(cntxt.cjmpbuf))) {
	if (R_ReturnedValue == R_RestartToken) {
	    cntxt.callflag = CTXT_RETURN;  /* turn restart off */
	    R_ReturnedValue = R_NilValue;  /* remove restart token */
1365
	    res = evalv(body, newrho, VARIANT_NOT_WHOLE_BODY);
Radford Neal's avatar
Radford Neal committed
1366
	}
1367
	else {
1368
	    res = R_ReturnedValue;
Radford Neal's avatar
Radford Neal committed
1369
            WAIT_UNTIL_COMPUTED(res);
1370
        }
Radford Neal's avatar
Radford Neal committed
1371 1372
    }
    else {
1373
	res = evalv(body, newrho, 0);
Radford Neal's avatar
Radford Neal committed
1374 1375
    }

1376 1377
    PROTECT(res);

1378
    R_Srcref = savedsrcref;
Radford Neal's avatar
Radford Neal committed
1379 1380 1381 1382
    endcontext(&cntxt);

    if (RDEBUG(op)) {
	Rprintf("exiting from: ");
1383
	printcall (call, rho);
Radford Neal's avatar
Radford Neal committed
1384
    }
Radford Neal's avatar
Radford Neal committed
1385

1386
    UNPROTECT(1);  /* res */
Radford Neal's avatar
Radford Neal committed
1387
    return res;
Radford Neal's avatar
Radford Neal committed
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
}

/* **** FIXME: Temporary code to execute S4 methods in a way that
   **** preserves lexical scope. */

/* called from methods_list_dispatch.c */
SEXP R_execMethod(SEXP op, SEXP rho)
{
    SEXP call, arglist, callerenv, newrho, next, val;
    RCNTXT *cptr;

    /* create a new environment frame enclosed by the lexical
       environment of the method */
    PROTECT(newrho = Rf_NewEnvironment(R_NilValue, R_NilValue, CLOENV(op)));

    /* copy the bindings for the formal environment from the top frame
       of the internal environment of the generic call to the new
       frame.  need to make sure missingness information is preserved
       and the environments for any default expression promises are
       set to the new environment.  should move this to envir.c where
       it can be done more efficiently. */
    for (next = FORMALS(op); next != R_NilValue; next = CDR(next)) {
	SEXP symbol =  TAG(next);
	R_varloc_t loc;
	int missing;
	loc = R_findVarLocInFrame(rho,symbol);
1414
	if (loc == R_NoObject)
Radford Neal's avatar
Radford Neal committed
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
	    error(_("could not find symbol \"%s\" in environment of the generic function"),
		  CHAR(PRINTNAME(symbol)));
	missing = R_GetVarLocMISSING(loc);
	val = R_GetVarLocValue(loc);
	SET_FRAME(newrho, CONS(val, FRAME(newrho)));
	SET_TAG(FRAME(newrho), symbol);
	if (missing) {
	    SET_MISSING(FRAME(newrho), missing);
	    if (TYPEOF(val) == PROMSXP && PRENV(val) == rho) {
		SEXP deflt;
		SET_PRENV(val, newrho);
		/* find the symbol in the method, copy its expression
		 * to the promise */
		for(deflt = CAR(op); deflt != R_NilValue; deflt = CDR(deflt)) {
		    if(TAG(deflt) == symbol)
			break;
		}
		if(deflt == R_NilValue)
		    error(_("symbol \"%s\" not in environment of method"),
			  CHAR(PRINTNAME(symbol)));
		SET_PRCODE(val, CAR(deflt));
	    }
	}
    }

    /* copy the bindings of the spacial dispatch variables in the top
       frame of the generic call to the new frame */
    defineVar(R_dot_defined, findVarInFrame(rho, R_dot_defined), newrho);
    defineVar(R_dot_Method, findVarInFrame(rho, R_dot_Method), newrho);
    defineVar(R_dot_target, findVarInFrame(rho, R_dot_target), newrho);

    /* copy the bindings for .Generic and .Methods.  We know (I think)
       that they are in the second frame, so we could use that. */
    defineVar(R_dot_Generic, findVar(R_dot_Generic, rho), newrho);
    defineVar(R_dot_Methods, findVar(R_dot_Methods, rho), newrho);

    /* Find the calling context.  Should be R_GlobalContext unless
       profiling has inserted a CTXT_BUILTIN frame. */
    cptr = R_GlobalContext;
    if (cptr->callflag & CTXT_BUILTIN)
	cptr = cptr->nextcontext;

    /* The calling environment should either be the environment of the
       generic, rho, or the environment of the caller of the generic,
       the current sysparent. */
    callerenv = cptr->sysparent; /* or rho? */

    /* get the rest of the stuff we need from the current context,
       execute the method, and return the result */
    call = cptr->call;
    arglist = cptr->promargs;
    val = R_execClosure(call, op, arglist, callerenv, newrho);
    UNPROTECT(1);
    return val;
}


Radford Neal's avatar
Radford Neal committed
1472
#define BodyHasBraces(body) \
1473
    (isLanguage(body) && CAR(body) == R_BraceSymbol)
Radford Neal's avatar
Radford Neal committed
1474

1475

Radford Neal's avatar
Radford Neal committed
1476
static SEXP do_if (SEXP call, SEXP op, SEXP args, SEXP rho, int variant)
1477
{
1478 1479
    /* Don't check arg count - missing are seen as R_NilValue, extra ignored. */

1480 1481 1482 1483 1484 1485
    SEXP Cond, Stmt;
    int absent_else = 0;

    Cond = CAR(args); args = CDR(args);
    Stmt = CAR(args); args = CDR(args);

1486 1487
    SEXP condval = EVALV_NC (Cond, rho, 
                             VARIANT_SCALAR_STACK_OK | VARIANT_ANY_ATTR);
1488

1489
    if ( ! asLogicalNoNA (condval, call)) {
1490
        /* go to else part */
1491 1492 1493 1494 1495 1496 1497 1498
        if (args != R_NilValue)
            Stmt = CAR(args);
        else {
            absent_else = 1;
            Stmt = R_NilValue;
        }
    }

1499 1500
    if (RDEBUG(rho) && Stmt!=R_NilValue && !BodyHasBraces(Stmt))
        start_browser (call, op, Stmt, rho);
1501 1502 1503 1504 1505 1506

    if (absent_else) {
        R_Visible = FALSE; /* case of no 'else' so return invisible NULL */
        return R_NilValue;
    }

1507
    return evalv (Stmt, rho, VARIANT_PASS_ON(variant));
1508 1509 1510
}


1511 1512
/* For statement.  Unevaluated arguments for different formats are as follows:

1513 1514 1515
       for (i in v) body          i, v, body
       for (i down v) body        i, down=v, body
       for (i across v) body      i, across=v, body
1516 1517 1518 1519
       for (i along v) body       i, along=v, body     (ok for vec or for array)
       for (i, j along M) body    i, j, along=M, body     (requires correct dim)
       etc.

1520 1521
   Extra variables after i are ignored for 'in', 'down', and 'across'.

1522 1523
   Evaluates body with VARIANT_NULL | VARIANT_PENDING_OK.
 */
1524

1525
#define DO_LOOP_RDEBUG(call, op, body, rho, bgn) do { \
1526 1527
        if (!bgn && RDEBUG(rho)) start_browser (call, op, body, rho); \
    } while (0)
Radford Neal's avatar
Radford Neal committed
1528

1529
static SEXP do_for (SEXP call, SEXP op, SEXP args, SEXP rho, int variant)
Radford Neal's avatar
Radford Neal committed
1530
{
Radford Neal's avatar
Radford Neal committed
1531
    /* Need to declare volatile variables whose values are relied on
1532 1533
       after for_next or for_break longjmps and that might change between
       the setjmp and longjmp calls.  Theoretically this does not include
1534
       n and some others, but gcc -O2 -Wclobbered warns about some, 
1535
       so to be safe we declare them volatile as well. */
1536

1537
    volatile int i, n;
1538 1539 1540
    volatile SEXP val, nval;
    volatile SEXP v, bcell;                /* for use with one 'for' variable */
    volatile SEXP indexes, ixvals, bcells; /* for use with >1 'for' variables */
Radford Neal's avatar
Radford Neal committed
1541
    int dbg, val_type;