The R Project SVN R

Rev

Rev 63181 | Rev 64933 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 r 1
/*
526 maechler 2
 *  R : A Computer Language for Statistical Data Analysis
2 r 3
 *  Copyright (C) 1995, 1996  Robert Gentleman and Ross Ihaka
62580 ripley 4
 *  Copyright (C) 2002-3     The R Foundation
5
 *  Copyright (C) 1999-2013  The R Core Team.
2 r 6
 *
7
 *  This program is free software; you can redistribute it and/or modify
8
 *  it under the terms of the GNU General Public License as published by
21352 maechler 9
 *  the Free Software Foundation; either version 2, or (at your option)
10
 *  any later version.
2 r 11
 *
21812 maechler 12
 *  This program is distributed in the hope that it will be useful,
13
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 *  GNU General Public License for more details.
2 r 16
 *
42307 ripley 17
 *  You should have received a copy of the GNU General Public License
18
 *  along with this program; if not, a copy is available at
19
 *  http://www.r-project.org/Licenses/
2 r 20
 */
21
 
1839 ihaka 22
/*  This module contains support for S-style generic */
23
/*  functions and "class" support.  Gag, barf ...  */
2 r 24
 
5187 hornik 25
#ifdef HAVE_CONFIG_H
7701 hornik 26
#include <config.h>
5187 hornik 27
#endif
28
 
57538 ripley 29
#define R_USE_SIGNALS 1
60667 ripley 30
#include <Defn.h>
31
#include <Internal.h>
39077 jmc 32
#include <R_ext/RS.h> /* for Calloc, Realloc and for S4 object bit */
2 r 33
 
34
static SEXP GetObject(RCNTXT *cptr)
35
{
8130 pd 36
    SEXP s, sysp, b, formals, funcall, tag;
37
    sysp = R_GlobalContext->sysparent;
38
 
39
    PROTECT(funcall = R_syscall(0, cptr));
40
 
41
    if ( TYPEOF(CAR(funcall)) == SYMSXP )
42
	PROTECT(b = findFun(CAR(funcall), sysp));
43
    else
44
	PROTECT(b = eval(CAR(funcall), sysp));
32867 ripley 45
    /**** use R_sysfunction here instead */
46
    if (TYPEOF(b) != CLOSXP) error(_("generic 'function' is not a function"));
8130 pd 47
    formals = FORMALS(b);
48
 
49
    tag = TAG(formals);
50
    if (tag != R_NilValue && tag != R_DotsSymbol) {
63050 luke 51
	s = NULL;
8130 pd 52
	/** exact matches **/
21352 maechler 53
	for (b = cptr->promargs ; b != R_NilValue ; b = CDR(b))
54
	    if (TAG(b) != R_NilValue && pmatch(tag, TAG(b), 1)) {
63050 luke 55
		if (s != NULL)
32867 ripley 56
		    error(_("formal argument \"%s\" matched by multiple actual arguments"), tag);
21352 maechler 57
		else
8130 pd 58
		    s = CAR(b);
59
	    }
60
 
63050 luke 61
	if (s == NULL)
8130 pd 62
	    /** partial matches **/
21352 maechler 63
	    for (b = cptr->promargs ; b != R_NilValue ; b = CDR(b))
64
		if (TAG(b) != R_NilValue && pmatch(tag, TAG(b), 0)) {
63050 luke 65
		    if ( s != NULL)
32867 ripley 66
			error(_("formal argument \"%s\" matched by multiple actual arguments"), tag);
21352 maechler 67
		    else
8130 pd 68
			s = CAR(b);
69
		}
63050 luke 70
	if (s == NULL)
8130 pd 71
	    /** first untagged argument **/
21352 maechler 72
	    for (b = cptr->promargs ; b != R_NilValue ; b = CDR(b))
73
		if (TAG(b) == R_NilValue )
8130 pd 74
		{
75
		    s = CAR(b);
76
		    break;
77
		}
63050 luke 78
	if (s == NULL)
8130 pd 79
	    s = CAR(cptr->promargs);
80
/*
81
	    error("failed to match argument for dispatch");
82
*/
83
    }
84
    else
85
	s = CAR(cptr->promargs);
86
 
87
    UNPROTECT(2);
1839 ihaka 88
    if (TYPEOF(s) == PROMSXP) {
8130 pd 89
	if (PRVALUE(s) == R_UnboundValue)
35450 murdoch 90
	    s = eval(s, R_BaseEnv);
18214 luke 91
	else
92
	    s = PRVALUE(s);
1839 ihaka 93
    }
94
    return(s);
2 r 95
}
96
 
97
static SEXP applyMethod(SEXP call, SEXP op, SEXP args, SEXP rho, SEXP newrho)
98
{
1839 ihaka 99
    SEXP ans;
100
    if (TYPEOF(op) == SPECIALSXP) {
40090 ripley 101
	int save = R_PPStackTop, flag = PRIMPRINT(op);
50745 ripley 102
	const void *vmax = vmaxget();
40090 ripley 103
	R_Visible = flag != 1;
1839 ihaka 104
	ans = PRIMFUN(op) (call, op, args, rho);
40090 ripley 105
	if (flag < 2) R_Visible = flag != 1;
39232 ripley 106
	check_stack_balance(op, save);
41825 ripley 107
	vmaxset(vmax);
1839 ihaka 108
    }
38982 ripley 109
    /* In other places we add a context to builtins when profiling,
42110 maechler 110
       but we have not bothered here (as there seem to be no primitives
38982 ripley 111
       used as methods, and this would have to be a primitive to be
112
       found).
38522 ripley 113
     */
1839 ihaka 114
    else if (TYPEOF(op) == BUILTINSXP) {
40090 ripley 115
	int save = R_PPStackTop, flag = PRIMPRINT(op);
50745 ripley 116
	const void *vmax = vmaxget();
50690 ripley 117
	PROTECT(args = evalList(args, rho, call, 0));
40090 ripley 118
	R_Visible = flag != 1;
1839 ihaka 119
	ans = PRIMFUN(op) (call, op, args, rho);
40090 ripley 120
	if (flag < 2) R_Visible = flag != 1;
1839 ihaka 121
	UNPROTECT(1);
39232 ripley 122
	check_stack_balance(op, save);
41825 ripley 123
	vmaxset(vmax);
1839 ihaka 124
    }
125
    else if (TYPEOF(op) == CLOSXP) {
126
	ans = applyClosure(call, op, args, rho, newrho);
127
    }
2342 maechler 128
    else
1839 ihaka 129
	ans = R_NilValue;  /* for -Wall */
130
    return ans;
2 r 131
}
132
 
133
 
1839 ihaka 134
/* "newintoold" -  a destructive matching of arguments; */
135
/* newargs comes first; any element of oldargs with */
136
/* a name that matches a named newarg is deleted; the */
137
/* two resulting lists are appended and returned. */
138
/* S claims to do this (white book) but doesn't seem to. */
2 r 139
 
39866 duncan 140
static SEXP newintoold(SEXP _new, SEXP old)
2 r 141
{
39866 duncan 142
    if (_new == R_NilValue) return R_NilValue;
143
    SETCDR(_new, newintoold(CDR(_new),old));
1839 ihaka 144
    while (old != R_NilValue) {
39866 duncan 145
	if (TAG(old) != R_NilValue && TAG(old) == TAG(_new)) {
146
	    SETCAR(old, CAR(_new));
147
	    return CDR(_new);
2 r 148
	}
1839 ihaka 149
	old = CDR(old);
150
    }
39866 duncan 151
    return _new;
2 r 152
}
153
 
154
static SEXP matchmethargs(SEXP oldargs, SEXP newargs)
155
{
1839 ihaka 156
    newargs = newintoold(newargs, oldargs);
157
    return listAppend(oldargs, newargs);
2 r 158
}
159
 
48117 jmc 160
#ifdef S3_for_S4_warn /* not currently used */
161
static SEXP s_check_S3_for_S4 = 0;
162
void R_warn_S3_for_S4(SEXP method) {
163
  SEXP call;
164
  if(!s_check_S3_for_S4)
165
    s_check_S3_for_S4 = install(".checkS3forS4");
166
  PROTECT(call = lang2(s_check_S3_for_S4, method));
167
  eval(call, R_MethodsNamespace);
168
  UNPROTECT(1);
169
}
170
#endif
171
 
2 r 172
/*  usemethod  -  calling functions need to evaluate the object
526 maechler 173
 *  (== 2nd argument).	They also need to ensure that the
2 r 174
 *  argument list is set up in the correct manner.
526 maechler 175
 *
2 r 176
 *    1. find the context for the calling function (i.e. the generic)
177
 *	 this gives us the unevaluated arguments for the original call
178
 *
179
 *    2. create an environment for evaluating the method and insert
526 maechler 180
 *	 a handful of variables (.Generic, .Class and .Method) into
181
 *	 that environment. Also copy any variables in the env of the
182
 *	 generic that are not formal (or actual) arguments.
2 r 183
 *
184
 *    3. fix up the argument list; it should be the arguments to the
526 maechler 185
 *	 generic matched to the formals of the method to be invoked */
2 r 186
 
61771 ripley 187
attribute_hidden
16335 luke 188
SEXP R_LookupMethod(SEXP method, SEXP rho, SEXP callrho, SEXP defrho)
189
{
190
    SEXP val;
191
 
38132 ripley 192
    if (TYPEOF(callrho) == NILSXP) {
193
	error(_("use of NULL environment is defunct"));
194
	callrho = R_BaseEnv;
195
    } else
36174 murdoch 196
	if (TYPEOF(callrho) != ENVSXP)
32867 ripley 197
	    error(_("bad generic call environment"));
38132 ripley 198
    if (TYPEOF(defrho) == NILSXP) {
37725 ripley 199
	    error(_("use of NULL environment is defunct"));
36174 murdoch 200
	    defrho = R_BaseEnv;
38132 ripley 201
    } else
36174 murdoch 202
	if (TYPEOF(defrho) != ENVSXP)
32867 ripley 203
	    error(_("bad generic definition environment"));
38132 ripley 204
    if (defrho == R_BaseEnv)
205
	defrho = R_BaseNamespace;
42110 maechler 206
 
38135 ripley 207
    /* This evaluates promises */
38134 ripley 208
    val = findVar1(method, callrho, FUNSXP, TRUE);
38132 ripley 209
    if (isFunction(val))
210
	return val;
211
    else {
38134 ripley 212
	/* We assume here that no one registered a non-function */
38132 ripley 213
	SEXP table = findVarInFrame3(defrho,
214
				     install(".__S3MethodsTable__."),
215
				     TRUE);
38135 ripley 216
	if (TYPEOF(table) == PROMSXP) table = eval(table, R_BaseEnv);
38132 ripley 217
	if (TYPEOF(table) == ENVSXP) {
218
	    val = findVarInFrame3(table, method, TRUE);
38134 ripley 219
	    if (TYPEOF(val) == PROMSXP) val = eval(val, rho);
38135 ripley 220
	    if (val != R_UnboundValue) return val;
16335 luke 221
	}
38132 ripley 222
	return R_UnboundValue;
16335 luke 223
    }
224
}
225
 
