The R Project SVN R

Rev

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