Debian Codegraph @

pTk/mTk/tclGeneric/tclNamesp.c

raw symbols SCIP
1 /*
2 * tclNamesp.c --
3 *
4 * Contains support for namespaces, which provide a separate context of
5 * commands and global variables. The global :: namespace is the
6 * traditional Tcl "global" scope. Other namespaces are created as
7 * children of the global namespace. These other namespaces contain
8 * special-purpose commands and variables for packages.
9 *
10 * Copyright (c) 1993-1997 Lucent Technologies.
11 * Copyright (c) 1997 Sun Microsystems, Inc.
12 * Copyright (c) 1998-1999 by Scriptics Corporation.
13 *
14 * Originally implemented by
15 * Michael J. McLennan
16 * Bell Labs Innovations for Lucent Technologies
17 * [email protected]
18 *
19 * See the file "license.terms" for information on usage and redistribution
20 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
21 *
22 * RCS: @(#) $Id: tclNamesp.c,v 1.31.2.1 2003/06/18 18:34:19 msofer Exp $
23 */
24
25 #include "tclInt.h"
26
27 /*
28 * Flag passed to TclGetNamespaceForQualName to indicate that it should
29 * search for a namespace rather than a command or variable inside a
30 * namespace. Note that this flag's value must not conflict with the values
31 * of TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY, or CREATE_NS_IF_UNKNOWN.
32 */
33
34 #define FIND_ONLY_NS 0x1000
35
36 /*
37 * Initial size of stack allocated space for tail list - used when resetting
38 * shadowed command references in the functin: TclResetShadowedCmdRefs.
39 */
40
41 #define NUM_TRAIL_ELEMS 5
42
43 /*
44 * Count of the number of namespaces created. This value is used as a
45 * unique id for each namespace.
46 */
47
48 static long numNsCreated = 0;
49 TCL_DECLARE_MUTEX(nsMutex)
50
51 /*
52 * This structure contains a cached pointer to a namespace that is the
53 * result of resolving the namespace's name in some other namespace. It is
54 * the internal representation for a nsName object. It contains the
55 * pointer along with some information that is used to check the cached
56 * pointer's validity.
57 */
58
59 typedef struct ResolvedNsName {
60 Namespace *nsPtr; /* A cached namespace pointer. */
61 long nsId; /* nsPtr's unique namespace id. Used to
62 * verify that nsPtr is still valid
63 * (e.g., it's possible that the namespace
64 * was deleted and a new one created at
65 * the same address). */
66 Namespace *refNsPtr; /* Points to the namespace containing the
67 * reference (not the namespace that
68 * contains the referenced namespace). */
69 int refCount; /* Reference count: 1 for each nsName
70 * object that has a pointer to this
71 * ResolvedNsName structure as its internal
72 * rep. This structure can be freed when
73 * refCount becomes zero. */
74 } ResolvedNsName;
75
76 /*
77 * Declarations for procedures local to this file:
78 */
79
80 static void DeleteImportedCmd _ANSI_ARGS_((
81 ClientData clientData));
82 static void DupNsNameInternalRep _ANSI_ARGS_((Tcl_Obj *objPtr,
83 Tcl_Obj *copyPtr));
84 static void FreeNsNameInternalRep _ANSI_ARGS_((
85 Tcl_Obj *objPtr));
86 static int GetNamespaceFromObj _ANSI_ARGS_((
87 Tcl_Interp *interp, Tcl_Obj *objPtr,
88 Tcl_Namespace **nsPtrPtr));
89 static int InvokeImportedCmd _ANSI_ARGS_((
90 ClientData clientData, Tcl_Interp *interp,
91 int objc, Tcl_Obj *CONST objv[]));
92 static int NamespaceChildrenCmd _ANSI_ARGS_((
93 ClientData dummy, Tcl_Interp *interp,
94 int objc, Tcl_Obj *CONST objv[]));
95 static int NamespaceCodeCmd _ANSI_ARGS_((
96 ClientData dummy, Tcl_Interp *interp,
97 int objc, Tcl_Obj *CONST objv[]));
98 static int NamespaceCurrentCmd _ANSI_ARGS_((
99 ClientData dummy, Tcl_Interp *interp,
100 int objc, Tcl_Obj *CONST objv[]));
101 static int NamespaceDeleteCmd _ANSI_ARGS_((
102 ClientData dummy, Tcl_Interp *interp,
103 int objc, Tcl_Obj *CONST objv[]));
104 static int NamespaceEvalCmd _ANSI_ARGS_((
105 ClientData dummy, Tcl_Interp *interp,
106 int objc, Tcl_Obj *CONST objv[]));
107 static int NamespaceExistsCmd _ANSI_ARGS_((
108 ClientData dummy, Tcl_Interp *interp,
109 int objc, Tcl_Obj *CONST objv[]));
110 static int NamespaceExportCmd _ANSI_ARGS_((
111 ClientData dummy, Tcl_Interp *interp,
112 int objc, Tcl_Obj *CONST objv[]));
113 static int NamespaceForgetCmd _ANSI_ARGS_((
114 ClientData dummy, Tcl_Interp *interp,
115 int objc, Tcl_Obj *CONST objv[]));
116 static void NamespaceFree _ANSI_ARGS_((Namespace *nsPtr));
117 static int NamespaceImportCmd _ANSI_ARGS_((
118 ClientData dummy, Tcl_Interp *interp,
119 int objc, Tcl_Obj *CONST objv[]));
120 static int NamespaceInscopeCmd _ANSI_ARGS_((
121 ClientData dummy, Tcl_Interp *interp,
122 int objc, Tcl_Obj *CONST objv[]));
123 static int NamespaceOriginCmd _ANSI_ARGS_((
124 ClientData dummy, Tcl_Interp *interp,
125 int objc, Tcl_Obj *CONST objv[]));
126 static int NamespaceParentCmd _ANSI_ARGS_((
127 ClientData dummy, Tcl_Interp *interp,
128 int objc, Tcl_Obj *CONST objv[]));
129 static int NamespaceQualifiersCmd _ANSI_ARGS_((
130 ClientData dummy, Tcl_Interp *interp,
131 int objc, Tcl_Obj *CONST objv[]));
132 static int NamespaceTailCmd _ANSI_ARGS_((
133 ClientData dummy, Tcl_Interp *interp,
134 int objc, Tcl_Obj *CONST objv[]));
135 static int NamespaceWhichCmd _ANSI_ARGS_((
136 ClientData dummy, Tcl_Interp *interp,
137 int objc, Tcl_Obj *CONST objv[]));
138 static int SetNsNameFromAny _ANSI_ARGS_((
139 Tcl_Interp *interp, Tcl_Obj *objPtr));
140 static void UpdateStringOfNsName _ANSI_ARGS_((Tcl_Obj *objPtr));
141
142 /*
143 * This structure defines a Tcl object type that contains a
144 * namespace reference. It is used in commands that take the
145 * name of a namespace as an argument. The namespace reference
146 * is resolved, and the result in cached in the object.
147 */
148
149 Tcl_ObjType tclNsNameType = {
150 "nsName", /* the type's name */
151 FreeNsNameInternalRep, /* freeIntRepProc */
152 DupNsNameInternalRep, /* dupIntRepProc */
153 UpdateStringOfNsName, /* updateStringProc */
154 SetNsNameFromAny /* setFromAnyProc */
155 };
156
157 /*
158 *----------------------------------------------------------------------
159 *
160 * TclInitNamespaceSubsystem --
161 *
162 * This procedure is called to initialize all the structures that
163 * are used by namespaces on a per-process basis.
164 *
165 * Results:
166 * None.
167 *
168 * Side effects:
169 * None.
170 *
171 *----------------------------------------------------------------------
172 */
173
174 void
175 TclInitNamespaceSubsystem()
176 {
177 /*
178 * Does nothing for now.
179 */
180 }
181
182 /*
183 *----------------------------------------------------------------------
184 *
185 * Tcl_GetCurrentNamespace --
186 *
187 * Returns a pointer to an interpreter's currently active namespace.
188 *
189 * Results:
190 * Returns a pointer to the interpreter's current namespace.
191 *
192 * Side effects:
193 * None.
194 *
195 *----------------------------------------------------------------------
196 */
197
198 Tcl_Namespace *
199 Tcl_GetCurrentNamespace(interp)
200 register Tcl_Interp *interp; /* Interpreter whose current namespace is
201 * being queried. */
202 {
203 register Interp *iPtr = (Interp *) interp;
204 register Namespace *nsPtr;
205
206 if (iPtr->varFramePtr != NULL) {
207 nsPtr = iPtr->varFramePtr->nsPtr;
208 } else {
209 nsPtr = iPtr->globalNsPtr;
210 }
211 return (Tcl_Namespace *) nsPtr;
212 }
213
214 /*
215 *----------------------------------------------------------------------
216 *
217 * Tcl_GetGlobalNamespace --
218 *
219 * Returns a pointer to an interpreter's global :: namespace.
220 *
221 * Results:
222 * Returns a pointer to the specified interpreter's global namespace.
223 *
224 * Side effects:
225 * None.
226 *
227 *----------------------------------------------------------------------
228 */
229
230 Tcl_Namespace *
231 Tcl_GetGlobalNamespace(interp)
232 register Tcl_Interp *interp; /* Interpreter whose global namespace
233 * should be returned. */
234 {
235 register Interp *iPtr = (Interp *) interp;
236
237 return (Tcl_Namespace *) iPtr->globalNsPtr;
238 }
239
240 /*
241 *----------------------------------------------------------------------
242 *
243 * Tcl_PushCallFrame --
244 *
245 * Pushes a new call frame onto the interpreter's Tcl call stack.
246 * Called when executing a Tcl procedure or a "namespace eval" or
247 * "namespace inscope" command.
248 *
249 * Results:
250 * Returns TCL_OK if successful, or TCL_ERROR (along with an error
251 * message in the interpreter's result object) if something goes wrong.
252 *
253 * Side effects:
254 * Modifies the interpreter's Tcl call stack.
255 *
256 *----------------------------------------------------------------------
257 */
258
259 int
260 Tcl_PushCallFrame(interp, callFramePtr, namespacePtr, isProcCallFrame)
261 Tcl_Interp *interp; /* Interpreter in which the new call frame
262 * is to be pushed. */
263 Tcl_CallFrame *callFramePtr; /* Points to a call frame structure to
264 * push. Storage for this has already been
265 * allocated by the caller; typically this
266 * is the address of a CallFrame structure
267 * allocated on the caller's C stack. The
268 * call frame will be initialized by this
269 * procedure. The caller can pop the frame
270 * later with Tcl_PopCallFrame, and it is
271 * responsible for freeing the frame's
272 * storage. */
273 Tcl_Namespace *namespacePtr; /* Points to the namespace in which the
274 * frame will execute. If NULL, the
275 * interpreter's current namespace will
276 * be used. */
277 int isProcCallFrame; /* If nonzero, the frame represents a
278 * called Tcl procedure and may have local
279 * vars. Vars will ordinarily be looked up
280 * in the frame. If new variables are
281 * created, they will be created in the
282 * frame. If 0, the frame is for a
283 * "namespace eval" or "namespace inscope"
284 * command and var references are treated
285 * as references to namespace variables. */
286 {
287 Interp *iPtr = (Interp *) interp;
288 register CallFrame *framePtr = (CallFrame *) callFramePtr;
289 register Namespace *nsPtr;
290
291 if (namespacePtr == NULL) {
292 nsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
293 } else {
294 nsPtr = (Namespace *) namespacePtr;
295 if (nsPtr->flags & NS_DEAD) {
296 panic("Trying to push call frame for dead namespace");
297 /*NOTREACHED*/
298 }
299 }
300
301 nsPtr->activationCount++;
302 framePtr->nsPtr = nsPtr;
303 framePtr->isProcCallFrame = isProcCallFrame;
304 framePtr->objc = 0;
305 framePtr->objv = NULL;
306 framePtr->callerPtr = iPtr->framePtr;
307 framePtr->callerVarPtr = iPtr->varFramePtr;
308 if (iPtr->varFramePtr != NULL) {
309 framePtr->level = (iPtr->varFramePtr->level + 1);
310 } else {
311 framePtr->level = 1;
312 }
313 framePtr->procPtr = NULL; /* no called procedure */
314 framePtr->varTablePtr = NULL; /* and no local variables */
315 framePtr->numCompiledLocals = 0;
316 framePtr->compiledLocals = NULL;
317
318 /*
319 * Push the new call frame onto the interpreter's stack of procedure
320 * call frames making it the current frame.
321 */
322
323 iPtr->framePtr = framePtr;
324 iPtr->varFramePtr = framePtr;
325 return TCL_OK;
326 }
327
328 /*
329 *----------------------------------------------------------------------
330 *
331 * Tcl_PopCallFrame --
332 *
333 * Removes a call frame from the Tcl call stack for the interpreter.
334 * Called to remove a frame previously pushed by Tcl_PushCallFrame.
335 *
336 * Results:
337 * None.
338 *
339 * Side effects:
340 * Modifies the call stack of the interpreter. Resets various fields of
341 * the popped call frame. If a namespace has been deleted and
342 * has no more activations on the call stack, the namespace is
343 * destroyed.
344 *
345 *----------------------------------------------------------------------
346 */
347
348 void
349 Tcl_PopCallFrame(interp)
350 Tcl_Interp* interp; /* Interpreter with call frame to pop. */
351 {
352 register Interp *iPtr = (Interp *) interp;
353 register CallFrame *framePtr = iPtr->framePtr;
354 int saveErrFlag;
355 Namespace *nsPtr;
356
357 /*
358 * It's important to remove the call frame from the interpreter's stack
359 * of call frames before deleting local variables, so that traces
360 * invoked by the variable deletion don't see the partially-deleted
361 * frame.
362 */
363
364 iPtr->framePtr = framePtr->callerPtr;
365 iPtr->varFramePtr = framePtr->callerVarPtr;
366
367 /*
368 * Delete the local variables. As a hack, we save then restore the
369 * ERR_IN_PROGRESS flag in the interpreter. The problem is that there
370 * could be unset traces on the variables, which cause scripts to be
371 * evaluated. This will clear the ERR_IN_PROGRESS flag, losing stack
372 * trace information if the procedure was exiting with an error. The
373 * code below preserves the flag. Unfortunately, that isn't really
374 * enough: we really should preserve the errorInfo variable too
375 * (otherwise a nested error in the trace script will trash errorInfo).
376 * What's really needed is a general-purpose mechanism for saving and
377 * restoring interpreter state.
378 */
379
380 saveErrFlag = (iPtr->flags & ERR_IN_PROGRESS);
381
382 if (framePtr->varTablePtr != NULL) {
383 TclDeleteVars(iPtr, framePtr->varTablePtr);
384 ckfree((char *) framePtr->varTablePtr);
385 framePtr->varTablePtr = NULL;
386 }
387 if (framePtr->numCompiledLocals > 0) {
388 TclDeleteCompiledLocalVars(iPtr, framePtr);
389 }
390
391 iPtr->flags |= saveErrFlag;
392
393 /*
394 * Decrement the namespace's count of active call frames. If the
395 * namespace is "dying" and there are no more active call frames,
396 * call Tcl_DeleteNamespace to destroy it.
397 */
398
399 nsPtr = framePtr->nsPtr;
400 nsPtr->activationCount--;
401 if ((nsPtr->flags & NS_DYING)
402 && (nsPtr->activationCount == 0)) {
403 Tcl_DeleteNamespace((Tcl_Namespace *) nsPtr);
404 }
405 framePtr->nsPtr = NULL;
406 }
407
408 /*
409 *----------------------------------------------------------------------
410 *
411 * Tcl_CreateNamespace --
412 *
413 * Creates a new namespace with the given name. If there is no
414 * active namespace (i.e., the interpreter is being initialized),
415 * the global :: namespace is created and returned.
416 *
417 * Results:
418 * Returns a pointer to the new namespace if successful. If the
419 * namespace already exists or if another error occurs, this routine
420 * returns NULL, along with an error message in the interpreter's
421 * result object.
422 *
423 * Side effects:
424 * If the name contains "::" qualifiers and a parent namespace does
425 * not already exist, it is automatically created.
426 *
427 *----------------------------------------------------------------------
428 */
429
430 Tcl_Namespace *
431 Tcl_CreateNamespace(interp, name, clientData, deleteProc)
432 Tcl_Interp *interp; /* Interpreter in which a new namespace
433 * is being created. Also used for
434 * error reporting. */
435 CONST char *name; /* Name for the new namespace. May be a
436 * qualified name with names of ancestor
437 * namespaces separated by "::"s. */
438 ClientData clientData; /* One-word value to store with
439 * namespace. */
440 Tcl_NamespaceDeleteProc *deleteProc;
441 /* Procedure called to delete client
442 * data when the namespace is deleted.
443 * NULL if no procedure should be
444 * called. */
445 {
446 Interp *iPtr = (Interp *) interp;
447 register Namespace *nsPtr, *ancestorPtr;
448 Namespace *parentPtr, *dummy1Ptr, *dummy2Ptr;
449 Namespace *globalNsPtr = iPtr->globalNsPtr;
450 CONST char *simpleName;
451 Tcl_HashEntry *entryPtr;
452 Tcl_DString buffer1, buffer2;
453 int newEntry;
454
455 /*
456 * If there is no active namespace, the interpreter is being
457 * initialized.
458 */
459
460 if ((globalNsPtr == NULL) && (iPtr->varFramePtr == NULL)) {
461 /*
462 * Treat this namespace as the global namespace, and avoid
463 * looking for a parent.
464 */
465
466 parentPtr = NULL;
467 simpleName = "";
468 } else if (*name == '\0') {
469 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
470 "can't create namespace \"\": only global namespace can have empty name", (char *) NULL);
471 return NULL;
472 } else {
473 /*
474 * Find the parent for the new namespace.
475 */
476
477 TclGetNamespaceForQualName(interp, name, (Namespace *) NULL,
478 /*flags*/ (CREATE_NS_IF_UNKNOWN | TCL_LEAVE_ERR_MSG),
479 &parentPtr, &dummy1Ptr, &dummy2Ptr, &simpleName);
480
481 /*
482 * If the unqualified name at the end is empty, there were trailing
483 * "::"s after the namespace's name which we ignore. The new
484 * namespace was already (recursively) created and is pointed to
485 * by parentPtr.
486 */
487
488 if (*simpleName == '\0') {
489 return (Tcl_Namespace *) parentPtr;
490 }
491
492 /*
493 * Check for a bad namespace name and make sure that the name
494 * does not already exist in the parent namespace.
495 */
496
497 if (Tcl_FindHashEntry(&parentPtr->childTable, simpleName) != NULL) {
498 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
499 "can't create namespace \"", name,
500 "\": already exists", (char *) NULL);
501 return NULL;
502 }
503 }
504
505 /*
506 * Create the new namespace and root it in its parent. Increment the
507 * count of namespaces created.
508 */
509
510
511 nsPtr = (Namespace *) ckalloc(sizeof(Namespace));
512 nsPtr->name = (char *) ckalloc((unsigned) (strlen(simpleName)+1));
513 strcpy(nsPtr->name, simpleName);
514 nsPtr->fullName = NULL; /* set below */
515 nsPtr->clientData = clientData;
516 nsPtr->deleteProc = deleteProc;
517 nsPtr->parentPtr = parentPtr;
518 Tcl_InitHashTable(&nsPtr->childTable, TCL_STRING_KEYS);
519 Tcl_MutexLock(&nsMutex);
520 numNsCreated++;
521 nsPtr->nsId = numNsCreated;
522 Tcl_MutexUnlock(&nsMutex);
523 nsPtr->interp = interp;
524 nsPtr->flags = 0;
525 nsPtr->activationCount = 0;
526 nsPtr->refCount = 0;
527 Tcl_InitHashTable(&nsPtr->cmdTable, TCL_STRING_KEYS);
528 Tcl_InitHashTable(&nsPtr->varTable, TCL_STRING_KEYS);
529 nsPtr->exportArrayPtr = NULL;
530 nsPtr->numExportPatterns = 0;
531 nsPtr->maxExportPatterns = 0;
532 nsPtr->cmdRefEpoch = 0;
533 nsPtr->resolverEpoch = 0;
534 nsPtr->cmdResProc = NULL;
535 nsPtr->varResProc = NULL;
536 nsPtr->compiledVarResProc = NULL;
537
538 if (parentPtr != NULL) {
539 entryPtr = Tcl_CreateHashEntry(&parentPtr->childTable, simpleName,
540 &newEntry);
541 Tcl_SetHashValue(entryPtr, (ClientData) nsPtr);
542 }
543
544 /*
545 * Build the fully qualified name for this namespace.
546 */
547
548 Tcl_DStringInit(&buffer1);
549 Tcl_DStringInit(&buffer2);
550 for (ancestorPtr = nsPtr; ancestorPtr != NULL;
551 ancestorPtr = ancestorPtr->parentPtr) {
552 if (ancestorPtr != globalNsPtr) {
553 Tcl_DStringAppend(&buffer1, "::", 2);
554 Tcl_DStringAppend(&buffer1, ancestorPtr->name, -1);
555 }
556 Tcl_DStringAppend(&buffer1, Tcl_DStringValue(&buffer2), -1);
557
558 Tcl_DStringSetLength(&buffer2, 0);
559 Tcl_DStringAppend(&buffer2, Tcl_DStringValue(&buffer1), -1);
560 Tcl_DStringSetLength(&buffer1, 0);
561 }
562
563 name = Tcl_DStringValue(&buffer2);
564 nsPtr->fullName = (char *) ckalloc((unsigned) (strlen(name)+1));
565 strcpy(nsPtr->fullName, name);
566
567 Tcl_DStringFree(&buffer1);
568 Tcl_DStringFree(&buffer2);
569
570 /*
571 * Return a pointer to the new namespace.
572 */
573
574 return (Tcl_Namespace *) nsPtr;
575 }
576
577 /*
578 *----------------------------------------------------------------------
579 *
580 * Tcl_DeleteNamespace --
581 *
582 * Deletes a namespace and all of the commands, variables, and other
583 * namespaces within it.
584 *
585 * Results:
586 * None.
587 *
588 * Side effects:
589 * When a namespace is deleted, it is automatically removed as a
590 * child of its parent namespace. Also, all its commands, variables
591 * and child namespaces are deleted.
592 *
593 *----------------------------------------------------------------------
594 */
595
596 void
597 Tcl_DeleteNamespace(namespacePtr)
598 Tcl_Namespace *namespacePtr; /* Points to the namespace to delete. */
599 {
600 register Namespace *nsPtr = (Namespace *) namespacePtr;
601 Interp *iPtr = (Interp *) nsPtr->interp;
602 Namespace *globalNsPtr =
603 (Namespace *) Tcl_GetGlobalNamespace((Tcl_Interp *) iPtr);
604 Tcl_HashEntry *entryPtr;
605
606 /*
607 * If the namespace is on the call frame stack, it is marked as "dying"
608 * (NS_DYING is OR'd into its flags): the namespace can't be looked up
609 * by name but its commands and variables are still usable by those
610 * active call frames. When all active call frames referring to the
611 * namespace have been popped from the Tcl stack, Tcl_PopCallFrame will
612 * call this procedure again to delete everything in the namespace.
613 * If no nsName objects refer to the namespace (i.e., if its refCount
614 * is zero), its commands and variables are deleted and the storage for
615 * its namespace structure is freed. Otherwise, if its refCount is
616 * nonzero, the namespace's commands and variables are deleted but the
617 * structure isn't freed. Instead, NS_DEAD is OR'd into the structure's
618 * flags to allow the namespace resolution code to recognize that the
619 * namespace is "deleted". The structure's storage is freed by
620 * FreeNsNameInternalRep when its refCount reaches 0.
621 */
622
623 if (nsPtr->activationCount > 0) {
624 nsPtr->flags |= NS_DYING;
625 if (nsPtr->parentPtr != NULL) {
626 entryPtr = Tcl_FindHashEntry(&nsPtr->parentPtr->childTable,
627 nsPtr->name);
628 if (entryPtr != NULL) {
629 Tcl_DeleteHashEntry(entryPtr);
630 }
631 }
632 nsPtr->parentPtr = NULL;
633 } else {
634 /*
635 * Delete the namespace and everything in it. If this is the global
636 * namespace, then clear it but don't free its storage unless the
637 * interpreter is being torn down.
638 */
639
640 TclTeardownNamespace(nsPtr);
641
642 if ((nsPtr != globalNsPtr) || (iPtr->flags & DELETED)) {
643 /*
644 * If this is the global namespace, then it may have residual
645 * "errorInfo" and "errorCode" variables for errors that
646 * occurred while it was being torn down. Try to clear the
647 * variable list one last time.
648 */
649
650 TclDeleteVars((Interp *) nsPtr->interp, &nsPtr->varTable);
651
652 Tcl_DeleteHashTable(&nsPtr->childTable);
653 Tcl_DeleteHashTable(&nsPtr->cmdTable);
654
655 /*
656 * If the reference count is 0, then discard the namespace.
657 * Otherwise, mark it as "dead" so that it can't be used.
658 */
659
660 if (nsPtr->refCount == 0) {
661 NamespaceFree(nsPtr);
662 } else {
663 nsPtr->flags |= NS_DEAD;
664 }
665 }
666 }
667 }
668
669 /*
670 *----------------------------------------------------------------------
671 *
672 * TclTeardownNamespace --
673 *
674 * Used internally to dismantle and unlink a namespace when it is
675 * deleted. Divorces the namespace from its parent, and deletes all
676 * commands, variables, and child namespaces.
677 *
678 * This is kept separate from Tcl_DeleteNamespace so that the global
679 * namespace can be handled specially. Global variables like
680 * "errorInfo" and "errorCode" need to remain intact while other
681 * namespaces and commands are torn down, in case any errors occur.
682 *
683 * Results:
684 * None.
685 *
686 * Side effects:
687 * Removes this namespace from its parent's child namespace hashtable.
688 * Deletes all commands, variables and namespaces in this namespace.
689 * If this is the global namespace, the "errorInfo" and "errorCode"
690 * variables are left alone and deleted later.
691 *
692 *----------------------------------------------------------------------
693 */
694
695 void
696 TclTeardownNamespace(nsPtr)
697 register Namespace *nsPtr; /* Points to the namespace to be dismantled
698 * and unlinked from its parent. */
699 {
700 Interp *iPtr = (Interp *) nsPtr->interp;
701 register Tcl_HashEntry *entryPtr;
702 Tcl_HashSearch search;
703 Tcl_Namespace *childNsPtr;
704 Tcl_Command cmd;
705 Namespace *globalNsPtr =
706 (Namespace *) Tcl_GetGlobalNamespace((Tcl_Interp *) iPtr);
707 int i;
708
709 /*
710 * Start by destroying the namespace's variable table,
711 * since variables might trigger traces.
712 */
713
714 if (nsPtr == globalNsPtr) {
715 /*
716 * This is the global namespace, so be careful to preserve the
717 * "errorInfo" and "errorCode" variables. These might be needed
718 * later on if errors occur while deleting commands. We are careful
719 * to destroy and recreate the "errorInfo" and "errorCode"
720 * variables, in case they had any traces on them.
721 */
722
723 CONST char *str;
724 char *errorInfoStr, *errorCodeStr;
725
726 str = Tcl_GetVar((Tcl_Interp *) iPtr, "errorInfo", TCL_GLOBAL_ONLY);
727 if (str != NULL) {
728 errorInfoStr = ckalloc((unsigned) (strlen(str)+1));
729 strcpy(errorInfoStr, str);
730 } else {
731 errorInfoStr = NULL;
732 }
733
734 str = Tcl_GetVar((Tcl_Interp *) iPtr, "errorCode", TCL_GLOBAL_ONLY);
735 if (str != NULL) {
736 errorCodeStr = ckalloc((unsigned) (strlen(str)+1));
737 strcpy(errorCodeStr, str);
738 } else {
739 errorCodeStr = NULL;
740 }
741
742 TclDeleteVars(iPtr, &nsPtr->varTable);
743 Tcl_InitHashTable(&nsPtr->varTable, TCL_STRING_KEYS);
744
745 if (errorInfoStr != NULL) {
746 Tcl_SetVar((Tcl_Interp *) iPtr, "errorInfo", errorInfoStr,
747 TCL_GLOBAL_ONLY);
748 ckfree(errorInfoStr);
749 }
750 if (errorCodeStr != NULL) {
751 Tcl_SetVar((Tcl_Interp *) iPtr, "errorCode", errorCodeStr,
752 TCL_GLOBAL_ONLY);
753 ckfree(errorCodeStr);
754 }
755 } else {
756 /*
757 * Variable table should be cleared but not freed! TclDeleteVars
758 * frees it, so we reinitialize it afterwards.
759 */
760
761 TclDeleteVars(iPtr, &nsPtr->varTable);
762 Tcl_InitHashTable(&nsPtr->varTable, TCL_STRING_KEYS);
763 }
764
765 /*
766 * Remove the namespace from its parent's child hashtable.
767 */
768
769 if (nsPtr->parentPtr != NULL) {
770 entryPtr = Tcl_FindHashEntry(&nsPtr->parentPtr->childTable,
771 nsPtr->name);
772 if (entryPtr != NULL) {
773 Tcl_DeleteHashEntry(entryPtr);
774 }
775 }
776 nsPtr->parentPtr = NULL;
777
778 /*
779 * Delete all the child namespaces.
780 *
781 * BE CAREFUL: When each child is deleted, it will divorce
782 * itself from its parent. You can't traverse a hash table
783 * properly if its elements are being deleted. We use only
784 * the Tcl_FirstHashEntry function to be safe.
785 */
786
787 for (entryPtr = Tcl_FirstHashEntry(&nsPtr->childTable, &search);
788 entryPtr != NULL;
789 entryPtr = Tcl_FirstHashEntry(&nsPtr->childTable, &search)) {
790 childNsPtr = (Tcl_Namespace *) Tcl_GetHashValue(entryPtr);
791 Tcl_DeleteNamespace(childNsPtr);
792 }
793
794 /*
795 * Delete all commands in this namespace. Be careful when traversing the
796 * hash table: when each command is deleted, it removes itself from the
797 * command table.
798 */
799
800 for (entryPtr = Tcl_FirstHashEntry(&nsPtr->cmdTable, &search);
801 entryPtr != NULL;
802 entryPtr = Tcl_FirstHashEntry(&nsPtr->cmdTable, &search)) {
803 cmd = (Tcl_Command) Tcl_GetHashValue(entryPtr);
804 Tcl_DeleteCommandFromToken((Tcl_Interp *) iPtr, cmd);
805 }
806 Tcl_DeleteHashTable(&nsPtr->cmdTable);
807 Tcl_InitHashTable(&nsPtr->cmdTable, TCL_STRING_KEYS);
808
809 /*
810 * Free the namespace's export pattern array.
811 */
812
813 if (nsPtr->exportArrayPtr != NULL) {
814 for (i = 0; i < nsPtr->numExportPatterns; i++) {
815 ckfree(nsPtr->exportArrayPtr[i]);
816 }
817 ckfree((char *) nsPtr->exportArrayPtr);
818 nsPtr->exportArrayPtr = NULL;
819 nsPtr->numExportPatterns = 0;
820 nsPtr->maxExportPatterns = 0;
821 }
822
823 /*
824 * Free any client data associated with the namespace.
825 */
826
827 if (nsPtr->deleteProc != NULL) {
828 (*nsPtr->deleteProc)(nsPtr->clientData);
829 }
830 nsPtr->deleteProc = NULL;
831 nsPtr->clientData = NULL;
832
833 /*
834 * Reset the namespace's id field to ensure that this namespace won't
835 * be interpreted as valid by, e.g., the cache validation code for
836 * cached command references in Tcl_GetCommandFromObj.
837 */
838
839 nsPtr->nsId = 0;
840 }
841
842 /*
843 *----------------------------------------------------------------------
844 *
845 * NamespaceFree --
846 *
847 * Called after a namespace has been deleted, when its
848 * reference count reaches 0. Frees the data structure
849 * representing the namespace.
850 *
851 * Results:
852 * None.
853 *
854 * Side effects:
855 * None.
856 *
857 *----------------------------------------------------------------------
858 */
859
860 static void
861 NamespaceFree(nsPtr)
862 register Namespace *nsPtr; /* Points to the namespace to free. */
863 {
864 /*
865 * Most of the namespace's contents are freed when the namespace is
866 * deleted by Tcl_DeleteNamespace. All that remains is to free its names
867 * (for error messages), and the structure itself.
868 */
869
870 ckfree(nsPtr->name);
871 ckfree(nsPtr->fullName);
872
873 ckfree((char *) nsPtr);
874 }
875
876
877 /*
878 *----------------------------------------------------------------------
879 *
880 * Tcl_Export --
881 *
882 * Makes all the commands matching a pattern available to later be
883 * imported from the namespace specified by namespacePtr (or the
884 * current namespace if namespacePtr is NULL). The specified pattern is
885 * appended onto the namespace's export pattern list, which is
886 * optionally cleared beforehand.
887 *
888 * Results:
889 * Returns TCL_OK if successful, or TCL_ERROR (along with an error
890 * message in the interpreter's result) if something goes wrong.
891 *
892 * Side effects:
893 * Appends the export pattern onto the namespace's export list.
894 * Optionally reset the namespace's export pattern list.
895 *
896 *----------------------------------------------------------------------
897 */
898
899 int
900 Tcl_Export(interp, namespacePtr, pattern, resetListFirst)
901 Tcl_Interp *interp; /* Current interpreter. */
902 Tcl_Namespace *namespacePtr; /* Points to the namespace from which
903 * commands are to be exported. NULL for
904 * the current namespace. */
905 CONST char *pattern; /* String pattern indicating which commands
906 * to export. This pattern may not include
907 * any namespace qualifiers; only commands
908 * in the specified namespace may be
909 * exported. */
910 int resetListFirst; /* If nonzero, resets the namespace's
911 * export list before appending. */
912 {
913 #define INIT_EXPORT_PATTERNS 5
914 Namespace *nsPtr, *exportNsPtr, *dummyPtr;
915 Namespace *currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
916 CONST char *simplePattern;
917 char *patternCpy;
918 int neededElems, len, i;
919
920 /*
921 * If the specified namespace is NULL, use the current namespace.
922 */
923
924 if (namespacePtr == NULL) {
925 nsPtr = (Namespace *) currNsPtr;
926 } else {
927 nsPtr = (Namespace *) namespacePtr;
928 }
929
930 /*
931 * If resetListFirst is true (nonzero), clear the namespace's export
932 * pattern list.
933 */
934
935 if (resetListFirst) {
936 if (nsPtr->exportArrayPtr != NULL) {
937 for (i = 0; i < nsPtr->numExportPatterns; i++) {
938 ckfree(nsPtr->exportArrayPtr[i]);
939 }
940 ckfree((char *) nsPtr->exportArrayPtr);
941 nsPtr->exportArrayPtr = NULL;
942 nsPtr->numExportPatterns = 0;
943 nsPtr->maxExportPatterns = 0;
944 }
945 }
946
947 /*
948 * Check that the pattern doesn't have namespace qualifiers.
949 */
950
951 TclGetNamespaceForQualName(interp, pattern, nsPtr,
952 /*flags*/ TCL_LEAVE_ERR_MSG, &exportNsPtr, &dummyPtr,
953 &dummyPtr, &simplePattern);
954
955 if ((exportNsPtr != nsPtr) || (strcmp(pattern, simplePattern) != 0)) {
956 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
957 "invalid export pattern \"", pattern,
958 "\": pattern can't specify a namespace",
959 (char *) NULL);
960 return TCL_ERROR;
961 }
962
963 /*
964 * Make sure that we don't already have the pattern in the array
965 */
966 if (nsPtr->exportArrayPtr != NULL) {
967 for (i = 0; i < nsPtr->numExportPatterns; i++) {
968 if (strcmp(pattern, nsPtr->exportArrayPtr[i]) == 0) {
969 /*
970 * The pattern already exists in the list
971 */
972 return TCL_OK;
973 }
974 }
975 }
976
977 /*
978 * Make sure there is room in the namespace's pattern array for the
979 * new pattern.
980 */
981
982 neededElems = nsPtr->numExportPatterns + 1;
983 if (nsPtr->exportArrayPtr == NULL) {
984 nsPtr->exportArrayPtr = (char **)
985 ckalloc((unsigned) (INIT_EXPORT_PATTERNS * sizeof(char *)));
986 nsPtr->numExportPatterns = 0;
987 nsPtr->maxExportPatterns = INIT_EXPORT_PATTERNS;
988 } else if (neededElems > nsPtr->maxExportPatterns) {
989 int numNewElems = 2 * nsPtr->maxExportPatterns;
990 size_t currBytes = nsPtr->numExportPatterns * sizeof(char *);
991 size_t newBytes = numNewElems * sizeof(char *);
992 char **newPtr = (char **) ckalloc((unsigned) newBytes);
993
994 memcpy((VOID *) newPtr, (VOID *) nsPtr->exportArrayPtr,
995 currBytes);
996 ckfree((char *) nsPtr->exportArrayPtr);
997 nsPtr->exportArrayPtr = (char **) newPtr;
998 nsPtr->maxExportPatterns = numNewElems;
999 }
1000
1001 /*
1002 * Add the pattern to the namespace's array of export patterns.
1003 */
1004
1005 len = strlen(pattern);
1006 patternCpy = (char *) ckalloc((unsigned) (len + 1));
1007 strcpy(patternCpy, pattern);
1008
1009 nsPtr->exportArrayPtr[nsPtr->numExportPatterns] = patternCpy;
1010 nsPtr->numExportPatterns++;
1011 return TCL_OK;
1012 #undef INIT_EXPORT_PATTERNS
1013 }
1014
1015 /*
1016 *----------------------------------------------------------------------
1017 *
1018 * Tcl_AppendExportList --
1019 *
1020 * Appends onto the argument object the list of export patterns for the
1021 * specified namespace.
1022 *
1023 * Results:
1024 * The return value is normally TCL_OK; in this case the object
1025 * referenced by objPtr has each export pattern appended to it. If an
1026 * error occurs, TCL_ERROR is returned and the interpreter's result
1027 * holds an error message.
1028 *
1029 * Side effects:
1030 * If necessary, the object referenced by objPtr is converted into
1031 * a list object.
1032 *
1033 *----------------------------------------------------------------------
1034 */
1035
1036 int
1037 Tcl_AppendExportList(interp, namespacePtr, objPtr)
1038 Tcl_Interp *interp; /* Interpreter used for error reporting. */
1039 Tcl_Namespace *namespacePtr; /* Points to the namespace whose export
1040 * pattern list is appended onto objPtr.
1041 * NULL for the current namespace. */
1042 Tcl_Obj *objPtr; /* Points to the Tcl object onto which the
1043 * export pattern list is appended. */
1044 {
1045 Namespace *nsPtr;
1046 int i, result;
1047
1048 /*
1049 * If the specified namespace is NULL, use the current namespace.
1050 */
1051
1052 if (namespacePtr == NULL) {
1053 nsPtr = (Namespace *) (Namespace *) Tcl_GetCurrentNamespace(interp);
1054 } else {
1055 nsPtr = (Namespace *) namespacePtr;
1056 }
1057
1058 /*
1059 * Append the export pattern list onto objPtr.
1060 */
1061
1062 for (i = 0; i < nsPtr->numExportPatterns; i++) {
1063 result = Tcl_ListObjAppendElement(interp, objPtr,
1064 Tcl_NewStringObj(nsPtr->exportArrayPtr[i], -1));
1065 if (result != TCL_OK) {
1066 return result;
1067 }
1068 }
1069 return TCL_OK;
1070 }
1071
1072 /*
1073 *----------------------------------------------------------------------
1074 *
1075 * Tcl_Import --
1076 *
1077 * Imports all of the commands matching a pattern into the namespace
1078 * specified by namespacePtr (or the current namespace if contextNsPtr
1079 * is NULL). This is done by creating a new command (the "imported
1080 * command") that points to the real command in its original namespace.
1081 *
1082 * If matching commands are on the autoload path but haven't been
1083 * loaded yet, this command forces them to be loaded, then creates
1084 * the links to them.
1085 *
1086 * Results:
1087 * Returns TCL_OK if successful, or TCL_ERROR (along with an error
1088 * message in the interpreter's result) if something goes wrong.
1089 *
1090 * Side effects:
1091 * Creates new commands in the importing namespace. These indirect
1092 * calls back to the real command and are deleted if the real commands
1093 * are deleted.
1094 *
1095 *----------------------------------------------------------------------
1096 */
1097
1098 int
1099 Tcl_Import(interp, namespacePtr, pattern, allowOverwrite)
1100 Tcl_Interp *interp; /* Current interpreter. */
1101 Tcl_Namespace *namespacePtr; /* Points to the namespace into which the
1102 * commands are to be imported. NULL for
1103 * the current namespace. */
1104 CONST char *pattern; /* String pattern indicating which commands
1105 * to import. This pattern should be
1106 * qualified by the name of the namespace
1107 * from which to import the command(s). */
1108 int allowOverwrite; /* If nonzero, allow existing commands to
1109 * be overwritten by imported commands.
1110 * If 0, return an error if an imported
1111 * cmd conflicts with an existing one. */
1112 {
1113 Interp *iPtr = (Interp *) interp;
1114 Namespace *nsPtr, *importNsPtr, *dummyPtr;
1115 Namespace *currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
1116 CONST char *simplePattern;
1117 char *cmdName;
1118 register Tcl_HashEntry *hPtr;
1119 Tcl_HashSearch search;
1120 Command *cmdPtr, *realCmdPtr;
1121 ImportRef *refPtr;
1122 Tcl_Command autoCmd, importedCmd;
1123 ImportedCmdData *dataPtr;
1124 int wasExported, i, result;
1125
1126 /*
1127 * If the specified namespace is NULL, use the current namespace.
1128 */
1129
1130 if (namespacePtr == NULL) {
1131 nsPtr = (Namespace *) currNsPtr;
1132 } else {
1133 nsPtr = (Namespace *) namespacePtr;
1134 }
1135
1136 /*
1137 * First, invoke the "auto_import" command with the pattern
1138 * being imported. This command is part of the Tcl library.
1139 * It looks for imported commands in autoloaded libraries and
1140 * loads them in. That way, they will be found when we try
1141 * to create links below.
1142 */
1143
1144 autoCmd = Tcl_FindCommand(interp, "auto_import",
1145 (Tcl_Namespace *) NULL, /*flags*/ TCL_GLOBAL_ONLY);
1146
1147 if (autoCmd != NULL) {
1148 Tcl_Obj *objv[2];
1149
1150 objv[0] = Tcl_NewStringObj("auto_import", -1);
1151 Tcl_IncrRefCount(objv[0]);
1152 objv[1] = Tcl_NewStringObj(pattern, -1);
1153 Tcl_IncrRefCount(objv[1]);
1154
1155 cmdPtr = (Command *) autoCmd;
1156 result = (*cmdPtr->objProc)(cmdPtr->objClientData, interp,
1157 2, objv);
1158
1159 Tcl_DecrRefCount(objv[0]);
1160 Tcl_DecrRefCount(objv[1]);
1161
1162 if (result != TCL_OK) {
1163 return TCL_ERROR;
1164 }
1165 Tcl_ResetResult(interp);
1166 }
1167
1168 /*
1169 * From the pattern, find the namespace from which we are importing
1170 * and get the simple pattern (no namespace qualifiers or ::'s) at
1171 * the end.
1172 */
1173
1174 if (strlen(pattern) == 0) {
1175 Tcl_SetStringObj(Tcl_GetObjResult(interp),
1176 "empty import pattern", -1);
1177 return TCL_ERROR;
1178 }
1179 TclGetNamespaceForQualName(interp, pattern, nsPtr,
1180 /*flags*/ TCL_LEAVE_ERR_MSG, &importNsPtr, &dummyPtr,
1181 &dummyPtr, &simplePattern);
1182
1183 if (importNsPtr == NULL) {
1184 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1185 "unknown namespace in import pattern \"",
1186 pattern, "\"", (char *) NULL);
1187 return TCL_ERROR;
1188 }
1189 if (importNsPtr == nsPtr) {
1190 if (pattern == simplePattern) {
1191 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1192 "no namespace specified in import pattern \"", pattern,
1193 "\"", (char *) NULL);
1194 } else {
1195 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1196 "import pattern \"", pattern,
1197 "\" tries to import from namespace \"",
1198 importNsPtr->name, "\" into itself", (char *) NULL);
1199 }
1200 return TCL_ERROR;
1201 }
1202
1203 /*
1204 * Scan through the command table in the source namespace and look for
1205 * exported commands that match the string pattern. Create an "imported
1206 * command" in the current namespace for each imported command; these
1207 * commands redirect their invocations to the "real" command.
1208 */
1209
1210 for (hPtr = Tcl_FirstHashEntry(&importNsPtr->cmdTable, &search);
1211 (hPtr != NULL);
1212 hPtr = Tcl_NextHashEntry(&search)) {
1213 cmdName = Tcl_GetHashKey(&importNsPtr->cmdTable, hPtr);
1214 if (Tcl_StringMatch(cmdName, simplePattern)) {
1215 /*
1216 * The command cmdName in the source namespace matches the
1217 * pattern. Check whether it was exported. If it wasn't,
1218 * we ignore it.
1219 */
1220
1221 wasExported = 0;
1222 for (i = 0; i < importNsPtr->numExportPatterns; i++) {
1223 if (Tcl_StringMatch(cmdName,
1224 importNsPtr->exportArrayPtr[i])) {
1225 wasExported = 1;
1226 break;
1227 }
1228 }
1229 if (!wasExported) {
1230 continue;
1231 }
1232
1233 /*
1234 * Unless there is a name clash, create an imported command
1235 * in the current namespace that refers to cmdPtr.
1236 */
1237
1238 if ((Tcl_FindHashEntry(&nsPtr->cmdTable, cmdName) == NULL)
1239 || allowOverwrite) {
1240 /*
1241 * Create the imported command and its client data.
1242 * To create the new command in the current namespace,
1243 * generate a fully qualified name for it.
1244 */
1245
1246 Tcl_DString ds;
1247
1248 Tcl_DStringInit(&ds);
1249 Tcl_DStringAppend(&ds, nsPtr->fullName, -1);
1250 if (nsPtr != iPtr->globalNsPtr) {
1251 Tcl_DStringAppend(&ds, "::", 2);
1252 }
1253 Tcl_DStringAppend(&ds, cmdName, -1);
1254
1255 /*
1256 * Check whether creating the new imported command in the
1257 * current namespace would create a cycle of imported->real
1258 * command references that also would destroy an existing
1259 * "real" command already in the current namespace.
1260 */
1261
1262 cmdPtr = (Command *) Tcl_GetHashValue(hPtr);
1263 if (cmdPtr->deleteProc == DeleteImportedCmd) {
1264 realCmdPtr = (Command *) TclGetOriginalCommand(
1265 (Tcl_Command) cmdPtr);
1266 if ((realCmdPtr != NULL)
1267 && (realCmdPtr->nsPtr == currNsPtr)
1268 && (Tcl_FindHashEntry(&currNsPtr->cmdTable,
1269 cmdName) != NULL)) {
1270 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1271 "import pattern \"", pattern,
1272 "\" would create a loop containing command \"",
1273 Tcl_DStringValue(&ds), "\"", (char *) NULL);
1274 Tcl_DStringFree(&ds);
1275 return TCL_ERROR;
1276 }
1277 }
1278
1279 dataPtr = (ImportedCmdData *)
1280 ckalloc(sizeof(ImportedCmdData));
1281 importedCmd = Tcl_CreateObjCommand(interp,
1282 Tcl_DStringValue(&ds), InvokeImportedCmd,
1283 (ClientData) dataPtr, DeleteImportedCmd);
1284 dataPtr->realCmdPtr = cmdPtr;
1285 dataPtr->selfPtr = (Command *) importedCmd;
1286 dataPtr->selfPtr->compileProc = cmdPtr->compileProc;
1287 Tcl_DStringFree(&ds);
1288
1289 /*
1290 * Create an ImportRef structure describing this new import
1291 * command and add it to the import ref list in the "real"
1292 * command.
1293 */
1294
1295 refPtr = (ImportRef *) ckalloc(sizeof(ImportRef));
1296 refPtr->importedCmdPtr = (Command *) importedCmd;
1297 refPtr->nextPtr = cmdPtr->importRefPtr;
1298 cmdPtr->importRefPtr = refPtr;
1299 } else {
1300 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1301 "can't import command \"", cmdName,
1302 "\": already exists", (char *) NULL);
1303 return TCL_ERROR;
1304 }
1305 }
1306 }
1307 return TCL_OK;
1308 }
1309
1310 /*
1311 *----------------------------------------------------------------------
1312 *
1313 * Tcl_ForgetImport --
1314 *
1315 * Deletes previously imported commands. Given a pattern that may
1316 * include the name of an exporting namespace, this procedure first
1317 * finds all matching exported commands. It then looks in the namespace
1318 * specified by namespacePtr for any corresponding previously imported
1319 * commands, which it deletes. If namespacePtr is NULL, commands are
1320 * deleted from the current namespace.
1321 *
1322 * Results:
1323 * Returns TCL_OK if successful. If there is an error, returns
1324 * TCL_ERROR and puts an error message in the interpreter's result
1325 * object.
1326 *
1327 * Side effects:
1328 * May delete commands.
1329 *
1330 *----------------------------------------------------------------------
1331 */
1332
1333 int
1334 Tcl_ForgetImport(interp, namespacePtr, pattern)
1335 Tcl_Interp *interp; /* Current interpreter. */
1336 Tcl_Namespace *namespacePtr; /* Points to the namespace from which
1337 * previously imported commands should be
1338 * removed. NULL for current namespace. */
1339 CONST char *pattern; /* String pattern indicating which imported
1340 * commands to remove. This pattern should
1341 * be qualified by the name of the
1342 * namespace from which the command(s) were
1343 * imported. */
1344 {
1345 Namespace *nsPtr, *importNsPtr, *dummyPtr, *actualCtxPtr;
1346 CONST char *simplePattern;
1347 char *cmdName;
1348 register Tcl_HashEntry *hPtr;
1349 Tcl_HashSearch search;
1350 Command *cmdPtr;
1351
1352 /*
1353 * If the specified namespace is NULL, use the current namespace.
1354 */
1355
1356 if (namespacePtr == NULL) {
1357 nsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
1358 } else {
1359 nsPtr = (Namespace *) namespacePtr;
1360 }
1361
1362 /*
1363 * From the pattern, find the namespace from which we are importing
1364 * and get the simple pattern (no namespace qualifiers or ::'s) at
1365 * the end.
1366 */
1367
1368 TclGetNamespaceForQualName(interp, pattern, nsPtr,
1369 /*flags*/ TCL_LEAVE_ERR_MSG, &importNsPtr, &dummyPtr,
1370 &actualCtxPtr, &simplePattern);
1371
1372 if (importNsPtr == NULL) {
1373 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1374 "unknown namespace in namespace forget pattern \"",
1375 pattern, "\"", (char *) NULL);
1376 return TCL_ERROR;
1377 }
1378
1379 /*
1380 * Scan through the command table in the source namespace and look for
1381 * exported commands that match the string pattern. If the current
1382 * namespace has an imported command that refers to one of those real
1383 * commands, delete it.
1384 */
1385
1386 for (hPtr = Tcl_FirstHashEntry(&importNsPtr->cmdTable, &search);
1387 (hPtr != NULL);
1388 hPtr = Tcl_NextHashEntry(&search)) {
1389 cmdName = Tcl_GetHashKey(&importNsPtr->cmdTable, hPtr);
1390 if (Tcl_StringMatch(cmdName, simplePattern)) {
1391 hPtr = Tcl_FindHashEntry(&nsPtr->cmdTable, cmdName);
1392 if (hPtr != NULL) { /* cmd of same name in current namespace */
1393 cmdPtr = (Command *) Tcl_GetHashValue(hPtr);
1394 if (cmdPtr->deleteProc == DeleteImportedCmd) {
1395 Tcl_DeleteCommandFromToken(interp, (Tcl_Command) cmdPtr);
1396 }
1397 }
1398 }
1399 }
1400 return TCL_OK;
1401 }
1402
1403 /*
1404 *----------------------------------------------------------------------
1405 *
1406 * TclGetOriginalCommand --
1407 *
1408 * An imported command is created in an namespace when a "real" command
1409 * is imported from another namespace. If the specified command is an
1410 * imported command, this procedure returns the original command it
1411 * refers to.
1412 *
1413 * Results:
1414 * If the command was imported into a sequence of namespaces a, b,...,n
1415 * where each successive namespace just imports the command from the
1416 * previous namespace, this procedure returns the Tcl_Command token in
1417 * the first namespace, a. Otherwise, if the specified command is not
1418 * an imported command, the procedure returns NULL.
1419 *
1420 * Side effects:
1421 * None.
1422 *
1423 *----------------------------------------------------------------------
1424 */
1425
1426 Tcl_Command
1427 TclGetOriginalCommand(command)
1428 Tcl_Command command; /* The imported command for which the
1429 * original command should be returned. */
1430 {
1431 register Command *cmdPtr = (Command *) command;
1432 ImportedCmdData *dataPtr;
1433
1434 if (cmdPtr->deleteProc != DeleteImportedCmd) {
1435 return (Tcl_Command) NULL;
1436 }
1437
1438 while (cmdPtr->deleteProc == DeleteImportedCmd) {
1439 dataPtr = (ImportedCmdData *) cmdPtr->objClientData;
1440 cmdPtr = dataPtr->realCmdPtr;
1441 }
1442 return (Tcl_Command) cmdPtr;
1443 }
1444
1445 /*
1446 *----------------------------------------------------------------------
1447 *
1448 * InvokeImportedCmd --
1449 *
1450 * Invoked by Tcl whenever the user calls an imported command that
1451 * was created by Tcl_Import. Finds the "real" command (in another
1452 * namespace), and passes control to it.
1453 *
1454 * Results:
1455 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
1456 *
1457 * Side effects:
1458 * Returns a result in the interpreter's result object. If anything
1459 * goes wrong, the result object is set to an error message.
1460 *
1461 *----------------------------------------------------------------------
1462 */
1463
1464 static int
1465 InvokeImportedCmd(clientData, interp, objc, objv)
1466 ClientData clientData; /* Points to the imported command's
1467 * ImportedCmdData structure. */
1468 Tcl_Interp *interp; /* Current interpreter. */
1469 int objc; /* Number of arguments. */
1470 Tcl_Obj *CONST objv[]; /* The argument objects. */
1471 {
1472 register ImportedCmdData *dataPtr = (ImportedCmdData *) clientData;
1473 register Command *realCmdPtr = dataPtr->realCmdPtr;
1474
1475 return (*realCmdPtr->objProc)(realCmdPtr->objClientData, interp,
1476 objc, objv);
1477 }
1478
1479 /*
1480 *----------------------------------------------------------------------
1481 *
1482 * DeleteImportedCmd --
1483 *
1484 * Invoked by Tcl whenever an imported command is deleted. The "real"
1485 * command keeps a list of all the imported commands that refer to it,
1486 * so those imported commands can be deleted when the real command is
1487 * deleted. This procedure removes the imported command reference from
1488 * the real command's list, and frees up the memory associated with
1489 * the imported command.
1490 *
1491 * Results:
1492 * None.
1493 *
1494 * Side effects:
1495 * Removes the imported command from the real command's import list.
1496 *
1497 *----------------------------------------------------------------------
1498 */
1499
1500 static void
1501 DeleteImportedCmd(clientData)
1502 ClientData clientData; /* Points to the imported command's
1503 * ImportedCmdData structure. */
1504 {
1505 ImportedCmdData *dataPtr = (ImportedCmdData *) clientData;
1506 Command *realCmdPtr = dataPtr->realCmdPtr;
1507 Command *selfPtr = dataPtr->selfPtr;
1508 register ImportRef *refPtr, *prevPtr;
1509
1510 prevPtr = NULL;
1511 for (refPtr = realCmdPtr->importRefPtr; refPtr != NULL;
1512 refPtr = refPtr->nextPtr) {
1513 if (refPtr->importedCmdPtr == selfPtr) {
1514 /*
1515 * Remove *refPtr from real command's list of imported commands
1516 * that refer to it.
1517 */
1518
1519 if (prevPtr == NULL) { /* refPtr is first in list */
1520 realCmdPtr->importRefPtr = refPtr->nextPtr;
1521 } else {
1522 prevPtr->nextPtr = refPtr->nextPtr;
1523 }
1524 ckfree((char *) refPtr);
1525 ckfree((char *) dataPtr);
1526 return;
1527 }
1528 prevPtr = refPtr;
1529 }
1530
1531 panic("DeleteImportedCmd: did not find cmd in real cmd's list of import references");
1532 }
1533
1534 /*
1535 *----------------------------------------------------------------------
1536 *
1537 * TclGetNamespaceForQualName --
1538 *
1539 * Given a qualified name specifying a command, variable, or namespace,
1540 * and a namespace in which to resolve the name, this procedure returns
1541 * a pointer to the namespace that contains the item. A qualified name
1542 * consists of the "simple" name of an item qualified by the names of
1543 * an arbitrary number of containing namespace separated by "::"s. If
1544 * the qualified name starts with "::", it is interpreted absolutely
1545 * from the global namespace. Otherwise, it is interpreted relative to
1546 * the namespace specified by cxtNsPtr if it is non-NULL. If cxtNsPtr
1547 * is NULL, the name is interpreted relative to the current namespace.
1548 *
1549 * A relative name like "foo::bar::x" can be found starting in either
1550 * the current namespace or in the global namespace. So each search
1551 * usually follows two tracks, and two possible namespaces are
1552 * returned. If the procedure sets either *nsPtrPtr or *altNsPtrPtr to
1553 * NULL, then that path failed.
1554 *
1555 * If "flags" contains TCL_GLOBAL_ONLY, the relative qualified name is
1556 * sought only in the global :: namespace. The alternate search
1557 * (also) starting from the global namespace is ignored and
1558 * *altNsPtrPtr is set NULL.
1559 *
1560 * If "flags" contains TCL_NAMESPACE_ONLY, the relative qualified
1561 * name is sought only in the namespace specified by cxtNsPtr. The
1562 * alternate search starting from the global namespace is ignored and
1563 * *altNsPtrPtr is set NULL. If both TCL_GLOBAL_ONLY and
1564 * TCL_NAMESPACE_ONLY are specified, TCL_GLOBAL_ONLY is ignored and
1565 * the search starts from the namespace specified by cxtNsPtr.
1566 *
1567 * If "flags" contains CREATE_NS_IF_UNKNOWN, all namespace
1568 * components of the qualified name that cannot be found are
1569 * automatically created within their specified parent. This makes sure
1570 * that functions like Tcl_CreateCommand always succeed. There is no
1571 * alternate search path, so *altNsPtrPtr is set NULL.
1572 *
1573 * If "flags" contains FIND_ONLY_NS, the qualified name is treated as a
1574 * reference to a namespace, and the entire qualified name is
1575 * followed. If the name is relative, the namespace is looked up only
1576 * in the current namespace. A pointer to the namespace is stored in
1577 * *nsPtrPtr and NULL is stored in *simpleNamePtr. Otherwise, if
1578 * FIND_ONLY_NS is not specified, only the leading components are
1579 * treated as namespace names, and a pointer to the simple name of the
1580 * final component is stored in *simpleNamePtr.
1581 *
1582 * Results:
1583 * It sets *nsPtrPtr and *altNsPtrPtr to point to the two possible
1584 * namespaces which represent the last (containing) namespace in the
1585 * qualified name. If the procedure sets either *nsPtrPtr or *altNsPtrPtr
1586 * to NULL, then the search along that path failed. The procedure also
1587 * stores a pointer to the simple name of the final component in
1588 * *simpleNamePtr. If the qualified name is "::" or was treated as a
1589 * namespace reference (FIND_ONLY_NS), the procedure stores a pointer
1590 * to the namespace in *nsPtrPtr, NULL in *altNsPtrPtr, and sets
1591 * *simpleNamePtr to point to an empty string.
1592 *
1593 * If there is an error, this procedure returns TCL_ERROR. If "flags"
1594 * contains TCL_LEAVE_ERR_MSG, an error message is returned in the
1595 * interpreter's result object. Otherwise, the interpreter's result
1596 * object is left unchanged.
1597 *
1598 * *actualCxtPtrPtr is set to the actual context namespace. It is
1599 * set to the input context namespace pointer in cxtNsPtr. If cxtNsPtr
1600 * is NULL, it is set to the current namespace context.
1601 *
1602 * For backwards compatibility with the TclPro byte code loader,
1603 * this function always returns TCL_OK.
1604 *
1605 * Side effects:
1606 * If "flags" contains CREATE_NS_IF_UNKNOWN, new namespaces may be
1607 * created.
1608 *
1609 *----------------------------------------------------------------------
1610 */
1611
1612 int
1613 TclGetNamespaceForQualName(interp, qualName, cxtNsPtr, flags,
1614 nsPtrPtr, altNsPtrPtr, actualCxtPtrPtr, simpleNamePtr)
1615 Tcl_Interp *interp; /* Interpreter in which to find the
1616 * namespace containing qualName. */
1617 CONST char *qualName; /* A namespace-qualified name of an
1618 * command, variable, or namespace. */
1619 Namespace *cxtNsPtr; /* The namespace in which to start the
1620 * search for qualName's namespace. If NULL
1621 * start from the current namespace.
1622 * Ignored if TCL_GLOBAL_ONLY or
1623 * TCL_NAMESPACE_ONLY are set. */
1624 int flags; /* Flags controlling the search: an OR'd
1625 * combination of TCL_GLOBAL_ONLY,
1626 * TCL_NAMESPACE_ONLY,
1627 * CREATE_NS_IF_UNKNOWN, and
1628 * FIND_ONLY_NS. */
1629 Namespace **nsPtrPtr; /* Address where procedure stores a pointer
1630 * to containing namespace if qualName is
1631 * found starting from *cxtNsPtr or, if
1632 * TCL_GLOBAL_ONLY is set, if qualName is
1633 * found in the global :: namespace. NULL
1634 * is stored otherwise. */
1635 Namespace **altNsPtrPtr; /* Address where procedure stores a pointer
1636 * to containing namespace if qualName is
1637 * found starting from the global ::
1638 * namespace. NULL is stored if qualName
1639 * isn't found starting from :: or if the
1640 * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
1641 * CREATE_NS_IF_UNKNOWN, FIND_ONLY_NS flag
1642 * is set. */
1643 Namespace **actualCxtPtrPtr; /* Address where procedure stores a pointer
1644 * to the actual namespace from which the
1645 * search started. This is either cxtNsPtr,
1646 * the :: namespace if TCL_GLOBAL_ONLY was
1647 * specified, or the current namespace if
1648 * cxtNsPtr was NULL. */
1649 CONST char **simpleNamePtr; /* Address where procedure stores the
1650 * simple name at end of the qualName, or
1651 * NULL if qualName is "::" or the flag
1652 * FIND_ONLY_NS was specified. */
1653 {
1654 Interp *iPtr = (Interp *) interp;
1655 Namespace *nsPtr = cxtNsPtr;
1656 Namespace *altNsPtr;
1657 Namespace *globalNsPtr = iPtr->globalNsPtr;
1658 CONST char *start, *end;
1659 CONST char *nsName;
1660 Tcl_HashEntry *entryPtr;
1661 Tcl_DString buffer;
1662 int len;
1663
1664 /*
1665 * Determine the context namespace nsPtr in which to start the primary
1666 * search. If TCL_NAMESPACE_ONLY or FIND_ONLY_NS was specified, search
1667 * from the current namespace. If the qualName name starts with a "::"
1668 * or TCL_GLOBAL_ONLY was specified, search from the global
1669 * namespace. Otherwise, use the given namespace given in cxtNsPtr, or
1670 * if that is NULL, use the current namespace context. Note that we
1671 * always treat two or more adjacent ":"s as a namespace separator.
1672 */
1673
1674 if (flags & (TCL_NAMESPACE_ONLY | FIND_ONLY_NS)) {
1675 nsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
1676 } else if (flags & TCL_GLOBAL_ONLY) {
1677 nsPtr = globalNsPtr;
1678 } else if (nsPtr == NULL) {
1679 if (iPtr->varFramePtr != NULL) {
1680 nsPtr = iPtr->varFramePtr->nsPtr;
1681 } else {
1682 nsPtr = iPtr->globalNsPtr;
1683 }
1684 }
1685
1686 start = qualName; /* pts to start of qualifying namespace */
1687 if ((*qualName == ':') && (*(qualName+1) == ':')) {
1688 start = qualName+2; /* skip over the initial :: */
1689 while (*start == ':') {
1690 start++; /* skip over a subsequent : */
1691 }
1692 nsPtr = globalNsPtr;
1693 if (*start == '\0') { /* qualName is just two or more ":"s */
1694 *nsPtrPtr = globalNsPtr;
1695 *altNsPtrPtr = NULL;
1696 *actualCxtPtrPtr = globalNsPtr;
1697 *simpleNamePtr = start; /* points to empty string */
1698 return TCL_OK;
1699 }
1700 }
1701 *actualCxtPtrPtr = nsPtr;
1702
1703 /*
1704 * Start an alternate search path starting with the global namespace.
1705 * However, if the starting context is the global namespace, or if the
1706 * flag is set to search only the namespace *cxtNsPtr, ignore the
1707 * alternate search path.
1708 */
1709
1710 altNsPtr = globalNsPtr;
1711 if ((nsPtr == globalNsPtr)
1712 || (flags & (TCL_NAMESPACE_ONLY | FIND_ONLY_NS))) {
1713 altNsPtr = NULL;
1714 }
1715
1716 /*
1717 * Loop to resolve each namespace qualifier in qualName.
1718 */
1719
1720 Tcl_DStringInit(&buffer);
1721 end = start;
1722 while (*start != '\0') {
1723 /*
1724 * Find the next namespace qualifier (i.e., a name ending in "::")
1725 * or the end of the qualified name (i.e., a name ending in "\0").
1726 * Set len to the number of characters, starting from start,
1727 * in the name; set end to point after the "::"s or at the "\0".
1728 */
1729
1730 len = 0;
1731 for (end = start; *end != '\0'; end++) {
1732 if ((*end == ':') && (*(end+1) == ':')) {
1733 end += 2; /* skip over the initial :: */
1734 while (*end == ':') {
1735 end++; /* skip over the subsequent : */
1736 }
1737 break; /* exit for loop; end is after ::'s */
1738 }
1739 len++;
1740 }
1741
1742 if ((*end == '\0')
1743 && !((end-start >= 2) && (*(end-1) == ':') && (*(end-2) == ':'))) {
1744 /*
1745 * qualName ended with a simple name at start. If FIND_ONLY_NS
1746 * was specified, look this up as a namespace. Otherwise,
1747 * start is the name of a cmd or var and we are done.
1748 */
1749
1750 if (flags & FIND_ONLY_NS) {
1751 nsName = start;
1752 } else {
1753 *nsPtrPtr = nsPtr;
1754 *altNsPtrPtr = altNsPtr;
1755 *simpleNamePtr = start;
1756 Tcl_DStringFree(&buffer);
1757 return TCL_OK;
1758 }
1759 } else {
1760 /*
1761 * start points to the beginning of a namespace qualifier ending
1762 * in "::". end points to the start of a name in that namespace
1763 * that might be empty. Copy the namespace qualifier to a
1764 * buffer so it can be null terminated. We can't modify the
1765 * incoming qualName since it may be a string constant.
1766 */
1767
1768 Tcl_DStringSetLength(&buffer, 0);
1769 Tcl_DStringAppend(&buffer, start, len);
1770 nsName = Tcl_DStringValue(&buffer);
1771 }
1772
1773 /*
1774 * Look up the namespace qualifier nsName in the current namespace
1775 * context. If it isn't found but CREATE_NS_IF_UNKNOWN is set,
1776 * create that qualifying namespace. This is needed for procedures
1777 * like Tcl_CreateCommand that cannot fail.
1778 */
1779
1780 if (nsPtr != NULL) {
1781 entryPtr = Tcl_FindHashEntry(&nsPtr->childTable, nsName);
1782 if (entryPtr != NULL) {
1783 nsPtr = (Namespace *) Tcl_GetHashValue(entryPtr);
1784 } else if (flags & CREATE_NS_IF_UNKNOWN) {
1785 Tcl_CallFrame frame;
1786
1787 (void) Tcl_PushCallFrame(interp, &frame,
1788 (Tcl_Namespace *) nsPtr, /*isProcCallFrame*/ 0);
1789
1790 nsPtr = (Namespace *) Tcl_CreateNamespace(interp, nsName,
1791 (ClientData) NULL, (Tcl_NamespaceDeleteProc *) NULL);
1792 Tcl_PopCallFrame(interp);
1793
1794 if (nsPtr == NULL) {
1795 panic("Could not create namespace '%s'", nsName);
1796 }
1797 } else { /* namespace not found and wasn't created */
1798 nsPtr = NULL;
1799 }
1800 }
1801
1802 /*
1803 * Look up the namespace qualifier in the alternate search path too.
1804 */
1805
1806 if (altNsPtr != NULL) {
1807 entryPtr = Tcl_FindHashEntry(&altNsPtr->childTable, nsName);
1808 if (entryPtr != NULL) {
1809 altNsPtr = (Namespace *) Tcl_GetHashValue(entryPtr);
1810 } else {
1811 altNsPtr = NULL;
1812 }
1813 }
1814
1815 /*
1816 * If both search paths have failed, return NULL results.
1817 */
1818
1819 if ((nsPtr == NULL) && (altNsPtr == NULL)) {
1820 *nsPtrPtr = NULL;
1821 *altNsPtrPtr = NULL;
1822 *simpleNamePtr = NULL;
1823 Tcl_DStringFree(&buffer);
1824 return TCL_OK;
1825 }
1826
1827 start = end;
1828 }
1829
1830 /*
1831 * We ignore trailing "::"s in a namespace name, but in a command or
1832 * variable name, trailing "::"s refer to the cmd or var named {}.
1833 */
1834
1835 if ((flags & FIND_ONLY_NS)
1836 || ((end > start ) && (*(end-1) != ':'))) {
1837 *simpleNamePtr = NULL; /* found namespace name */
1838 } else {
1839 *simpleNamePtr = end; /* found cmd/var: points to empty string */
1840 }
1841
1842 /*
1843 * As a special case, if we are looking for a namespace and qualName
1844 * is "" and the current active namespace (nsPtr) is not the global
1845 * namespace, return NULL (no namespace was found). This is because
1846 * namespaces can not have empty names except for the global namespace.
1847 */
1848
1849 if ((flags & FIND_ONLY_NS) && (*qualName == '\0')
1850 && (nsPtr != globalNsPtr)) {
1851 nsPtr = NULL;
1852 }
1853
1854 *nsPtrPtr = nsPtr;
1855 *altNsPtrPtr = altNsPtr;
1856 Tcl_DStringFree(&buffer);
1857 return TCL_OK;
1858 }
1859
1860 /*
1861 *----------------------------------------------------------------------
1862 *
1863 * Tcl_FindNamespace --
1864 *
1865 * Searches for a namespace.
1866 *
1867 * Results:
1868 * Returns a pointer to the namespace if it is found. Otherwise,
1869 * returns NULL and leaves an error message in the interpreter's
1870 * result object if "flags" contains TCL_LEAVE_ERR_MSG.
1871 *
1872 * Side effects:
1873 * None.
1874 *
1875 *----------------------------------------------------------------------
1876 */
1877
1878 Tcl_Namespace *
1879 Tcl_FindNamespace(interp, name, contextNsPtr, flags)
1880 Tcl_Interp *interp; /* The interpreter in which to find the
1881 * namespace. */
1882 CONST char *name; /* Namespace name. If it starts with "::",
1883 * will be looked up in global namespace.
1884 * Else, looked up first in contextNsPtr
1885 * (current namespace if contextNsPtr is
1886 * NULL), then in global namespace. */
1887 Tcl_Namespace *contextNsPtr; /* Ignored if TCL_GLOBAL_ONLY flag is set
1888 * or if the name starts with "::".
1889 * Otherwise, points to namespace in which
1890 * to resolve name; if NULL, look up name
1891 * in the current namespace. */
1892 register int flags; /* Flags controlling namespace lookup: an
1893 * OR'd combination of TCL_GLOBAL_ONLY and
1894 * TCL_LEAVE_ERR_MSG flags. */
1895 {
1896 Namespace *nsPtr, *dummy1Ptr, *dummy2Ptr;
1897 CONST char *dummy;
1898
1899 /*
1900 * Find the namespace(s) that contain the specified namespace name.
1901 * Add the FIND_ONLY_NS flag to resolve the name all the way down
1902 * to its last component, a namespace.
1903 */
1904
1905 TclGetNamespaceForQualName(interp, name, (Namespace *) contextNsPtr,
1906 (flags | FIND_ONLY_NS), &nsPtr, &dummy1Ptr, &dummy2Ptr, &dummy);
1907
1908 if (nsPtr != NULL) {
1909 return (Tcl_Namespace *) nsPtr;
1910 } else if (flags & TCL_LEAVE_ERR_MSG) {
1911 Tcl_ResetResult(interp);
1912 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1913 "unknown namespace \"", name, "\"", (char *) NULL);
1914 }
1915 return NULL;
1916 }
1917
1918 /*
1919 *----------------------------------------------------------------------
1920 *
1921 * Tcl_FindCommand --
1922 *
1923 * Searches for a command.
1924 *
1925 * Results:
1926 * Returns a token for the command if it is found. Otherwise, if it
1927 * can't be found or there is an error, returns NULL and leaves an
1928 * error message in the interpreter's result object if "flags"
1929 * contains TCL_LEAVE_ERR_MSG.
1930 *
1931 * Side effects:
1932 * None.
1933 *
1934 *----------------------------------------------------------------------
1935 */
1936
1937 Tcl_Command
1938 Tcl_FindCommand(interp, name, contextNsPtr, flags)
1939 Tcl_Interp *interp; /* The interpreter in which to find the
1940 * command and to report errors. */
1941 CONST char *name; /* Command's name. If it starts with "::",
1942 * will be looked up in global namespace.
1943 * Else, looked up first in contextNsPtr
1944 * (current namespace if contextNsPtr is
1945 * NULL), then in global namespace. */
1946 Tcl_Namespace *contextNsPtr; /* Ignored if TCL_GLOBAL_ONLY flag set.
1947 * Otherwise, points to namespace in which
1948 * to resolve name. If NULL, look up name
1949 * in the current namespace. */
1950 int flags; /* An OR'd combination of flags:
1951 * TCL_GLOBAL_ONLY (look up name only in
1952 * global namespace), TCL_NAMESPACE_ONLY
1953 * (look up only in contextNsPtr, or the
1954 * current namespace if contextNsPtr is
1955 * NULL), and TCL_LEAVE_ERR_MSG. If both
1956 * TCL_GLOBAL_ONLY and TCL_NAMESPACE_ONLY
1957 * are given, TCL_GLOBAL_ONLY is
1958 * ignored. */
1959 {
1960 Interp *iPtr = (Interp*)interp;
1961
1962 ResolverScheme *resPtr;
1963 Namespace *nsPtr[2], *cxtNsPtr;
1964 CONST char *simpleName;
1965 register Tcl_HashEntry *entryPtr;
1966 register Command *cmdPtr;
1967 register int search;
1968 int result;
1969 Tcl_Command cmd;
1970
1971 /*
1972 * If this namespace has a command resolver, then give it first
1973 * crack at the command resolution. If the interpreter has any
1974 * command resolvers, consult them next. The command resolver
1975 * procedures may return a Tcl_Command value, they may signal
1976 * to continue onward, or they may signal an error.
1977 */
1978 if ((flags & TCL_GLOBAL_ONLY) != 0) {
1979 cxtNsPtr = (Namespace *) Tcl_GetGlobalNamespace(interp);
1980 }
1981 else if (contextNsPtr != NULL) {
1982 cxtNsPtr = (Namespace *) contextNsPtr;
1983 }
1984 else {
1985 cxtNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
1986 }
1987
1988 if (cxtNsPtr->cmdResProc != NULL || iPtr->resolverPtr != NULL) {
1989 resPtr = iPtr->resolverPtr;
1990
1991 if (cxtNsPtr->cmdResProc) {
1992 result = (*cxtNsPtr->cmdResProc)(interp, name,
1993 (Tcl_Namespace *) cxtNsPtr, flags, &cmd);
1994 } else {
1995 result = TCL_CONTINUE;
1996 }
1997
1998 while (result == TCL_CONTINUE && resPtr) {
1999 if (resPtr->cmdResProc) {
2000 result = (*resPtr->cmdResProc)(interp, name,
2001 (Tcl_Namespace *) cxtNsPtr, flags, &cmd);
2002 }
2003 resPtr = resPtr->nextPtr;
2004 }
2005
2006 if (result == TCL_OK) {
2007 return cmd;
2008 }
2009 else if (result != TCL_CONTINUE) {
2010 return (Tcl_Command) NULL;
2011 }
2012 }
2013
2014 /*
2015 * Find the namespace(s) that contain the command.
2016 */
2017
2018 TclGetNamespaceForQualName(interp, name, (Namespace *) contextNsPtr,
2019 flags, &nsPtr[0], &nsPtr[1], &cxtNsPtr, &simpleName);
2020
2021 /*
2022 * Look for the command in the command table of its namespace.
2023 * Be sure to check both possible search paths: from the specified
2024 * namespace context and from the global namespace.
2025 */
2026
2027 cmdPtr = NULL;
2028 for (search = 0; (search < 2) && (cmdPtr == NULL); search++) {
2029 if ((nsPtr[search] != NULL) && (simpleName != NULL)) {
2030 entryPtr = Tcl_FindHashEntry(&nsPtr[search]->cmdTable,
2031 simpleName);
2032 if (entryPtr != NULL) {
2033 cmdPtr = (Command *) Tcl_GetHashValue(entryPtr);
2034 }
2035 }
2036 }
2037 if (cmdPtr != NULL) {
2038 return (Tcl_Command) cmdPtr;
2039 } else if (flags & TCL_LEAVE_ERR_MSG) {
2040 Tcl_ResetResult(interp);
2041 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
2042 "unknown command \"", name, "\"", (char *) NULL);
2043 }
2044
2045 return (Tcl_Command) NULL;
2046 }
2047
2048 /*
2049 *----------------------------------------------------------------------
2050 *
2051 * Tcl_FindNamespaceVar --
2052 *
2053 * Searches for a namespace variable, a variable not local to a
2054 * procedure. The variable can be either a scalar or an array, but
2055 * may not be an element of an array.
2056 *
2057 * Results:
2058 * Returns a token for the variable if it is found. Otherwise, if it
2059 * can't be found or there is an error, returns NULL and leaves an
2060 * error message in the interpreter's result object if "flags"
2061 * contains TCL_LEAVE_ERR_MSG.
2062 *
2063 * Side effects:
2064 * None.
2065 *
2066 *----------------------------------------------------------------------
2067 */
2068
2069 Tcl_Var
2070 Tcl_FindNamespaceVar(interp, name, contextNsPtr, flags)
2071 Tcl_Interp *interp; /* The interpreter in which to find the
2072 * variable. */
2073 CONST char *name; /* Variable's name. If it starts with "::",
2074 * will be looked up in global namespace.
2075 * Else, looked up first in contextNsPtr
2076 * (current namespace if contextNsPtr is
2077 * NULL), then in global namespace. */
2078 Tcl_Namespace *contextNsPtr; /* Ignored if TCL_GLOBAL_ONLY flag set.
2079 * Otherwise, points to namespace in which
2080 * to resolve name. If NULL, look up name
2081 * in the current namespace. */
2082 int flags; /* An OR'd combination of flags:
2083 * TCL_GLOBAL_ONLY (look up name only in
2084 * global namespace), TCL_NAMESPACE_ONLY
2085 * (look up only in contextNsPtr, or the
2086 * current namespace if contextNsPtr is
2087 * NULL), and TCL_LEAVE_ERR_MSG. If both
2088 * TCL_GLOBAL_ONLY and TCL_NAMESPACE_ONLY
2089 * are given, TCL_GLOBAL_ONLY is
2090 * ignored. */
2091 {
2092 Interp *iPtr = (Interp*)interp;
2093 ResolverScheme *resPtr;
2094 Namespace *nsPtr[2], *cxtNsPtr;
2095 CONST char *simpleName;
2096 Tcl_HashEntry *entryPtr;
2097 Var *varPtr;
2098 register int search;
2099 int result;
2100 Tcl_Var var;
2101
2102 /*
2103 * If this namespace has a variable resolver, then give it first
2104 * crack at the variable resolution. It may return a Tcl_Var
2105 * value, it may signal to continue onward, or it may signal
2106 * an error.
2107 */
2108 if ((flags & TCL_GLOBAL_ONLY) != 0) {
2109 cxtNsPtr = (Namespace *) Tcl_GetGlobalNamespace(interp);
2110 }
2111 else if (contextNsPtr != NULL) {
2112 cxtNsPtr = (Namespace *) contextNsPtr;
2113 }
2114 else {
2115 cxtNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
2116 }
2117
2118 if (cxtNsPtr->varResProc != NULL || iPtr->resolverPtr != NULL) {
2119 resPtr = iPtr->resolverPtr;
2120
2121 if (cxtNsPtr->varResProc) {
2122 result = (*cxtNsPtr->varResProc)(interp, name,
2123 (Tcl_Namespace *) cxtNsPtr, flags, &var);
2124 } else {
2125 result = TCL_CONTINUE;
2126 }
2127
2128 while (result == TCL_CONTINUE && resPtr) {
2129 if (resPtr->varResProc) {
2130 result = (*resPtr->varResProc)(interp, name,
2131 (Tcl_Namespace *) cxtNsPtr, flags, &var);
2132 }
2133 resPtr = resPtr->nextPtr;
2134 }
2135
2136 if (result == TCL_OK) {
2137 return var;
2138 }
2139 else if (result != TCL_CONTINUE) {
2140 return (Tcl_Var) NULL;
2141 }
2142 }
2143
2144 /*
2145 * Find the namespace(s) that contain the variable.
2146 */
2147
2148 TclGetNamespaceForQualName(interp, name, (Namespace *) contextNsPtr,
2149 flags, &nsPtr[0], &nsPtr[1], &cxtNsPtr, &simpleName);
2150
2151 /*
2152 * Look for the variable in the variable table of its namespace.
2153 * Be sure to check both possible search paths: from the specified
2154 * namespace context and from the global namespace.
2155 */
2156
2157 varPtr = NULL;
2158 for (search = 0; (search < 2) && (varPtr == NULL); search++) {
2159 if ((nsPtr[search] != NULL) && (simpleName != NULL)) {
2160 entryPtr = Tcl_FindHashEntry(&nsPtr[search]->varTable,
2161 simpleName);
2162 if (entryPtr != NULL) {
2163 varPtr = (Var *) Tcl_GetHashValue(entryPtr);
2164 }
2165 }
2166 }
2167 if (varPtr != NULL) {
2168 return (Tcl_Var) varPtr;
2169 } else if (flags & TCL_LEAVE_ERR_MSG) {
2170 Tcl_ResetResult(interp);
2171 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
2172 "unknown variable \"", name, "\"", (char *) NULL);
2173 }
2174 return (Tcl_Var) NULL;
2175 }
2176
2177 /*
2178 *----------------------------------------------------------------------
2179 *
2180 * TclResetShadowedCmdRefs --
2181 *
2182 * Called when a command is added to a namespace to check for existing
2183 * command references that the new command may invalidate. Consider the
2184 * following cases that could happen when you add a command "foo" to a
2185 * namespace "b":
2186 * 1. It could shadow a command named "foo" at the global scope.
2187 * If it does, all command references in the namespace "b" are
2188 * suspect.
2189 * 2. Suppose the namespace "b" resides in a namespace "a".
2190 * Then to "a" the new command "b::foo" could shadow another
2191 * command "b::foo" in the global namespace. If so, then all
2192 * command references in "a" are suspect.
2193 * The same checks are applied to all parent namespaces, until we
2194 * reach the global :: namespace.
2195 *
2196 * Results:
2197 * None.
2198 *
2199 * Side effects:
2200 * If the new command shadows an existing command, the cmdRefEpoch
2201 * counter is incremented in each namespace that sees the shadow.
2202 * This invalidates all command references that were previously cached
2203 * in that namespace. The next time the commands are used, they are
2204 * resolved from scratch.
2205 *
2206 *----------------------------------------------------------------------
2207 */
2208
2209 void
2210 TclResetShadowedCmdRefs(interp, newCmdPtr)
2211 Tcl_Interp *interp; /* Interpreter containing the new command. */
2212 Command *newCmdPtr; /* Points to the new command. */
2213 {
2214 char *cmdName;
2215 Tcl_HashEntry *hPtr;
2216 register Namespace *nsPtr;
2217 Namespace *trailNsPtr, *shadowNsPtr;
2218 Namespace *globalNsPtr = (Namespace *) Tcl_GetGlobalNamespace(interp);
2219 int found, i;
2220
2221 /*
2222 * This procedure generates an array used to hold the trail list. This
2223 * starts out with stack-allocated space but uses dynamically-allocated
2224 * storage if needed.
2225 */
2226
2227 Namespace *(trailStorage[NUM_TRAIL_ELEMS]);
2228 Namespace **trailPtr = trailStorage;
2229 int trailFront = -1;
2230 int trailSize = NUM_TRAIL_ELEMS;
2231
2232 /*
2233 * Start at the namespace containing the new command, and work up
2234 * through the list of parents. Stop just before the global namespace,
2235 * since the global namespace can't "shadow" its own entries.
2236 *
2237 * The namespace "trail" list we build consists of the names of each
2238 * namespace that encloses the new command, in order from outermost to
2239 * innermost: for example, "a" then "b". Each iteration of this loop
2240 * eventually extends the trail upwards by one namespace, nsPtr. We use
2241 * this trail list to see if nsPtr (e.g. "a" in 2. above) could have
2242 * now-invalid cached command references. This will happen if nsPtr
2243 * (e.g. "a") contains a sequence of child namespaces (e.g. "b")
2244 * such that there is a identically-named sequence of child namespaces
2245 * starting from :: (e.g. "::b") whose tail namespace contains a command
2246 * also named cmdName.
2247 */
2248
2249 cmdName = Tcl_GetHashKey(newCmdPtr->hPtr->tablePtr, newCmdPtr->hPtr);
2250 for (nsPtr = newCmdPtr->nsPtr;
2251 (nsPtr != NULL) && (nsPtr != globalNsPtr);
2252 nsPtr = nsPtr->parentPtr) {
2253 /*
2254 * Find the maximal sequence of child namespaces contained in nsPtr
2255 * such that there is a identically-named sequence of child
2256 * namespaces starting from ::. shadowNsPtr will be the tail of this
2257 * sequence, or the deepest namespace under :: that might contain a
2258 * command now shadowed by cmdName. We check below if shadowNsPtr
2259 * actually contains a command cmdName.
2260 */
2261
2262 found = 1;
2263 shadowNsPtr = globalNsPtr;
2264
2265 for (i = trailFront; i >= 0; i--) {
2266 trailNsPtr = trailPtr[i];
2267 hPtr = Tcl_FindHashEntry(&shadowNsPtr->childTable,
2268 trailNsPtr->name);
2269 if (hPtr != NULL) {
2270 shadowNsPtr = (Namespace *) Tcl_GetHashValue(hPtr);
2271 } else {
2272 found = 0;
2273 break;
2274 }
2275 }
2276
2277 /*
2278 * If shadowNsPtr contains a command named cmdName, we invalidate
2279 * all of the command refs cached in nsPtr. As a boundary case,
2280 * shadowNsPtr is initially :: and we check for case 1. above.
2281 */
2282
2283 if (found) {
2284 hPtr = Tcl_FindHashEntry(&shadowNsPtr->cmdTable, cmdName);
2285 if (hPtr != NULL) {
2286 nsPtr->cmdRefEpoch++;
2287
2288 /*
2289 * If the shadowed command was compiled to bytecodes, we
2290 * invalidate all the bytecodes in nsPtr, to force a new
2291 * compilation. We use the resolverEpoch to signal the need
2292 * for a fresh compilation of every bytecode.
2293 */
2294
2295 if ((((Command *) Tcl_GetHashValue(hPtr))->compileProc) != NULL) {
2296 nsPtr->resolverEpoch++;
2297 }
2298 }
2299 }
2300
2301 /*
2302 * Insert nsPtr at the front of the trail list: i.e., at the end
2303 * of the trailPtr array.
2304 */
2305
2306 trailFront++;
2307 if (trailFront == trailSize) {
2308 size_t currBytes = trailSize * sizeof(Namespace *);
2309 int newSize = 2*trailSize;
2310 size_t newBytes = newSize * sizeof(Namespace *);
2311 Namespace **newPtr =
2312 (Namespace **) ckalloc((unsigned) newBytes);
2313
2314 memcpy((VOID *) newPtr, (VOID *) trailPtr, currBytes);
2315 if (trailPtr != trailStorage) {
2316 ckfree((char *) trailPtr);
2317 }
2318 trailPtr = newPtr;
2319 trailSize = newSize;
2320 }
2321 trailPtr[trailFront] = nsPtr;
2322 }
2323
2324 /*
2325 * Free any allocated storage.
2326 */
2327
2328 if (trailPtr != trailStorage) {
2329 ckfree((char *) trailPtr);
2330 }
2331 }
2332
2333 /*
2334 *----------------------------------------------------------------------
2335 *
2336 * GetNamespaceFromObj --
2337 *
2338 * Gets the namespace specified by the name in a Tcl_Obj.
2339 *
2340 * Results:
2341 * Returns TCL_OK if the namespace was resolved successfully, and
2342 * stores a pointer to the namespace in the location specified by
2343 * nsPtrPtr. If the namespace can't be found, the procedure stores
2344 * NULL in *nsPtrPtr and returns TCL_OK. If anything else goes wrong,
2345 * this procedure returns TCL_ERROR.
2346 *
2347 * Side effects:
2348 * May update the internal representation for the object, caching the
2349 * namespace reference. The next time this procedure is called, the
2350 * namespace value can be found quickly.
2351 *
2352 * If anything goes wrong, an error message is left in the
2353 * interpreter's result object.
2354 *
2355 *----------------------------------------------------------------------
2356 */
2357
2358 static int
2359 GetNamespaceFromObj(interp, objPtr, nsPtrPtr)
2360 Tcl_Interp *interp; /* The current interpreter. */
2361 Tcl_Obj *objPtr; /* The object to be resolved as the name
2362 * of a namespace. */
2363 Tcl_Namespace **nsPtrPtr; /* Result namespace pointer goes here. */
2364 {
2365 Interp *iPtr = (Interp *) interp;
2366 register ResolvedNsName *resNamePtr;
2367 register Namespace *nsPtr;
2368 Namespace *currNsPtr;
2369 CallFrame *savedFramePtr;
2370 int result = TCL_OK;
2371 char *name;
2372
2373 /*
2374 * If the namespace name is fully qualified, do as if the lookup were
2375 * done from the global namespace; this helps avoid repeated lookups
2376 * of fully qualified names.
2377 */
2378
2379 savedFramePtr = iPtr->varFramePtr;
2380 name = Tcl_GetString(objPtr);
2381 if ((*name++ == ':') && (*name == ':')) {
2382 iPtr->varFramePtr = NULL;
2383 }
2384
2385 currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
2386
2387 /*
2388 * Get the internal representation, converting to a namespace type if
2389 * needed. The internal representation is a ResolvedNsName that points
2390 * to the actual namespace.
2391 */
2392
2393 if (objPtr->typePtr != &tclNsNameType) {
2394 result = tclNsNameType.setFromAnyProc(interp, objPtr);
2395 if (result != TCL_OK) {
2396 goto done;
2397 }
2398 }
2399 resNamePtr = (ResolvedNsName *) objPtr->internalRep.otherValuePtr;
2400
2401 /*
2402 * Check the context namespace of the resolved symbol to make sure that
2403 * it is fresh. If not, then force another conversion to the namespace
2404 * type, to discard the old rep and create a new one. Note that we
2405 * verify that the namespace id of the cached namespace is the same as
2406 * the id when we cached it; this insures that the namespace wasn't
2407 * deleted and a new one created at the same address.
2408 */
2409
2410 nsPtr = NULL;
2411 if ((resNamePtr != NULL)
2412 && (resNamePtr->refNsPtr == currNsPtr)
2413 && (resNamePtr->nsId == resNamePtr->nsPtr->nsId)) {
2414 nsPtr = resNamePtr->nsPtr;
2415 if (nsPtr->flags & NS_DEAD) {
2416 nsPtr = NULL;
2417 }
2418 }
2419 if (nsPtr == NULL) { /* try again */
2420 result = tclNsNameType.setFromAnyProc(interp, objPtr);
2421 if (result != TCL_OK) {
2422 goto done;
2423 }
2424 resNamePtr = (ResolvedNsName *) objPtr->internalRep.otherValuePtr;
2425 if (resNamePtr != NULL) {
2426 nsPtr = resNamePtr->nsPtr;
2427 if (nsPtr->flags & NS_DEAD) {
2428 nsPtr = NULL;
2429 }
2430 }
2431 }
2432 *nsPtrPtr = (Tcl_Namespace *) nsPtr;
2433
2434 done:
2435 iPtr->varFramePtr = savedFramePtr;
2436 return result;
2437 }
2438
2439 /*
2440 *----------------------------------------------------------------------
2441 *
2442 * Tcl_NamespaceObjCmd --
2443 *
2444 * Invoked to implement the "namespace" command that creates, deletes,
2445 * or manipulates Tcl namespaces. Handles the following syntax:
2446 *
2447 * namespace children ?name? ?pattern?
2448 * namespace code arg
2449 * namespace current
2450 * namespace delete ?name name...?
2451 * namespace eval name arg ?arg...?
2452 * namespace exists name
2453 * namespace export ?-clear? ?pattern pattern...?
2454 * namespace forget ?pattern pattern...?
2455 * namespace import ?-force? ?pattern pattern...?
2456 * namespace inscope name arg ?arg...?
2457 * namespace origin name
2458 * namespace parent ?name?
2459 * namespace qualifiers string
2460 * namespace tail string
2461 * namespace which ?-command? ?-variable? name
2462 *
2463 * Results:
2464 * Returns TCL_OK if the command is successful. Returns TCL_ERROR if
2465 * anything goes wrong.
2466 *
2467 * Side effects:
2468 * Based on the subcommand name (e.g., "import"), this procedure
2469 * dispatches to a corresponding procedure NamespaceXXXCmd defined
2470 * statically in this file. This procedure's side effects depend on
2471 * whatever that subcommand procedure does. If there is an error, this
2472 * procedure returns an error message in the interpreter's result
2473 * object. Otherwise it may return a result in the interpreter's result
2474 * object.
2475 *
2476 *----------------------------------------------------------------------
2477 */
2478
2479 int
2480 Tcl_NamespaceObjCmd(clientData, interp, objc, objv)
2481 ClientData clientData; /* Arbitrary value passed to cmd. */
2482 Tcl_Interp *interp; /* Current interpreter. */
2483 register int objc; /* Number of arguments. */
2484 register Tcl_Obj *CONST objv[]; /* Argument objects. */
2485 {
2486 static CONST char *subCmds[] = {
2487 "children", "code", "current", "delete",
2488 "eval", "exists", "export", "forget", "import",
2489 "inscope", "origin", "parent", "qualifiers",
2490 "tail", "which", (char *) NULL
2491 };
2492 enum NSSubCmdIdx {
2493 NSChildrenIdx, NSCodeIdx, NSCurrentIdx, NSDeleteIdx,
2494 NSEvalIdx, NSExistsIdx, NSExportIdx, NSForgetIdx, NSImportIdx,
2495 NSInscopeIdx, NSOriginIdx, NSParentIdx, NSQualifiersIdx,
2496 NSTailIdx, NSWhichIdx
2497 };
2498 int index, result;
2499
2500 if (objc < 2) {
2501 Tcl_WrongNumArgs(interp, 1, objv, "subcommand ?arg ...?");
2502 return TCL_ERROR;
2503 }
2504
2505 /*
2506 * Return an index reflecting the particular subcommand.
2507 */
2508
2509 result = Tcl_GetIndexFromObj((Tcl_Interp *) interp, objv[1], subCmds,
2510 "option", /*flags*/ 0, (int *) &index);
2511 if (result != TCL_OK) {
2512 return result;
2513 }
2514
2515 switch (index) {
2516 case NSChildrenIdx:
2517 result = NamespaceChildrenCmd(clientData, interp, objc, objv);
2518 break;
2519 case NSCodeIdx:
2520 result = NamespaceCodeCmd(clientData, interp, objc, objv);
2521 break;
2522 case NSCurrentIdx:
2523 result = NamespaceCurrentCmd(clientData, interp, objc, objv);
2524 break;
2525 case NSDeleteIdx:
2526 result = NamespaceDeleteCmd(clientData, interp, objc, objv);
2527 break;
2528 case NSEvalIdx:
2529 result = NamespaceEvalCmd(clientData, interp, objc, objv);
2530 break;
2531 case NSExistsIdx:
2532 result = NamespaceExistsCmd(clientData, interp, objc, objv);
2533 break;
2534 case NSExportIdx:
2535 result = NamespaceExportCmd(clientData, interp, objc, objv);
2536 break;
2537 case NSForgetIdx:
2538 result = NamespaceForgetCmd(clientData, interp, objc, objv);
2539 break;
2540 case NSImportIdx:
2541 result = NamespaceImportCmd(clientData, interp, objc, objv);
2542 break;
2543 case NSInscopeIdx:
2544 result = NamespaceInscopeCmd(clientData, interp, objc, objv);
2545 break;
2546 case NSOriginIdx:
2547 result = NamespaceOriginCmd(clientData, interp, objc, objv);
2548 break;
2549 case NSParentIdx:
2550 result = NamespaceParentCmd(clientData, interp, objc, objv);
2551 break;
2552 case NSQualifiersIdx:
2553 result = NamespaceQualifiersCmd(clientData, interp, objc, objv);
2554 break;
2555 case NSTailIdx:
2556 result = NamespaceTailCmd(clientData, interp, objc, objv);
2557 break;
2558 case NSWhichIdx:
2559 result = NamespaceWhichCmd(clientData, interp, objc, objv);
2560 break;
2561 }
2562 return result;
2563 }
2564
2565 /*
2566 *----------------------------------------------------------------------
2567 *
2568 * NamespaceChildrenCmd --
2569 *
2570 * Invoked to implement the "namespace children" command that returns a
2571 * list containing the fully-qualified names of the child namespaces of
2572 * a given namespace. Handles the following syntax:
2573 *
2574 * namespace children ?name? ?pattern?
2575 *
2576 * Results:
2577 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
2578 *
2579 * Side effects:
2580 * Returns a result in the interpreter's result object. If anything
2581 * goes wrong, the result is an error message.
2582 *
2583 *----------------------------------------------------------------------
2584 */
2585
2586 static int
2587 NamespaceChildrenCmd(dummy, interp, objc, objv)
2588 ClientData dummy; /* Not used. */
2589 Tcl_Interp *interp; /* Current interpreter. */
2590 int objc; /* Number of arguments. */
2591 Tcl_Obj *CONST objv[]; /* Argument objects. */
2592 {
2593 Tcl_Namespace *namespacePtr;
2594 Namespace *nsPtr, *childNsPtr;
2595 Namespace *globalNsPtr = (Namespace *) Tcl_GetGlobalNamespace(interp);
2596 char *pattern = NULL;
2597 Tcl_DString buffer;
2598 register Tcl_HashEntry *entryPtr;
2599 Tcl_HashSearch search;
2600 Tcl_Obj *listPtr, *elemPtr;
2601
2602 /*
2603 * Get a pointer to the specified namespace, or the current namespace.
2604 */
2605
2606 if (objc == 2) {
2607 nsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
2608 } else if ((objc == 3) || (objc == 4)) {
2609 if (GetNamespaceFromObj(interp, objv[2], &namespacePtr) != TCL_OK) {
2610 return TCL_ERROR;
2611 }
2612 if (namespacePtr == NULL) {
2613 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
2614 "unknown namespace \"", Tcl_GetString(objv[2]),
2615 "\" in namespace children command", (char *) NULL);
2616 return TCL_ERROR;
2617 }
2618 nsPtr = (Namespace *) namespacePtr;
2619 } else {
2620 Tcl_WrongNumArgs(interp, 2, objv, "?name? ?pattern?");
2621 return TCL_ERROR;
2622 }
2623
2624 /*
2625 * Get the glob-style pattern, if any, used to narrow the search.
2626 */
2627
2628 Tcl_DStringInit(&buffer);
2629 if (objc == 4) {
2630 char *name = Tcl_GetString(objv[3]);
2631
2632 if ((*name == ':') && (*(name+1) == ':')) {
2633 pattern = name;
2634 } else {
2635 Tcl_DStringAppend(&buffer, nsPtr->fullName, -1);
2636 if (nsPtr != globalNsPtr) {
2637 Tcl_DStringAppend(&buffer, "::", 2);
2638 }
2639 Tcl_DStringAppend(&buffer, name, -1);
2640 pattern = Tcl_DStringValue(&buffer);
2641 }
2642 }
2643
2644 /*
2645 * Create a list containing the full names of all child namespaces
2646 * whose names match the specified pattern, if any.
2647 */
2648
2649 listPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
2650 entryPtr = Tcl_FirstHashEntry(&nsPtr->childTable, &search);
2651 while (entryPtr != NULL) {
2652 childNsPtr = (Namespace *) Tcl_GetHashValue(entryPtr);
2653 if ((pattern == NULL)
2654 || Tcl_StringMatch(childNsPtr->fullName, pattern)) {
2655 elemPtr = Tcl_NewStringObj(childNsPtr->fullName, -1);
2656 Tcl_ListObjAppendElement(interp, listPtr, elemPtr);
2657 }
2658 entryPtr = Tcl_NextHashEntry(&search);
2659 }
2660
2661 Tcl_SetObjResult(interp, listPtr);
2662 Tcl_DStringFree(&buffer);
2663 return TCL_OK;
2664 }
2665
2666 /*
2667 *----------------------------------------------------------------------
2668 *
2669 * NamespaceCodeCmd --
2670 *
2671 * Invoked to implement the "namespace code" command to capture the
2672 * namespace context of a command. Handles the following syntax:
2673 *
2674 * namespace code arg
2675 *
2676 * Here "arg" can be a list. "namespace code arg" produces a result
2677 * equivalent to that produced by the command
2678 *
2679 * list ::namespace inscope [namespace current] $arg
2680 *
2681 * However, if "arg" is itself a scoped value starting with
2682 * "::namespace inscope", then the result is just "arg".
2683 *
2684 * Results:
2685 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
2686 *
2687 * Side effects:
2688 * If anything goes wrong, this procedure returns an error
2689 * message as the result in the interpreter's result object.
2690 *
2691 *----------------------------------------------------------------------
2692 */
2693
2694 static int
2695 NamespaceCodeCmd(dummy, interp, objc, objv)
2696 ClientData dummy; /* Not used. */
2697 Tcl_Interp *interp; /* Current interpreter. */
2698 int objc; /* Number of arguments. */
2699 Tcl_Obj *CONST objv[]; /* Argument objects. */
2700 {
2701 Namespace *currNsPtr;
2702 Tcl_Obj *listPtr, *objPtr;
2703 register char *arg, *p;
2704 int length;
2705
2706 if (objc != 3) {
2707 Tcl_WrongNumArgs(interp, 2, objv, "arg");
2708 return TCL_ERROR;
2709 }
2710
2711 /*
2712 * If "arg" is already a scoped value, then return it directly.
2713 */
2714
2715 arg = Tcl_GetStringFromObj(objv[2], &length);
2716 while (*arg == ':') {
2717 arg++;
2718 length--;
2719 }
2720 if ((*arg == 'n') && (length > 17)
2721 && (strncmp(arg, "namespace", 9) == 0)) {
2722 for (p = (arg + 9); (*p == ' '); p++) {
2723 /* empty body: skip over spaces */
2724 }
2725 if ((*p == 'i') && ((p + 7) <= (arg + length))
2726 && (strncmp(p, "inscope", 7) == 0)) {
2727 Tcl_SetObjResult(interp, objv[2]);
2728 return TCL_OK;
2729 }
2730 }
2731
2732 /*
2733 * Otherwise, construct a scoped command by building a list with
2734 * "namespace inscope", the full name of the current namespace, and
2735 * the argument "arg". By constructing a list, we ensure that scoped
2736 * commands are interpreted properly when they are executed later,
2737 * by the "namespace inscope" command.
2738 */
2739
2740 listPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
2741 Tcl_ListObjAppendElement(interp, listPtr,
2742 Tcl_NewStringObj("::namespace", -1));
2743 Tcl_ListObjAppendElement(interp, listPtr,
2744 Tcl_NewStringObj("inscope", -1));
2745
2746 currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
2747 if (currNsPtr == (Namespace *) Tcl_GetGlobalNamespace(interp)) {
2748 objPtr = Tcl_NewStringObj("::", -1);
2749 } else {
2750 objPtr = Tcl_NewStringObj(currNsPtr->fullName, -1);
2751 }
2752 Tcl_ListObjAppendElement(interp, listPtr, objPtr);
2753
2754 Tcl_ListObjAppendElement(interp, listPtr, objv[2]);
2755
2756 Tcl_SetObjResult(interp, listPtr);
2757 return TCL_OK;
2758 }
2759
2760 /*
2761 *----------------------------------------------------------------------
2762 *
2763 * NamespaceCurrentCmd --
2764 *
2765 * Invoked to implement the "namespace current" command which returns
2766 * the fully-qualified name of the current namespace. Handles the
2767 * following syntax:
2768 *
2769 * namespace current
2770 *
2771 * Results:
2772 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
2773 *
2774 * Side effects:
2775 * Returns a result in the interpreter's result object. If anything
2776 * goes wrong, the result is an error message.
2777 *
2778 *----------------------------------------------------------------------
2779 */
2780
2781 static int
2782 NamespaceCurrentCmd(dummy, interp, objc, objv)
2783 ClientData dummy; /* Not used. */
2784 Tcl_Interp *interp; /* Current interpreter. */
2785 int objc; /* Number of arguments. */
2786 Tcl_Obj *CONST objv[]; /* Argument objects. */
2787 {
2788 register Namespace *currNsPtr;
2789
2790 if (objc != 2) {
2791 Tcl_WrongNumArgs(interp, 2, objv, NULL);
2792 return TCL_ERROR;
2793 }
2794
2795 /*
2796 * The "real" name of the global namespace ("::") is the null string,
2797 * but we return "::" for it as a convenience to programmers. Note that
2798 * "" and "::" are treated as synonyms by the namespace code so that it
2799 * is still easy to do things like:
2800 *
2801 * namespace [namespace current]::bar { ... }
2802 */
2803
2804 currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
2805 if (currNsPtr == (Namespace *) Tcl_GetGlobalNamespace(interp)) {
2806 Tcl_AppendToObj(Tcl_GetObjResult(interp), "::", -1);
2807 } else {
2808 Tcl_AppendToObj(Tcl_GetObjResult(interp), currNsPtr->fullName, -1);
2809 }
2810 return TCL_OK;
2811 }
2812
2813 /*
2814 *----------------------------------------------------------------------
2815 *
2816 * NamespaceDeleteCmd --
2817 *
2818 * Invoked to implement the "namespace delete" command to delete
2819 * namespace(s). Handles the following syntax:
2820 *
2821 * namespace delete ?name name...?
2822 *
2823 * Each name identifies a namespace. It may include a sequence of
2824 * namespace qualifiers separated by "::"s. If a namespace is found, it
2825 * is deleted: all variables and procedures contained in that namespace
2826 * are deleted. If that namespace is being used on the call stack, it
2827 * is kept alive (but logically deleted) until it is removed from the
2828 * call stack: that is, it can no longer be referenced by name but any
2829 * currently executing procedure that refers to it is allowed to do so
2830 * until the procedure returns. If the namespace can't be found, this
2831 * procedure returns an error. If no namespaces are specified, this
2832 * command does nothing.
2833 *
2834 * Results:
2835 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
2836 *
2837 * Side effects:
2838 * Deletes the specified namespaces. If anything goes wrong, this
2839 * procedure returns an error message in the interpreter's
2840 * result object.
2841 *
2842 *----------------------------------------------------------------------
2843 */
2844
2845 static int
2846 NamespaceDeleteCmd(dummy, interp, objc, objv)
2847 ClientData dummy; /* Not used. */
2848 Tcl_Interp *interp; /* Current interpreter. */
2849 int objc; /* Number of arguments. */
2850 Tcl_Obj *CONST objv[]; /* Argument objects. */
2851 {
2852 Tcl_Namespace *namespacePtr;
2853 char *name;
2854 register int i;
2855
2856 if (objc < 2) {
2857 Tcl_WrongNumArgs(interp, 2, objv, "?name name...?");
2858 return TCL_ERROR;
2859 }
2860
2861 /*
2862 * Destroying one namespace may cause another to be destroyed. Break
2863 * this into two passes: first check to make sure that all namespaces on
2864 * the command line are valid, and report any errors.
2865 */
2866
2867 for (i = 2; i < objc; i++) {
2868 name = Tcl_GetString(objv[i]);
2869 namespacePtr = Tcl_FindNamespace(interp, name,
2870 (Tcl_Namespace *) NULL, /*flags*/ 0);
2871 if (namespacePtr == NULL) {
2872 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
2873 "unknown namespace \"", Tcl_GetString(objv[i]),
2874 "\" in namespace delete command", (char *) NULL);
2875 return TCL_ERROR;
2876 }
2877 }
2878
2879 /*
2880 * Okay, now delete each namespace.
2881 */
2882
2883 for (i = 2; i < objc; i++) {
2884 name = Tcl_GetString(objv[i]);
2885 namespacePtr = Tcl_FindNamespace(interp, name,
2886 (Tcl_Namespace *) NULL, /* flags */ 0);
2887 if (namespacePtr) {
2888 Tcl_DeleteNamespace(namespacePtr);
2889 }
2890 }
2891 return TCL_OK;
2892 }
2893
2894 /*
2895 *----------------------------------------------------------------------
2896 *
2897 * NamespaceEvalCmd --
2898 *
2899 * Invoked to implement the "namespace eval" command. Executes
2900 * commands in a namespace. If the namespace does not already exist,
2901 * it is created. Handles the following syntax:
2902 *
2903 * namespace eval name arg ?arg...?
2904 *
2905 * If more than one arg argument is specified, the command that is
2906 * executed is the result of concatenating the arguments together with
2907 * a space between each argument.
2908 *
2909 * Results:
2910 * Returns TCL_OK if the namespace is found and the commands are
2911 * executed successfully. Returns TCL_ERROR if anything goes wrong.
2912 *
2913 * Side effects:
2914 * Returns the result of the command in the interpreter's result
2915 * object. If anything goes wrong, this procedure returns an error
2916 * message as the result.
2917 *
2918 *----------------------------------------------------------------------
2919 */
2920
2921 static int
2922 NamespaceEvalCmd(dummy, interp, objc, objv)
2923 ClientData dummy; /* Not used. */
2924 Tcl_Interp *interp; /* Current interpreter. */
2925 int objc; /* Number of arguments. */
2926 Tcl_Obj *CONST objv[]; /* Argument objects. */
2927 {
2928 Tcl_Namespace *namespacePtr;
2929 CallFrame frame;
2930 Tcl_Obj *objPtr;
2931 char *name;
2932 int length, result;
2933
2934 if (objc < 4) {
2935 Tcl_WrongNumArgs(interp, 2, objv, "name arg ?arg...?");
2936 return TCL_ERROR;
2937 }
2938
2939 /*
2940 * Try to resolve the namespace reference, caching the result in the
2941 * namespace object along the way.
2942 */
2943
2944 result = GetNamespaceFromObj(interp, objv[2], &namespacePtr);
2945 if (result != TCL_OK) {
2946 return result;
2947 }
2948
2949 /*
2950 * If the namespace wasn't found, try to create it.
2951 */
2952
2953 if (namespacePtr == NULL) {
2954 name = Tcl_GetStringFromObj(objv[2], &length);
2955 namespacePtr = Tcl_CreateNamespace(interp, name, (ClientData) NULL,
2956 (Tcl_NamespaceDeleteProc *) NULL);
2957 if (namespacePtr == NULL) {
2958 return TCL_ERROR;
2959 }
2960 }
2961
2962 /*
2963 * Make the specified namespace the current namespace and evaluate
2964 * the command(s).
2965 */
2966
2967 result = Tcl_PushCallFrame(interp, (Tcl_CallFrame *) &frame,
2968 namespacePtr, /*isProcCallFrame*/ 0);
2969 if (result != TCL_OK) {
2970 return TCL_ERROR;
2971 }
2972 frame.objc = objc;
2973 frame.objv = objv; /* ref counts do not need to be incremented here */
2974
2975 if (objc == 4) {
2976 result = Tcl_EvalObjEx(interp, objv[3], 0);
2977 } else {
2978 /*
2979 * More than one argument: concatenate them together with spaces
2980 * between, then evaluate the result. Tcl_EvalObjEx will delete
2981 * the object when it decrements its refcount after eval'ing it.
2982 */
2983 objPtr = Tcl_ConcatObj(objc-3, objv+3);
2984 result = Tcl_EvalObjEx(interp, objPtr, TCL_EVAL_DIRECT);
2985 }
2986 if (result == TCL_ERROR) {
2987 char msg[256 + TCL_INTEGER_SPACE];
2988
2989 sprintf(msg, "\n (in namespace eval \"%.200s\" script line %d)",
2990 namespacePtr->fullName, interp->errorLine);
2991 Tcl_AddObjErrorInfo(interp, msg, -1);
2992 }
2993
2994 /*
2995 * Restore the previous "current" namespace.
2996 */
2997
2998 Tcl_PopCallFrame(interp);
2999 return result;
3000 }
3001
3002 /*
3003 *----------------------------------------------------------------------
3004 *
3005 * NamespaceExistsCmd --
3006 *
3007 * Invoked to implement the "namespace exists" command that returns
3008 * true if the given namespace currently exists, and false otherwise.
3009 * Handles the following syntax:
3010 *
3011 * namespace exists name
3012 *
3013 * Results:
3014 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3015 *
3016 * Side effects:
3017 * Returns a result in the interpreter's result object. If anything
3018 * goes wrong, the result is an error message.
3019 *
3020 *----------------------------------------------------------------------
3021 */
3022
3023 static int
3024 NamespaceExistsCmd(dummy, interp, objc, objv)
3025 ClientData dummy; /* Not used. */
3026 Tcl_Interp *interp; /* Current interpreter. */
3027 int objc; /* Number of arguments. */
3028 Tcl_Obj *CONST objv[]; /* Argument objects. */
3029 {
3030 Tcl_Namespace *namespacePtr;
3031
3032 if (objc != 3) {
3033 Tcl_WrongNumArgs(interp, 2, objv, "name");
3034 return TCL_ERROR;
3035 }
3036
3037 /*
3038 * Check whether the given namespace exists
3039 */
3040
3041 if (GetNamespaceFromObj(interp, objv[2], &namespacePtr) != TCL_OK) {
3042 return TCL_ERROR;
3043 }
3044
3045 Tcl_SetBooleanObj(Tcl_GetObjResult(interp), (namespacePtr != NULL));
3046 return TCL_OK;
3047 }
3048
3049 /*
3050 *----------------------------------------------------------------------
3051 *
3052 * NamespaceExportCmd --
3053 *
3054 * Invoked to implement the "namespace export" command that specifies
3055 * which commands are exported from a namespace. The exported commands
3056 * are those that can be imported into another namespace using
3057 * "namespace import". Both commands defined in a namespace and
3058 * commands the namespace has imported can be exported by a
3059 * namespace. This command has the following syntax:
3060 *
3061 * namespace export ?-clear? ?pattern pattern...?
3062 *
3063 * Each pattern may contain "string match"-style pattern matching
3064 * special characters, but the pattern may not include any namespace
3065 * qualifiers: that is, the pattern must specify commands in the
3066 * current (exporting) namespace. The specified patterns are appended
3067 * onto the namespace's list of export patterns.
3068 *
3069 * To reset the namespace's export pattern list, specify the "-clear"
3070 * flag.
3071 *
3072 * If there are no export patterns and the "-clear" flag isn't given,
3073 * this command returns the namespace's current export list.
3074 *
3075 * Results:
3076 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3077 *
3078 * Side effects:
3079 * Returns a result in the interpreter's result object. If anything
3080 * goes wrong, the result is an error message.
3081 *
3082 *----------------------------------------------------------------------
3083 */
3084
3085 static int
3086 NamespaceExportCmd(dummy, interp, objc, objv)
3087 ClientData dummy; /* Not used. */
3088 Tcl_Interp *interp; /* Current interpreter. */
3089 int objc; /* Number of arguments. */
3090 Tcl_Obj *CONST objv[]; /* Argument objects. */
3091 {
3092 Namespace *currNsPtr = (Namespace*) Tcl_GetCurrentNamespace(interp);
3093 char *pattern, *string;
3094 int resetListFirst = 0;
3095 int firstArg, patternCt, i, result;
3096
3097 if (objc < 2) {
3098 Tcl_WrongNumArgs(interp, 2, objv,
3099 "?-clear? ?pattern pattern...?");
3100 return TCL_ERROR;
3101 }
3102
3103 /*
3104 * Process the optional "-clear" argument.
3105 */
3106
3107 firstArg = 2;
3108 if (firstArg < objc) {
3109 string = Tcl_GetString(objv[firstArg]);
3110 if (strcmp(string, "-clear") == 0) {
3111 resetListFirst = 1;
3112 firstArg++;
3113 }
3114 }
3115
3116 /*
3117 * If no pattern arguments are given, and "-clear" isn't specified,
3118 * return the namespace's current export pattern list.
3119 */
3120
3121 patternCt = (objc - firstArg);
3122 if (patternCt == 0) {
3123 if (firstArg > 2) {
3124 return TCL_OK;
3125 } else { /* create list with export patterns */
3126 Tcl_Obj *listPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3127 result = Tcl_AppendExportList(interp,
3128 (Tcl_Namespace *) currNsPtr, listPtr);
3129 if (result != TCL_OK) {
3130 return result;
3131 }
3132 Tcl_SetObjResult(interp, listPtr);
3133 return TCL_OK;
3134 }
3135 }
3136
3137 /*
3138 * Add each pattern to the namespace's export pattern list.
3139 */
3140
3141 for (i = firstArg; i < objc; i++) {
3142 pattern = Tcl_GetString(objv[i]);
3143 result = Tcl_Export(interp, (Tcl_Namespace *) currNsPtr, pattern,
3144 ((i == firstArg)? resetListFirst : 0));
3145 if (result != TCL_OK) {
3146 return result;
3147 }
3148 }
3149 return TCL_OK;
3150 }
3151
3152 /*
3153 *----------------------------------------------------------------------
3154 *
3155 * NamespaceForgetCmd --
3156 *
3157 * Invoked to implement the "namespace forget" command to remove
3158 * imported commands from a namespace. Handles the following syntax:
3159 *
3160 * namespace forget ?pattern pattern...?
3161 *
3162 * Each pattern is a name like "foo::*" or "a::b::x*". That is, the
3163 * pattern may include the special pattern matching characters
3164 * recognized by the "string match" command, but only in the command
3165 * name at the end of the qualified name; the special pattern
3166 * characters may not appear in a namespace name. All of the commands
3167 * that match that pattern are checked to see if they have an imported
3168 * command in the current namespace that refers to the matched
3169 * command. If there is an alias, it is removed.
3170 *
3171 * Results:
3172 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3173 *
3174 * Side effects:
3175 * Imported commands are removed from the current namespace. If
3176 * anything goes wrong, this procedure returns an error message in the
3177 * interpreter's result object.
3178 *
3179 *----------------------------------------------------------------------
3180 */
3181
3182 static int
3183 NamespaceForgetCmd(dummy, interp, objc, objv)
3184 ClientData dummy; /* Not used. */
3185 Tcl_Interp *interp; /* Current interpreter. */
3186 int objc; /* Number of arguments. */
3187 Tcl_Obj *CONST objv[]; /* Argument objects. */
3188 {
3189 char *pattern;
3190 register int i, result;
3191
3192 if (objc < 2) {
3193 Tcl_WrongNumArgs(interp, 2, objv, "?pattern pattern...?");
3194 return TCL_ERROR;
3195 }
3196
3197 for (i = 2; i < objc; i++) {
3198 pattern = Tcl_GetString(objv[i]);
3199 result = Tcl_ForgetImport(interp, (Tcl_Namespace *) NULL, pattern);
3200 if (result != TCL_OK) {
3201 return result;
3202 }
3203 }
3204 return TCL_OK;
3205 }
3206
3207 /*
3208 *----------------------------------------------------------------------
3209 *
3210 * NamespaceImportCmd --
3211 *
3212 * Invoked to implement the "namespace import" command that imports
3213 * commands into a namespace. Handles the following syntax:
3214 *
3215 * namespace import ?-force? ?pattern pattern...?
3216 *
3217 * Each pattern is a namespace-qualified name like "foo::*",
3218 * "a::b::x*", or "bar::p". That is, the pattern may include the
3219 * special pattern matching characters recognized by the "string match"
3220 * command, but only in the command name at the end of the qualified
3221 * name; the special pattern characters may not appear in a namespace
3222 * name. All of the commands that match the pattern and which are
3223 * exported from their namespace are made accessible from the current
3224 * namespace context. This is done by creating a new "imported command"
3225 * in the current namespace that points to the real command in its
3226 * original namespace; when the imported command is called, it invokes
3227 * the real command.
3228 *
3229 * If an imported command conflicts with an existing command, it is
3230 * treated as an error. But if the "-force" option is included, then
3231 * existing commands are overwritten by the imported commands.
3232 *
3233 * Results:
3234 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3235 *
3236 * Side effects:
3237 * Adds imported commands to the current namespace. If anything goes
3238 * wrong, this procedure returns an error message in the interpreter's
3239 * result object.
3240 *
3241 *----------------------------------------------------------------------
3242 */
3243
3244 static int
3245 NamespaceImportCmd(dummy, interp, objc, objv)
3246 ClientData dummy; /* Not used. */
3247 Tcl_Interp *interp; /* Current interpreter. */
3248 int objc; /* Number of arguments. */
3249 Tcl_Obj *CONST objv[]; /* Argument objects. */
3250 {
3251 int allowOverwrite = 0;
3252 char *string, *pattern;
3253 register int i, result;
3254 int firstArg;
3255
3256 if (objc < 2) {
3257 Tcl_WrongNumArgs(interp, 2, objv,
3258 "?-force? ?pattern pattern...?");
3259 return TCL_ERROR;
3260 }
3261
3262 /*
3263 * Skip over the optional "-force" as the first argument.
3264 */
3265
3266 firstArg = 2;
3267 if (firstArg < objc) {
3268 string = Tcl_GetString(objv[firstArg]);
3269 if ((*string == '-') && (strcmp(string, "-force") == 0)) {
3270 allowOverwrite = 1;
3271 firstArg++;
3272 }
3273 }
3274
3275 /*
3276 * Handle the imports for each of the patterns.
3277 */
3278
3279 for (i = firstArg; i < objc; i++) {
3280 pattern = Tcl_GetString(objv[i]);
3281 result = Tcl_Import(interp, (Tcl_Namespace *) NULL, pattern,
3282 allowOverwrite);
3283 if (result != TCL_OK) {
3284 return result;
3285 }
3286 }
3287 return TCL_OK;
3288 }
3289
3290 /*
3291 *----------------------------------------------------------------------
3292 *
3293 * NamespaceInscopeCmd --
3294 *
3295 * Invoked to implement the "namespace inscope" command that executes a
3296 * script in the context of a particular namespace. This command is not
3297 * expected to be used directly by programmers; calls to it are
3298 * generated implicitly when programs use "namespace code" commands
3299 * to register callback scripts. Handles the following syntax:
3300 *
3301 * namespace inscope name arg ?arg...?
3302 *
3303 * The "namespace inscope" command is much like the "namespace eval"
3304 * command except that it has lappend semantics and the namespace must
3305 * already exist. It treats the first argument as a list, and appends
3306 * any arguments after the first onto the end as proper list elements.
3307 * For example,
3308 *
3309 * namespace inscope ::foo a b c d
3310 *
3311 * is equivalent to
3312 *
3313 * namespace eval ::foo [concat a [list b c d]]
3314 *
3315 * This lappend semantics is important because many callback scripts
3316 * are actually prefixes.
3317 *
3318 * Results:
3319 * Returns TCL_OK to indicate success, or TCL_ERROR to indicate
3320 * failure.
3321 *
3322 * Side effects:
3323 * Returns a result in the Tcl interpreter's result object.
3324 *
3325 *----------------------------------------------------------------------
3326 */
3327
3328 static int
3329 NamespaceInscopeCmd(dummy, interp, objc, objv)
3330 ClientData dummy; /* Not used. */
3331 Tcl_Interp *interp; /* Current interpreter. */
3332 int objc; /* Number of arguments. */
3333 Tcl_Obj *CONST objv[]; /* Argument objects. */
3334 {
3335 Tcl_Namespace *namespacePtr;
3336 Tcl_CallFrame frame;
3337 int i, result;
3338
3339 if (objc < 4) {
3340 Tcl_WrongNumArgs(interp, 2, objv, "name arg ?arg...?");
3341 return TCL_ERROR;
3342 }
3343
3344 /*
3345 * Resolve the namespace reference.
3346 */
3347
3348 result = GetNamespaceFromObj(interp, objv[2], &namespacePtr);
3349 if (result != TCL_OK) {
3350 return result;
3351 }
3352 if (namespacePtr == NULL) {
3353 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
3354 "unknown namespace \"", Tcl_GetString(objv[2]),
3355 "\" in inscope namespace command", (char *) NULL);
3356 return TCL_ERROR;
3357 }
3358
3359 /*
3360 * Make the specified namespace the current namespace.
3361 */
3362
3363 result = Tcl_PushCallFrame(interp, &frame, namespacePtr,
3364 /*isProcCallFrame*/ 0);
3365 if (result != TCL_OK) {
3366 return result;
3367 }
3368
3369 /*
3370 * Execute the command. If there is just one argument, just treat it as
3371 * a script and evaluate it. Otherwise, create a list from the arguments
3372 * after the first one, then concatenate the first argument and the list
3373 * of extra arguments to form the command to evaluate.
3374 */
3375
3376 if (objc == 4) {
3377 result = Tcl_EvalObjEx(interp, objv[3], 0);
3378 } else {
3379 Tcl_Obj *concatObjv[2];
3380 register Tcl_Obj *listPtr, *cmdObjPtr;
3381
3382 listPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3383 for (i = 4; i < objc; i++) {
3384 result = Tcl_ListObjAppendElement(interp, listPtr, objv[i]);
3385 if (result != TCL_OK) {
3386 Tcl_DecrRefCount(listPtr); /* free unneeded obj */
3387 return result;
3388 }
3389 }
3390
3391 concatObjv[0] = objv[3];
3392 concatObjv[1] = listPtr;
3393 cmdObjPtr = Tcl_ConcatObj(2, concatObjv);
3394 result = Tcl_EvalObjEx(interp, cmdObjPtr, TCL_EVAL_DIRECT);
3395 Tcl_DecrRefCount(listPtr); /* we're done with the list object */
3396 }
3397 if (result == TCL_ERROR) {
3398 char msg[256 + TCL_INTEGER_SPACE];
3399
3400 sprintf(msg,
3401 "\n (in namespace inscope \"%.200s\" script line %d)",
3402 namespacePtr->fullName, interp->errorLine);
3403 Tcl_AddObjErrorInfo(interp, msg, -1);
3404 }
3405
3406 /*
3407 * Restore the previous "current" namespace.
3408 */
3409
3410 Tcl_PopCallFrame(interp);
3411 return result;
3412 }
3413
3414 /*
3415 *----------------------------------------------------------------------
3416 *
3417 * NamespaceOriginCmd --
3418 *
3419 * Invoked to implement the "namespace origin" command to return the
3420 * fully-qualified name of the "real" command to which the specified
3421 * "imported command" refers. Handles the following syntax:
3422 *
3423 * namespace origin name
3424 *
3425 * Results:
3426 * An imported command is created in an namespace when that namespace
3427 * imports a command from another namespace. If a command is imported
3428 * into a sequence of namespaces a, b,...,n where each successive
3429 * namespace just imports the command from the previous namespace, this
3430 * command returns the fully-qualified name of the original command in
3431 * the first namespace, a. If "name" does not refer to an alias, its
3432 * fully-qualified name is returned. The returned name is stored in the
3433 * interpreter's result object. This procedure returns TCL_OK if
3434 * successful, and TCL_ERROR if anything goes wrong.
3435 *
3436 * Side effects:
3437 * If anything goes wrong, this procedure returns an error message in
3438 * the interpreter's result object.
3439 *
3440 *----------------------------------------------------------------------
3441 */
3442
3443 static int
3444 NamespaceOriginCmd(dummy, interp, objc, objv)
3445 ClientData dummy; /* Not used. */
3446 Tcl_Interp *interp; /* Current interpreter. */
3447 int objc; /* Number of arguments. */
3448 Tcl_Obj *CONST objv[]; /* Argument objects. */
3449 {
3450 Tcl_Command command, origCommand;
3451
3452 if (objc != 3) {
3453 Tcl_WrongNumArgs(interp, 2, objv, "name");
3454 return TCL_ERROR;
3455 }
3456
3457 command = Tcl_GetCommandFromObj(interp, objv[2]);
3458 if (command == (Tcl_Command) NULL) {
3459 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
3460 "invalid command name \"", Tcl_GetString(objv[2]),
3461 "\"", (char *) NULL);
3462 return TCL_ERROR;
3463 }
3464 origCommand = TclGetOriginalCommand(command);
3465 if (origCommand == (Tcl_Command) NULL) {
3466 /*
3467 * The specified command isn't an imported command. Return the
3468 * command's name qualified by the full name of the namespace it
3469 * was defined in.
3470 */
3471
3472 Tcl_GetCommandFullName(interp, command, Tcl_GetObjResult(interp));
3473 } else {
3474 Tcl_GetCommandFullName(interp, origCommand, Tcl_GetObjResult(interp));
3475 }
3476 return TCL_OK;
3477 }
3478
3479 /*
3480 *----------------------------------------------------------------------
3481 *
3482 * NamespaceParentCmd --
3483 *
3484 * Invoked to implement the "namespace parent" command that returns the
3485 * fully-qualified name of the parent namespace for a specified
3486 * namespace. Handles the following syntax:
3487 *
3488 * namespace parent ?name?
3489 *
3490 * Results:
3491 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3492 *
3493 * Side effects:
3494 * Returns a result in the interpreter's result object. If anything
3495 * goes wrong, the result is an error message.
3496 *
3497 *----------------------------------------------------------------------
3498 */
3499
3500 static int
3501 NamespaceParentCmd(dummy, interp, objc, objv)
3502 ClientData dummy; /* Not used. */
3503 Tcl_Interp *interp; /* Current interpreter. */
3504 int objc; /* Number of arguments. */
3505 Tcl_Obj *CONST objv[]; /* Argument objects. */
3506 {
3507 Tcl_Namespace *nsPtr;
3508 int result;
3509
3510 if (objc == 2) {
3511 nsPtr = Tcl_GetCurrentNamespace(interp);
3512 } else if (objc == 3) {
3513 result = GetNamespaceFromObj(interp, objv[2], &nsPtr);
3514 if (result != TCL_OK) {
3515 return result;
3516 }
3517 if (nsPtr == NULL) {
3518 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
3519 "unknown namespace \"", Tcl_GetString(objv[2]),
3520 "\" in namespace parent command", (char *) NULL);
3521 return TCL_ERROR;
3522 }
3523 } else {
3524 Tcl_WrongNumArgs(interp, 2, objv, "?name?");
3525 return TCL_ERROR;
3526 }
3527
3528 /*
3529 * Report the parent of the specified namespace.
3530 */
3531
3532 if (nsPtr->parentPtr != NULL) {
3533 Tcl_SetStringObj(Tcl_GetObjResult(interp),
3534 nsPtr->parentPtr->fullName, -1);
3535 }
3536 return TCL_OK;
3537 }
3538
3539 /*
3540 *----------------------------------------------------------------------
3541 *
3542 * NamespaceQualifiersCmd --
3543 *
3544 * Invoked to implement the "namespace qualifiers" command that returns
3545 * any leading namespace qualifiers in a string. These qualifiers are
3546 * namespace names separated by "::"s. For example, for "::foo::p" this
3547 * command returns "::foo", and for "::" it returns "". This command
3548 * is the complement of the "namespace tail" command. Note that this
3549 * command does not check whether the "namespace" names are, in fact,
3550 * the names of currently defined namespaces. Handles the following
3551 * syntax:
3552 *
3553 * namespace qualifiers string
3554 *
3555 * Results:
3556 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3557 *
3558 * Side effects:
3559 * Returns a result in the interpreter's result object. If anything
3560 * goes wrong, the result is an error message.
3561 *
3562 *----------------------------------------------------------------------
3563 */
3564
3565 static int
3566 NamespaceQualifiersCmd(dummy, interp, objc, objv)
3567 ClientData dummy; /* Not used. */
3568 Tcl_Interp *interp; /* Current interpreter. */
3569 int objc; /* Number of arguments. */
3570 Tcl_Obj *CONST objv[]; /* Argument objects. */
3571 {
3572 register char *name, *p;
3573 int length;
3574
3575 if (objc != 3) {
3576 Tcl_WrongNumArgs(interp, 2, objv, "string");
3577 return TCL_ERROR;
3578 }
3579
3580 /*
3581 * Find the end of the string, then work backward and find
3582 * the start of the last "::" qualifier.
3583 */
3584
3585 name = Tcl_GetString(objv[2]);
3586 for (p = name; *p != '\0'; p++) {
3587 /* empty body */
3588 }
3589 while (--p >= name) {
3590 if ((*p == ':') && (p > name) && (*(p-1) == ':')) {
3591 p -= 2; /* back up over the :: */
3592 while ((p >= name) && (*p == ':')) {
3593 p--; /* back up over the preceeding : */
3594 }
3595 break;
3596 }
3597 }
3598
3599 if (p >= name) {
3600 length = p-name+1;
3601 Tcl_AppendToObj(Tcl_GetObjResult(interp), name, length);
3602 }
3603 return TCL_OK;
3604 }
3605
3606 /*
3607 *----------------------------------------------------------------------
3608 *
3609 * NamespaceTailCmd --
3610 *
3611 * Invoked to implement the "namespace tail" command that returns the
3612 * trailing name at the end of a string with "::" namespace
3613 * qualifiers. These qualifiers are namespace names separated by
3614 * "::"s. For example, for "::foo::p" this command returns "p", and for
3615 * "::" it returns "". This command is the complement of the "namespace
3616 * qualifiers" command. Note that this command does not check whether
3617 * the "namespace" names are, in fact, the names of currently defined
3618 * namespaces. Handles the following syntax:
3619 *
3620 * namespace tail string
3621 *
3622 * Results:
3623 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3624 *
3625 * Side effects:
3626 * Returns a result in the interpreter's result object. If anything
3627 * goes wrong, the result is an error message.
3628 *
3629 *----------------------------------------------------------------------
3630 */
3631
3632 static int
3633 NamespaceTailCmd(dummy, interp, objc, objv)
3634 ClientData dummy; /* Not used. */
3635 Tcl_Interp *interp; /* Current interpreter. */
3636 int objc; /* Number of arguments. */
3637 Tcl_Obj *CONST objv[]; /* Argument objects. */
3638 {
3639 register char *name, *p;
3640
3641 if (objc != 3) {
3642 Tcl_WrongNumArgs(interp, 2, objv, "string");
3643 return TCL_ERROR;
3644 }
3645
3646 /*
3647 * Find the end of the string, then work backward and find the
3648 * last "::" qualifier.
3649 */
3650
3651 name = Tcl_GetString(objv[2]);
3652 for (p = name; *p != '\0'; p++) {
3653 /* empty body */
3654 }
3655 while (--p > name) {
3656 if ((*p == ':') && (*(p-1) == ':')) {
3657 p++; /* just after the last "::" */
3658 break;
3659 }
3660 }
3661
3662 if (p >= name) {
3663 Tcl_AppendToObj(Tcl_GetObjResult(interp), p, -1);
3664 }
3665 return TCL_OK;
3666 }
3667
3668 /*
3669 *----------------------------------------------------------------------
3670 *
3671 * NamespaceWhichCmd --
3672 *
3673 * Invoked to implement the "namespace which" command that returns the
3674 * fully-qualified name of a command or variable. If the specified
3675 * command or variable does not exist, it returns "". Handles the
3676 * following syntax:
3677 *
3678 * namespace which ?-command? ?-variable? name
3679 *
3680 * Results:
3681 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3682 *
3683 * Side effects:
3684 * Returns a result in the interpreter's result object. If anything
3685 * goes wrong, the result is an error message.
3686 *
3687 *----------------------------------------------------------------------
3688 */
3689
3690 static int
3691 NamespaceWhichCmd(dummy, interp, objc, objv)
3692 ClientData dummy; /* Not used. */
3693 Tcl_Interp *interp; /* Current interpreter. */
3694 int objc; /* Number of arguments. */
3695 Tcl_Obj *CONST objv[]; /* Argument objects. */
3696 {
3697 register char *arg;
3698 Tcl_Command cmd;
3699 Tcl_Var variable;
3700 int argIndex, lookup;
3701
3702 if (objc < 3) {
3703 badArgs:
3704 Tcl_WrongNumArgs(interp, 2, objv,
3705 "?-command? ?-variable? name");
3706 return TCL_ERROR;
3707 }
3708
3709 /*
3710 * Look for a flag controlling the lookup.
3711 */
3712
3713 argIndex = 2;
3714 lookup = 0; /* assume command lookup by default */
3715 arg = Tcl_GetString(objv[2]);
3716 if (*arg == '-') {
3717 if (strncmp(arg, "-command", 8) == 0) {
3718 lookup = 0;
3719 } else if (strncmp(arg, "-variable", 9) == 0) {
3720 lookup = 1;
3721 } else {
3722 goto badArgs;
3723 }
3724 argIndex = 3;
3725 }
3726 if (objc != (argIndex + 1)) {
3727 goto badArgs;
3728 }
3729
3730 switch (lookup) {
3731 case 0: /* -command */
3732 cmd = Tcl_GetCommandFromObj(interp, objv[argIndex]);
3733 if (cmd == (Tcl_Command) NULL) {
3734 return TCL_OK; /* cmd not found, just return (no error) */
3735 }
3736 Tcl_GetCommandFullName(interp, cmd, Tcl_GetObjResult(interp));
3737 break;
3738
3739 case 1: /* -variable */
3740 arg = Tcl_GetString(objv[argIndex]);
3741 variable = Tcl_FindNamespaceVar(interp, arg, (Tcl_Namespace *) NULL,
3742 /*flags*/ 0);
3743 if (variable != (Tcl_Var) NULL) {
3744 Tcl_GetVariableFullName(interp, variable, Tcl_GetObjResult(interp));
3745 }
3746 break;
3747 }
3748 return TCL_OK;
3749 }
3750
3751 /*
3752 *----------------------------------------------------------------------
3753 *
3754 * FreeNsNameInternalRep --
3755 *
3756 * Frees the resources associated with a nsName object's internal
3757 * representation.
3758 *
3759 * Results:
3760 * None.
3761 *
3762 * Side effects:
3763 * Decrements the ref count of any Namespace structure pointed
3764 * to by the nsName's internal representation. If there are no more
3765 * references to the namespace, it's structure will be freed.
3766 *
3767 *----------------------------------------------------------------------
3768 */
3769
3770 static void
3771 FreeNsNameInternalRep(objPtr)
3772 register Tcl_Obj *objPtr; /* nsName object with internal
3773 * representation to free */
3774 {
3775 register ResolvedNsName *resNamePtr =
3776 (ResolvedNsName *) objPtr->internalRep.otherValuePtr;
3777 Namespace *nsPtr;
3778
3779 /*
3780 * Decrement the reference count of the namespace. If there are no
3781 * more references, free it up.
3782 */
3783
3784 if (resNamePtr != NULL) {
3785 resNamePtr->refCount--;
3786 if (resNamePtr->refCount == 0) {
3787
3788 /*
3789 * Decrement the reference count for the cached namespace. If
3790 * the namespace is dead, and there are no more references to
3791 * it, free it.
3792 */
3793
3794 nsPtr = resNamePtr->nsPtr;
3795 nsPtr->refCount--;
3796 if ((nsPtr->refCount == 0) && (nsPtr->flags & NS_DEAD)) {
3797 NamespaceFree(nsPtr);
3798 }
3799 ckfree((char *) resNamePtr);
3800 }
3801 }
3802 }
3803
3804 /*
3805 *----------------------------------------------------------------------
3806 *
3807 * DupNsNameInternalRep --
3808 *
3809 * Initializes the internal representation of a nsName object to a copy
3810 * of the internal representation of another nsName object.
3811 *
3812 * Results:
3813 * None.
3814 *
3815 * Side effects:
3816 * copyPtr's internal rep is set to refer to the same namespace
3817 * referenced by srcPtr's internal rep. Increments the ref count of
3818 * the ResolvedNsName structure used to hold the namespace reference.
3819 *
3820 *----------------------------------------------------------------------
3821 */
3822
3823 static void
3824 DupNsNameInternalRep(srcPtr, copyPtr)
3825 Tcl_Obj *srcPtr; /* Object with internal rep to copy. */
3826 register Tcl_Obj *copyPtr; /* Object with internal rep to set. */
3827 {
3828 register ResolvedNsName *resNamePtr =
3829 (ResolvedNsName *) srcPtr->internalRep.otherValuePtr;
3830
3831 copyPtr->internalRep.otherValuePtr = (VOID *) resNamePtr;
3832 if (resNamePtr != NULL) {
3833 resNamePtr->refCount++;
3834 }
3835 copyPtr->typePtr = &tclNsNameType;
3836 }
3837
3838 /*
3839 *----------------------------------------------------------------------
3840 *
3841 * SetNsNameFromAny --
3842 *
3843 * Attempt to generate a nsName internal representation for a
3844 * Tcl object.
3845 *
3846 * Results:
3847 * Returns TCL_OK if the value could be converted to a proper
3848 * namespace reference. Otherwise, it returns TCL_ERROR, along
3849 * with an error message in the interpreter's result object.
3850 *
3851 * Side effects:
3852 * If successful, the object is made a nsName object. Its internal rep
3853 * is set to point to a ResolvedNsName, which contains a cached pointer
3854 * to the Namespace. Reference counts are kept on both the
3855 * ResolvedNsName and the Namespace, so we can keep track of their
3856 * usage and free them when appropriate.
3857 *
3858 *----------------------------------------------------------------------
3859 */
3860
3861 static int
3862 SetNsNameFromAny(interp, objPtr)
3863 Tcl_Interp *interp; /* Points to the namespace in which to
3864 * resolve name. Also used for error
3865 * reporting if not NULL. */
3866 register Tcl_Obj *objPtr; /* The object to convert. */
3867 {
3868 register Tcl_ObjType *oldTypePtr = objPtr->typePtr;
3869 char *name;
3870 CONST char *dummy;
3871 Namespace *nsPtr, *dummy1Ptr, *dummy2Ptr;
3872 register ResolvedNsName *resNamePtr;
3873
3874 /*
3875 * Get the string representation. Make it up-to-date if necessary.
3876 */
3877
3878 name = objPtr->bytes;
3879 if (name == NULL) {
3880 name = Tcl_GetString(objPtr);
3881 }
3882
3883 /*
3884 * Look for the namespace "name" in the current namespace. If there is
3885 * an error parsing the (possibly qualified) name, return an error.
3886 * If the namespace isn't found, we convert the object to an nsName
3887 * object with a NULL ResolvedNsName* internal rep.
3888 */
3889
3890 TclGetNamespaceForQualName(interp, name, (Namespace *) NULL,
3891 FIND_ONLY_NS, &nsPtr, &dummy1Ptr, &dummy2Ptr, &dummy);
3892
3893 /*
3894 * If we found a namespace, then create a new ResolvedNsName structure
3895 * that holds a reference to it.
3896 */
3897
3898 if (nsPtr != NULL) {
3899 Namespace *currNsPtr =
3900 (Namespace *) Tcl_GetCurrentNamespace(interp);
3901
3902 nsPtr->refCount++;
3903 resNamePtr = (ResolvedNsName *) ckalloc(sizeof(ResolvedNsName));
3904 resNamePtr->nsPtr = nsPtr;
3905 resNamePtr->nsId = nsPtr->nsId;
3906 resNamePtr->refNsPtr = currNsPtr;
3907 resNamePtr->refCount = 1;
3908 } else {
3909 resNamePtr = NULL;
3910 }
3911
3912 /*
3913 * Free the old internalRep before setting the new one.
3914 * We do this as late as possible to allow the conversion code
3915 * (in particular, Tcl_GetStringFromObj) to use that old internalRep.
3916 */
3917
3918 if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) {
3919 oldTypePtr->freeIntRepProc(objPtr);
3920 }
3921
3922 objPtr->internalRep.otherValuePtr = (VOID *) resNamePtr;
3923 objPtr->typePtr = &tclNsNameType;
3924 return TCL_OK;
3925 }
3926
3927 /*
3928 *----------------------------------------------------------------------
3929 *
3930 * UpdateStringOfNsName --
3931 *
3932 * Updates the string representation for a nsName object.
3933 * Note: This procedure does not free an existing old string rep
3934 * so storage will be lost if this has not already been done.
3935 *
3936 * Results:
3937 * None.
3938 *
3939 * Side effects:
3940 * The object's string is set to a copy of the fully qualified
3941 * namespace name.
3942 *
3943 *----------------------------------------------------------------------
3944 */
3945
3946 static void
3947 UpdateStringOfNsName(objPtr)
3948 register Tcl_Obj *objPtr; /* nsName object with string rep to update. */
3949 {
3950 ResolvedNsName *resNamePtr =
3951 (ResolvedNsName *) objPtr->internalRep.otherValuePtr;
3952 register Namespace *nsPtr;
3953 char *name = "";
3954 int length;
3955
3956 if ((resNamePtr != NULL)
3957 && (resNamePtr->nsId == resNamePtr->nsPtr->nsId)) {
3958 nsPtr = resNamePtr->nsPtr;
3959 if (nsPtr->flags & NS_DEAD) {
3960 nsPtr = NULL;
3961 }
3962 if (nsPtr != NULL) {
3963 name = nsPtr->fullName;
3964 }
3965 }
3966
3967 /*
3968 * The following sets the string rep to an empty string on the heap
3969 * if the internal rep is NULL.
3970 */
3971
3972 length = strlen(name);
3973 if (length == 0) {
3974 objPtr->bytes = tclEmptyStringRep;
3975 } else {
3976 objPtr->bytes = (char *) ckalloc((unsigned) (length + 1));
3977 memcpy((VOID *) objPtr->bytes, (VOID *) name, (unsigned) length);
3978 objPtr->bytes[length] = '\0';
3979 }
3980 objPtr->length = length;
3981 }