48068 ripley 226
#ifdef UNUSED
48062 jmc 227
static int match_to_obj(SEXP arg, SEXP obj) {
228
  return (arg == obj) ||
229
    (TYPEOF(arg) == PROMSXP && PRVALUE(arg) == obj);
230
}
48068 ripley 231
#endif
48062 jmc 232
 
48694 jmc 233
/* look up the class name in the methods package table of S3 classes
234
   which should be explicitly converted when an S3 method is applied
235
   to an object from an S4 subclass.
236
*/
48724 jmc 237
int isBasicClass(const char *ss) {
48694 jmc 238
    static SEXP s_S3table = 0;
239
    if(!s_S3table) {
240
      s_S3table = findVarInFrame3(R_MethodsNamespace, install(".S3MethodsClasses"), TRUE);
241
      if(s_S3table == R_UnboundValue)
60844 ripley 242
	error(_("no '.S3MethodsClass' table, cannot use S4 objects with S3 methods ('methods' package not attached?)"));
48694 jmc 243
	if (TYPEOF(s_S3table) == PROMSXP)  /* findVar... ignores lazy data */
244
	    s_S3table = eval(s_S3table, R_MethodsNamespace);
245
    }
246
    if(s_S3table == R_UnboundValue)
247
      return FALSE; /* too screwed up to do conversions */
248
    return findVarInFrame3(s_S3table, install(ss), FALSE) != R_UnboundValue;
249
}
250
 
52431 maechler 251
 
61771 ripley 252
attribute_hidden
41784 ripley 253
int usemethod(const char *generic, SEXP obj, SEXP call, SEXP args,
16335 luke 254
	      SEXP rho, SEXP callrho, SEXP defrho, SEXP *ans)
2 r 255
{
52266 jmc 256
    SEXP klass, method, sxp, t, s, matchedarg, sort_list;
55061 ripley 257
    SEXP op, formals, newrho, newcall;
1839 ihaka 258
    char buf[512];
52273 ripley 259
    int i, j, nclass, matched, /* S4toS3, */ nprotect;
1839 ihaka 260
    RCNTXT *cptr;
2 r 261
 
1839 ihaka 262
    /* Get the context which UseMethod was called from. */
2 r 263
 
1839 ihaka 264
    cptr = R_GlobalContext;
6188 rgentlem 265
    if ( !(cptr->callflag & CTXT_FUNCTION) || cptr->cloenv != rho)
33412 ripley 266
	error(_("'UseMethod' used in an inappropriate fashion"));
214 rgentlem 267
 
1839 ihaka 268
    /* Create a new environment without any */
269
    /* of the formals to the generic in it. */
2 r 270
 
1839 ihaka 271
    PROTECT(newrho = allocSExp(ENVSXP));
8516 pd 272
    op = CAR(cptr->call);
273
    switch (TYPEOF(op)) {
274
    case SYMSXP:
275
	PROTECT(op = findFun(op, cptr->sysparent));
276
	break;
277
    case LANGSXP:
278
	PROTECT(op = eval(op, cptr->sysparent));
279
	break;
280
    case CLOSXP:
281
    case BUILTINSXP:
282
    case SPECIALSXP:
283
	PROTECT(op);
284
	break;
285
    default:
60844 ripley 286
	error(_("invalid generic function in 'usemethod'"));
8516 pd 287
    }
288
 
48409 jmc 289
    nprotect = 5;
1839 ihaka 290
    if (TYPEOF(op) == CLOSXP) {
291
	formals = FORMALS(op);
292
	for (s = FRAME(cptr->cloenv); s != R_NilValue; s = CDR(s)) {
293
	    matched = 0;
294
	    for (t = formals; t != R_NilValue; t = CDR(t))
48062 jmc 295
	        if (TAG(t) == TAG(s)) {
296
		    matched = 1;
297
		}
38135 ripley 298
 
299
	    if (!matched) defineVar(TAG(s), CAR(s), newrho);
2 r 300
	}
1839 ihaka 301
    }
2 r 302
 
1839 ihaka 303
    PROTECT(matchedarg = cptr->promargs);
304
    PROTECT(newcall = duplicate(cptr->call));
2 r 305
 
39866 duncan 306
    PROTECT(klass = R_data_class2(obj));
52266 jmc 307
    sort_list = install("sort.list");
48062 jmc 308
 
39866 duncan 309
    nclass = length(klass);
48409 jmc 310
    for (i = 0; i < nclass; i++) {
63181 ripley 311
	const void *vmax = vmaxget();
48409 jmc 312
        const char *ss = translateChar(STRING_ELT(klass, i));
40705 ripley 313
	if(strlen(generic) + strlen(ss) + 2 > 512)
33297 ripley 314
	    error(_("class name too long in '%s'"), generic);
62580 ripley 315
	snprintf(buf, 512, "%s.%s", generic, ss);
22764 jmc 316
	method = install(buf);
63181 ripley 317
	vmaxset(vmax);
22764 jmc 318
	sxp = R_LookupMethod(method, rho, callrho, defrho);
319
	if (isFunction(sxp)) {
52266 jmc 320
	    if(method == sort_list && CLOENV(sxp) == R_BaseNamespace)
321
		continue; /* kludge because sort.list is not a method */
49005 rgentlem 322
            if( RDEBUG(op) || RSTEP(op) )
323
                SET_RSTEP(sxp, 1);
54029 luke 324
	    defineVar(R_dot_Generic, mkString(generic), newrho);
24519 ripley 325
	    if (i > 0) {
48409 jmc 326
	        int ii;
327
		PROTECT(t = allocVector(STRSXP, nclass - i));
328
		for(j = 0, ii = i; j < length(t); j++, ii++)
329
		      SET_STRING_ELT(t, j, STRING_ELT(klass, ii));
39866 duncan 330
		setAttrib(t, install("previous"), klass);
54029 luke 331
		defineVar(R_dot_Class, t, newrho);
24519 ripley 332
		UNPROTECT(1);
38135 ripley 333
	    } else
54029 luke 334
		defineVar(R_dot_Class, klass, newrho);
24519 ripley 335
	    PROTECT(t = mkString(buf));
54029 luke 336
	    defineVar(R_dot_Method, t, newrho);
22764 jmc 337
	    UNPROTECT(1);
54029 luke 338
	    defineVar(R_dot_GenericCallEnv, callrho, newrho);
339
	    defineVar(R_dot_GenericDefEnv, defrho, newrho);
24519 ripley 340
	    t = newcall;
341
	    SETCAR(t, method);
342
	    R_GlobalContext->callflag = CTXT_GENERIC;
343
	    *ans = applyMethod(t, sxp, matchedarg, rho, newrho);
344
	    R_GlobalContext->callflag = CTXT_RETURN;
48409 jmc 345
	    UNPROTECT(nprotect);
24519 ripley 346
	    return 1;
2 r 347
	}
1839 ihaka 348
    }
25630 ripley 349
    if(strlen(generic) + strlen("default") + 2 > 512)
33297 ripley 350
	error(_("class name too long in '%s'"), generic);
62580 ripley 351
    snprintf(buf, 512, "%s.default", generic);
1839 ihaka 352
    method = install(buf);
16335 luke 353
    sxp = R_LookupMethod(method, rho, callrho, defrho);
1839 ihaka 354
    if (isFunction(sxp)) {
49005 rgentlem 355
        if( RDEBUG(op) || RSTEP(op) )
356
            SET_RSTEP(sxp, 1);
54029 luke 357
	defineVar(R_dot_Generic, mkString(generic), newrho);
358
	defineVar(R_dot_Class, R_NilValue, newrho);
1839 ihaka 359
	PROTECT(t = mkString(buf));
54029 luke 360
	defineVar(R_dot_Method, t, newrho);
1839 ihaka 361
	UNPROTECT(1);
54029 luke 362
	defineVar(R_dot_GenericCallEnv, callrho, newrho);
363
	defineVar(R_dot_GenericDefEnv, defrho, newrho);
1839 ihaka 364
	t = newcall;
10172 luke 365
	SETCAR(t, method);
1839 ihaka 366
	R_GlobalContext->callflag = CTXT_GENERIC;
367
	*ans = applyMethod(t, sxp, matchedarg, rho, newrho);
368
	R_GlobalContext->callflag = CTXT_RETURN;
26136 luke 369
	UNPROTECT(5);
1839 ihaka 370
	return 1;
371
    }
26136 luke 372
    UNPROTECT(5);
1839 ihaka 373
    cptr->callflag = CTXT_RETURN;
374
    return 0;
2 r 375
}
376
 
51245 ripley 377
/* Note: "do_usemethod" is not the only entry point to
378
   "usemethod". Things like [ and [[ call usemethod directly,
52431 maechler 379
   hence do_usemethod should just be an interface to usemethod.
51245 ripley 380
*/
2 r 381
 
