Debian Codegraph @

generic/tclOO.c

raw
1 /*
2 * tclOO.c --
3 *
4 * This file contains the object-system core (NB: not Tcl_Obj, but ::oo)
5 *
6 * Copyright (c) 2005-2012 by Donal K. Fellows
7 * Copyright (c) 2017 by Nathan Coulter
8 *
9 * See the file "license.terms" for information on usage and redistribution of
10 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 */
12
13 #ifdef HAVE_CONFIG_H
14 #include "config.h"
15 #endif
16 #include "tclInt.h"
17 #include "tclOOInt.h"
18
19 /*
20 * Commands in oo::define.
21 */
22
23 static const struct {
24 const char *name;
25 Tcl_ObjCmdProc *objProc;
26 int flag;
27 } defineCmds[] = {
28 {"constructor", TclOODefineConstructorObjCmd, 0},
29 {"deletemethod", TclOODefineDeleteMethodObjCmd, 0},
30 {"destructor", TclOODefineDestructorObjCmd, 0},
31 {"export", TclOODefineExportObjCmd, 0},
32 {"forward", TclOODefineForwardObjCmd, 0},
33 {"method", TclOODefineMethodObjCmd, 0},
34 {"renamemethod", TclOODefineRenameMethodObjCmd, 0},
35 {"self", TclOODefineSelfObjCmd, 0},
36 {"unexport", TclOODefineUnexportObjCmd, 0},
37 {NULL, NULL, 0}
38 }, objdefCmds[] = {
39 {"class", TclOODefineClassObjCmd, 1},
40 {"deletemethod", TclOODefineDeleteMethodObjCmd, 1},
41 {"export", TclOODefineExportObjCmd, 1},
42 {"forward", TclOODefineForwardObjCmd, 1},
43 {"method", TclOODefineMethodObjCmd, 1},
44 {"renamemethod", TclOODefineRenameMethodObjCmd, 1},
45 {"unexport", TclOODefineUnexportObjCmd, 1},
46 {NULL, NULL, 0}
47 };
48
49 /*
50 * What sort of size of things we like to allocate.
51 */
52
53 #define ALLOC_CHUNK 8
54
55 /*
56 * Function declarations for things defined in this file.
57 */
58
59 static Object * AllocObject(Tcl_Interp *interp, const char *nameStr,
60 Namespace *nsPtr, const char *nsNameStr);
61 static int CloneClassMethod(Tcl_Interp *interp, Class *clsPtr,
62 Method *mPtr, Tcl_Obj *namePtr,
63 Method **newMPtrPtr);
64 static int CloneObjectMethod(Tcl_Interp *interp, Object *oPtr,
65 Method *mPtr, Tcl_Obj *namePtr);
66 static void DeletedDefineNamespace(ClientData clientData);
67 static void DeletedObjdefNamespace(ClientData clientData);
68 static void DeletedHelpersNamespace(ClientData clientData);
69 static Tcl_NRPostProc FinalizeAlloc;
70 static Tcl_NRPostProc FinalizeNext;
71 static Tcl_NRPostProc FinalizeObjectCall;
72 static void initClassPath(Tcl_Interp * interp, Class *clsPtr);
73 static int InitFoundation(Tcl_Interp *interp);
74 static void KillFoundation(ClientData clientData,
75 Tcl_Interp *interp);
76 static void MyDeleted(ClientData clientData);
77 static void ObjectNamespaceDeleted(ClientData clientData);
78 static void ObjectRenamedTrace(ClientData clientData,
79 Tcl_Interp *interp, const char *oldName,
80 const char *newName, int flags);
81 static inline void SquelchCachedName(Object *oPtr);
82
83 static int PublicObjectCmd(ClientData clientData,
84 Tcl_Interp *interp, int objc,
85 Tcl_Obj *const *objv);
86 static int PublicNRObjectCmd(ClientData clientData,
87 Tcl_Interp *interp, int objc,
88 Tcl_Obj *const *objv);
89 static int PrivateObjectCmd(ClientData clientData,
90 Tcl_Interp *interp, int objc,
91 Tcl_Obj *const *objv);
92 static int PrivateNRObjectCmd(ClientData clientData,
93 Tcl_Interp *interp, int objc,
94 Tcl_Obj *const *objv);
95 static void RemoveClass(Class ** list, int num, int idx);
96 static void RemoveObject(Object ** list, int num, int idx);
97
98 /*
99 * Methods in the oo::object and oo::class classes. First, we define a helper
100 * macro that makes building the method type declaration structure a lot
101 * easier. No point in making life harder than it has to be!
102 *
103 * Note that the core methods don't need clone or free proc callbacks.
104 */
105
106 #define DCM(name,visibility,proc) \
107 {name,visibility,\
108 {TCL_OO_METHOD_VERSION_CURRENT,"core method: "#name,proc,NULL,NULL}}
109
110 static const DeclaredClassMethod objMethods[] = {
111 DCM("destroy", 1, TclOO_Object_Destroy),
112 DCM("eval", 0, TclOO_Object_Eval),
113 DCM("unknown", 0, TclOO_Object_Unknown),
114 DCM("variable", 0, TclOO_Object_LinkVar),
115 DCM("varname", 0, TclOO_Object_VarName),
116 {NULL, 0, {0, NULL, NULL, NULL, NULL}}
117 }, clsMethods[] = {
118 DCM("create", 1, TclOO_Class_Create),
119 DCM("new", 1, TclOO_Class_New),
120 DCM("createWithNamespace", 0, TclOO_Class_CreateNs),
121 {NULL, 0, {0, NULL, NULL, NULL, NULL}}
122 };
123
124 /*
125 * And for the oo::class constructor...
126 */
127
128 static const Tcl_MethodType classConstructor = {
129 TCL_OO_METHOD_VERSION_CURRENT,
130 "oo::class constructor",
131 TclOO_Class_Constructor, NULL, NULL
132 };
133
134 /*
135 * Scripted parts of TclOO. First, the main script (cannot be outside this
136 * file).
137 */
138
139 static const char initScript[] =
140 "package ifneeded TclOO " TCLOO_PATCHLEVEL " {# Already present, OK?};"
141 "namespace eval ::oo { variable version " TCLOO_VERSION " };"
142 "namespace eval ::oo { variable patchlevel " TCLOO_PATCHLEVEL " };";
143 /* "tcl_findLibrary tcloo $oo::version $oo::version" */
144 /* " tcloo.tcl OO_LIBRARY oo::library;"; */
145
146 /*
147 * The scripted part of the definitions of slots.
148 */
149
150 static const char *slotScript =
151 "::oo::define ::oo::Slot {\n"
152 " method Get {} {error unimplemented}\n"
153 " method Set list {error unimplemented}\n"
154 " method -set args {\n"
155 " uplevel 1 [list [namespace which my] Set $args]\n"
156 " }\n"
157 " method -append args {\n"
158 " uplevel 1 [list [namespace which my] Set [list"
159 " {*}[uplevel 1 [list [namespace which my] Get]] {*}$args]]\n"
160 " }\n"
161 " method -clear {} {uplevel 1 [list [namespace which my] Set {}]}\n"
162 " forward --default-operation my -append\n"
163 " method unknown {args} {\n"
164 " set def --default-operation\n"
165 " if {[llength $args] == 0} {\n"
166 " return [uplevel 1 [list [namespace which my] $def]]\n"
167 " } elseif {![string match -* [lindex $args 0]]} {\n"
168 " return [uplevel 1 [list [namespace which my] $def {*}$args]]\n"
169 " }\n"
170 " next {*}$args\n"
171 " }\n"
172 " export -set -append -clear\n"
173 " unexport unknown destroy\n"
174 "}\n"
175 "::oo::objdefine ::oo::define::superclass forward --default-operation my -set\n"
176 "::oo::objdefine ::oo::define::mixin forward --default-operation my -set\n"
177 "::oo::objdefine ::oo::objdefine::mixin forward --default-operation my -set\n";
178
179 /*
180 * The body of the <cloned> method of oo::object.
181 */
182
183 static const char *clonedBody =
184 "foreach p [info procs [info object namespace $originObject]::*] {"
185 " set args [info args $p];"
186 " set idx -1;"
187 " foreach a $args {"
188 " lset args [incr idx] "
189 " [if {[info default $p $a d]} {list $a $d} {list $a}]"
190 " };"
191 " set b [info body $p];"
192 " set p [namespace tail $p];"
193 " proc $p $args $b;"
194 "};"
195 "foreach v [info vars [info object namespace $originObject]::*] {"
196 " upvar 0 $v vOrigin;"
197 " namespace upvar [namespace current] [namespace tail $v] vNew;"
198 " if {[info exists vOrigin]} {"
199 " if {[array exists vOrigin]} {"
200 " array set vNew [array get vOrigin];"
201 " } else {"
202 " set vNew $vOrigin;"
203 " }"
204 " }"
205 "}";
206
207 /*
208 * The actual definition of the variable holding the TclOO stub table.
209 */
210
211 MODULE_SCOPE const TclOOStubs tclOOStubs;
212
213 /*
214 * Convenience macro for getting the foundation from an interpreter.
215 */
216
217 #define GetFoundation(interp) \
218 ((Foundation *)((Interp *)(interp))->objectFoundation)
219
220 /*
221 * Macros to make inspecting into the guts of an object cleaner.
222 *
223 * The ocPtr parameter (only in these macros) is assumed to work fine with
224 * either an oPtr or a classPtr. Note that the roots oo::object and oo::class
225 * have _both_ their object and class flags tagged with ROOT_OBJECT and
226 * ROOT_CLASS respectively.
227 */
228
229 #define Destructing(oPtr) ((oPtr)->flags & OBJECT_DESTRUCTING)
230 #define IsRootObject(ocPtr) ((ocPtr)->flags & ROOT_OBJECT)
231 #define IsRootClass(ocPtr) ((ocPtr)->flags & ROOT_CLASS)
232 #define IsRoot(ocPtr) ((ocPtr)->flags & (ROOT_OBJECT|ROOT_CLASS))
233
234 #define RemoveItem(type, lst, i) \
235 do { \
236 Remove ## type ((lst).list, (lst).num, i); \
237 (lst).num--; \
238 } while (0)
239
240 /*
241 * ----------------------------------------------------------------------
242 *
243 * TclOOInit --
244 *
245 * Called to initialise the OO system within an interpreter.
246 *
247 * Result:
248 * TCL_OK if the setup succeeded. Currently assumed to always work.
249 *
250 * Side effects:
251 * Creates namespaces, commands, several classes and a number of
252 * callbacks. Upon return, the OO system is ready for use.
253 *
254 * ----------------------------------------------------------------------
255 */
256
257 int
258 TclOOInit(
259 Tcl_Interp *interp) /* The interpreter to install into. */
260 {
261 /*
262 * Build the core of the OO system.
263 */
264
265 if (InitFoundation(interp) != TCL_OK) {
266 return TCL_ERROR;
267 }
268
269 /*
270 * Run our initialization script and, if that works, declare the package
271 * to be fully provided.
272 */
273
274 if (Tcl_Eval(interp, initScript) != TCL_OK) {
275 return TCL_ERROR;
276 }
277
278 return Tcl_PkgProvideEx(interp, "TclOO", TCLOO_PATCHLEVEL,
279 &tclOOStubs);
280 }
281
282 /*
283 * ----------------------------------------------------------------------
284 *
285 * TclOOGetFoundation --
286 *
287 * Get a reference to the OO core class system.
288 *
289 * ----------------------------------------------------------------------
290 */
291
292 Foundation *
293 TclOOGetFoundation(
294 Tcl_Interp *interp)
295 {
296 return GetFoundation(interp);
297 }
298
299 /*
300 * ----------------------------------------------------------------------
301 *
302 * InitFoundation --
303 *
304 * Set up the core of the OO core class system. This is a structure
305 * holding references to the magical bits that need to be known about in
306 * other places, plus the oo::object and oo::class classes.
307 *
308 * ----------------------------------------------------------------------
309 */
310
311 static int
312 InitFoundation(
313 Tcl_Interp *interp)
314 {
315 static Tcl_ThreadDataKey tsdKey;
316 ThreadLocalData *tsdPtr =
317 Tcl_GetThreadData(&tsdKey, sizeof(ThreadLocalData));
318 Foundation *fPtr = ckalloc(sizeof(Foundation));
319 Tcl_Obj *namePtr, *argsPtr, *bodyPtr;
320
321 Class fakeCls;
322 Object fakeObject;
323
324 Tcl_DString buffer;
325 Command *cmdPtr;
326 int i;
327
328 /*
329 * Initialize the structure that holds the OO system core. This is
330 * attached to the interpreter via an assocData entry; not very efficient,
331 * but the best we can do without hacking the core more.
332 */
333
334 memset(fPtr, 0, sizeof(Foundation));
335 ((Interp *) interp)->objectFoundation = fPtr;
336 fPtr->interp = interp;
337 fPtr->ooNs = Tcl_CreateNamespace(interp, "::oo", fPtr, NULL);
338 Tcl_Export(interp, fPtr->ooNs, "[a-z]*", 1);
339 fPtr->defineNs = Tcl_CreateNamespace(interp, "::oo::define", fPtr,
340 DeletedDefineNamespace);
341 fPtr->objdefNs = Tcl_CreateNamespace(interp, "::oo::objdefine", fPtr,
342 DeletedObjdefNamespace);
343 fPtr->helpersNs = Tcl_CreateNamespace(interp, "::oo::Helpers", fPtr,
344 DeletedHelpersNamespace);
345 fPtr->epoch = 0;
346 fPtr->tsdPtr = tsdPtr;
347 TclNewLiteralStringObj(fPtr->unknownMethodNameObj, "unknown");
348 TclNewLiteralStringObj(fPtr->constructorName, "<constructor>");
349 TclNewLiteralStringObj(fPtr->destructorName, "<destructor>");
350 TclNewLiteralStringObj(fPtr->clonedName, "<cloned>");
351 TclNewLiteralStringObj(fPtr->defineName, "::oo::define");
352 Tcl_IncrRefCount(fPtr->unknownMethodNameObj);
353 Tcl_IncrRefCount(fPtr->constructorName);
354 Tcl_IncrRefCount(fPtr->destructorName);
355 Tcl_IncrRefCount(fPtr->clonedName);
356 Tcl_IncrRefCount(fPtr->defineName);
357 Tcl_CreateObjCommand(interp, "::oo::UnknownDefinition",
358 TclOOUnknownDefinition, NULL, NULL);
359 TclNewLiteralStringObj(namePtr, "::oo::UnknownDefinition");
360 Tcl_SetNamespaceUnknownHandler(interp, fPtr->defineNs, namePtr);
361 Tcl_SetNamespaceUnknownHandler(interp, fPtr->objdefNs, namePtr);
362
363 /*
364 * Create the subcommands in the oo::define and oo::objdefine spaces.
365 */
366
367 Tcl_DStringInit(&buffer);
368 for (i = 0 ; defineCmds[i].name ; i++) {
369 TclDStringAppendLiteral(&buffer, "::oo::define::");
370 Tcl_DStringAppend(&buffer, defineCmds[i].name, -1);
371 Tcl_CreateObjCommand(interp, Tcl_DStringValue(&buffer),
372 defineCmds[i].objProc, INT2PTR(defineCmds[i].flag), NULL);
373 Tcl_DStringFree(&buffer);
374 }
375 for (i = 0 ; objdefCmds[i].name ; i++) {
376 TclDStringAppendLiteral(&buffer, "::oo::objdefine::");
377 Tcl_DStringAppend(&buffer, objdefCmds[i].name, -1);
378 Tcl_CreateObjCommand(interp, Tcl_DStringValue(&buffer),
379 objdefCmds[i].objProc, INT2PTR(objdefCmds[i].flag), NULL);
380 Tcl_DStringFree(&buffer);
381 }
382
383 Tcl_CallWhenDeleted(interp, KillFoundation, NULL);
384
385 /*
386 * Create the objects at the core of the object system. These need to be
387 * spliced manually.
388 */
389
390 /*
391 * Stand up a phony class for bootstrapping.
392 */
393
394 fPtr->objectCls = &fakeCls;
395
396 /*
397 * Referenced in TclOOAllocClass to increment the refCount.
398 */
399
400 fakeCls.thisPtr = &fakeObject;
401 fakeObject.refCount = 0; /* Do not increment an uninitialized value. */
402
403 fPtr->objectCls = TclOOAllocClass(interp,
404 AllocObject(interp, "object", (Namespace *)fPtr->ooNs, NULL));
405 /*
406 * Corresponding TclOODecrRefCount in KillFoundation.
407 */
408
409 AddRef(fPtr->objectCls->thisPtr);
410
411 /*
412 * This is why it is unnecessary in this routine to replace the
413 * incremented reference count of fPtr->objectCls that was swallowed by
414 * fakeObject.
415 */
416
417 fPtr->objectCls->superclasses.num = 0;
418 ckfree(fPtr->objectCls->superclasses.list);
419 fPtr->objectCls->superclasses.list = NULL;
420
421 /*
422 * Special initialization for the primordial objects.
423 */
424
425 fPtr->objectCls->thisPtr->flags |= ROOT_OBJECT;
426 fPtr->objectCls->flags |= ROOT_OBJECT;
427
428 fPtr->classCls = TclOOAllocClass(interp,
429 AllocObject(interp, "class", (Namespace *)fPtr->ooNs, NULL));
430
431 /*
432 * Corresponding TclOODecrRefCount in KillFoundation.
433 */
434
435 AddRef(fPtr->classCls->thisPtr);
436
437 /*
438 * Increment reference counts for each reference because these
439 * relationships can be dynamically changed.
440 *
441 * Corresponding TclOODecrRefCount for all incremented refcounts is in
442 * KillFoundation.
443 */
444
445 /*
446 * Rewire bootstrapped objects.
447 */
448
449 fPtr->objectCls->thisPtr->selfCls = fPtr->classCls;
450 AddRef(fPtr->classCls->thisPtr);
451 TclOOAddToInstances(fPtr->objectCls->thisPtr, fPtr->classCls);
452
453 fPtr->classCls->thisPtr->selfCls = fPtr->classCls;
454 AddRef(fPtr->classCls->thisPtr);
455 TclOOAddToInstances(fPtr->classCls->thisPtr, fPtr->classCls);
456
457 fPtr->classCls->thisPtr->flags |= ROOT_CLASS;
458 fPtr->classCls->flags |= ROOT_CLASS;
459
460 /*
461 * Standard initialization for new Objects.
462 */
463
464 TclOOAddToSubclasses(fPtr->classCls, fPtr->objectCls);
465
466 /*
467 * Basic method declarations for the core classes.
468 */
469
470 for (i = 0 ; objMethods[i].name ; i++) {
471 TclOONewBasicMethod(interp, fPtr->objectCls, &objMethods[i]);
472 }
473 for (i = 0 ; clsMethods[i].name ; i++) {
474 TclOONewBasicMethod(interp, fPtr->classCls, &clsMethods[i]);
475 }
476
477 /*
478 * Create the default <cloned> method implementation, used when 'oo::copy'
479 * is called to finish the copying of one object to another.
480 */
481
482 TclNewLiteralStringObj(argsPtr, "originObject");
483 Tcl_IncrRefCount(argsPtr);
484 bodyPtr = Tcl_NewStringObj(clonedBody, -1);
485 TclOONewProcMethod(interp, fPtr->objectCls, 0, fPtr->clonedName, argsPtr,
486 bodyPtr, NULL);
487 TclDecrRefCount(argsPtr);
488
489 /*
490 * Finish setting up the class of classes by marking the 'new' method as
491 * private; classes, unlike general objects, must have explicit names. We
492 * also need to create the constructor for classes.
493 */
494
495 TclNewLiteralStringObj(namePtr, "new");
496 Tcl_NewInstanceMethod(interp, (Tcl_Object) fPtr->classCls->thisPtr,
497 namePtr /* keeps ref */, 0 /* private */, NULL, NULL);
498 fPtr->classCls->constructorPtr = (Method *) Tcl_NewMethod(interp,
499 (Tcl_Class) fPtr->classCls, NULL, 0, &classConstructor, NULL);
500
501 /*
502 * Create non-object commands and plug ourselves into the Tcl [info]
503 * ensemble.
504 */
505
506 cmdPtr = (Command *) Tcl_NRCreateCommand(interp, "::oo::Helpers::next",
507 NULL, TclOONextObjCmd, NULL, NULL);
508 cmdPtr->compileProc = TclCompileObjectNextCmd;
509 cmdPtr = (Command *) Tcl_NRCreateCommand(interp, "::oo::Helpers::nextto",
510 NULL, TclOONextToObjCmd, NULL, NULL);
511 cmdPtr->compileProc = TclCompileObjectNextToCmd;
512 cmdPtr = (Command *) Tcl_CreateObjCommand(interp, "::oo::Helpers::self",
513 TclOOSelfObjCmd, NULL, NULL);
514 cmdPtr->compileProc = TclCompileObjectSelfCmd;
515 Tcl_CreateObjCommand(interp, "::oo::define", TclOODefineObjCmd, NULL,
516 NULL);
517 Tcl_CreateObjCommand(interp, "::oo::objdefine", TclOOObjDefObjCmd, NULL,
518 NULL);
519 Tcl_CreateObjCommand(interp, "::oo::copy", TclOOCopyObjectCmd, NULL,NULL);
520 TclOOInitInfo(interp);
521
522 /*
523 * Now make the class of slots.
524 */
525
526 if (TclOODefineSlots(fPtr) != TCL_OK) {
527 return TCL_ERROR;
528 }
529 return Tcl_Eval(interp, slotScript);
530 }
531
532 /*
533 * ----------------------------------------------------------------------
534 *
535 * DeletedDefineNamespace, DeletedObjdefNamespace, DeletedHelpersNamespace --
536 *
537 * Simple helpers used to clear fields of the foundation when they no
538 * longer hold useful information.
539 *
540 * ----------------------------------------------------------------------
541 */
542
543 static void
544 DeletedDefineNamespace(
545 ClientData clientData)
546 {
547 Foundation *fPtr = clientData;
548
549 fPtr->defineNs = NULL;
550 }
551
552 static void
553 DeletedObjdefNamespace(
554 ClientData clientData)
555 {
556 Foundation *fPtr = clientData;
557
558 fPtr->objdefNs = NULL;
559 }
560
561 static void
562 DeletedHelpersNamespace(
563 ClientData clientData)
564 {
565 Foundation *fPtr = clientData;
566
567 fPtr->helpersNs = NULL;
568 }
569
570 /*
571 * ----------------------------------------------------------------------
572 *
573 * KillFoundation --
574 *
575 * Delete those parts of the OO core that are not deleted automatically
576 * when the objects and classes themselves are destroyed.
577 *
578 * ----------------------------------------------------------------------
579 */
580
581 static void
582 KillFoundation(
583 ClientData clientData, /* Pointer to the OO system foundation
584 * structure. */
585 Tcl_Interp *interp) /* The interpreter containing the OO system
586 * foundation. */
587 {
588 Foundation *fPtr = GetFoundation(interp);
589
590 TclDecrRefCount(fPtr->unknownMethodNameObj);
591 TclDecrRefCount(fPtr->constructorName);
592 TclDecrRefCount(fPtr->destructorName);
593 TclDecrRefCount(fPtr->clonedName);
594 TclDecrRefCount(fPtr->defineName);
595 TclOODecrRefCount(fPtr->objectCls->thisPtr);
596 TclOODecrRefCount(fPtr->classCls->thisPtr);
597
598 ckfree(fPtr);
599 }
600
601 /*
602 * ----------------------------------------------------------------------
603 *
604 * AllocObject --
605 *
606 * Allocate an object of basic type. Does not splice the object into its
607 * class's instance list. The caller must set the classPtr on the object
608 * to either a class or NULL, call TclOOAddToInstances to add the object
609 * to the class's instance list, and if the object itself is a class, use
610 * call TclOOAddToSubclasses() to add it to the right class's list of
611 * subclasses.
612 *
613 * Returns:
614 * Pointer to the object structure created, or NULL if a specific
615 * namespace was asked for but couldn't be created.
616 *
617 * ----------------------------------------------------------------------
618 */
619
620 static Object *
621 AllocObject(
622 Tcl_Interp *interp, /* Interpreter within which to create the
623 * object. */
624 const char *nameStr, /* The name of the object to create, or NULL
625 * if the OO system should pick the object
626 * name itself (equal to the namespace
627 * name). */
628 Namespace *nsPtr, /* The namespace to create the object in,
629 or NULL if *nameStr is NULL */
630 const char *nsNameStr) /* The name of the namespace to create, or
631 * NULL if the OO system should pick a unique
632 * name itself. If this is non-NULL but names
633 * a namespace that already exists, the effect
634 * will be the same as if this was NULL. */
635 {
636 Foundation *fPtr = GetFoundation(interp);
637 Object *oPtr;
638 Command *cmdPtr;
639 CommandTrace *tracePtr;
640 int creationEpoch;
641
642 oPtr = ckalloc(sizeof(Object));
643 memset(oPtr, 0, sizeof(Object));
644
645 /*
646 * Every object has a namespace; make one. Note that this also normally
647 * computes the creation epoch value for the object, a sequence number
648 * that is unique to the object (and which allows us to manage method
649 * caching without comparing pointers).
650 *
651 * When creating a namespace, we first check to see if the caller
652 * specified the name for the namespace. If not, we generate namespace
653 * names using the epoch until such time as a new namespace is actually
654 * created.
655 */
656
657 if (nsNameStr != NULL) {
658 oPtr->namespacePtr = Tcl_CreateNamespace(interp, nsNameStr, oPtr, NULL);
659 if (oPtr->namespacePtr == NULL) {
660 /*
661 * Couldn't make the specific namespace. Report as an error.
662 * [Bug 154f0982f2]
663 */
664 ckfree(oPtr);
665 return NULL;
666 }
667 creationEpoch = ++fPtr->tsdPtr->nsCount;
668 goto configNamespace;
669 }
670
671 while (1) {
672 char objName[10 + TCL_INTEGER_SPACE];
673
674 snprintf(objName, sizeof(objName), "::oo::Obj%d", ++fPtr->tsdPtr->nsCount);
675 oPtr->namespacePtr = Tcl_CreateNamespace(interp, objName, oPtr, NULL);
676 if (oPtr->namespacePtr != NULL) {
677 creationEpoch = fPtr->tsdPtr->nsCount;
678 break;
679 }
680
681 /*
682 * Could not make that namespace, so we make another. But first we
683 * have to get rid of the error message from Tcl_CreateNamespace,
684 * since that's something that should not be exposed to the user.
685 */
686
687 Tcl_ResetResult(interp);
688 }
689
690 configNamespace:
691 ((Namespace *) oPtr->namespacePtr)->refCount++;
692
693 /*
694 * Make the namespace know about the helper commands. This grants access
695 * to the [self] and [next] commands.
696 */
697
698 if (fPtr->helpersNs != NULL) {
699 TclSetNsPath((Namespace *) oPtr->namespacePtr, 1, &fPtr->helpersNs);
700 }
701 TclOOSetupVariableResolver(oPtr->namespacePtr);
702
703 /*
704 * Suppress use of compiled versions of the commands in this object's
705 * namespace and its children; causes wrong behaviour without expensive
706 * recompilation. [Bug 2037727]
707 */
708
709 ((Namespace *) oPtr->namespacePtr)->flags |= NS_SUPPRESS_COMPILATION;
710
711 /*
712 * Set up a callback to get notification of the deletion of a namespace
713 * when enough of the namespace still remains to execute commands and
714 * access variables in it. [Bug 2950259]
715 */
716
717 ((Namespace *) oPtr->namespacePtr)->earlyDeleteProc = ObjectNamespaceDeleted;
718
719 /*
720 * Fill in the rest of the non-zero/NULL parts of the structure.
721 */
722
723 oPtr->fPtr = fPtr;
724 oPtr->creationEpoch = creationEpoch;
725
726 /*
727 * An object starts life with a refCount of 2 to mark the two stages of
728 * destruction it occur: A call to ObjectRenamedTrace(), and a call to
729 * ObjectNamespaceDeleted().
730 */
731 oPtr->refCount = 2;
732
733 oPtr->flags = USE_CLASS_CACHE;
734
735 /*
736 * Finally, create the object commands and initialize the trace on the
737 * public command (so that the object structures are deleted when the
738 * command is deleted).
739 */
740
741 if (!nameStr) {
742 nameStr = oPtr->namespacePtr->name;
743 nsPtr = (Namespace *)oPtr->namespacePtr;
744 if (nsPtr->parentPtr != NULL) {
745 nsPtr = nsPtr->parentPtr;
746 }
747
748 }
749 oPtr->command = TclCreateObjCommandInNs(interp, nameStr,
750 (Tcl_Namespace *)nsPtr, PublicObjectCmd, oPtr, NULL);
751
752 /*
753 * Add the NRE command and trace directly. While this breaks a number of
754 * abstractions, it is faster and we're inside Tcl here so we're allowed.
755 */
756
757 cmdPtr = (Command *) oPtr->command;
758 cmdPtr->nreProc = PublicNRObjectCmd;
759 cmdPtr->tracePtr = tracePtr = ckalloc(sizeof(CommandTrace));
760 tracePtr->traceProc = ObjectRenamedTrace;
761 tracePtr->clientData = oPtr;
762 tracePtr->flags = TCL_TRACE_RENAME|TCL_TRACE_DELETE;
763 tracePtr->nextPtr = NULL;
764 tracePtr->refCount = 1;
765
766 oPtr->myCommand = TclNRCreateCommandInNs(interp, "my", oPtr->namespacePtr,
767 PrivateObjectCmd, PrivateNRObjectCmd, oPtr, MyDeleted);
768 return oPtr;
769 }
770
771 /*
772 * ----------------------------------------------------------------------
773 *
774 * SquelchCachedName --
775 *
776 * Encapsulates how to throw away a cached object name. Called from
777 * object rename traces and at object destruction.
778 *
779 * ----------------------------------------------------------------------
780 */
781
782 static inline void
783 SquelchCachedName(
784 Object *oPtr)
785 {
786 if (oPtr->cachedNameObj) {
787 Tcl_DecrRefCount(oPtr->cachedNameObj);
788 oPtr->cachedNameObj = NULL;
789 }
790 }
791
792 /*
793 * ----------------------------------------------------------------------
794 *
795 * MyDeleted --
796 *
797 * This callback is triggered when the object's [my] command is deleted
798 * by any mechanism. It just marks the object as not having a [my]
799 * command, and so prevents cleanup of that when the object itself is
800 * deleted.
801 *
802 * ----------------------------------------------------------------------
803 */
804
805 static void
806 MyDeleted(
807 ClientData clientData) /* Reference to the object whose [my] has been
808 * squelched. */
809 {
810 Object *oPtr = clientData;
811
812 oPtr->myCommand = NULL;
813 }
814
815 /*
816 * ----------------------------------------------------------------------
817 *
818 * ObjectRenamedTrace --
819 *
820 * This callback is triggered when the object is deleted by any
821 * mechanism. It runs the destructors and arranges for the actual cleanup
822 * of the object's namespace, which in turn triggers cleansing of the
823 * object data structures.
824 *
825 * ----------------------------------------------------------------------
826 */
827
828 static void
829 ObjectRenamedTrace(
830 void *clientData, /* The object being deleted. */
831 Tcl_Interp *interp, /* The interpreter containing the object. */
832 const char *oldName, /* What the object was (last) called. */
833 const char *newName, /* What it's getting renamed to. (unused) */
834 int flags) /* Why was the object deleted? */
835 {
836 Object *oPtr = clientData;
837 /*
838 * If this is a rename and not a delete of the object, we just flush the
839 * cache of the object name.
840 */
841
842 if (flags & TCL_TRACE_RENAME) {
843 SquelchCachedName(oPtr);
844 return;
845 }
846
847 /*
848 * The namespace is only deleted if it hasn't already been deleted. [Bug
849 * 2950259].
850 */
851
852 if (!Destructing(oPtr)) {
853 Tcl_DeleteNamespace(oPtr->namespacePtr);
854 }
855 oPtr->command = NULL;
856 TclOODecrRefCount(oPtr);
857 return;
858 }
859
860 /*
861 * ----------------------------------------------------------------------
862 *
863 * TclOODeleteDescendants --
864 *
865 * Delete all descendants of a particular class.
866 *
867 * ----------------------------------------------------------------------
868 */
869
870 void
871 TclOODeleteDescendants(
872 Tcl_Interp *interp, /* The interpreter containing the class. */
873 Object *oPtr) /* The object representing the class. */
874 {
875 Class *clsPtr = oPtr->classPtr, *subclassPtr, *mixinSubclassPtr;
876 Object *instancePtr;
877
878 /*
879 * Squelch classes that this class has been mixed into.
880 */
881
882 if (clsPtr->mixinSubs.num > 0) {
883 while (clsPtr->mixinSubs.num > 0) {
884 mixinSubclassPtr =
885 clsPtr->mixinSubs.list[clsPtr->mixinSubs.num - 1];
886
887 /*
888 * This condition also covers the case where mixinSubclassPtr ==
889 * clsPtr
890 */
891
892 if (!Destructing(mixinSubclassPtr->thisPtr)
893 && !(mixinSubclassPtr->thisPtr->flags & DONT_DELETE)) {
894 Tcl_DeleteCommandFromToken(interp,
895 mixinSubclassPtr->thisPtr->command);
896 }
897 TclOORemoveFromMixinSubs(mixinSubclassPtr, clsPtr);
898 }
899 }
900 if (clsPtr->mixinSubs.size > 0) {
901 ckfree(clsPtr->mixinSubs.list);
902 clsPtr->mixinSubs.size = 0;
903 }
904 /*
905 * Squelch subclasses of this class.
906 */
907
908 if (clsPtr->subclasses.num > 0) {
909 while (clsPtr->subclasses.num > 0) {
910 subclassPtr = clsPtr->subclasses.list[clsPtr->subclasses.num - 1];
911 if (!Destructing(subclassPtr->thisPtr) && !IsRoot(subclassPtr)
912 && !(subclassPtr->thisPtr->flags & DONT_DELETE)) {
913 Tcl_DeleteCommandFromToken(interp,
914 subclassPtr->thisPtr->command);
915 }
916 TclOORemoveFromSubclasses(subclassPtr, clsPtr);
917 }
918 }
919 if (clsPtr->subclasses.size > 0) {
920 ckfree(clsPtr->subclasses.list);
921 clsPtr->subclasses.list = NULL;
922 clsPtr->subclasses.size = 0;
923 }
924
925 /*
926 * Squelch instances of this class (includes objects we're mixed into).
927 */
928
929 if (clsPtr->instances.num > 0) {
930 while (clsPtr->instances.num > 0) {
931 instancePtr = clsPtr->instances.list[clsPtr->instances.num - 1];
932
933 /*
934 * This condition also covers the case where instancePtr == oPtr
935 */
936
937 if (!Destructing(instancePtr) && !IsRoot(instancePtr) &&
938 !(instancePtr->flags & DONT_DELETE)) {
939 Tcl_DeleteCommandFromToken(interp, instancePtr->command);
940 }
941 TclOORemoveFromInstances(instancePtr, clsPtr);
942 }
943 }
944 if (clsPtr->instances.size > 0) {
945 ckfree(clsPtr->instances.list);
946 clsPtr->instances.list = NULL;
947 clsPtr->instances.size = 0;
948 }
949 }
950
951 /*
952 * ----------------------------------------------------------------------
953 *
954 * TclOOReleaseClassContents --
955 *
956 * Tear down the special class data structure, including deleting all
957 * dependent classes and objects.
958 *
959 * ----------------------------------------------------------------------
960 */
961
962 void
963 TclOOReleaseClassContents(
964 Tcl_Interp *interp, /* The interpreter containing the class. */
965 Object *oPtr) /* The object representing the class. */
966 {
967 FOREACH_HASH_DECLS;
968 int i;
969 Class *clsPtr = oPtr->classPtr, *tmpClsPtr;
970 Method *mPtr;
971 Foundation *fPtr = oPtr->fPtr;
972 Tcl_Obj *variableObj;
973
974 /*
975 * Sanity check!
976 */
977
978 if (!Destructing(oPtr)) {
979 if (IsRootClass(oPtr)) {
980 Tcl_Panic("deleting class structure for non-deleted %s",
981 "::oo::class");
982 } else if (IsRootObject(oPtr)) {
983 Tcl_Panic("deleting class structure for non-deleted %s",
984 "::oo::object");
985 }
986 }
987
988 /*
989 * Squelch method implementation chain caches.
990 */
991
992 if (clsPtr->constructorChainPtr) {
993 TclOODeleteChain(clsPtr->constructorChainPtr);
994 clsPtr->constructorChainPtr = NULL;
995 }
996 if (clsPtr->destructorChainPtr) {
997 TclOODeleteChain(clsPtr->destructorChainPtr);
998 clsPtr->destructorChainPtr = NULL;
999 }
1000 if (clsPtr->classChainCache) {
1001 CallChain *callPtr;
1002
1003 FOREACH_HASH_VALUE(callPtr, clsPtr->classChainCache) {
1004 TclOODeleteChain(callPtr);
1005 }
1006 Tcl_DeleteHashTable(clsPtr->classChainCache);
1007 ckfree(clsPtr->classChainCache);
1008 clsPtr->classChainCache = NULL;
1009 }
1010
1011 /*
1012 * Squelch our filter list.
1013 */
1014
1015 if (clsPtr->filters.num) {
1016 Tcl_Obj *filterObj;
1017
1018 FOREACH(filterObj, clsPtr->filters) {
1019 TclDecrRefCount(filterObj);
1020 }
1021 ckfree(clsPtr->filters.list);
1022 clsPtr->filters.list = NULL;
1023 clsPtr->filters.num = 0;
1024 }
1025
1026 /*
1027 * Squelch our metadata.
1028 */
1029
1030 if (clsPtr->metadataPtr != NULL) {
1031 Tcl_ObjectMetadataType *metadataTypePtr;
1032 ClientData value;
1033
1034 FOREACH_HASH(metadataTypePtr, value, clsPtr->metadataPtr) {
1035 metadataTypePtr->deleteProc(value);
1036 }
1037 Tcl_DeleteHashTable(clsPtr->metadataPtr);
1038 ckfree(clsPtr->metadataPtr);
1039 clsPtr->metadataPtr = NULL;
1040 }
1041
1042 if (clsPtr->mixins.num) {
1043 FOREACH(tmpClsPtr, clsPtr->mixins) {
1044 TclOORemoveFromMixinSubs(clsPtr, tmpClsPtr);
1045 TclOODecrRefCount(tmpClsPtr->thisPtr);
1046 }
1047 ckfree(clsPtr->mixins.list);
1048 clsPtr->mixins.list = NULL;
1049 clsPtr->mixins.num = 0;
1050 }
1051
1052 if (clsPtr->superclasses.num > 0) {
1053 FOREACH(tmpClsPtr, clsPtr->superclasses) {
1054 TclOORemoveFromSubclasses(clsPtr, tmpClsPtr);
1055 TclOODecrRefCount(tmpClsPtr->thisPtr);
1056 }
1057 ckfree(clsPtr->superclasses.list);
1058 clsPtr->superclasses.num = 0;
1059 clsPtr->superclasses.list = NULL;
1060 }
1061
1062 FOREACH_HASH_VALUE(mPtr, &clsPtr->classMethods) {
1063 /* instance gets deleted, so if method remains, reset it there */
1064 if (mPtr->refCount > 1 && mPtr->declaringClassPtr == clsPtr) {
1065 mPtr->declaringClassPtr = NULL;
1066 }
1067 TclOODelMethodRef(mPtr);
1068 }
1069 Tcl_DeleteHashTable(&clsPtr->classMethods);
1070 TclOODelMethodRef(clsPtr->constructorPtr);
1071 TclOODelMethodRef(clsPtr->destructorPtr);
1072
1073 FOREACH(variableObj, clsPtr->variables) {
1074 TclDecrRefCount(variableObj);
1075 }
1076 if (i) {
1077 ckfree(clsPtr->variables.list);
1078 }
1079
1080 if (IsRootClass(oPtr) && !Destructing(fPtr->objectCls->thisPtr)) {
1081 Tcl_DeleteCommandFromToken(interp, fPtr->objectCls->thisPtr->command);
1082 }
1083 }
1084
1085 /*
1086 * ----------------------------------------------------------------------
1087 *
1088 * ObjectNamespaceDeleted --
1089 *
1090 * Callback when the object's namespace is deleted. Used to clean up the
1091 * data structures associated with the object. The complicated bit is
1092 * that this can sometimes happen before the object's command is deleted
1093 * (interpreter teardown is complex!)
1094 *
1095 * ----------------------------------------------------------------------
1096 */
1097
1098 static void
1099 ObjectNamespaceDeleted(
1100 ClientData clientData) /* Pointer to the class whose namespace is
1101 * being deleted. */
1102 {
1103 Object *oPtr = clientData;
1104 Foundation *fPtr = oPtr->fPtr;
1105 FOREACH_HASH_DECLS;
1106 Class *mixinPtr;
1107 Method *mPtr;
1108 Tcl_Obj *filterObj, *variableObj;
1109 Tcl_Interp *interp = fPtr->interp;
1110 int i;
1111
1112 if (Destructing(oPtr)) {
1113 /*
1114 * TODO: Can ObjectNamespaceDeleted ever be called twice? If not,
1115 * this guard could be removed.
1116 */
1117 return;
1118 }
1119
1120 /*
1121 * One rule for the teardown routines is that if an object is in the
1122 * process of being deleted, nothing else may modify its bookkeeping
1123 * records. This is the flag that
1124 */
1125 oPtr->flags |= OBJECT_DESTRUCTING;
1126
1127 /*
1128 * Let the dominoes fall!
1129 */
1130
1131 if (oPtr->classPtr) {
1132 TclOODeleteDescendants(interp, oPtr);
1133 }
1134
1135 /*
1136 * We do not run destructors on the core class objects when the
1137 * interpreter is being deleted; their incestuous nature causes problems
1138 * in that case when the destructor is partially deleted before the uses
1139 * of it have gone. [Bug 2949397]
1140 */
1141
1142 if (!Tcl_InterpDeleted(interp) && !(oPtr->flags & DESTRUCTOR_CALLED)) {
1143 CallContext *contextPtr =
1144 TclOOGetCallContext(oPtr, NULL, DESTRUCTOR, NULL);
1145
1146 oPtr->flags |= DESTRUCTOR_CALLED;
1147 if (contextPtr != NULL) {
1148 int result;
1149 Tcl_InterpState state;
1150
1151 contextPtr->callPtr->flags |= DESTRUCTOR;
1152 contextPtr->skip = 0;
1153 state = Tcl_SaveInterpState(interp, TCL_OK);
1154 result = Tcl_NRCallObjProc(interp, TclOOInvokeContext,
1155 contextPtr, 0, NULL);
1156 if (result != TCL_OK) {
1157 Tcl_BackgroundException(interp, result);
1158 }
1159 Tcl_RestoreInterpState(interp, state);
1160 TclOODeleteContext(contextPtr);
1161 }
1162 }
1163
1164 /*
1165 * Instruct everyone to no longer use any allocated fields of the object.
1166 * Also delete the command that refers to the object at this point (if it
1167 * still exists) because otherwise its pointer to the object points into
1168 * freed memory.
1169 */
1170
1171 if (((Command *) oPtr->command)->flags & CMD_IS_DELETED) {
1172 /*
1173 * Something has already started the command deletion process. We can
1174 * go ahead and clean up the namespace,
1175 */
1176 } else {
1177 /*
1178 * The namespace must have been deleted directly. Delete the command
1179 * as well.
1180 */
1181
1182 Tcl_DeleteCommandFromToken(interp, oPtr->command);
1183 }
1184
1185 if (oPtr->myCommand) {
1186 Tcl_DeleteCommandFromToken(interp, oPtr->myCommand);
1187 }
1188
1189 /*
1190 * Splice the object out of its context. After this, we must *not* call
1191 * methods on the object.
1192 */
1193
1194 /* TODO: Should this be protected with a !IsRoot() condition? */
1195 TclOORemoveFromInstances(oPtr, oPtr->selfCls);
1196
1197 if (oPtr->mixins.num > 0) {
1198 FOREACH(mixinPtr, oPtr->mixins) {
1199 TclOORemoveFromInstances(oPtr, mixinPtr);
1200 TclOODecrRefCount(mixinPtr->thisPtr);
1201 }
1202 if (oPtr->mixins.list != NULL) {
1203 ckfree(oPtr->mixins.list);
1204 }
1205 }
1206
1207 FOREACH(filterObj, oPtr->filters) {
1208 TclDecrRefCount(filterObj);
1209 }
1210 if (i) {
1211 ckfree(oPtr->filters.list);
1212 }
1213
1214 if (oPtr->methodsPtr) {
1215 FOREACH_HASH_VALUE(mPtr, oPtr->methodsPtr) {
1216 /* instance gets deleted, so if method remains, reset it there */
1217 if (mPtr->refCount > 1 && mPtr->declaringObjectPtr == oPtr) {
1218 mPtr->declaringObjectPtr = NULL;
1219 }
1220 TclOODelMethodRef(mPtr);
1221 }
1222 Tcl_DeleteHashTable(oPtr->methodsPtr);
1223 ckfree(oPtr->methodsPtr);
1224 }
1225
1226 FOREACH(variableObj, oPtr->variables) {
1227 TclDecrRefCount(variableObj);
1228 }
1229 if (i) {
1230 ckfree(oPtr->variables.list);
1231 }
1232
1233 if (oPtr->chainCache) {
1234 TclOODeleteChainCache(oPtr->chainCache);
1235 }
1236
1237 SquelchCachedName(oPtr);
1238
1239 if (oPtr->metadataPtr != NULL) {
1240 Tcl_ObjectMetadataType *metadataTypePtr;
1241 ClientData value;
1242
1243 FOREACH_HASH(metadataTypePtr, value, oPtr->metadataPtr) {
1244 metadataTypePtr->deleteProc(value);
1245 }
1246 Tcl_DeleteHashTable(oPtr->metadataPtr);
1247 ckfree(oPtr->metadataPtr);
1248 oPtr->metadataPtr = NULL;
1249 }
1250
1251 /*
1252 * Because an object can be a class that is an instance of itself, the
1253 * class object's class structure should only be cleaned after most of
1254 * the cleanup on the object is done.
1255 *
1256 * The class of objects needs some special care; if it is deleted (and
1257 * we're not killing the whole interpreter) we force the delete of the
1258 * class of classes now as well. Due to the incestuous nature of those two
1259 * classes, if one goes the other must too and yet the tangle can
1260 * sometimes not go away automatically; we force it here. [Bug 2962664]
1261 */
1262
1263 if (IsRootObject(oPtr) && !Destructing(fPtr->classCls->thisPtr)
1264 && !Tcl_InterpDeleted(interp)) {
1265 Tcl_DeleteCommandFromToken(interp, fPtr->classCls->thisPtr->command);
1266 }
1267
1268 if (oPtr->classPtr != NULL) {
1269 TclOOReleaseClassContents(interp, oPtr);
1270 }
1271
1272 /*
1273 * Delete the object structure itself.
1274 */
1275
1276 TclNsDecrRefCount((Namespace *)oPtr->namespacePtr);
1277 oPtr->namespacePtr = NULL;
1278 TclOODecrRefCount(oPtr->selfCls->thisPtr);
1279 oPtr->selfCls = NULL;
1280 TclOODecrRefCount(oPtr);
1281 return;
1282 }
1283
1284 /*
1285 * ----------------------------------------------------------------------
1286 *
1287 * TclOODecrRef --
1288 *
1289 * Decrement the refcount of an object and deallocate storage then object
1290 * is no longer referenced. Returns 1 if storage was deallocated, and 0
1291 * otherwise.
1292 *
1293 * ----------------------------------------------------------------------
1294 */
1295 int TclOODecrRefCount(Object *oPtr) {
1296 if (oPtr->refCount-- <= 1) {
1297 if (oPtr->classPtr != NULL) {
1298 ckfree(oPtr->classPtr);
1299 }
1300 ckfree(oPtr);
1301 return 1;
1302 }
1303 return 0;
1304 }
1305
1306 /*
1307 * ----------------------------------------------------------------------
1308 *
1309 * TclOOObjectDestroyed --
1310 *
1311 * Returns TCL_OK if an object is entirely deleted, i.e. the destruction
1312 * sequence has completed.
1313 *
1314 * ----------------------------------------------------------------------
1315 */
1316 int TclOOObjectDestroyed(Object *oPtr) {
1317 return (oPtr->namespacePtr == NULL);
1318 }
1319
1320 /*
1321 * Setting the "empty" location to NULL makes debugging a little easier.
1322 */
1323
1324 #define REMOVEBODY { \
1325 for (; idx < num - 1; idx++) { \
1326 list[idx] = list[idx + 1]; \
1327 } \
1328 list[idx] = NULL; \
1329 return; \
1330 }
1331 void RemoveClass(Class **list, int num, int idx) REMOVEBODY
1332
1333 void RemoveObject(Object **list, int num, int idx) REMOVEBODY
1334
1335 /*
1336 * ----------------------------------------------------------------------
1337 *
1338 * TclOORemoveFromInstances --
1339 *
1340 * Utility function to remove an object from the list of instances within
1341 * a class.
1342 *
1343 * ----------------------------------------------------------------------
1344 */
1345
1346 int
1347 TclOORemoveFromInstances(
1348 Object *oPtr, /* The instance to remove. */
1349 Class *clsPtr) /* The class (possibly) containing the
1350 * reference to the instance. */
1351 {
1352 int i, res = 0;
1353 Object *instPtr;
1354
1355 FOREACH(instPtr, clsPtr->instances) {
1356 if (oPtr == instPtr) {
1357 RemoveItem(Object, clsPtr->instances, i);
1358 TclOODecrRefCount(oPtr);
1359 res++;
1360 break;
1361 }
1362 }
1363 return res;
1364 }
1365
1366 /*
1367 * ----------------------------------------------------------------------
1368 *
1369 * TclOOAddToInstances --
1370 *
1371 * Utility function to add an object to the list of instances within a
1372 * class.
1373 *
1374 * ----------------------------------------------------------------------
1375 */
1376
1377 void
1378 TclOOAddToInstances(
1379 Object *oPtr, /* The instance to add. */
1380 Class *clsPtr) /* The class to add the instance to. It is
1381 * assumed that the class is not already
1382 * present as an instance in the class. */
1383 {
1384 if (clsPtr->instances.num >= clsPtr->instances.size) {
1385 clsPtr->instances.size += ALLOC_CHUNK;
1386 if (clsPtr->instances.size == ALLOC_CHUNK) {
1387 clsPtr->instances.list = ckalloc(sizeof(Object *) * ALLOC_CHUNK);
1388 } else {
1389 clsPtr->instances.list = ckrealloc(clsPtr->instances.list,
1390 sizeof(Object *) * clsPtr->instances.size);
1391 }
1392 }
1393 clsPtr->instances.list[clsPtr->instances.num++] = oPtr;
1394 AddRef(oPtr);
1395 }
1396
1397 /*
1398 * ----------------------------------------------------------------------
1399 *
1400 * TclOORemoveFromMixins --
1401 *
1402 * Utility function to remove a class from the list of mixins within an
1403 * object.
1404 *
1405 * ----------------------------------------------------------------------
1406 */
1407
1408 int
1409 TclOORemoveFromMixins(
1410 Class *mixinPtr, /* The mixin to remove. */
1411 Object *oPtr) /* The object (possibly) containing the
1412 * reference to the mixin. */
1413 {
1414 int i, res = 0;
1415 Class *mixPtr;
1416
1417 FOREACH(mixPtr, oPtr->mixins) {
1418 if (mixinPtr == mixPtr) {
1419 RemoveItem(Class, oPtr->mixins, i);
1420 TclOODecrRefCount(mixPtr->thisPtr);
1421 res++;
1422 break;
1423 }
1424 }
1425 if (oPtr->mixins.num == 0) {
1426 ckfree(oPtr->mixins.list);
1427 oPtr->mixins.list = NULL;
1428 }
1429 return res;
1430 }
1431
1432 /*
1433 * ----------------------------------------------------------------------
1434 *
1435 * TclOORemoveFromSubclasses --
1436 *
1437 * Utility function to remove a class from the list of subclasses within
1438 * another class. Returns the number of removals performed.
1439 *
1440 * ----------------------------------------------------------------------
1441 */
1442
1443 int
1444 TclOORemoveFromSubclasses(
1445 Class *subPtr, /* The subclass to remove. */
1446 Class *superPtr) /* The superclass to possibly remove the
1447 * subclass reference from. */
1448 {
1449 int i, res = 0;
1450 Class *subclsPtr;
1451
1452 FOREACH(subclsPtr, superPtr->subclasses) {
1453 if (subPtr == subclsPtr) {
1454 RemoveItem(Class, superPtr->subclasses, i);
1455 TclOODecrRefCount(subPtr->thisPtr);
1456 res++;
1457 }
1458 }
1459 return res;
1460 }
1461
1462 /*
1463 * ----------------------------------------------------------------------
1464 *
1465 * TclOOAddToSubclasses --
1466 *
1467 * Utility function to add a class to the list of subclasses within
1468 * another class.
1469 *
1470 * ----------------------------------------------------------------------
1471 */
1472
1473 void
1474 TclOOAddToSubclasses(
1475 Class *subPtr, /* The subclass to add. */
1476 Class *superPtr) /* The superclass to add the subclass to. It
1477 * is assumed that the class is not already
1478 * present as a subclass in the superclass. */
1479 {
1480 if (Destructing(superPtr->thisPtr)) {
1481 return;
1482 }
1483 if (superPtr->subclasses.num >= superPtr->subclasses.size) {
1484 superPtr->subclasses.size += ALLOC_CHUNK;
1485 if (superPtr->subclasses.size == ALLOC_CHUNK) {
1486 superPtr->subclasses.list = ckalloc(sizeof(Class *) * ALLOC_CHUNK);
1487 } else {
1488 superPtr->subclasses.list = ckrealloc(superPtr->subclasses.list,
1489 sizeof(Class *) * superPtr->subclasses.size);
1490 }
1491 }
1492 superPtr->subclasses.list[superPtr->subclasses.num++] = subPtr;
1493 AddRef(subPtr->thisPtr);
1494 }
1495
1496 /*
1497 * ----------------------------------------------------------------------
1498 *
1499 * TclOORemoveFromMixinSubs --
1500 *
1501 * Utility function to remove a class from the list of mixinSubs within
1502 * another class.
1503 *
1504 * ----------------------------------------------------------------------
1505 */
1506
1507 int
1508 TclOORemoveFromMixinSubs(
1509 Class *subPtr, /* The subclass to remove. */
1510 Class *superPtr) /* The superclass to possibly remove the
1511 * subclass reference from. */
1512 {
1513 int i, res = 0;
1514 Class *subclsPtr;
1515
1516 FOREACH(subclsPtr, superPtr->mixinSubs) {
1517 if (subPtr == subclsPtr) {
1518 RemoveItem(Class, superPtr->mixinSubs, i);
1519 TclOODecrRefCount(subPtr->thisPtr);
1520 res++;
1521 break;
1522 }
1523 }
1524 return res;
1525 }
1526
1527 /*
1528 * ----------------------------------------------------------------------
1529 *
1530 * TclOOAddToMixinSubs --
1531 *
1532 * Utility function to add a class to the list of mixinSubs within
1533 * another class.
1534 *
1535 * ----------------------------------------------------------------------
1536 */
1537
1538 void
1539 TclOOAddToMixinSubs(
1540 Class *subPtr, /* The subclass to add. */
1541 Class *superPtr) /* The superclass to add the subclass to. It
1542 * is assumed that the class is not already
1543 * present as a subclass in the superclass. */
1544 {
1545 if (Destructing(superPtr->thisPtr)) {
1546 return;
1547 }
1548 if (superPtr->mixinSubs.num >= superPtr->mixinSubs.size) {
1549 superPtr->mixinSubs.size += ALLOC_CHUNK;
1550 if (superPtr->mixinSubs.size == ALLOC_CHUNK) {
1551 superPtr->mixinSubs.list = ckalloc(sizeof(Class *) * ALLOC_CHUNK);
1552 } else {
1553 superPtr->mixinSubs.list = ckrealloc(superPtr->mixinSubs.list,
1554 sizeof(Class *) * superPtr->mixinSubs.size);
1555 }
1556 }
1557 superPtr->mixinSubs.list[superPtr->mixinSubs.num++] = subPtr;
1558 AddRef(subPtr->thisPtr);
1559 }
1560
1561 /*
1562 * ----------------------------------------------------------------------
1563 *
1564 * TclOOAllocClass --
1565 *
1566 * Allocate a basic class. Does not add class to its class's instance
1567 * list.
1568 *
1569 * ----------------------------------------------------------------------
1570 */
1571
1572 Class *
1573 TclOOAllocClass(
1574 Tcl_Interp *interp, /* Interpreter within which to allocate the
1575 * class. */
1576 Object *useThisObj) /* Object that is to act as the class
1577 * representation. */
1578 {
1579 Foundation *fPtr = GetFoundation(interp);
1580 Class *clsPtr = ckalloc(sizeof(Class));
1581
1582 memset(clsPtr, 0, sizeof(Class));
1583 clsPtr->thisPtr = useThisObj;
1584
1585 /*
1586 * Configure the namespace path for the class's object.
1587 */
1588 initClassPath(interp, clsPtr);
1589
1590 /*
1591 * Classes are subclasses of oo::object, i.e. the objects they create are
1592 * objects.
1593 */
1594
1595 clsPtr->superclasses.num = 1;
1596 clsPtr->superclasses.list = ckalloc(sizeof(Class *));
1597 clsPtr->superclasses.list[0] = fPtr->objectCls;
1598 AddRef(fPtr->objectCls->thisPtr);
1599
1600 /*
1601 * Finish connecting the class structure to the object structure.
1602 */
1603
1604 clsPtr->thisPtr->classPtr = clsPtr;
1605
1606 /*
1607 * That's the complicated bit. Now fill in the rest of the non-zero/NULL
1608 * fields.
1609 */
1610
1611 Tcl_InitObjHashTable(&clsPtr->classMethods);
1612 return clsPtr;
1613 }
1614 static void
1615 initClassPath(Tcl_Interp *interp, Class *clsPtr) {
1616 Foundation *fPtr = GetFoundation(interp);
1617 if (fPtr->helpersNs != NULL) {
1618 Tcl_Namespace *path[2];
1619 path[0] = fPtr->helpersNs;
1620 path[1] = fPtr->ooNs;
1621 TclSetNsPath((Namespace *) clsPtr->thisPtr->namespacePtr, 2, path);
1622 } else {
1623 TclSetNsPath((Namespace *) clsPtr->thisPtr->namespacePtr, 1,
1624 &fPtr->ooNs);
1625 }
1626 }
1627
1628 /*
1629 * ----------------------------------------------------------------------
1630 *
1631 * Tcl_NewObjectInstance --
1632 *
1633 * Allocate a new instance of an object.
1634 *
1635 * ----------------------------------------------------------------------
1636 */
1637 Tcl_Object
1638 Tcl_NewObjectInstance(
1639 Tcl_Interp *interp, /* Interpreter context. */
1640 Tcl_Class cls, /* Class to create an instance of. */
1641 const char *nameStr, /* Name of object to create, or NULL to ask
1642 * the code to pick its own unique name. */
1643 const char *nsNameStr, /* Name of namespace to create inside object,
1644 * or NULL to ask the code to pick its own
1645 * unique name. */
1646 int objc, /* Number of arguments. Negative value means
1647 * do not call constructor. */
1648 Tcl_Obj *const *objv, /* Argument list. */
1649 int skip) /* Number of arguments to _not_ pass to the
1650 * constructor. */
1651 {
1652 Class *classPtr = (Class *) cls;
1653 Object *oPtr;
1654 ClientData clientData[4];
1655
1656 oPtr = TclNewObjectInstanceCommon(interp, classPtr, nameStr, nsNameStr);
1657 if (oPtr == NULL) {return NULL;}
1658
1659 /*
1660 * Run constructors, except when objc < 0, which is a special flag case
1661 * used for object cloning only.
1662 */
1663
1664 if (objc >= 0) {
1665 CallContext *contextPtr =
1666 TclOOGetCallContext(oPtr, NULL, CONSTRUCTOR, NULL);
1667
1668 if (contextPtr != NULL) {
1669 int isRoot, result;
1670 Tcl_InterpState state;
1671
1672 state = Tcl_SaveInterpState(interp, TCL_OK);
1673 contextPtr->callPtr->flags |= CONSTRUCTOR;
1674 contextPtr->skip = skip;
1675
1676 /*
1677 * Adjust the ensemble tracking record if necessary. [Bug 3514761]
1678 */
1679
1680 isRoot = TclInitRewriteEnsemble(interp, skip, skip, objv);
1681 result = Tcl_NRCallObjProc(interp, TclOOInvokeContext, contextPtr,
1682 objc, objv);
1683
1684 if (isRoot) {
1685 TclResetRewriteEnsemble(interp, 1);
1686 }
1687
1688 clientData[0] = contextPtr;
1689 clientData[1] = oPtr;
1690 clientData[2] = state;
1691 clientData[3] = &oPtr;
1692
1693 result = FinalizeAlloc(clientData, interp, result);
1694 if (result != TCL_OK) {
1695 return NULL;
1696 }
1697 }
1698 }
1699
1700 return (Tcl_Object) oPtr;
1701 }
1702
1703 int
1704 TclNRNewObjectInstance(
1705 Tcl_Interp *interp, /* Interpreter context. */
1706 Tcl_Class cls, /* Class to create an instance of. */
1707 const char *nameStr, /* Name of object to create, or NULL to ask
1708 * the code to pick its own unique name. */
1709 const char *nsNameStr, /* Name of namespace to create inside object,
1710 * or NULL to ask the code to pick its own
1711 * unique name. */
1712 int objc, /* Number of arguments. Negative value means
1713 * do not call constructor. */
1714 Tcl_Obj *const *objv, /* Argument list. */
1715 int skip, /* Number of arguments to _not_ pass to the
1716 * constructor. */
1717 Tcl_Object *objectPtr) /* Place to write the object reference upon
1718 * successful allocation. */
1719 {
1720 Class *classPtr = (Class *) cls;
1721 CallContext *contextPtr;
1722 Tcl_InterpState state;
1723 Object *oPtr;
1724
1725 oPtr = TclNewObjectInstanceCommon(interp, classPtr, nameStr, nsNameStr);
1726 if (oPtr == NULL) {return TCL_ERROR;}
1727
1728 /*
1729 * Run constructors, except when objc < 0 (a special flag case used for
1730 * object cloning only). If there aren't any constructors, we do nothing.
1731 */
1732
1733 if (objc < 0) {
1734 *objectPtr = (Tcl_Object) oPtr;
1735 return TCL_OK;
1736 }
1737 contextPtr = TclOOGetCallContext(oPtr, NULL, CONSTRUCTOR, NULL);
1738 if (contextPtr == NULL) {
1739 *objectPtr = (Tcl_Object) oPtr;
1740 return TCL_OK;
1741 }
1742
1743 state = Tcl_SaveInterpState(interp, TCL_OK);
1744 contextPtr->callPtr->flags |= CONSTRUCTOR;
1745 contextPtr->skip = skip;
1746
1747 /*
1748 * Adjust the ensemble tracking record if necessary. [Bug 3514761]
1749 */
1750
1751 if (TclInitRewriteEnsemble(interp, skip, skip, objv)) {
1752 TclNRAddCallback(interp, TclClearRootEnsemble, NULL, NULL, NULL, NULL);
1753 }
1754
1755 /*
1756 * Fire off the constructors non-recursively.
1757 */
1758
1759 TclNRAddCallback(interp, FinalizeAlloc, contextPtr, oPtr, state,
1760 objectPtr);
1761 TclPushTailcallPoint(interp);
1762 return TclOOInvokeContext(contextPtr, interp, objc, objv);
1763 }
1764
1765 Object *
1766 TclNewObjectInstanceCommon(
1767 Tcl_Interp *interp,
1768 Class *classPtr,
1769 const char *nameStr,
1770 const char *nsNameStr)
1771 {
1772 Tcl_HashEntry *hPtr;
1773 Foundation *fPtr = GetFoundation(interp);
1774 Object *oPtr;
1775 const char *simpleName = NULL;
1776 Namespace *nsPtr = NULL, *dummy,
1777 *inNsPtr = (Namespace *)TclGetCurrentNamespace(interp);
1778
1779 if (nameStr) {
1780 TclGetNamespaceForQualName(interp, nameStr, inNsPtr,
1781 TCL_CREATE_NS_IF_UNKNOWN, &nsPtr, &dummy, &dummy, &simpleName);
1782
1783 /*
1784 * Disallow creation of an object over an existing command.
1785 */
1786
1787 hPtr = Tcl_FindHashEntry(&nsPtr->cmdTable, simpleName);
1788 if (hPtr) {
1789 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1790 "can't create object \"%s\": command already exists with"
1791 " that name", nameStr));
1792 Tcl_SetErrorCode(interp, "TCL", "OO", "OVERWRITE_OBJECT", (char *)NULL);
1793 return NULL;
1794 }
1795 }
1796
1797 /*
1798 * Create the object.
1799 */
1800
1801 oPtr = AllocObject(interp, simpleName, nsPtr, nsNameStr);
1802 if (oPtr == NULL) {
1803 return NULL;
1804 }
1805 oPtr->selfCls = classPtr;
1806 AddRef(classPtr->thisPtr);
1807 TclOOAddToInstances(oPtr, classPtr);
1808
1809 /*
1810 * Check to see if we're really creating a class. If so, allocate the
1811 * class structure as well.
1812 */
1813
1814 if (TclOOIsReachable(fPtr->classCls, classPtr)) {
1815 /*
1816 * Is a class, so attach a class structure. Note that the
1817 * TclOOAllocClass function splices the structure into the object, so
1818 * we don't have to. Once that's done, we need to repatch the object
1819 * to have the right class since TclOOAllocClass interferes with that.
1820 */
1821
1822 TclOOAllocClass(interp, oPtr);
1823 TclOOAddToSubclasses(oPtr->classPtr, fPtr->objectCls);
1824 } else {
1825 oPtr->classPtr = NULL;
1826 }
1827 return oPtr;
1828 }
1829
1830 static int
1831 FinalizeAlloc(
1832 ClientData data[],
1833 Tcl_Interp *interp,
1834 int result)
1835 {
1836 CallContext *contextPtr = data[0];
1837 Object *oPtr = data[1];
1838 Tcl_InterpState state = data[2];
1839 Tcl_Object *objectPtr = data[3];
1840
1841 /*
1842 * Ensure an error if the object was deleted in the constructor.
1843 * Don't want to lose errors by accident. [Bug 2903011]
1844 */
1845
1846 if (result != TCL_ERROR && Destructing(oPtr)) {
1847 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1848 "object deleted in constructor", -1));
1849 Tcl_SetErrorCode(interp, "TCL", "OO", "STILLBORN", (char *)NULL);
1850 result = TCL_ERROR;
1851 }
1852 if (result != TCL_OK) {
1853 Tcl_DiscardInterpState(state);
1854
1855 /*
1856 * Take care to not delete a deleted object; that would be bad. [Bug
1857 * 2903011] Also take care to make sure that we have the name of the
1858 * command before we delete it. [Bug 9dd1bd7a74]
1859 */
1860
1861 if (!Destructing(oPtr)) {
1862 (void) TclOOObjectName(interp, oPtr);
1863 Tcl_DeleteCommandFromToken(interp, oPtr->command);
1864 }
1865
1866 /*
1867 * This decrements the refcount of oPtr.
1868 */
1869
1870 TclOODeleteContext(contextPtr);
1871 return TCL_ERROR;
1872 }
1873 Tcl_RestoreInterpState(interp, state);
1874 *objectPtr = (Tcl_Object) oPtr;
1875
1876 /*
1877 * This decrements the refcount of oPtr.
1878 */
1879
1880 TclOODeleteContext(contextPtr);
1881 return TCL_OK;
1882 }
1883
1884 /*
1885 * ----------------------------------------------------------------------
1886 *
1887 * Tcl_CopyObjectInstance --
1888 *
1889 * Creates a copy of an object. Does not copy the backing namespace,
1890 * since the correct way to do that (e.g., shallow/deep) depends on the
1891 * object/class's own policies.
1892 *
1893 * ----------------------------------------------------------------------
1894 */
1895
1896 Tcl_Object
1897 Tcl_CopyObjectInstance(
1898 Tcl_Interp *interp,
1899 Tcl_Object sourceObject,
1900 const char *targetName,
1901 const char *targetNamespaceName)
1902 {
1903 Object *oPtr = (Object *) sourceObject, *o2Ptr;
1904 FOREACH_HASH_DECLS;
1905 Method *mPtr;
1906 Class *mixinPtr;
1907 CallContext *contextPtr;
1908 Tcl_Obj *keyPtr, *filterObj, *variableObj, *args[3];
1909 int i, result;
1910
1911 /*
1912 * Sanity check.
1913 */
1914
1915 if (IsRootClass(oPtr)) {
1916 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1917 "may not clone the class of classes", -1));
1918 Tcl_SetErrorCode(interp, "TCL", "OO", "CLONING_CLASS", (char *)NULL);
1919 return NULL;
1920 }
1921
1922 /*
1923 * Build the instance. Note that this does not run any constructors.
1924 */
1925
1926 o2Ptr = (Object *) Tcl_NewObjectInstance(interp,
1927 (Tcl_Class) oPtr->selfCls, targetName, targetNamespaceName, -1,
1928 NULL, -1);
1929 if (o2Ptr == NULL) {
1930 return NULL;
1931 }
1932
1933 /*
1934 * Copy the object-local methods to the new object.
1935 */
1936
1937 if (oPtr->methodsPtr) {
1938 FOREACH_HASH(keyPtr, mPtr, oPtr->methodsPtr) {
1939 if (CloneObjectMethod(interp, o2Ptr, mPtr, keyPtr) != TCL_OK) {
1940 Tcl_DeleteCommandFromToken(interp, o2Ptr->command);
1941 return NULL;
1942 }
1943 }
1944 }
1945
1946 /*
1947 * Copy the object's mixin references to the new object.
1948 */
1949
1950 if (o2Ptr->mixins.num != 0) {
1951 FOREACH(mixinPtr, o2Ptr->mixins) {
1952 if (mixinPtr && mixinPtr != o2Ptr->selfCls) {
1953 TclOORemoveFromInstances(o2Ptr, mixinPtr);
1954 }
1955 TclOODecrRefCount(mixinPtr->thisPtr);
1956 }
1957 ckfree(o2Ptr->mixins.list);
1958 }
1959 DUPLICATE(o2Ptr->mixins, oPtr->mixins, Class *);
1960 FOREACH(mixinPtr, o2Ptr->mixins) {
1961 if (mixinPtr && mixinPtr != o2Ptr->selfCls) {
1962 TclOOAddToInstances(o2Ptr, mixinPtr);
1963 }
1964
1965 /*
1966 * For the reference just created in DUPLICATE.
1967 */
1968
1969 AddRef(mixinPtr->thisPtr);
1970 }
1971
1972 /*
1973 * Copy the object's filter list to the new object.
1974 */
1975
1976 DUPLICATE(o2Ptr->filters, oPtr->filters, Tcl_Obj *);
1977 FOREACH(filterObj, o2Ptr->filters) {
1978 Tcl_IncrRefCount(filterObj);
1979 }
1980
1981 /*
1982 * Copy the object's variable resolution list to the new object.
1983 */
1984
1985 DUPLICATE(o2Ptr->variables, oPtr->variables, Tcl_Obj *);
1986 FOREACH(variableObj, o2Ptr->variables) {
1987 Tcl_IncrRefCount(variableObj);
1988 }
1989
1990 /*
1991 * Copy the object's flags to the new object, clearing those that must be
1992 * kept object-local. The duplicate is never deleted at this point, nor is
1993 * it the root of the object system or in the midst of processing a filter
1994 * call.
1995 */
1996
1997 o2Ptr->flags = oPtr->flags & ~(
1998 OBJECT_DESTRUCTING | ROOT_OBJECT | ROOT_CLASS | FILTER_HANDLING);
1999
2000 /*
2001 * Copy the object's metadata.
2002 */
2003
2004 if (oPtr->metadataPtr != NULL) {
2005 Tcl_ObjectMetadataType *metadataTypePtr;
2006 ClientData value, duplicate;
2007
2008 FOREACH_HASH(metadataTypePtr, value, oPtr->metadataPtr) {
2009 if (metadataTypePtr->cloneProc == NULL) {
2010 duplicate = value;
2011 } else {
2012 if (metadataTypePtr->cloneProc(interp, value,
2013 &duplicate) != TCL_OK) {
2014 Tcl_DeleteCommandFromToken(interp, o2Ptr->command);
2015 return NULL;
2016 }
2017 }
2018 if (duplicate != NULL) {
2019 Tcl_ObjectSetMetadata((Tcl_Object) o2Ptr, metadataTypePtr,
2020 duplicate);
2021 }
2022 }
2023 }
2024
2025 /*
2026 * Copy the class, if present. Note that if there is a class present in
2027 * the source object, there must also be one in the copy.
2028 */
2029
2030 if (oPtr->classPtr != NULL) {
2031 Class *clsPtr = oPtr->classPtr;
2032 Class *cls2Ptr = o2Ptr->classPtr;
2033 Class *superPtr;
2034
2035 /*
2036 * Copy the class flags across.
2037 */
2038
2039 cls2Ptr->flags = clsPtr->flags;
2040
2041 /*
2042 * Ensure that the new class's superclass structure is the same as the
2043 * old class's.
2044 */
2045
2046 FOREACH(superPtr, cls2Ptr->superclasses) {
2047 TclOORemoveFromSubclasses(cls2Ptr, superPtr);
2048 TclOODecrRefCount(superPtr->thisPtr);
2049 }
2050 if (cls2Ptr->superclasses.num) {
2051 cls2Ptr->superclasses.list = ckrealloc(cls2Ptr->superclasses.list,
2052 sizeof(Class *) * clsPtr->superclasses.num);
2053 } else {
2054 cls2Ptr->superclasses.list =
2055 ckalloc(sizeof(Class *) * clsPtr->superclasses.num);
2056 }
2057 memcpy(cls2Ptr->superclasses.list, clsPtr->superclasses.list,
2058 sizeof(Class *) * clsPtr->superclasses.num);
2059 cls2Ptr->superclasses.num = clsPtr->superclasses.num;
2060 FOREACH(superPtr, cls2Ptr->superclasses) {
2061 TclOOAddToSubclasses(cls2Ptr, superPtr);
2062
2063 /*
2064 * For the new item in cls2Ptr->superclasses that memcpy just
2065 * created.
2066 */
2067
2068 AddRef(superPtr->thisPtr);
2069 }
2070
2071 /*
2072 * Duplicate the source class's filters.
2073 */
2074
2075 DUPLICATE(cls2Ptr->filters, clsPtr->filters, Tcl_Obj *);
2076 FOREACH(filterObj, cls2Ptr->filters) {
2077 Tcl_IncrRefCount(filterObj);
2078 }
2079
2080 /*
2081 * Copy the source class's variable resolution list.
2082 */
2083
2084 DUPLICATE(cls2Ptr->variables, clsPtr->variables, Tcl_Obj *);
2085 FOREACH(variableObj, cls2Ptr->variables) {
2086 Tcl_IncrRefCount(variableObj);
2087 }
2088
2089 /*
2090 * Duplicate the source class's mixins (which cannot be circular
2091 * references to the duplicate).
2092 */
2093
2094 if (cls2Ptr->mixins.num != 0) {
2095 FOREACH(mixinPtr, cls2Ptr->mixins) {
2096 TclOORemoveFromMixinSubs(cls2Ptr, mixinPtr);
2097 TclOODecrRefCount(mixinPtr->thisPtr);
2098 }
2099 ckfree(clsPtr->mixins.list);
2100 }
2101 DUPLICATE(cls2Ptr->mixins, clsPtr->mixins, Class *);
2102 FOREACH(mixinPtr, cls2Ptr->mixins) {
2103 TclOOAddToMixinSubs(cls2Ptr, mixinPtr);
2104
2105 /*
2106 * For the copy just created in DUPLICATE.
2107 */
2108
2109 AddRef(mixinPtr->thisPtr);
2110 }
2111
2112 /*
2113 * Duplicate the source class's methods, constructor and destructor.
2114 */
2115
2116 FOREACH_HASH(keyPtr, mPtr, &clsPtr->classMethods) {
2117 if (CloneClassMethod(interp, cls2Ptr, mPtr, keyPtr,
2118 NULL) != TCL_OK) {
2119 Tcl_DeleteCommandFromToken(interp, o2Ptr->command);
2120 return NULL;
2121 }
2122 }
2123 if (clsPtr->constructorPtr) {
2124 if (CloneClassMethod(interp, cls2Ptr, clsPtr->constructorPtr,
2125 NULL, &cls2Ptr->constructorPtr) != TCL_OK) {
2126 Tcl_DeleteCommandFromToken(interp, o2Ptr->command);
2127 return NULL;
2128 }
2129 }
2130 if (clsPtr->destructorPtr) {
2131 if (CloneClassMethod(interp, cls2Ptr, clsPtr->destructorPtr, NULL,
2132 &cls2Ptr->destructorPtr) != TCL_OK) {
2133 Tcl_DeleteCommandFromToken(interp, o2Ptr->command);
2134 return NULL;
2135 }
2136 }
2137
2138 /*
2139 * Duplicate the class's metadata.
2140 */
2141
2142 if (clsPtr->metadataPtr != NULL) {
2143 Tcl_ObjectMetadataType *metadataTypePtr;
2144 ClientData value, duplicate;
2145
2146 FOREACH_HASH(metadataTypePtr, value, clsPtr->metadataPtr) {
2147 if (metadataTypePtr->cloneProc == NULL) {
2148 duplicate = value;
2149 } else {
2150 if (metadataTypePtr->cloneProc(interp, value,
2151 &duplicate) != TCL_OK) {
2152 Tcl_DeleteCommandFromToken(interp, o2Ptr->command);
2153 return NULL;
2154 }
2155 }
2156 if (duplicate != NULL) {
2157 Tcl_ClassSetMetadata((Tcl_Class) cls2Ptr, metadataTypePtr,
2158 duplicate);
2159 }
2160 }
2161 }
2162 }
2163
2164 TclResetRewriteEnsemble(interp, 1);
2165 contextPtr = TclOOGetCallContext(o2Ptr, oPtr->fPtr->clonedName, 0, NULL);
2166 if (contextPtr) {
2167 args[0] = TclOOObjectName(interp, o2Ptr);
2168 args[1] = oPtr->fPtr->clonedName;
2169 args[2] = TclOOObjectName(interp, oPtr);
2170 Tcl_IncrRefCount(args[0]);
2171 Tcl_IncrRefCount(args[1]);
2172 Tcl_IncrRefCount(args[2]);
2173 result = Tcl_NRCallObjProc(interp, TclOOInvokeContext, contextPtr, 3,
2174 args);
2175 TclDecrRefCount(args[0]);
2176 TclDecrRefCount(args[1]);
2177 TclDecrRefCount(args[2]);
2178 TclOODeleteContext(contextPtr);
2179 if (result == TCL_ERROR) {
2180 Tcl_AddErrorInfo(interp,
2181 "\n (while performing post-copy callback)");
2182 }
2183 if (result != TCL_OK) {
2184 Tcl_DeleteCommandFromToken(interp, o2Ptr->command);
2185 return NULL;
2186 }
2187 }
2188
2189 return (Tcl_Object) o2Ptr;
2190 }
2191
2192 /*
2193 * ----------------------------------------------------------------------
2194 *
2195 * CloneObjectMethod, CloneClassMethod --
2196 *
2197 * Helper functions used for cloning methods. They work identically to
2198 * each other, except for the difference between them in how they
2199 * register the cloned method on a successful clone.
2200 *
2201 * ----------------------------------------------------------------------
2202 */
2203
2204 static int
2205 CloneObjectMethod(
2206 Tcl_Interp *interp,
2207 Object *oPtr,
2208 Method *mPtr,
2209 Tcl_Obj *namePtr)
2210 {
2211 if (mPtr->typePtr == NULL) {
2212 Tcl_NewInstanceMethod(interp, (Tcl_Object) oPtr, namePtr,
2213 mPtr->flags & PUBLIC_METHOD, NULL, NULL);
2214 } else if (mPtr->typePtr->cloneProc) {
2215 ClientData newClientData;
2216
2217 if (mPtr->typePtr->cloneProc(interp, mPtr->clientData,
2218 &newClientData) != TCL_OK) {
2219 return TCL_ERROR;
2220 }
2221 Tcl_NewInstanceMethod(interp, (Tcl_Object) oPtr, namePtr,
2222 mPtr->flags & PUBLIC_METHOD, mPtr->typePtr, newClientData);
2223 } else {
2224 Tcl_NewInstanceMethod(interp, (Tcl_Object) oPtr, namePtr,
2225 mPtr->flags & PUBLIC_METHOD, mPtr->typePtr, mPtr->clientData);
2226 }
2227 return TCL_OK;
2228 }
2229
2230 static int
2231 CloneClassMethod(
2232 Tcl_Interp *interp,
2233 Class *clsPtr,
2234 Method *mPtr,
2235 Tcl_Obj *namePtr,
2236 Method **m2PtrPtr)
2237 {
2238 Method *m2Ptr;
2239
2240 if (mPtr->typePtr == NULL) {
2241 m2Ptr = (Method *) Tcl_NewMethod(interp, (Tcl_Class) clsPtr,
2242 namePtr, mPtr->flags & PUBLIC_METHOD, NULL, NULL);
2243 } else if (mPtr->typePtr->cloneProc) {
2244 ClientData newClientData;
2245
2246 if (mPtr->typePtr->cloneProc(interp, mPtr->clientData,
2247 &newClientData) != TCL_OK) {
2248 return TCL_ERROR;
2249 }
2250 m2Ptr = (Method *) Tcl_NewMethod(interp, (Tcl_Class) clsPtr,
2251 namePtr, mPtr->flags & PUBLIC_METHOD, mPtr->typePtr,
2252 newClientData);
2253 } else {
2254 m2Ptr = (Method *) Tcl_NewMethod(interp, (Tcl_Class) clsPtr,
2255 namePtr, mPtr->flags & PUBLIC_METHOD, mPtr->typePtr,
2256 mPtr->clientData);
2257 }
2258 if (m2PtrPtr != NULL) {
2259 *m2PtrPtr = m2Ptr;
2260 }
2261 return TCL_OK;
2262 }
2263
2264 /*
2265 * ----------------------------------------------------------------------
2266 *
2267 * Tcl_ClassGetMetadata, Tcl_ClassSetMetadata, Tcl_ObjectGetMetadata,
2268 * Tcl_ObjectSetMetadata --
2269 *
2270 * Metadata management API. The metadata system allows code in extensions
2271 * to attach arbitrary non-NULL pointers to objects and classes without
2272 * the different things that might be interested being able to interfere
2273 * with each other. Apart from non-NULL-ness, these routines attach no
2274 * interpretation to the meaning of the metadata pointers.
2275 *
2276 * The Tcl_*GetMetadata routines get the metadata pointer attached that
2277 * has been related with a particular type, or NULL if no metadata
2278 * associated with the given type has been attached.
2279 *
2280 * The Tcl_*SetMetadata routines set or delete the metadata pointer that
2281 * is related to a particular type. The value associated with the type is
2282 * deleted (if present; no-op otherwise) if the value is NULL, and
2283 * attached (replacing the previous value, which is deleted if present)
2284 * otherwise. This means it is impossible to attach a NULL value for any
2285 * metadata type.
2286 *
2287 * ----------------------------------------------------------------------
2288 */
2289
2290 ClientData
2291 Tcl_ClassGetMetadata(
2292 Tcl_Class clazz,
2293 const Tcl_ObjectMetadataType *typePtr)
2294 {
2295 Class *clsPtr = (Class *) clazz;
2296 Tcl_HashEntry *hPtr;
2297
2298 /*
2299 * If there's no metadata store attached, the type in question has
2300 * definitely not been attached either!
2301 */
2302
2303 if (clsPtr->metadataPtr == NULL) {
2304 return NULL;
2305 }
2306
2307 /*
2308 * There is a metadata store, so look in it for the given type.
2309 */
2310
2311 hPtr = Tcl_FindHashEntry(clsPtr->metadataPtr, (char *) typePtr);
2312
2313 /*
2314 * Return the metadata value if we found it, otherwise NULL.
2315 */
2316
2317 if (hPtr == NULL) {
2318 return NULL;
2319 }
2320 return Tcl_GetHashValue(hPtr);
2321 }
2322
2323 void
2324 Tcl_ClassSetMetadata(
2325 Tcl_Class clazz,
2326 const Tcl_ObjectMetadataType *typePtr,
2327 ClientData metadata)
2328 {
2329 Class *clsPtr = (Class *) clazz;
2330 Tcl_HashEntry *hPtr;
2331 int isNew;
2332
2333 /*
2334 * Attach the metadata store if not done already.
2335 */
2336
2337 if (clsPtr->metadataPtr == NULL) {
2338 if (metadata == NULL) {
2339 return;
2340 }
2341 clsPtr->metadataPtr = ckalloc(sizeof(Tcl_HashTable));
2342 Tcl_InitHashTable(clsPtr->metadataPtr, TCL_ONE_WORD_KEYS);
2343 }
2344
2345 /*
2346 * If the metadata is NULL, we're deleting the metadata for the type.
2347 */
2348
2349 if (metadata == NULL) {
2350 hPtr = Tcl_FindHashEntry(clsPtr->metadataPtr, (char *) typePtr);
2351 if (hPtr != NULL) {
2352 typePtr->deleteProc(Tcl_GetHashValue(hPtr));
2353 Tcl_DeleteHashEntry(hPtr);
2354 }
2355 return;
2356 }
2357
2358 /*
2359 * Otherwise we're attaching the metadata. Note that if there was already
2360 * some metadata attached of this type, we delete that first.
2361 */
2362
2363 hPtr = Tcl_CreateHashEntry(clsPtr->metadataPtr, (char *) typePtr, &isNew);
2364 if (!isNew) {
2365 typePtr->deleteProc(Tcl_GetHashValue(hPtr));
2366 }
2367 Tcl_SetHashValue(hPtr, metadata);
2368 }
2369
2370 ClientData
2371 Tcl_ObjectGetMetadata(
2372 Tcl_Object object,
2373 const Tcl_ObjectMetadataType *typePtr)
2374 {
2375 Object *oPtr = (Object *) object;
2376 Tcl_HashEntry *hPtr;
2377
2378 /*
2379 * If there's no metadata store attached, the type in question has
2380 * definitely not been attached either!
2381 */
2382
2383 if (oPtr->metadataPtr == NULL) {
2384 return NULL;
2385 }
2386
2387 /*
2388 * There is a metadata store, so look in it for the given type.
2389 */
2390
2391 hPtr = Tcl_FindHashEntry(oPtr->metadataPtr, (char *) typePtr);
2392
2393 /*
2394 * Return the metadata value if we found it, otherwise NULL.
2395 */
2396
2397 if (hPtr == NULL) {
2398 return NULL;
2399 }
2400 return Tcl_GetHashValue(hPtr);
2401 }
2402
2403 void
2404 Tcl_ObjectSetMetadata(
2405 Tcl_Object object,
2406 const Tcl_ObjectMetadataType *typePtr,
2407 ClientData metadata)
2408 {
2409 Object *oPtr = (Object *) object;
2410 Tcl_HashEntry *hPtr;
2411 int isNew;
2412
2413 /*
2414 * Attach the metadata store if not done already.
2415 */
2416
2417 if (oPtr->metadataPtr == NULL) {
2418 if (metadata == NULL) {
2419 return;
2420 }
2421 oPtr->metadataPtr = ckalloc(sizeof(Tcl_HashTable));
2422 Tcl_InitHashTable(oPtr->metadataPtr, TCL_ONE_WORD_KEYS);
2423 }
2424
2425 /*
2426 * If the metadata is NULL, we're deleting the metadata for the type.
2427 */
2428
2429 if (metadata == NULL) {
2430 hPtr = Tcl_FindHashEntry(oPtr->metadataPtr, (char *) typePtr);
2431 if (hPtr != NULL) {
2432 typePtr->deleteProc(Tcl_GetHashValue(hPtr));
2433 Tcl_DeleteHashEntry(hPtr);
2434 }
2435 return;
2436 }
2437
2438 /*
2439 * Otherwise we're attaching the metadata. Note that if there was already
2440 * some metadata attached of this type, we delete that first.
2441 */
2442
2443 hPtr = Tcl_CreateHashEntry(oPtr->metadataPtr, (char *) typePtr, &isNew);
2444 if (!isNew) {
2445 typePtr->deleteProc(Tcl_GetHashValue(hPtr));
2446 }
2447 Tcl_SetHashValue(hPtr, metadata);
2448 }
2449
2450 /*
2451 * ----------------------------------------------------------------------
2452 *
2453 * PublicObjectCmd, PrivateObjectCmd, TclOOInvokeObject --
2454 *
2455 * Main entry point for object invocations. The Public* and Private*
2456 * wrapper functions (implementations of both object instance commands
2457 * and [my]) are just thin wrappers round the main TclOOObjectCmdCore
2458 * function. Note that the core is function is NRE-aware.
2459 *
2460 * ----------------------------------------------------------------------
2461 */
2462
2463 static int
2464 PublicObjectCmd(
2465 ClientData clientData,
2466 Tcl_Interp *interp,
2467 int objc,
2468 Tcl_Obj *const *objv)
2469 {
2470 return Tcl_NRCallObjProc(interp, PublicNRObjectCmd, clientData,objc,objv);
2471 }
2472
2473 static int
2474 PublicNRObjectCmd(
2475 ClientData clientData,
2476 Tcl_Interp *interp,
2477 int objc,
2478 Tcl_Obj *const *objv)
2479 {
2480 return TclOOObjectCmdCore(clientData, interp, objc, objv, PUBLIC_METHOD,
2481 NULL);
2482 }
2483
2484 static int
2485 PrivateObjectCmd(
2486 ClientData clientData,
2487 Tcl_Interp *interp,
2488 int objc,
2489 Tcl_Obj *const *objv)
2490 {
2491 return Tcl_NRCallObjProc(interp, PrivateNRObjectCmd,clientData,objc,objv);
2492 }
2493
2494 static int
2495 PrivateNRObjectCmd(
2496 ClientData clientData,
2497 Tcl_Interp *interp,
2498 int objc,
2499 Tcl_Obj *const *objv)
2500 {
2501 return TclOOObjectCmdCore(clientData, interp, objc, objv, 0, NULL);
2502 }
2503
2504 int
2505 TclOOInvokeObject(
2506 Tcl_Interp *interp, /* Interpreter for commands, variables,
2507 * results, error reporting, etc. */
2508 Tcl_Object object, /* The object to invoke. */
2509 Tcl_Class startCls, /* Where in the class chain to start the
2510 * invoke from, or NULL to traverse the whole
2511 * chain including filters. */
2512 int publicPrivate, /* Whether this is an invoke from a public
2513 * context (PUBLIC_METHOD), a private context
2514 * (PRIVATE_METHOD), or a *really* private
2515 * context (any other value; conventionally
2516 * 0). */
2517 int objc, /* Number of arguments. */
2518 Tcl_Obj *const *objv) /* Array of argument objects. It is assumed
2519 * that the name of the method to invoke will
2520 * be at index 1. */
2521 {
2522 switch (publicPrivate) {
2523 case PUBLIC_METHOD:
2524 return TclOOObjectCmdCore((Object *) object, interp, objc, objv,
2525 PUBLIC_METHOD, (Class *) startCls);
2526 case PRIVATE_METHOD:
2527 return TclOOObjectCmdCore((Object *) object, interp, objc, objv,
2528 PRIVATE_METHOD, (Class *) startCls);
2529 default:
2530 return TclOOObjectCmdCore((Object *) object, interp, objc, objv, 0,
2531 (Class *) startCls);
2532 }
2533 }
2534
2535 /*
2536 * ----------------------------------------------------------------------
2537 *
2538 * TclOOObjectCmdCore, FinalizeObjectCall --
2539 *
2540 * Main function for object invocations. Does call chain creation,
2541 * management and invocation. The function FinalizeObjectCall exists to
2542 * clean up after the non-recursive processing of TclOOObjectCmdCore.
2543 *
2544 * ----------------------------------------------------------------------
2545 */
2546
2547 int
2548 TclOOObjectCmdCore(
2549 Object *oPtr, /* The object being invoked. */
2550 Tcl_Interp *interp, /* The interpreter containing the object. */
2551 int objc, /* How many arguments are being passed in. */
2552 Tcl_Obj *const *objv, /* The array of arguments. */
2553 int flags, /* Whether this is an invocation through the
2554 * public or the private command interface. */
2555 Class *startCls) /* Where to start in the call chain, or NULL
2556 * if we are to start at the front with
2557 * filters and the object's methods (which is
2558 * the normal case). */
2559 {
2560 CallContext *contextPtr;
2561 Tcl_Obj *methodNamePtr;
2562 int result;
2563
2564 /*
2565 * If we've no method name, throw this directly into the unknown
2566 * processing.
2567 */
2568
2569 if (objc < 2) {
2570 flags |= FORCE_UNKNOWN;
2571 methodNamePtr = NULL;
2572 goto noMapping;
2573 }
2574
2575 /*
2576 * Give plugged in code a chance to remap the method name.
2577 */
2578
2579 methodNamePtr = objv[1];
2580 if (oPtr->mapMethodNameProc != NULL) {
2581 Class **startClsPtr = &startCls;
2582 Tcl_Obj *mappedMethodName = Tcl_DuplicateObj(methodNamePtr);
2583
2584 result = oPtr->mapMethodNameProc(interp, (Tcl_Object) oPtr,
2585 (Tcl_Class *) startClsPtr, mappedMethodName);
2586 if (result != TCL_OK) {
2587 TclDecrRefCount(mappedMethodName);
2588 if (result == TCL_BREAK) {
2589 goto noMapping;
2590 } else if (result == TCL_ERROR) {
2591 Tcl_AddErrorInfo(interp, "\n (while mapping method name)");
2592 }
2593 return result;
2594 }
2595
2596 /*
2597 * Get the call chain for the remapped name.
2598 */
2599
2600 Tcl_IncrRefCount(mappedMethodName);
2601 contextPtr = TclOOGetCallContext(oPtr, mappedMethodName,
2602 flags | (oPtr->flags & FILTER_HANDLING), methodNamePtr);
2603 TclDecrRefCount(mappedMethodName);
2604 if (contextPtr == NULL) {
2605 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2606 "impossible to invoke method \"%s\": no defined method or"
2607 " unknown method", TclGetString(methodNamePtr)));
2608 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "METHOD_MAPPED",
2609 TclGetString(methodNamePtr), (char *)NULL);
2610 return TCL_ERROR;
2611 }
2612 } else {
2613 /*
2614 * Get the call chain.
2615 */
2616
2617 noMapping:
2618 contextPtr = TclOOGetCallContext(oPtr, methodNamePtr,
2619 flags | (oPtr->flags & FILTER_HANDLING), NULL);
2620 if (contextPtr == NULL) {
2621 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2622 "impossible to invoke method \"%s\": no defined method or"
2623 " unknown method", TclGetString(methodNamePtr)));
2624 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "METHOD",
2625 TclGetString(methodNamePtr), (char *)NULL);
2626 return TCL_ERROR;
2627 }
2628 }
2629
2630 /*
2631 * Check to see if we need to apply magical tricks to start part way
2632 * through the call chain.
2633 */
2634
2635 if (startCls != NULL) {
2636 for (; contextPtr->index < contextPtr->callPtr->numChain;
2637 contextPtr->index++) {
2638 struct MInvoke *miPtr =
2639 &contextPtr->callPtr->chain[contextPtr->index];
2640
2641 if (miPtr->isFilter) {
2642 continue;
2643 }
2644 if (miPtr->mPtr->declaringClassPtr == startCls) {
2645 break;
2646 }
2647 }
2648 if (contextPtr->index >= contextPtr->callPtr->numChain) {
2649 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2650 "no valid method implementation", -1));
2651 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "METHOD",
2652 TclGetString(methodNamePtr), (char *)NULL);
2653 TclOODeleteContext(contextPtr);
2654 return TCL_ERROR;
2655 }
2656 }
2657
2658 /*
2659 * Invoke the call chain, locking the object structure against deletion
2660 * for the duration.
2661 */
2662
2663 TclNRAddCallback(interp, FinalizeObjectCall, contextPtr, NULL,NULL,NULL);
2664 return TclOOInvokeContext(contextPtr, interp, objc, objv);
2665 }
2666
2667 static int
2668 FinalizeObjectCall(
2669 ClientData data[],
2670 Tcl_Interp *interp,
2671 int result)
2672 {
2673 /*
2674 * Dispose of the call chain, which drops the lock on the object's
2675 * structure.
2676 */
2677
2678 TclOODeleteContext(data[0]);
2679 return result;
2680 }
2681
2682 /*
2683 * ----------------------------------------------------------------------
2684 *
2685 * Tcl_ObjectContextInvokeNext, TclNRObjectContextInvokeNext, FinalizeNext --
2686 *
2687 * Invokes the next stage of the call chain described in an object
2688 * context. This is the core of the implementation of the [next] command.
2689 * Does not do management of the call-frame stack. Available in public
2690 * (standard API) and private (NRE-aware) forms. FinalizeNext is a
2691 * private function used to clean up in the NRE case.
2692 *
2693 * ----------------------------------------------------------------------
2694 */
2695
2696 int
2697 Tcl_ObjectContextInvokeNext(
2698 Tcl_Interp *interp,
2699 Tcl_ObjectContext context,
2700 int objc,
2701 Tcl_Obj *const *objv,
2702 int skip)
2703 {
2704 CallContext *contextPtr = (CallContext *) context;
2705 int savedIndex = contextPtr->index;
2706 int savedSkip = contextPtr->skip;
2707 int result;
2708
2709 if (contextPtr->index + 1 >= contextPtr->callPtr->numChain) {
2710 /*
2711 * We're at the end of the chain; generate an error message unless the
2712 * interpreter is being torn down, in which case we might be getting
2713 * here because of methods/destructors doing a [next] (or equivalent)
2714 * unexpectedly.
2715 */
2716
2717 const char *methodType;
2718
2719 if (Tcl_InterpDeleted(interp)) {
2720 return TCL_OK;
2721 }
2722
2723 if (contextPtr->callPtr->flags & CONSTRUCTOR) {
2724 methodType = "constructor";
2725 } else if (contextPtr->callPtr->flags & DESTRUCTOR) {
2726 methodType = "destructor";
2727 } else {
2728 methodType = "method";
2729 }
2730
2731 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2732 "no next %s implementation", methodType));
2733 Tcl_SetErrorCode(interp, "TCL", "OO", "NOTHING_NEXT", (char *)NULL);
2734 return TCL_ERROR;
2735 }
2736
2737 /*
2738 * Advance to the next method implementation in the chain in the method
2739 * call context while we process the body. However, need to adjust the
2740 * argument-skip control because we're guaranteed to have a single prefix
2741 * arg (i.e., 'next') and not the variable amount that can happen because
2742 * method invocations (i.e., '$obj meth' and 'my meth'), constructors
2743 * (i.e., '$cls new' and '$cls create obj') and destructors (no args at
2744 * all) come through the same code.
2745 */
2746
2747 contextPtr->index++;
2748 contextPtr->skip = skip;
2749
2750 /*
2751 * Invoke the (advanced) method call context in the caller context.
2752 */
2753
2754 result = Tcl_NRCallObjProc(interp, TclOOInvokeContext, contextPtr, objc,
2755 objv);
2756
2757 /*
2758 * Restore the call chain context index as we've finished the inner invoke
2759 * and want to operate in the outer context again.
2760 */
2761
2762 contextPtr->index = savedIndex;
2763 contextPtr->skip = savedSkip;
2764
2765 return result;
2766 }
2767
2768 int
2769 TclNRObjectContextInvokeNext(
2770 Tcl_Interp *interp,
2771 Tcl_ObjectContext context,
2772 int objc,
2773 Tcl_Obj *const *objv,
2774 int skip)
2775 {
2776 CallContext *contextPtr = (CallContext *) context;
2777
2778 if (contextPtr->index + 1 >= contextPtr->callPtr->numChain) {
2779 /*
2780 * We're at the end of the chain; generate an error message unless the
2781 * interpreter is being torn down, in which case we might be getting
2782 * here because of methods/destructors doing a [next] (or equivalent)
2783 * unexpectedly.
2784 */
2785
2786 const char *methodType;
2787
2788 if (Tcl_InterpDeleted(interp)) {
2789 return TCL_OK;
2790 }
2791
2792 if (contextPtr->callPtr->flags & CONSTRUCTOR) {
2793 methodType = "constructor";
2794 } else if (contextPtr->callPtr->flags & DESTRUCTOR) {
2795 methodType = "destructor";
2796 } else {
2797 methodType = "method";
2798 }
2799
2800 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2801 "no next %s implementation", methodType));
2802 Tcl_SetErrorCode(interp, "TCL", "OO", "NOTHING_NEXT", (char *)NULL);
2803 return TCL_ERROR;
2804 }
2805
2806 /*
2807 * Advance to the next method implementation in the chain in the method
2808 * call context while we process the body. However, need to adjust the
2809 * argument-skip control because we're guaranteed to have a single prefix
2810 * arg (i.e., 'next') and not the variable amount that can happen because
2811 * method invocations (i.e., '$obj meth' and 'my meth'), constructors
2812 * (i.e., '$cls new' and '$cls create obj') and destructors (no args at
2813 * all) come through the same code.
2814 */
2815
2816 TclNRAddCallback(interp, FinalizeNext, contextPtr,
2817 INT2PTR(contextPtr->index), INT2PTR(contextPtr->skip), NULL);
2818 contextPtr->index++;
2819 contextPtr->skip = skip;
2820
2821 /*
2822 * Invoke the (advanced) method call context in the caller context.
2823 */
2824
2825 return TclOOInvokeContext(contextPtr, interp, objc, objv);
2826 }
2827
2828 static int
2829 FinalizeNext(
2830 ClientData data[],
2831 Tcl_Interp *interp,
2832 int result)
2833 {
2834 CallContext *contextPtr = data[0];
2835
2836 /*
2837 * Restore the call chain context index as we've finished the inner invoke
2838 * and want to operate in the outer context again.
2839 */
2840
2841 contextPtr->index = PTR2INT(data[1]);
2842 contextPtr->skip = PTR2INT(data[2]);
2843 return result;
2844 }
2845
2846 /*
2847 * ----------------------------------------------------------------------
2848 *
2849 * Tcl_GetObjectFromObj --
2850 *
2851 * Utility function to get an object from a Tcl_Obj containing its name.
2852 *
2853 * ----------------------------------------------------------------------
2854 */
2855
2856 Tcl_Object
2857 Tcl_GetObjectFromObj(
2858 Tcl_Interp *interp, /* Interpreter in which to locate the object.
2859 * Will have an error message placed in it if
2860 * the name does not refer to an object. */
2861 Tcl_Obj *objPtr) /* The name of the object to look up, which is
2862 * exactly the name of its public command. */
2863 {
2864 Command *cmdPtr = (Command *) Tcl_GetCommandFromObj(interp, objPtr);
2865
2866 if (cmdPtr == NULL) {
2867 goto notAnObject;
2868 }
2869 if (cmdPtr->objProc != PublicObjectCmd) {
2870 cmdPtr = (Command *) TclGetOriginalCommand((Tcl_Command) cmdPtr);
2871 if (cmdPtr == NULL || cmdPtr->objProc != PublicObjectCmd) {
2872 goto notAnObject;
2873 }
2874 }
2875 return cmdPtr->objClientData;
2876
2877 notAnObject:
2878 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2879 "%s does not refer to an object", TclGetString(objPtr)));
2880 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "OBJECT", TclGetString(objPtr),
2881 (char *)NULL);
2882 return NULL;
2883 }
2884
2885 /*
2886 * ----------------------------------------------------------------------
2887 *
2888 * TclOOIsReachable --
2889 *
2890 * Utility function that tests whether a class is a subclass (whether
2891 * directly or indirectly) of another class.
2892 *
2893 * ----------------------------------------------------------------------
2894 */
2895
2896 int
2897 TclOOIsReachable(
2898 Class *targetPtr,
2899 Class *startPtr)
2900 {
2901 int i;
2902 Class *superPtr;
2903
2904 tailRecurse:
2905 if (startPtr == targetPtr) {
2906 return 1;
2907 }
2908 if (startPtr->superclasses.num == 1 && startPtr->mixins.num == 0) {
2909 startPtr = startPtr->superclasses.list[0];
2910 goto tailRecurse;
2911 }
2912 FOREACH(superPtr, startPtr->superclasses) {
2913 if (TclOOIsReachable(targetPtr, superPtr)) {
2914 return 1;
2915 }
2916 }
2917 FOREACH(superPtr, startPtr->mixins) {
2918 if (TclOOIsReachable(targetPtr, superPtr)) {
2919 return 1;
2920 }
2921 }
2922 return 0;
2923 }
2924
2925 /*
2926 * ----------------------------------------------------------------------
2927 *
2928 * TclOOObjectName, Tcl_GetObjectName --
2929 *
2930 * Utility function that returns the name of the object. Note that this
2931 * simplifies cache management by keeping the code to do it in one place
2932 * and not sprayed all over. The value returned always has a reference
2933 * count of at least one.
2934 *
2935 * ----------------------------------------------------------------------
2936 */
2937
2938 Tcl_Obj *
2939 TclOOObjectName(
2940 Tcl_Interp *interp,
2941 Object *oPtr)
2942 {
2943 Tcl_Obj *namePtr;
2944
2945 if (oPtr->cachedNameObj) {
2946 return oPtr->cachedNameObj;
2947 }
2948 TclNewObj(namePtr);
2949 Tcl_GetCommandFullName(interp, oPtr->command, namePtr);
2950 Tcl_IncrRefCount(namePtr);
2951 oPtr->cachedNameObj = namePtr;
2952 return namePtr;
2953 }
2954
2955 Tcl_Obj *
2956 Tcl_GetObjectName(
2957 Tcl_Interp *interp,
2958 Tcl_Object object)
2959 {
2960 return TclOOObjectName(interp, (Object *) object);
2961 }
2962
2963 /*
2964 * ----------------------------------------------------------------------
2965 *
2966 * assorted trivial 'getter' functions
2967 *
2968 * ----------------------------------------------------------------------
2969 */
2970
2971 Tcl_Method
2972 Tcl_ObjectContextMethod(
2973 Tcl_ObjectContext context)
2974 {
2975 CallContext *contextPtr = (CallContext *) context;
2976 return (Tcl_Method) contextPtr->callPtr->chain[contextPtr->index].mPtr;
2977 }
2978
2979 int
2980 Tcl_ObjectContextIsFiltering(
2981 Tcl_ObjectContext context)
2982 {
2983 CallContext *contextPtr = (CallContext *) context;
2984 return contextPtr->callPtr->chain[contextPtr->index].isFilter;
2985 }
2986
2987 Tcl_Object
2988 Tcl_ObjectContextObject(
2989 Tcl_ObjectContext context)
2990 {
2991 return (Tcl_Object) ((CallContext *)context)->oPtr;
2992 }
2993
2994 int
2995 Tcl_ObjectContextSkippedArgs(
2996 Tcl_ObjectContext context)
2997 {
2998 return ((CallContext *)context)->skip;
2999 }
3000
3001 Tcl_Namespace *
3002 Tcl_GetObjectNamespace(
3003 Tcl_Object object)
3004 {
3005 return ((Object *)object)->namespacePtr;
3006 }
3007
3008 Tcl_Command
3009 Tcl_GetObjectCommand(
3010 Tcl_Object object)
3011 {
3012 return ((Object *)object)->command;
3013 }
3014
3015 Tcl_Class
3016 Tcl_GetObjectAsClass(
3017 Tcl_Object object)
3018 {
3019 return (Tcl_Class) ((Object *)object)->classPtr;
3020 }
3021
3022 int
3023 Tcl_ObjectDeleted(
3024 Tcl_Object object)
3025 {
3026 return ((Object *)object)->command == NULL;
3027 }
3028
3029 Tcl_Object
3030 Tcl_GetClassAsObject(
3031 Tcl_Class clazz)
3032 {
3033 return (Tcl_Object) ((Class *)clazz)->thisPtr;
3034 }
3035
3036 Tcl_ObjectMapMethodNameProc *
3037 Tcl_ObjectGetMethodNameMapper(
3038 Tcl_Object object)
3039 {
3040 return ((Object *) object)->mapMethodNameProc;
3041 }
3042
3043 void
3044 Tcl_ObjectSetMethodNameMapper(
3045 Tcl_Object object,
3046 Tcl_ObjectMapMethodNameProc *mapMethodNameProc)
3047 {
3048 ((Object *) object)->mapMethodNameProc = mapMethodNameProc;
3049 }
3050
3051 /*
3052 * Local Variables:
3053 * mode: c
3054 * c-basic-offset: 4
3055 * fill-column: 78
3056 * End:
3057 */