51245 ripley 382
/* This is a primitive SPECIALSXP */
36990 ripley 383
SEXP attribute_hidden do_usemethod(SEXP call, SEXP op, SEXP args, SEXP env)
2 r 384
{
38158 ripley 385
    SEXP ans, generic = R_NilValue /* -Wall */, obj, val;
16335 luke 386
    SEXP callenv, defenv;
51265 ripley 387
    SEXP ap, argList;
1839 ihaka 388
    RCNTXT *cptr;
2 r 389
 
51265 ripley 390
    PROTECT(ap = list2(R_NilValue, R_NilValue));
391
    SET_TAG(ap,  install("generic"));
392
    SET_TAG(CDR(ap), install("object"));
393
    PROTECT(argList =  matchArgs(ap, args, call));
394
    if (CAR(argList) == R_MissingArg)
52431 maechler 395
	errorcall(call, _("there must be a 'generic' argument"));
396
    else
51265 ripley 397
	PROTECT(generic = eval(CAR(argList), env));
398
    if(!isString(generic) || length(generic) != 1)
399
	errorcall(call, _("'generic' argument must be a character string"));
2 r 400
 
1858 ihaka 401
 
16335 luke 402
    /* get environments needed for dispatching.
403
       callenv = environment from which the generic was called
404
       defenv = environment where the generic was defined */
405
    cptr = R_GlobalContext;
406
    if ( !(cptr->callflag & CTXT_FUNCTION) || cptr->cloenv != env)
41713 ripley 407
	errorcall(call, _("'UseMethod' used in an inappropriate fashion"));
16335 luke 408
    callenv = cptr->sysparent;
38132 ripley 409
    /* We need to find the generic to find out where it is defined.
410
       This is set up to avoid getting caught by things like
42110 maechler 411
 
45446 ripley 412
	mycoef <- function(x)
38132 ripley 413
       {
45446 ripley 414
	   mycoef <- function(x) stop("not this one")
415
	   UseMethod("mycoef")
38132 ripley 416
       }
38141 ripley 417
 
418
	The generic need not be a closure (Henrik Bengtsson writes
419
	UseMethod("$"), although only functions are documented.)
38132 ripley 420
    */
63223 ripley 421
    val = findVar1(installTrChar(STRING_ELT(generic, 0)),
40705 ripley 422
		   ENCLOS(env), FUNSXP, TRUE); /* That has evaluated promises */
38158 ripley 423
    if(TYPEOF(val) == CLOSXP) defenv = CLOENV(val);
424
    else defenv = R_BaseNamespace;
2 r 425
 
51265 ripley 426
    if (CADR(argList) != R_MissingArg)
427
	PROTECT(obj = eval(CADR(argList), env));
1839 ihaka 428
    else {
429
	cptr = R_GlobalContext;
430
	while (cptr != NULL) {
6188 rgentlem 431
	    if ( (cptr->callflag & CTXT_FUNCTION) && cptr->cloenv == env)
1839 ihaka 432
		break;
433
	    cptr = cptr->nextcontext;
2 r 434
	}
1839 ihaka 435
	if (cptr == NULL)
60844 ripley 436
	    errorcall(call, _("'UseMethod' called from outside a function"));
1839 ihaka 437
	PROTECT(obj = GetObject(cptr));
438
    }
526 maechler 439
 
24519 ripley 440
    if (TYPEOF(generic) != STRSXP ||
441
	LENGTH(generic) < 1 ||
40724 ripley 442
	CHAR(STRING_ELT(generic, 0))[0] == '\0')
32867 ripley 443
	errorcall(call, _("first argument must be a generic name"));
2 r 444
 
40705 ripley 445
    if (usemethod(translateChar(STRING_ELT(generic, 0)), obj, call, CDR(args),
16335 luke 446
		  env, callenv, defenv, &ans) == 1) {
51265 ripley 447
	UNPROTECT(3); /* obj, ap, argList */
2579 pd 448
	PROTECT(ans);
40236 ripley 449
	findcontext(CTXT_RETURN, env, ans); /* does not return */
1839 ihaka 450
    }
48717 ripley 451
    else {
452
	SEXP klass;
453
	int nclass;
454
	char cl[1000];
455
	PROTECT(klass = R_data_class2(obj));
456
	nclass = length(klass);
52431 maechler 457
	if (nclass == 1)
48717 ripley 458
	    strcpy(cl, translateChar(STRING_ELT(klass, 0)));
459
	else {
460
	    int i;
461
	    strcpy(cl, "c('");
462
	    for (i = 0; i < nclass; i++) {
463
		if (i > 0) strcat(cl, "', '");
464
		strcat(cl, translateChar(STRING_ELT(klass, i)));
465
	    }
466
	    strcat(cl, "')");
467
	}
468
	errorcall(call, _("no applicable method for '%s' applied to an object of class \"%s\""),
469
		  translateChar(STRING_ELT(generic, 0)), cl);
470
    }
51265 ripley 471
    /* Not reached */
472
    return R_NilValue;
2 r 473
}
474
 
2524 maechler 475
/*
2515 rgentlem 476
   fixcall: fixes up the call when arguments to the function may
477
   have changed; for now we only worry about tagged args, appending
478
   them if they are not already there
479
*/
480
 
481
static SEXP fixcall(SEXP call, SEXP args)
482
{
2524 maechler 483
    SEXP s, t;
2515 rgentlem 484
    int found;
485
 
38135 ripley 486
    for(t = args; t != R_NilValue; t = CDR(t)) {
487
	if(TAG(t) != R_NilValue) {
2515 rgentlem 488
		found = 0;
38135 ripley 489
		for(s = call; CDR(s) != R_NilValue; s = CDR(s))
490
		    if(TAG(CDR(s)) == TAG(t)) found = 1;
2515 rgentlem 491
		if( !found ) {
10172 luke 492
			SETCDR(s, allocList(1));
493
			SET_TAG(CDR(s), TAG(t));
494
			SETCAR(CDR(s), duplicate(CAR(t)));
2515 rgentlem 495
		}
496
	}
497
    }
2519 pd 498
    return call;
2515 rgentlem 499
}
500
 
1839 ihaka 501
/* If NextMethod has any arguments the first must be the generic */
502
/* the second the object and any remaining are matched with the */
503
/* formals of the chosen method. */
526 maechler 504
 
2 r 505
#define ARGUSED(x) LEVELS(x)
506
 
51245 ripley 507
/* This is a special .Internal */
36990 ripley 508
SEXP attribute_hidden do_nextmethod(SEXP call, SEXP op, SEXP args, SEXP env)
2 r 509
{
41784 ripley 510
    char buf[512], b[512], bb[512], tbuf[10];
511
    const char *sb, *sg, *sk;
39866 duncan 512
    SEXP ans, s, t, klass, method, matchedarg, generic, nextfun;
1839 ihaka 513
    SEXP sysp, m, formals, actuals, tmp, newcall;
6113 rgentlem 514
    SEXP a, group, basename;
16335 luke 515
    SEXP callenv, defenv;
1839 ihaka 516
    RCNTXT *cptr;
55061 ripley 517
    int i, j;
2 r 518
 
1839 ihaka 519
    cptr = R_GlobalContext;
520
    cptr->callflag = CTXT_GENERIC;
2 r 521
 
1839 ihaka 522
    /* get the env NextMethod was called from */
523
    sysp = R_GlobalContext->sysparent;
524
    while (cptr != NULL) {
38135 ripley 525
	if (cptr->callflag & CTXT_FUNCTION && cptr->cloenv == sysp) break;
1839 ihaka 526
	cptr = cptr->nextcontext;
21352 maechler 527
    }
1839 ihaka 528
    if (cptr == NULL)
33692 ripley 529
	error(_("'NextMethod' called from outside a function"));
2 r 530
 
1839 ihaka 531
    PROTECT(newcall = duplicate(cptr->call));
214 rgentlem 532
 
21349 tlumley 533
    /* eg get("print.ts")(1) */
534
    if (TYPEOF(CAR(cptr->call)) == LANGSXP)
33692 ripley 535
       error(_("'NextMethod' called from an anonymous function"));
21349 tlumley 536
 
23391 luke 537
    /* Find dispatching environments. Promises shouldn't occur, but
538
       check to be on the safe side.  If the variables are not in the
539
       environment (the method was called outside a method dispatch)
540
       then chose reasonable defaults. */
38132 ripley 541
    callenv = findVarInFrame3(R_GlobalContext->sysparent,
54029 luke 542
			      R_dot_GenericCallEnv, TRUE);
38132 ripley 543
    if (TYPEOF(callenv) == PROMSXP)
544
	callenv = eval(callenv, R_BaseEnv);
545
    else if (callenv == R_UnboundValue)
23391 luke 546
	    callenv = env;
38132 ripley 547
    defenv = findVarInFrame3(R_GlobalContext->sysparent,
54029 luke 548
			     R_dot_GenericDefEnv, TRUE);
38135 ripley 549
    if (TYPEOF(defenv) == PROMSXP) defenv = eval(defenv, R_BaseEnv);
550
    else if (defenv == R_UnboundValue) defenv = R_GlobalEnv;
23391 luke 551
 
1839 ihaka 552
    /* set up the arglist */
52883 maechler 553
    if (TYPEOF(CAR(cptr->call)) == CLOSXP)
554
	// e.g., in do.call(function(x) NextMethod('foo'),list())
555
	s = CAR(cptr->call);
556
    else
557
	s = R_LookupMethod(CAR(cptr->call), env, callenv, defenv);
42110 maechler 558
    if (TYPEOF(s) == SYMSXP && s == R_UnboundValue)
33297 ripley 559
	error(_("no calling generic was found: was a method called directly?"));
38134 ripley 560
    if (TYPEOF(s) != CLOSXP){ /* R_LookupMethod looked for a function */
42110 maechler 561
	errorcall(R_NilValue,
562
		  _("'function' is not a function, but of type %d"),
27412 ripley 563
		  TYPEOF(s));
21352 maechler 564
    }
1975 rgentlem 565
    /* get formals and actuals; attach the names of the formals to
566
       the actuals, expanding any ... that occurs */
1839 ihaka 567
    formals = FORMALS(s);
41613 ripley 568
    PROTECT(actuals = matchArgs(formals, cptr->promargs, call));
2 r 569
 
38135 ripley 570
    i = 0;
571
    for(s = formals, t = actuals; s != R_NilValue; s = CDR(s), t = CDR(t)) {
10172 luke 572
	SET_TAG(t, TAG(s));
38135 ripley 573
	if(TAG(t) == R_DotsSymbol) i = length(CAR(t));
1975 rgentlem 574
    }
575
    if(i) {   /* we need to expand out the dots */
2524 maechler 576
	PROTECT(t = allocList(i+length(actuals)-1));
38135 ripley 577
	for(s = actuals, m = t; s != R_NilValue; s = CDR(s)) {
2758 pd 578
	    if(TYPEOF(CAR(s)) == DOTSXP) {
42110 maechler 579
		for(i = 1, a = CAR(s); a != R_NilValue;
38135 ripley 580
		    a = CDR(a), i++, m = CDR(m)) {
62580 ripley 581
		    snprintf(tbuf, 10, "..%d", i);
10172 luke 582
		    SET_TAG(m, mkSYMSXP(mkChar(tbuf), R_UnboundValue));
583
		    SETCAR(m, CAR(a));
2524 maechler 584
		}
38135 ripley 585
	    } else {
10172 luke 586
		SET_TAG(m, TAG(s));
587
		SETCAR(m, CAR(s));
38134 ripley 588
		m = CDR(m);
2758 pd 589
	    }
21352 maechler 590
	}
2758 pd 591
	UNPROTECT(1);
38134 ripley 592
	actuals = t;
1975 rgentlem 593
    }
2758 pd 594
    PROTECT(actuals);
1975 rgentlem 595
 
2757 pd 596
 
1839 ihaka 597
    /* we can't duplicate because it would force the promises */
598
    /* so we do our own duplication of the promargs */
1975 rgentlem 599
 
1839 ihaka 600
    PROTECT(matchedarg = allocList(length(cptr->promargs)));
601
    for (t = matchedarg, s = cptr->promargs; t != R_NilValue;
38135 ripley 602
	 s = CDR(s), t = CDR(t)) {
21352 maechler 603
	SETCAR(t, CAR(s));
604
	SET_TAG(t, TAG(s));
1839 ihaka 605
    }
606
    for (t = matchedarg; t != R_NilValue; t = CDR(t)) {
1975 rgentlem 607
	for (m = actuals; m != R_NilValue; m = CDR(m))
608
	    if (CAR(m) == CAR(t))  {
1839 ihaka 609
		if (CAR(m) == R_MissingArg) {
17233 ripley 610
		    tmp = findVarInFrame3(cptr->cloenv, TAG(m), TRUE);
38135 ripley 611
		    if (tmp == R_MissingArg) break;
1839 ihaka 612
		}
10172 luke 613
		SETCAR(t, mkPROMISE(TAG(m), cptr->cloenv));
1839 ihaka 614
		break;
2524 maechler 615
	   }
1839 ihaka 616
    }
617
    /*
618
      Now see if there were any other arguments passed in
2515 rgentlem 619
      Currently we seem to only allow named args to change
620
      or to be added, this is at variance with p. 470 of the
621
      White Book
622
    */
2 r 623
 
1839 ihaka 624
    s = CADDR(args); /* this is ... and we need to see if it's bound */
625
    if (s == R_DotsSymbol) {
17233 ripley 626
	t = findVarInFrame3(env, s, TRUE);
1839 ihaka 627
	if (t != R_NilValue && t != R_MissingArg) {
10172 luke 628
	    SET_TYPEOF(t, LISTSXP); /* a safe mutation */
38135 ripley 629
	    s = matchmethargs(matchedarg, t);
1839 ihaka 630
	    UNPROTECT(1);
631
	    PROTECT(matchedarg = s);
2515 rgentlem 632
	    newcall = fixcall(newcall, matchedarg);
2 r 633
	}
1839 ihaka 634
    }
635
    else
41686 ripley 636
	error(_("wrong argument ..."));
2 r 637
 
2515 rgentlem 638
    /*
639
      .Class is used to determine the next method; if it doesn't
640
      exist the first argument to the current method is used
641
      the second argument to NextMethod is another option but
642
      isn't currently used).
643
    */
39866 duncan 644
    klass = findVarInFrame3(R_GlobalContext->sysparent,
54029 luke 645
			    R_dot_Class, TRUE);
2515 rgentlem 646
 
39866 duncan 647
    if (klass == R_UnboundValue) {
1839 ihaka 648
	s = GetObject(cptr);
41686 ripley 649
	if (!isObject(s)) error(_("object not specified"));
39866 duncan 650
	klass = getAttrib(s, R_ClassSymbol);
1839 ihaka 651
    }
2 r 652
 
6113 rgentlem 653
    /* the generic comes from either the sysparent or it's named */
21352 maechler 654
    generic = findVarInFrame3(R_GlobalContext->sysparent,
54029 luke 655
			      R_dot_Generic, TRUE);
6113 rgentlem 656
    if (generic == R_UnboundValue)
657
	generic = eval(CAR(args), env);
658
    if( generic == R_NilValue )
41686 ripley 659
	error(_("generic function not specified"));
1839 ihaka 660
    PROTECT(generic);
2 r 661
 
56153 ripley 662
    if (!isString(generic) || length(generic) != 1)
60844 ripley 663
	error(_("invalid generic argument to 'NextMethod'"));
21352 maechler 664
 
40724 ripley 665
    if (CHAR(STRING_ELT(generic, 0))[0] == '\0')
41686 ripley 666
	error(_("generic function not specified"));
2 r 667
 
6113 rgentlem 668
    /* determine whether we are in a Group dispatch */
669
 
38135 ripley 670
    group = findVarInFrame3(R_GlobalContext->sysparent,
54029 luke 671
			    R_dot_Group, TRUE);
38135 ripley 672
    if (group == R_UnboundValue) PROTECT(group = mkString(""));
673
    else PROTECT(group);
6113 rgentlem 674
 
56153 ripley 675
    if (!isString(group) || length(group) != 1)
60844 ripley 676
	error(_("invalid 'group' argument found in 'NextMethod'"));
2 r 677
 
6113 rgentlem 678
    /* determine the root: either the group or the generic will be it */
679
 
40724 ripley 680
    if (CHAR(STRING_ELT(group, 0))[0] == '\0') basename = generic;
38135 ripley 681
    else basename = group;
6113 rgentlem 682
 
683
    nextfun = R_NilValue;
684
 
42110 maechler 685
    /*
38135 ripley 686
       Find the method currently being invoked and jump over the current call
687
       If t is R_UnboundValue then we called the current method directly
688
    */
6113 rgentlem 689
 
38135 ripley 690
    method = findVarInFrame3(R_GlobalContext->sysparent,
54029 luke 691
			     R_dot_Method, TRUE);
6113 rgentlem 692
    if( method != R_UnboundValue) {
41784 ripley 693
	const char *ss;
21352 maechler 694
	if( !isString(method) )
33297 ripley 695
	    error(_("wrong value for .Method"));
38135 ripley 696
	for(i = 0; i < length(method); i++) {
40705 ripley 697
	    ss = translateChar(STRING_ELT(method, i));
698
	    if(strlen(ss) >= 512)
699
		error(_("method name too long in '%s'"), ss);
62580 ripley 700
	    snprintf(b, 512, "%s", ss);
40705 ripley 701
	    if(strlen(b)) break;
6113 rgentlem 702
	}
21352 maechler 703
	/* for binary operators check that the second argument's method
21282 tlumley 704
	   is the same or absent */
62580 ripley 705
	for(j = i; j < length(method); j++) {
41784 ripley 706
	    const char *ss = translateChar(STRING_ELT(method, j));
40705 ripley 707
	    if(strlen(ss) >= 512)
708
		error(_("method name too long in '%s'"), ss);
62580 ripley 709
	    snprintf(bb, 512, "%s", ss);
710
	    if (strlen(bb) && strcmp(b,bb))
711
		warning(_("Incompatible methods ignored"));
21282 tlumley 712
	}
6113 rgentlem 713
    }
714
    else {
25630 ripley 715
	if(strlen(CHAR(PRINTNAME(CAR(cptr->call)))) >= 512)
33297 ripley 716
	   error(_("call name too long in '%s'"),
62883 murdoch 717
		 EncodeChar(PRINTNAME(CAR(cptr->call))));
62580 ripley 718
	snprintf(b, 512, "%s", CHAR(PRINTNAME(CAR(cptr->call))));
6113 rgentlem 719
    }
42110 maechler 720
 
40705 ripley 721
    sb = translateChar(STRING_ELT(basename, 0));
39866 duncan 722
    for (j = 0; j < length(klass); j++) {
40705 ripley 723
	sk = translateChar(STRING_ELT(klass, j));
724
	if(strlen(sb) + strlen(sk) + 2 > 512)
725
	    error(_("class name too long in '%s'"), sb);
62580 ripley 726
	snprintf(buf, 512, "%s.%s", sb, sk);
38135 ripley 727
	if (!strcmp(buf, b)) break;
1839 ihaka 728
    }
2 r 729
 
38135 ripley 730
    if (!strcmp(buf, b)) /* we found a match and start from there */
6113 rgentlem 731
      j++;
732
    else
733
      j = 0;  /*no match so start with the first element of .Class */
734
 
21282 tlumley 735
    /* we need the value of i on exit from the for loop to figure out
736
	   how many classes to drop. */
42110 maechler 737
 
40705 ripley 738
    sg = translateChar(STRING_ELT(generic, 0));
39866 duncan 739
    for (i = j ; i < length(klass); i++) {
40705 ripley 740
	sk = translateChar(STRING_ELT(klass, i));
741
	if(strlen(sg) + strlen(sk) + 2 > 512)
742
	    error(_("class name too long in '%s'"), sg);
62580 ripley 743
	snprintf(buf, 512, "%s.%s", sg, sk);
16335 luke 744
	nextfun = R_LookupMethod(install(buf), env, callenv, defenv);
38135 ripley 745
	if (isFunction(nextfun)) break;
38134 ripley 746
	if (group != R_UnboundValue) {
21282 tlumley 747
	    /* if not Generic.foo, look for Group.foo */
40705 ripley 748
	    if(strlen(sb) + strlen(sk) + 2 > 512)
749
		error(_("class name too long in '%s'"), sb);
62580 ripley 750
	    snprintf(buf, 512, "%s.%s", sb, sk);
21352 maechler 751
	    nextfun = R_LookupMethod(install(buf), env, callenv, defenv);
752
	    if(isFunction(nextfun))
753
		break;
21282 tlumley 754
	}
1839 ihaka 755
	if (isFunction(nextfun))
756
	    break;
757
    }
758
    if (!isFunction(nextfun)) {
62580 ripley 759
	snprintf(buf, 512, "%s.default", sg);
16335 luke 760
	nextfun = R_LookupMethod(install(buf), env, callenv, defenv);
39508 ripley 761
	/* If there is no default method, try the generic itself,
762
	   provided it is primitive or a wrapper for a .Internal
763
	   function of the same name.
764
	 */
1839 ihaka 765
	if (!isFunction(nextfun)) {
40705 ripley 766
	    t = install(sg);
39508 ripley 767
	    nextfun = findVar(t, env);
768
	    if (TYPEOF(nextfun) == PROMSXP)
22881 luke 769
		nextfun = eval(nextfun, env);
1839 ihaka 770
	    if (!isFunction(nextfun))
33297 ripley 771
		error(_("no method to invoke"));
1839 ihaka 772
	    if (TYPEOF(nextfun) == CLOSXP) {
773
		if (INTERNAL(t) != R_NilValue)
774
		    nextfun = INTERNAL(t);
775
		else
33297 ripley 776
		    error(_("no method to invoke"));
1839 ihaka 777
	    }
2 r 778
	}
1839 ihaka 779
    }
39866 duncan 780
    PROTECT(s = allocVector(STRSXP, length(klass) - i));
781
    PROTECT(klass = duplicate(klass));
1839 ihaka 782
    PROTECT(m = allocSExp(ENVSXP));
783
    for (j = 0; j < length(s); j++)
39866 duncan 784
	SET_STRING_ELT(s, j, duplicate(STRING_ELT(klass, i++)));
785
    setAttrib(s, install("previous"), klass);
54029 luke 786
    defineVar(R_dot_Class, s, m);
39508 ripley 787
    /* It is possible that if a method was called directly that
38913 ripley 788
	'method' is unset */
789
    if (method != R_UnboundValue) {
45446 ripley 790
	/* for Ops we need `method' to be a vector */
38913 ripley 791
	PROTECT(method = duplicate(method));
792
	for(j = 0; j < length(method); j++) {
793
	    if (strlen(CHAR(STRING_ELT(method,j))))
794
		SET_STRING_ELT(method, j,  mkChar(buf));
45446 ripley 795
	}
38913 ripley 796
    } else
797
	PROTECT(method = mkString(buf));
54029 luke 798
    defineVar(R_dot_Method, method, m);
799
    defineVar(R_dot_GenericCallEnv, callenv, m);
800
    defineVar(R_dot_GenericDefEnv, defenv, m);
38132 ripley 801
 
1839 ihaka 802
    method = install(buf);
2 r 803
 
54029 luke 804
    defineVar(R_dot_Generic, generic, m);
2 r 805
 
54029 luke 806
    defineVar(R_dot_Group, group, m);
526 maechler 807
 
10172 luke 808
    SETCAR(newcall, method);
63147 pd 809
 
810
    /* applyMethod expects that the parent of the caller is the caller
811
       of the generic, so fixup by brute force. This should fix
812
       PR#15267 --pd */
813
    R_GlobalContext->sysparent = callenv;
814
 
1839 ihaka 815
    ans = applyMethod(newcall, nextfun, matchedarg, env, m);
6113 rgentlem 816
    UNPROTECT(10);
1839 ihaka 817
    return(ans);
2 r 818
}
819
 
51267 ripley 820
/* primitive */
36990 ripley 821
SEXP attribute_hidden do_unclass(SEXP call, SEXP op, SEXP args, SEXP env)
2 r 822
{
1839 ihaka 823
    checkArity(op, args);
51267 ripley 824
    check1arg(args, call, "x");
825
 
32014 ripley 826
    switch(TYPEOF(CAR(args))) {
827
    case ENVSXP:
41713 ripley 828
	errorcall(call, _("cannot unclass an environment"));
32014 ripley 829
	break;
830
    case EXTPTRSXP:
41713 ripley 831
	errorcall(call, _("cannot unclass an external pointer"));
32014 ripley 832
	break;
833
    default:
834
	break;
835
    }
1839 ihaka 836
    if (isObject(CAR(args))) {
10172 luke 837
	SETCAR(args, duplicate(CAR(args)));
1839 ihaka 838
	setAttrib(CAR(args), R_ClassSymbol, R_NilValue);
839
    }
840
    return CAR(args);
2 r 841
}
842
 
46128 jmc 843
 
52431 maechler 844
 
845
/* NOTE: Fast  inherits(x, what)    in ../include/Rinlinedfuns.h
846
 * ----        ----------------- */
847
/** C API for  R  inherits(x, what, which)
848
 *
849
 * @param x any R object
850
 * @param what character vector
851
 * @param which logical: "want vector result" ?
852
 *
853
 * @return if which is false, logical TRUE or FALSE
854
 *	   if which is true, integer vector of length(what) ..
855
 */
61765 ripley 856
static SEXP inherits3(SEXP x, SEXP what, SEXP which)
9608 rgentlem 857
{
63181 ripley 858
    const void *vmax = vmaxget();
52431 maechler 859
    SEXP klass, rval = R_NilValue /* -Wall */;
63181 ripley 860
 
46128 jmc 861
    if(IS_S4_OBJECT(x))
52266 jmc 862
	PROTECT(klass = R_data_class2(x));
48409 jmc 863
    else
52266 jmc 864
	PROTECT(klass = R_data_class(x, FALSE));
52431 maechler 865
    int nclass = length(klass);
9608 rgentlem 866
 
38135 ripley 867
    if(!isString(what))
41686 ripley 868
	error(_("'what' must be a character vector"));
52431 maechler 869
    int j, nwhat = length(what);
9608 rgentlem 870
 
871
    if( !isLogical(which) || (length(which) != 1) )
41686 ripley 872
	error(_("'which' must be a length 1 logical vector"));
52431 maechler 873
    int isvec = asLogical(which);
9608 rgentlem 874
 
42110 maechler 875
#ifdef _be_too_picky_
876
    if(IS_S4_OBJECT(x) && nwhat == 1 && !isvec &&
877
       !isNull(R_getClassDef(translateChar(STRING_ELT(what, 0)))))
878
	warning(_("use 'is()' instead of 'inherits()' on S4 objects"));
879
#endif
880
 
38135 ripley 881
    if(isvec)
50715 murdoch 882
	PROTECT(rval = allocVector(INTSXP, nwhat));
9608 rgentlem 883
 
38135 ripley 884
    for(j = 0; j < nwhat; j++) {
52431 maechler 885
	const char *ss = translateChar(STRING_ELT(what, j)); int i;
886
	if(isvec)
887
	    INTEGER(rval)[j] = 0;
38135 ripley 888
	for(i = 0; i < nclass; i++) {
40705 ripley 889
	    if(!strcmp(translateChar(STRING_ELT(klass, i)), ss)) {
21352 maechler 890
		if(isvec)
52431 maechler 891
		    INTEGER(rval)[j] = i+1;
50715 murdoch 892
		else {
893
		    UNPROTECT(1);
9608 rgentlem 894
		    return mkTrue();
50715 murdoch 895
		}
9608 rgentlem 896
		break;
897
	    }
898
	}
899
    }
63181 ripley 900
    vmaxset(vmax);
50715 murdoch 901
    if(!isvec) {
902
    	UNPROTECT(1);
9608 rgentlem 903
	return mkFalse();
50715 murdoch 904
    }
905
    UNPROTECT(2);
9608 rgentlem 906
    return rval;
907
}
15890 jmc 908
 
52431 maechler 909
SEXP attribute_hidden do_inherits(SEXP call, SEXP op, SEXP args, SEXP env)
910
{
911
    checkArity(op, args);
21352 maechler 912
 
52431 maechler 913
    return inherits3(/* x = */ CAR(args),
914
		     /* what = */ CADR(args),
915
		     /* which = */ CADDR(args));
916
}
917
 
918
 
54492 maechler 919
/**
920
 * Return the 0-based index of an is() match in a vector of class-name
921
 * strings terminated by an empty string.  Returns -1 for no match.
922
 *
923
 * @param x  an R object, about which we want is(x, .) information.
924
 * @param valid vector of possible matches terminated by an empty string.
925
 * @param rho  the environment in which the class definitions exist.
926
 *
927
 * @return index of match or -1 for no match
928
 */
929
int R_check_class_and_super(SEXP x, const char **valid, SEXP rho)
930
{
931
    int ans;
932
    SEXP cl = getAttrib(x, R_ClassSymbol);
933
    const char *class = CHAR(asChar(cl));
934
    for (ans = 0; ; ans++) {
935
	if (!strlen(valid[ans])) // empty string
936
	    break;
937
	if (!strcmp(class, valid[ans])) return ans;
938
    }
939
    /* if not found directly, now search the non-virtual super classes :*/
940
    if(IS_S4_OBJECT(x)) {
57849 maechler 941
	/* now try the superclasses, i.e.,  try   is(x, "....");  superCl :=
942
	   .selectSuperClasses(getClass("....")@contains, dropVirtual=TRUE)  */
54492 maechler 943
	SEXP classExts, superCl, _call;
944
	static SEXP s_contains = NULL, s_selectSuperCl = NULL;
945
	int i;
946
	if(!s_contains) {
947
	    s_contains      = install("contains");
948
	    s_selectSuperCl = install(".selectSuperClasses");
949
	}
950
 
951
	PROTECT(classExts = R_do_slot(R_getClassDef(class), s_contains));
952
	PROTECT(_call = lang3(s_selectSuperCl, classExts,
953
			      /* dropVirtual = */ ScalarLogical(1)));
954
	superCl = eval(_call, rho);
955
	UNPROTECT(2);
956
	PROTECT(superCl);
957
	for(i=0; i < length(superCl); i++) {
958
	    const char *s_class = CHAR(STRING_ELT(superCl, i));
959
	    for (ans = 0; ; ans++) {
960
		if (!strlen(valid[ans]))
961
		    break;
962
		if (!strcmp(s_class, valid[ans])) {
963
		    UNPROTECT(1);
964
		    return ans;
965
		}
966
	    }
967
	}
968
	UNPROTECT(1);
969
    }
970
    return -1;
971
}
972
 
57849 maechler 973
 
974
/**
975
 * Return the 0-based index of an is() match in a vector of class-name
976
 * strings terminated by an empty string.  Returns -1 for no match.
977
 * Strives to find the correct environment() for is(), using .classEnv()
978
 * (from \pkg{methods}).
979
 *
980
 * @param x  an R object, about which we want is(x, .) information.
981
 * @param valid vector of possible matches terminated by an empty string.
982
 *
983
 * @return index of match or -1 for no match
984
 */
985
int R_check_class_etc(SEXP x, const char **valid)
986
{
987
    static SEXP meth_classEnv = NULL;
988
    SEXP cl = getAttrib(x, R_ClassSymbol), rho = R_GlobalEnv, pkg;
989
    if(!meth_classEnv)
990
	meth_classEnv = install(".classEnv");
991
 
992
    pkg = getAttrib(cl, R_PackageSymbol); /* ==R== packageSlot(class(x)) */
993
    if(!isNull(pkg)) { /* find  rho := correct class Environment */
994
	SEXP clEnvCall;
995
	// FIXME: fails if 'methods' is not attached.
996
	PROTECT(clEnvCall = lang2(meth_classEnv, cl));
997
	rho = eval(clEnvCall, R_GlobalEnv);
998
	UNPROTECT(1);
999
	if(!isEnvironment(rho))
1000
	    error(_("could not find correct environment; please report!"));
1001
    }
1002
    return R_check_class_and_super(x, valid, rho);
1003
}
1004
 
38135 ripley 1005
/*
1006
   ==============================================================
1007
 
42110 maechler 1008
     code from here on down is support for the methods package
38135 ripley 1009
 
1010
   ==============================================================
1011
*/
1012
 
15890 jmc 1013
/* standardGeneric:  uses a pointer to R_standardGeneric, to be
1014
   initialized when the methods package is attached.  When and if the
1015
   methods code is automatically included, the pointer will not be
21352 maechler 1016
   needed
15912 ripley 1017
 
15890 jmc 1018
*/
15938 jmc 1019
static R_stdGen_ptr_t R_standardGeneric_ptr = 0;
21102 jmc 1020
static SEXP dispatchNonGeneric(SEXP name, SEXP env, SEXP fdef);
1021
#define NOT_METHODS_DISPATCH_PTR(ptr) (ptr == 0 || ptr == dispatchNonGeneric)
15890 jmc 1022
 
61776 ripley 1023
static
44195 ripley 1024
R_stdGen_ptr_t R_get_standardGeneric_ptr(void)
16747 ripley 1025
{
1026
    return R_standardGeneric_ptr;
15938 jmc 1027
}
1028
 
26082 jmc 1029
R_stdGen_ptr_t R_set_standardGeneric_ptr(R_stdGen_ptr_t val, SEXP envir)
16747 ripley 1030
{
1031
    R_stdGen_ptr_t old = R_standardGeneric_ptr;
1032
    R_standardGeneric_ptr = val;
26082 jmc 1033
    if(envir && !isNull(envir))
1034
	R_MethodsNamespace = envir;
1035
    /* just in case ... */
1036
    if(!R_MethodsNamespace)
1037
	R_MethodsNamespace = R_GlobalEnv;
16747 ripley 1038
    return old;
15938 jmc 1039
}
1040
 
61771 ripley 1041
static SEXP R_isMethodsDispatchOn(SEXP onOff) {
21102 jmc 1042
    SEXP value = allocVector(LGLSXP, 1);
1043
    Rboolean onOffValue;
1044
    R_stdGen_ptr_t old = R_get_standardGeneric_ptr();
1045
    LOGICAL(value)[0] = !NOT_METHODS_DISPATCH_PTR(old);
23073 ripley 1046
    if(length(onOff) > 0) {
60395 ripley 1047
	onOffValue = asLogical(onOff);
1048
	if(onOffValue == NA_INTEGER)
1049
	    error(_("'onOff' must be TRUE or FALSE"));
1050
	else if(onOffValue == FALSE)
1051
	    R_set_standardGeneric_ptr(0, 0);
1052
	else if(NOT_METHODS_DISPATCH_PTR(old)) {
1053
	    SEXP call;
1054
	    PROTECT(call = allocList(2));
1055
	    SETCAR(call, install("initMethodsDispatch"));
1056
	    eval(call, R_GlobalEnv); /* only works with
1057
					methods	 attached */
1058
	    UNPROTECT(1);
1059
	}
21102 jmc 1060
    }
1061
    return value;
1062
}
1063
 
60395 ripley 1064
/* simpler version for internal use, in attrib.c and print.c */
37088 ripley 1065
attribute_hidden
23073 ripley 1066
Rboolean isMethodsDispatchOn(void)
1067
{
1068
    return !NOT_METHODS_DISPATCH_PTR(R_standardGeneric_ptr);
1069
}
1070
 
1071
 
60395 ripley 1072
attribute_hidden
1073
SEXP do_S4on(SEXP call, SEXP op, SEXP args, SEXP env)
1074
{
1075
    if(length(args) == 0) return ScalarLogical(isMethodsDispatchOn());
1076
    return R_isMethodsDispatchOn(CAR(args));
1077
}
1078
 
1079
 
21352 maechler 1080
static SEXP dispatchNonGeneric(SEXP name, SEXP env, SEXP fdef)
16747 ripley 1081
{
1082
    /* dispatch the non-generic definition of `name'.  Used to trap
1083
       calls to standardGeneric during the loading of the methods package */
54029 luke 1084
    SEXP e, value, rho, fun, symbol;
16747 ripley 1085
    RCNTXT *cptr;
63181 ripley 1086
 
16747 ripley 1087
    /* find a non-generic function */
63223 ripley 1088
    symbol = installTrChar(asChar(name));
36174 murdoch 1089
    for(rho = ENCLOS(env); rho != R_EmptyEnv;
16747 ripley 1090
	rho = ENCLOS(rho)) {
17233 ripley 1091
	fun = findVarInFrame3(rho, symbol, TRUE);
16747 ripley 1092
	if(fun == R_UnboundValue) continue;
1093
	switch(TYPEOF(fun)) {
1094
	case CLOSXP:
54029 luke 1095
	    value = findVarInFrame3(CLOENV(fun), R_dot_Generic, TRUE);
16747 ripley 1096
	    if(value == R_UnboundValue) break;
31908 ripley 1097
	case BUILTINSXP:  case SPECIALSXP:
1098
	default:
1099
	    /* in all other cases, go on to the parent environment */
1100
	    break;
16747 ripley 1101
	}
1102
	fun = R_UnboundValue;
16372 jmc 1103
    }
16747 ripley 1104
    fun = SYMVALUE(symbol);
1105
    if(fun == R_UnboundValue)
33297 ripley 1106
	error(_("unable to find a non-generic version of function \"%s\""),
40705 ripley 1107
	      translateChar(asChar(name)));
16747 ripley 1108
    cptr = R_GlobalContext;
1109
    /* check this is the right context */
16372 jmc 1110
    while (cptr != R_ToplevelContext) {
1111
	if (cptr->callflag & CTXT_FUNCTION )
1112
	    if (cptr->cloenv == env)
1113
		break;
1114
	cptr = cptr->nextcontext;
1115
    }
21352 maechler 1116
 
16747 ripley 1117
    PROTECT(e = duplicate(R_syscall(0, cptr)));
1118
    SETCAR(e, fun);
1119
    /* evaluate a call the non-generic with the same arguments and from
1120
       the same environment as the call to the generic version */
1121
    value = eval(e, cptr->sysparent);
1122
    UNPROTECT(1);
1123
    return value;
16372 jmc 1124
}
1125
 
20089 jmc 1126
 
1127
static SEXP get_this_generic(SEXP args);
1128
 
36990 ripley 1129
SEXP attribute_hidden do_standardGeneric(SEXP call, SEXP op, SEXP args, SEXP env)
15890 jmc 1130
{
20089 jmc 1131
    SEXP arg, value, fdef; R_stdGen_ptr_t ptr = R_get_standardGeneric_ptr();
51267 ripley 1132
 
1133
    checkArity(op, args);
1134
    check1arg(args, call, "f");
1135
 
16747 ripley 1136
    if(!ptr) {
42110 maechler 1137
	warningcall(call,
60844 ripley 1138
		    _("'standardGeneric' called without 'methods' dispatch enabled (will be ignored)"));
26082 jmc 1139
	R_set_standardGeneric_ptr(dispatchNonGeneric, NULL);
16747 ripley 1140
	ptr = R_get_standardGeneric_ptr();
1141
    }
42110 maechler 1142
 
42675 ripley 1143
    checkArity(op, args); /* set to -1 */
41270 ripley 1144
    arg = CAR(args);
22291 jmc 1145
    if(!isValidStringF(arg))
42675 ripley 1146
	errorcall(call,
60844 ripley 1147
		  _("argument to 'standardGeneric' must be a non-empty character string"));
22291 jmc 1148
 
20089 jmc 1149
    PROTECT(fdef = get_this_generic(args));
15890 jmc 1150
 
22291 jmc 1151
    if(isNull(fdef))
42675 ripley 1152
	error(_("call to standardGeneric(\"%s\") apparently not from the body of that generic function"), translateChar(STRING_ELT(arg, 0)));
22291 jmc 1153
 
20089 jmc 1154
    value = (*ptr)(arg, env, fdef);
21352 maechler 1155
 
41270 ripley 1156
    UNPROTECT(1);
16747 ripley 1157
    return value;
15890 jmc 1158
}
1159
 
16707 jmc 1160
static int maxMethodsOffset = 0, curMaxOffset;
50609 jmc 1161
static Rboolean allowPrimitiveMethods = TRUE;
16707 jmc 1162
typedef enum {NO_METHODS, NEEDS_RESET, HAS_METHODS, SUPPRESSED} prim_methods_t;
1163
 
1164
static prim_methods_t *prim_methods;
1165
static SEXP *prim_generics;
1166
static SEXP *prim_mlist;
1167
#define DEFAULT_N_PRIM_METHODS 100
1168
 
41111 ripley 1169
/* This is used in the methods package, in src/methods_list_dispatch.c */
16707 jmc 1170
SEXP R_set_prim_method(SEXP fname, SEXP op, SEXP code_vec, SEXP fundef,
1171
		       SEXP mlist)
1172
{
41784 ripley 1173
    const char *code_string;
63181 ripley 1174
    const void *vmax = vmaxget();
16747 ripley 1175
    if(!isValidString(code_vec))
33297 ripley 1176
	error(_("argument 'code' must be a character string"));
40705 ripley 1177
    code_string = translateChar(asChar(code_vec));
50609 jmc 1178
    /* with a NULL op, turns all primitive matching off or on (used to avoid possible infinite
1179
     recursion in methods computations*/
1180
    if(op == R_NilValue) {
1181
	SEXP value;
1182
	value = allowPrimitiveMethods ? mkTrue() : mkFalse();
1183
	switch(code_string[0]) {
1184
	case 'c': case 'C':/* clear */
1185
	    allowPrimitiveMethods = FALSE; break;
1186
	case 's': case 'S': /* set */
1187
	    allowPrimitiveMethods = TRUE; break;
1188
	default: /* just report the current state */
1189
	    break;
1190
	}
1191
	return value;
1192
    }
16747 ripley 1193
    do_set_prim_method(op, code_string, fundef, mlist);
63181 ripley 1194
    vmaxset(vmax);
1195
    return fname;
16707 jmc 1196
}
1197
 
20089 jmc 1198
SEXP R_primitive_methods(SEXP op)
1199
{
1200
    int offset = PRIMOFFSET(op);
24661 ripley 1201
    if(offset < 0 || offset > curMaxOffset)
21352 maechler 1202
	return R_NilValue;
20089 jmc 1203
    else {
21352 maechler 1204
	SEXP value = prim_mlist[offset];
20089 jmc 1205
	return value ? value : R_NilValue;
1206
    }
1207
}
1208
 
39016 jmc 1209
SEXP R_primitive_generic(SEXP op)
1210
{
1211
    int offset = PRIMOFFSET(op);
1212
    if(offset < 0 || offset > curMaxOffset)
1213
	return R_NilValue;
1214
    else {
1215
	SEXP value = prim_generics[offset];
1216
	return value ? value : R_NilValue;
1217
    }
1218
}
1219
 
41111 ripley 1220
/* This is used in the methods package, in src/methods_list_dispatch.c */
41784 ripley 1221
SEXP do_set_prim_method(SEXP op, const char *code_string, SEXP fundef,
1222
			SEXP mlist)
16707 jmc 1223
{
18397 ripley 1224
    int offset = 0;
1225
    prim_methods_t code = NO_METHODS; /* -Wall */
1226
    SEXP value;
1227
    Rboolean errorcase = FALSE;
1228
    switch(code_string[0]) {
1229
    case 'c': /* clear */
1230
	code = NO_METHODS; break;
1231
    case 'r': /* reset */
1232
	code = NEEDS_RESET; break;
20089 jmc 1233
    case 's': /* set or suppress */
18397 ripley 1234
	switch(code_string[1]) {
1235
	case 'e': code = HAS_METHODS; break;
1236
	case 'u': code = SUPPRESSED; break;
1237
	default: errorcase = TRUE;
1238
	}
1239
	break;
1240
    default:
1241
	errorcase = TRUE;
16707 jmc 1242
    }
18397 ripley 1243
    if(errorcase) {
33297 ripley 1244
	error(_("invalid primitive methods code (\"%s\"): should be \"clear\", \"reset\", \"set\", or \"suppress\""), code_string);
18397 ripley 1245
	return R_NilValue;
1246
    }
1247
    switch(TYPEOF(op)) {
1248
    case BUILTINSXP: case SPECIALSXP:
1249
	offset = PRIMOFFSET(op);
1250
	break;
21352 maechler 1251
    default:
33297 ripley 1252
	error(_("invalid object: must be a primitive function"));
18397 ripley 1253
    }
1254
    if(offset >= maxMethodsOffset) {
1255
	int n;
24205 ripley 1256
	n = offset + 1;
18397 ripley 1257
	if(n < DEFAULT_N_PRIM_METHODS)
1258
	    n = DEFAULT_N_PRIM_METHODS;
1259
	if(n < 2*maxMethodsOffset)
1260
	    n = 2 * maxMethodsOffset;
1261
	if(prim_methods) {
19214 pd 1262
	    int i;
19197 pd 1263
 
19214 pd 1264
	    prim_methods  = Realloc(prim_methods,  n, prim_methods_t);
1265
	    prim_generics = Realloc(prim_generics, n, SEXP);
21352 maechler 1266
	    prim_mlist	  = Realloc(prim_mlist,	   n, SEXP);
19214 pd 1267
 
1268
	    /* Realloc does not clear the added memory, hence: */
1269
	    for (i = maxMethodsOffset ; i < n ; i++) {
21352 maechler 1270
		prim_methods[i]	 = NO_METHODS;
19214 pd 1271
		prim_generics[i] = NULL;
21352 maechler 1272
		prim_mlist[i]	 = NULL;
19214 pd 1273
	    }
18397 ripley 1274
	}
1275
	else {
19214 pd 1276
	    prim_methods  = Calloc(n, prim_methods_t);
18397 ripley 1277
	    prim_generics = Calloc(n, SEXP);
21352 maechler 1278
	    prim_mlist	  = Calloc(n, SEXP);
18397 ripley 1279
	}
1280
	maxMethodsOffset = n;
1281
    }
1282
    if(offset > curMaxOffset)
1283
	curMaxOffset = offset;
1284
    prim_methods[offset] = code;
1285
    /* store a preserved pointer to the generic function if there is not
1286
       one there currently.  Unpreserve it if no more methods, but don't
1287
       replace it otherwise:  the generic definition is not allowed to
1288
       change while it's still defined! (the stored methods list can,
1289
       however) */
1290
    value = prim_generics[offset];
20089 jmc 1291
    if(code == SUPPRESSED) {} /* leave the structure alone */
1292
    else if(code == NO_METHODS && prim_generics[offset]) {
18397 ripley 1293
	R_ReleaseObject(prim_generics[offset]);
1294
	prim_generics[offset] = 0;
1295
	prim_mlist[offset] = 0;
1296
    }
1297
    else if(fundef && !isNull(fundef) && !prim_generics[offset]) {
1298
	if(TYPEOF(fundef) != CLOSXP)
33297 ripley 1299
	    error(_("the formal definition of a primitive generic must be a function object (got type '%s')"),
37720 ripley 1300
		  type2char(TYPEOF(fundef)));
18397 ripley 1301
	R_PreserveObject(fundef);
1302
	prim_generics[offset] = fundef;
1303
    }
41111 ripley 1304
    if(code == HAS_METHODS) {
20089 jmc 1305
	if(!mlist  || isNull(mlist)) {
41111 ripley 1306
	    /* turning methods back on after a SUPPRESSED */
1307
	} else {
1308
	    if(prim_mlist[offset])
1309
		R_ReleaseObject(prim_mlist[offset]);
1310
	    R_PreserveObject(mlist);
1311
	    prim_mlist[offset] = mlist;
20089 jmc 1312
	}
18397 ripley 1313
    }
1314
    return value;
16707 jmc 1315
}
1316
 
17092 jmc 1317
static SEXP get_primitive_methods(SEXP op, SEXP rho)
1318
{
50609 jmc 1319
    SEXP f, e, val;
17092 jmc 1320
    int nprotect = 0;
1321
    f = PROTECT(allocVector(STRSXP, 1));  nprotect++;
1322
    SET_STRING_ELT(f, 0, mkChar(PRIMNAME(op)));
1323
    PROTECT(e = allocVector(LANGSXP, 2)); nprotect++;
50609 jmc 1324
    SETCAR(e, install("getGeneric"));
1325
    val = CDR(e); SETCAR(val, f);
1326
    val = eval(e, rho);
1327
    /* a rough sanity check that this looks like a generic function */
1328
    if(TYPEOF(val) != CLOSXP || !IS_S4_OBJECT(val))
60844 ripley 1329
	error(_("object returned as generic function \"%s\" does not appear to be one"), PRIMNAME(op));
17092 jmc 1330
    UNPROTECT(nprotect);
50609 jmc 1331
    return CLOENV(val);
17092 jmc 1332
}
20089 jmc 1333
 
50609 jmc 1334
 
20089 jmc 1335
/* get the generic function, defined to be the function definition for
1336
the call to standardGeneric(), or for primitives, passed as the second
1337
argument to standardGeneric.
1338
*/
1339
static SEXP get_this_generic(SEXP args)
1340
{
63176 luke 1341
    const void *vmax = vmaxget();
22450 ripley 1342
    SEXP value = R_NilValue; static SEXP gen_name;
20994 jmc 1343
    int i, n;
41784 ripley 1344
    RCNTXT *cptr;
1345
    const char *fname;
20277 ripley 1346
 
20089 jmc 1347
    /* a second argument to the call, if any, is taken as the function */
1348
    if(CDR(args) != R_NilValue)
20277 ripley 1349
	return CAR(CDR(args));
20994 jmc 1350
    /* else use sys.function (this is fairly expensive-- would be good
1351
     * to force a second argument if possible) */
20154 jmc 1352
    PROTECT(args);
20994 jmc 1353
    if(!gen_name)
1354
	gen_name = install("generic");
20089 jmc 1355
    cptr = R_GlobalContext;
40705 ripley 1356
    fname = translateChar(asChar(CAR(args)));
20994 jmc 1357
    n = framedepth(cptr);
1358
    /* check for a matching "generic" slot */
1359
    for(i=0;  i<n; i++) {
22379 ripley 1360
	SEXP rval = R_sysfunction(i, cptr);
20994 jmc 1361
	if(isObject(rval)) {
1362
	    SEXP generic = getAttrib(rval, gen_name);
1363
	    if(TYPEOF(generic) == STRSXP &&
40705 ripley 1364
	       !strcmp(translateChar(asChar(generic)), fname)) {
22291 jmc 1365
	      value = rval;
1366
	      break;
1367
	    }
20994 jmc 1368
	}
20154 jmc 1369
    }
1370
    UNPROTECT(1);
63176 luke 1371
    vmaxset(vmax);
63181 ripley 1372
 
1373
    return value;
20089 jmc 1374
}
17092 jmc 1375
 
21352 maechler 1376
/* Could there be methods for this op?	Checks
16707 jmc 1377
   only whether methods are currently being dispatched and, if so,
1378
   whether methods are currently defined for this op. */
61771 ripley 1379
attribute_hidden
17000 jmc 1380
Rboolean R_has_methods(SEXP op)
16707 jmc 1381
{
16747 ripley 1382
    R_stdGen_ptr_t ptr = R_get_standardGeneric_ptr(); int offset;
21102 jmc 1383
    if(NOT_METHODS_DISPATCH_PTR(ptr))
17000 jmc 1384
	return(FALSE);
22764 jmc 1385
    if(!op || TYPEOF(op) == CLOSXP) /* except for primitives, just test for the package */
17000 jmc 1386
	return(TRUE);
50609 jmc 1387
    if(!allowPrimitiveMethods) /* all primitives turned off by a call to R_set_prim */
1388
	return FALSE;
16747 ripley 1389
    offset = PRIMOFFSET(op);
1390
    if(offset > curMaxOffset || prim_methods[offset] == NO_METHODS
1391
       || prim_methods[offset] == SUPPRESSED)
17000 jmc 1392
	return(FALSE);
1393
    return(TRUE);
16707 jmc 1394
}
1395
 
1396
static SEXP deferred_default_object;
1397
 
1398
SEXP R_deferred_default_method()
1399
{
16747 ripley 1400
    if(!deferred_default_object)
1401
	deferred_default_object = install("__Deferred_Default_Marker__");
1402
    return(deferred_default_object);
16707 jmc 1403
}
1404
 
1405
 
1406
static R_stdGen_ptr_t quick_method_check_ptr = NULL;
1407
void R_set_quick_method_check(R_stdGen_ptr_t value)
1408
{
16747 ripley 1409
    quick_method_check_ptr = value;
16707 jmc 1410
}
23073 ripley 1411
 
16707 jmc 1412
/* try to dispatch the formal method for this primitive op, by calling
21352 maechler 1413
   the stored generic function corresponding to the op.	 Requires that
16707 jmc 1414
   the methods be set up to return a special object rather than trying
1415
   to evaluate the default (which would get us into a loop). */
42292 ripley 1416
 
1417
/* called from DispatchOrEval, DispatchGroup, do_matprod
1418
   When called from the first the arguments have been enclosed in
1419
   promises, but not from the other two: there all the arguments have
1420
   already been evaluated.
1421
 */
38705 ripley 1422
SEXP attribute_hidden
45446 ripley 1423
R_possible_dispatch(SEXP call, SEXP op, SEXP args, SEXP rho,
42292 ripley 1424
		    Rboolean promisedArgs)
16707 jmc 1425
{
42292 ripley 1426
    SEXP fundef, value, mlist=R_NilValue, s, a, b;
42110 maechler 1427
    int offset;
27710 ripley 1428
    prim_methods_t current;
23073 ripley 1429
    offset = PRIMOFFSET(op);
1430
    if(offset < 0 || offset > curMaxOffset)
33297 ripley 1431
	error(_("invalid primitive operation given for dispatch"));
23073 ripley 1432
    current = prim_methods[offset];
1433
    if(current == NO_METHODS || current == SUPPRESSED)
1434
	return(NULL);
1435
    /* check that the methods for this function have been set */
1436
    if(current == NEEDS_RESET) {
1437
	/* get the methods and store them in the in-core primitive
1438
	   method table.	The entries will be preserved via
1439
	   R_preserveobject, so later we can just grab mlist from
1440
	   prim_mlist */
26648 ripley 1441
	do_set_prim_method(op, "suppressed", R_NilValue, mlist);
23073 ripley 1442
	PROTECT(mlist = get_primitive_methods(op, rho));
1443
	do_set_prim_method(op, "set", R_NilValue, mlist);
26016 jmc 1444
	current = prim_methods[offset]; /* as revised by do_set_prim_method */
23073 ripley 1445
	UNPROTECT(1);
1446
    }
1447
    mlist = prim_mlist[offset];
1448
    if(mlist && !isNull(mlist)
1449
       && quick_method_check_ptr) {
1450
	value = (*quick_method_check_ptr)(args, mlist, op);
1451
	if(isPrimitive(value))
1452
	    return(NULL);
42292 ripley 1453
	if(isFunction(value)) {
1454
	    /* found a method, call it with promised args */
1455
	    if(!promisedArgs) {
1456
		PROTECT(s = promiseArgs(CDR(call), rho));
1457
		if (length(s) != length(args)) error(_("dispatch error"));
1458
		for (a = args, b = s; a != R_NilValue; a = CDR(a), b = CDR(b))
1459
		    SET_PRVALUE(CAR(b), CAR(a));
1460
		value =  applyClosure(call, value, s, rho, R_BaseEnv);
1461
		UNPROTECT(1);
1462
		return value;
1463
	    } else
1464
		return applyClosure(call, value, args, rho, R_BaseEnv);
1465
	}
23073 ripley 1466
	/* else, need to perform full method search */
1467
    }
1468
    fundef = prim_generics[offset];
1469
    if(!fundef || TYPEOF(fundef) != CLOSXP)
33387 ripley 1470
	error(_("primitive function \"%s\" has been set for methods but no generic function supplied"),
23073 ripley 1471
	      PRIMNAME(op));
1472
    /* To do:  arrange for the setting to be restored in case of an
45446 ripley 1473
       error in method search */
42292 ripley 1474
    if(!promisedArgs) {
1475
	PROTECT(s = promiseArgs(CDR(call), rho));
1476
	if (length(s) != length(args)) error(_("dispatch error"));
1477
	for (a = args, b = s; a != R_NilValue; a = CDR(a), b = CDR(b))
1478
	    SET_PRVALUE(CAR(b), CAR(a));
1479
	value = applyClosure(call, fundef, s, rho, R_BaseEnv);
1480
	UNPROTECT(1);
1481
    } else
1482
	value = applyClosure(call, fundef, args, rho, R_BaseEnv);
23073 ripley 1483
    prim_methods[offset] = current;
1484
    if(value == deferred_default_object)
1485
	return NULL;
1486
    else
1487
	return value;
16707 jmc 1488
}
21853 jmc 1489
 
41771 ripley 1490
SEXP R_do_MAKE_CLASS(const char *what)
21853 jmc 1491
{
1492
    static SEXP s_getClass = NULL;
1493
    SEXP e, call;
1494
    if(!what)
32867 ripley 1495
	error(_("C level MAKE_CLASS macro called with NULL string pointer"));
48346 maechler 1496
    if(!s_getClass) s_getClass = install("getClass");
21853 jmc 1497
    PROTECT(call = allocVector(LANGSXP, 2));
1498
    SETCAR(call, s_getClass);
1499
    SETCAR(CDR(call), mkString(what));
1500
    e = eval(call, R_GlobalEnv);
1501
    UNPROTECT(1);
1502
    return(e);
1503
}
1504
 
42110 maechler 1505
/* this very similar, but gives NULL instead of an error for a non-existing class */
1506
SEXP R_getClassDef(const char *what)
1507
{
1508
    static SEXP s_getClassDef = NULL;
1509
    SEXP e, call;
1510
    if(!what)
1511
	error(_("R_getClassDef(.) called with NULL string pointer"));
48346 maechler 1512
    if(!s_getClassDef) s_getClassDef = install("getClassDef");
42110 maechler 1513
    PROTECT(call = allocVector(LANGSXP, 2));
1514
    SETCAR(call, s_getClassDef);
1515
    SETCAR(CDR(call), mkString(what));
1516
    e = eval(call, R_GlobalEnv);
1517
    UNPROTECT(1);
1518
    return(e);
1519
}
1520
 
60044 ripley 1521
/* in Rinternals.h */
21853 jmc 1522
SEXP R_do_new_object(SEXP class_def)
1523
{
1524
    static SEXP s_virtual = NULL, s_prototype, s_className;
1525
    SEXP e, value;
63181 ripley 1526
    const void *vmax = vmaxget();
21853 jmc 1527
    if(!s_virtual) {
48346 maechler 1528
	s_virtual = install("virtual");
1529
	s_prototype = install("prototype");
1530
	s_className = install("className");
41111 ripley 1531
    }
21853 jmc 1532
    if(!class_def)
32867 ripley 1533
	error(_("C level NEW macro called with null class definition pointer"));
21853 jmc 1534
    e = R_do_slot(class_def, s_virtual);
1535
    if(asLogical(e) != 0)  { /* includes NA, TRUE, or anything other than FALSE */
1536
	e = R_do_slot(class_def, s_className);
39077 jmc 1537
	error(_("trying to generate an object from a virtual class (\"%s\")"),
40705 ripley 1538
	      translateChar(asChar(e)));
21853 jmc 1539
    }
1540
    e = R_do_slot(class_def, s_className);
22303 jmc 1541
    value = duplicate(R_do_slot(class_def, s_prototype));
48346 maechler 1542
    if(TYPEOF(value) == S4SXP || getAttrib(e, R_PackageSymbol) != R_NilValue)
41111 ripley 1543
    { /* Anything but an object from a base "class" (numeric, matrix,..) */
1544
	setAttrib(value, R_ClassSymbol, e);
1545
	SET_S4_OBJECT(value);
1546
    }
63181 ripley 1547
    vmaxset(vmax);
21853 jmc 1548
    return value;
1549
}
37403 jmc 1550
 
41270 ripley 1551
Rboolean attribute_hidden R_seemsOldStyleS4Object(SEXP object)
1552
{
1553
    SEXP klass;
1554
    if(!isObject(object) || IS_S4_OBJECT(object)) return FALSE;
1555
    /* We want to know about S4SXPs with no S4 bit */
1556
    /* if(TYPEOF(object) == S4SXP) return FALSE; */
1557
    klass = getAttrib(object, R_ClassSymbol);
1558
    return (klass != R_NilValue && LENGTH(klass) == 1 &&
48346 maechler 1559
	    getAttrib(klass, R_PackageSymbol) != R_NilValue) ? TRUE: FALSE;
41270 ripley 1560
}
39103 jmc 1561
 
60633 ripley 1562
SEXP attribute_hidden do_setS4Object(SEXP call, SEXP op, SEXP args, SEXP env)
41111 ripley 1563
{
60633 ripley 1564
    checkArity(op, args);
1565
    SEXP object = CAR(args);
1566
    int flag = asLogical(CADR(args)), complete = asInteger(CADDR(args));
1567
    if(length(CADR(args)) != 1 || flag == NA_INTEGER)
60395 ripley 1568
	error("invalid '%s' argument", "flag");
1569
    if(complete == NA_INTEGER)
1570
	error("invalid '%s' argument", "complete");
41111 ripley 1571
    if(flag == IS_S4_OBJECT(object))
45446 ripley 1572
	return object;
48062 jmc 1573
    else
1574
      return asS4(object, flag, complete);
39077 jmc 1575
}
39348 ripley 1576
 
61776 ripley 1577
#ifdef UNUSED
42110 maechler 1578
SEXP R_get_primname(SEXP object)
39348 ripley 1579
{
1580
    SEXP f;
1581
    if(TYPEOF(object) != BUILTINSXP && TYPEOF(object) != SPECIALSXP)
60044 ripley 1582
	error("'R_get_primname' called on a non-primitive");
48062 jmc 1583
    PROTECT(f = allocVector(STRSXP, 1));
39348 ripley 1584
    SET_STRING_ELT(f, 0, mkChar(PRIMNAME(object)));
1585
    UNPROTECT(1);
1586
    return f;
1587
}
61776 ripley 1588
#endif
41631 ripley 1589
 
61776 ripley 1590
 
41631 ripley 1591
Rboolean isS4(SEXP s)
1592
{
1593
    return IS_S4_OBJECT(s);
1594
}
1595
 
48062 jmc 1596
SEXP asS4(SEXP s, Rboolean flag, int complete)
41631 ripley 1597
{
1598
    if(flag == IS_S4_OBJECT(s))
45446 ripley 1599
	return s;
48062 jmc 1600
    PROTECT(s);
41631 ripley 1601
    if(NAMED(s) == 2)
45446 ripley 1602
	s = duplicate(s);
48062 jmc 1603
    UNPROTECT(1);
41631 ripley 1604
    if(flag) SET_S4_OBJECT(s);
48062 jmc 1605
    else {
1606
	if(complete) {
1607
	    SEXP value;
1608
	    /* TENTATIVE:  how much does this change? */
1609
	    if((value = R_getS4DataSlot(s, ANYSXP))
1610
	       != R_NilValue && !IS_S4_OBJECT(value))
1611
	      return value;
1612
	    /* else no plausible S3 object*/
1613
	    else if(complete == 1) /* ordinary case (2, for conditional) */
60844 ripley 1614
	      error(_("object of class \"%s\" does not correspond to a valid S3 object"),
48062 jmc 1615
		      CHAR(STRING_ELT(R_data_class(s, FALSE), 0)));
1616
	    else return s; /*  unchanged */
1617
	}
1618
	UNSET_S4_OBJECT(s);
1619
    }
41631 ripley 1620
    return s;
1621
}