Debian Codegraph @

generic/tclNamesp.c

raw
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 Scriptics Corporation.
13 * Copyright (c) 2002-2005 Donal K. Fellows.
14 * Copyright (c) 2006 Neil Madden.
15 * Contributions from Don Porter, NIST, 2007. (not subject to US copyright)
16 *
17 * Originally implemented by
18 * Michael J. McLennan
19 * Bell Labs Innovations for Lucent Technologies
20 * [email protected]
21 *
22 * See the file "license.terms" for information on usage and redistribution of
23 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
24 */
25
26 #include "tclInt.h"
27 #include "tclCompile.h" /* for TclLogCommandInfo visibility */
28
29 /*
30 * Thread-local storage used to avoid having a global lock on data that is not
31 * limited to a single interpreter.
32 */
33
34 typedef struct {
35 long numNsCreated; /* Count of the number of namespaces created
36 * within the thread. This value is used as a
37 * unique id for each namespace. Cannot be
38 * per-interp because the nsId is used to
39 * distinguish objects which can be passed
40 * around between interps in the same thread,
41 * but does not need to be global because
42 * object internal reps are always per-thread
43 * anyway. */
44 } ThreadSpecificData;
45
46 static Tcl_ThreadDataKey dataKey;
47
48 /*
49 * This structure contains a cached pointer to a namespace that is the result
50 * of resolving the namespace's name in some other namespace. It is the
51 * internal representation for a nsName object. It contains the pointer along
52 * with some information that is used to check the cached pointer's validity.
53 */
54
55 typedef struct ResolvedNsName {
56 Namespace *nsPtr; /* A cached pointer to the Namespace that the
57 * name resolved to. */
58 Namespace *refNsPtr; /* Points to the namespace context in which
59 * the name was resolved. NULL if the name is
60 * fully qualified and thus the resolution
61 * does not depend on the context. */
62 int refCount; /* Reference count: 1 for each nsName object
63 * that has a pointer to this ResolvedNsName
64 * structure as its internal rep. This
65 * structure can be freed when refCount
66 * becomes zero. */
67 } ResolvedNsName;
68
69 /*
70 * Declarations for functions local to this file:
71 */
72
73 static void DeleteImportedCmd(ClientData clientData);
74 static int DoImport(Tcl_Interp *interp,
75 Namespace *nsPtr, Tcl_HashEntry *hPtr,
76 const char *cmdName, const char *pattern,
77 Namespace *importNsPtr, int allowOverwrite);
78 static void DupNsNameInternalRep(Tcl_Obj *objPtr,Tcl_Obj *copyPtr);
79 static char * ErrorCodeRead(ClientData clientData,Tcl_Interp *interp,
80 const char *name1, const char *name2, int flags);
81 static char * ErrorInfoRead(ClientData clientData,Tcl_Interp *interp,
82 const char *name1, const char *name2, int flags);
83 static char * EstablishErrorCodeTraces(ClientData clientData,
84 Tcl_Interp *interp, const char *name1,
85 const char *name2, int flags);
86 static char * EstablishErrorInfoTraces(ClientData clientData,
87 Tcl_Interp *interp, const char *name1,
88 const char *name2, int flags);
89 static void FreeNsNameInternalRep(Tcl_Obj *objPtr);
90 static int GetNamespaceFromObj(Tcl_Interp *interp,
91 Tcl_Obj *objPtr, Tcl_Namespace **nsPtrPtr);
92 static int InvokeImportedNRCmd(ClientData clientData,
93 Tcl_Interp *interp,int objc,Tcl_Obj *const objv[]);
94 static Tcl_ObjCmdProc InvokeImportedCmd;
95 static Tcl_ObjCmdProc NamespaceChildrenCmd;
96 static Tcl_ObjCmdProc NamespaceCodeCmd;
97 static Tcl_ObjCmdProc NamespaceCurrentCmd;
98 static Tcl_ObjCmdProc NamespaceDeleteCmd;
99 static Tcl_ObjCmdProc NamespaceEvalCmd;
100 static Tcl_ObjCmdProc NRNamespaceEvalCmd;
101 static Tcl_ObjCmdProc NamespaceExistsCmd;
102 static Tcl_ObjCmdProc NamespaceExportCmd;
103 static Tcl_ObjCmdProc NamespaceForgetCmd;
104 static void NamespaceFree(Namespace *nsPtr);
105 static Tcl_ObjCmdProc NamespaceImportCmd;
106 static Tcl_ObjCmdProc NamespaceInscopeCmd;
107 static Tcl_ObjCmdProc NRNamespaceInscopeCmd;
108 static Tcl_ObjCmdProc NamespaceOriginCmd;
109 static Tcl_ObjCmdProc NamespaceParentCmd;
110 static Tcl_ObjCmdProc NamespacePathCmd;
111 static Tcl_ObjCmdProc NamespaceQualifiersCmd;
112 static Tcl_ObjCmdProc NamespaceTailCmd;
113 static Tcl_ObjCmdProc NamespaceUpvarCmd;
114 static Tcl_ObjCmdProc NamespaceUnknownCmd;
115 static Tcl_ObjCmdProc NamespaceWhichCmd;
116 static int SetNsNameFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr);
117 static void UnlinkNsPath(Namespace *nsPtr);
118
119 static Tcl_NRPostProc NsEval_Callback;
120
121 /*
122 * This structure defines a Tcl object type that contains a namespace
123 * reference. It is used in commands that take the name of a namespace as an
124 * argument. The namespace reference is resolved, and the result in cached in
125 * the object.
126 */
127
128 static const Tcl_ObjType nsNameType = {
129 "nsName", /* the type's name */
130 FreeNsNameInternalRep, /* freeIntRepProc */
131 DupNsNameInternalRep, /* dupIntRepProc */
132 NULL, /* updateStringProc */
133 SetNsNameFromAny /* setFromAnyProc */
134 };
135
136 /*
137 * Array of values describing how to implement each standard subcommand of the
138 * "namespace" command.
139 */
140
141 static const EnsembleImplMap defaultNamespaceMap[] = {
142 {"children", NamespaceChildrenCmd, TclCompileBasic0To2ArgCmd, NULL, NULL, 0},
143 {"code", NamespaceCodeCmd, TclCompileNamespaceCodeCmd, NULL, NULL, 0},
144 {"current", NamespaceCurrentCmd, TclCompileNamespaceCurrentCmd, NULL, NULL, 0},
145 {"delete", NamespaceDeleteCmd, TclCompileBasicMin0ArgCmd, NULL, NULL, 0},
146 {"ensemble", TclNamespaceEnsembleCmd, NULL, NULL, NULL, 0},
147 {"eval", NamespaceEvalCmd, NULL, NRNamespaceEvalCmd, NULL, 0},
148 {"exists", NamespaceExistsCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
149 {"export", NamespaceExportCmd, TclCompileBasicMin0ArgCmd, NULL, NULL, 0},
150 {"forget", NamespaceForgetCmd, TclCompileBasicMin0ArgCmd, NULL, NULL, 0},
151 {"import", NamespaceImportCmd, TclCompileBasicMin0ArgCmd, NULL, NULL, 0},
152 {"inscope", NamespaceInscopeCmd, NULL, NRNamespaceInscopeCmd, NULL, 0},
153 {"origin", NamespaceOriginCmd, TclCompileNamespaceOriginCmd, NULL, NULL, 0},
154 {"parent", NamespaceParentCmd, TclCompileBasic0Or1ArgCmd, NULL, NULL, 0},
155 {"path", NamespacePathCmd, TclCompileBasic0Or1ArgCmd, NULL, NULL, 0},
156 {"qualifiers", NamespaceQualifiersCmd, TclCompileNamespaceQualifiersCmd, NULL, NULL, 0},
157 {"tail", NamespaceTailCmd, TclCompileNamespaceTailCmd, NULL, NULL, 0},
158 {"unknown", NamespaceUnknownCmd, TclCompileBasic0Or1ArgCmd, NULL, NULL, 0},
159 {"upvar", NamespaceUpvarCmd, TclCompileNamespaceUpvarCmd, NULL, NULL, 0},
160 {"which", NamespaceWhichCmd, TclCompileNamespaceWhichCmd, NULL, NULL, 0},
161 {NULL, NULL, NULL, NULL, NULL, 0}
162 };
163
164 /*
165 *----------------------------------------------------------------------
166 *
167 * TclInitNamespaceSubsystem --
168 *
169 * This function is called to initialize all the structures that are used
170 * by namespaces on a per-process basis.
171 *
172 * Results:
173 * None.
174 *
175 * Side effects:
176 * None.
177 *
178 *----------------------------------------------------------------------
179 */
180
181 void
182 TclInitNamespaceSubsystem(void)
183 {
184 /*
185 * Does nothing for now.
186 */
187 }
188
189 /*
190 *----------------------------------------------------------------------
191 *
192 * Tcl_GetCurrentNamespace --
193 *
194 * Returns a pointer to an interpreter's currently active namespace.
195 *
196 * Results:
197 * Returns a pointer to the interpreter's current namespace.
198 *
199 * Side effects:
200 * None.
201 *
202 *----------------------------------------------------------------------
203 */
204
205 Tcl_Namespace *
206 Tcl_GetCurrentNamespace(
207 Tcl_Interp *interp) /* Interpreter whose current namespace is
208 * being queried. */
209 {
210 return TclGetCurrentNamespace(interp);
211 }
212
213 /*
214 *----------------------------------------------------------------------
215 *
216 * Tcl_GetGlobalNamespace --
217 *
218 * Returns a pointer to an interpreter's global :: namespace.
219 *
220 * Results:
221 * Returns a pointer to the specified interpreter's global namespace.
222 *
223 * Side effects:
224 * None.
225 *
226 *----------------------------------------------------------------------
227 */
228
229 Tcl_Namespace *
230 Tcl_GetGlobalNamespace(
231 Tcl_Interp *interp) /* Interpreter whose global namespace should
232 * be returned. */
233 {
234 return TclGetGlobalNamespace(interp);
235 }
236
237 /*
238 *----------------------------------------------------------------------
239 *
240 * Tcl_PushCallFrame --
241 *
242 * Pushes a new call frame onto the interpreter's Tcl call stack. Called
243 * when executing a Tcl procedure or a "namespace eval" or "namespace
244 * inscope" command.
245 *
246 * Results:
247 * Returns TCL_OK if successful, or TCL_ERROR (along with an error
248 * message in the interpreter's result object) if something goes wrong.
249 *
250 * Side effects:
251 * Modifies the interpreter's Tcl call stack.
252 *
253 *----------------------------------------------------------------------
254 */
255
256 int
257 Tcl_PushCallFrame(
258 Tcl_Interp *interp, /* Interpreter in which the new call frame is
259 * to be pushed. */
260 Tcl_CallFrame *callFramePtr,/* Points to a call frame structure to push.
261 * Storage for this has already been allocated
262 * by the caller; typically this is the
263 * address of a CallFrame structure allocated
264 * on the caller's C stack. The call frame
265 * will be initialized by this function. The
266 * caller can pop the frame later with
267 * Tcl_PopCallFrame, and it is responsible for
268 * freeing the frame's storage. */
269 Tcl_Namespace *namespacePtr,/* Points to the namespace in which the frame
270 * will execute. If NULL, the interpreter's
271 * current namespace will be used. */
272 int isProcCallFrame) /* If nonzero, the frame represents a called
273 * Tcl procedure and may have local vars. Vars
274 * will ordinarily be looked up in the frame.
275 * If new variables are created, they will be
276 * created in the frame. If 0, the frame is
277 * for a "namespace eval" or "namespace
278 * inscope" command and var references are
279 * treated as references to namespace
280 * variables. */
281 {
282 Interp *iPtr = (Interp *) interp;
283 CallFrame *framePtr = (CallFrame *) callFramePtr;
284 Namespace *nsPtr;
285
286 if (namespacePtr == NULL) {
287 nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
288 } else {
289 nsPtr = (Namespace *) namespacePtr;
290
291 /*
292 * TODO: Examine whether it would be better to guard based on NS_DYING
293 * or NS_KILLED. It appears that these are not tested because they can
294 * be set in a global interp that has been [namespace delete]d, but
295 * which never really completely goes away because of lingering global
296 * things like ::errorInfo and [::unknown] and hidden commands.
297 * Review of those designs might permit stricter checking here.
298 */
299
300 if (nsPtr->flags & NS_DEAD) {
301 Tcl_Panic("Trying to push call frame for dead namespace");
302 }
303 }
304
305 nsPtr->activationCount++;
306 framePtr->nsPtr = nsPtr;
307 framePtr->isProcCallFrame = isProcCallFrame;
308 framePtr->objc = 0;
309 framePtr->objv = NULL;
310 framePtr->callerPtr = iPtr->framePtr;
311 framePtr->callerVarPtr = iPtr->varFramePtr;
312 if (iPtr->varFramePtr != NULL) {
313 framePtr->level = (iPtr->varFramePtr->level + 1);
314 } else {
315 framePtr->level = 0;
316 }
317 framePtr->procPtr = NULL; /* no called procedure */
318 framePtr->varTablePtr = NULL; /* and no local variables */
319 framePtr->numCompiledLocals = 0;
320 framePtr->compiledLocals = NULL;
321 framePtr->clientData = NULL;
322 framePtr->localCachePtr = NULL;
323 framePtr->tailcallPtr = NULL;
324
325 /*
326 * Push the new call frame onto the interpreter's stack of procedure call
327 * frames making it the current frame.
328 */
329
330 iPtr->framePtr = framePtr;
331 iPtr->varFramePtr = framePtr;
332
333 return TCL_OK;
334 }
335
336 /*
337 *----------------------------------------------------------------------
338 *
339 * Tcl_PopCallFrame --
340 *
341 * Removes a call frame from the Tcl call stack for the interpreter.
342 * Called to remove a frame previously pushed by Tcl_PushCallFrame.
343 *
344 * Results:
345 * None.
346 *
347 * Side effects:
348 * Modifies the call stack of the interpreter. Resets various fields of
349 * the popped call frame. If a namespace has been deleted and has no more
350 * activations on the call stack, the namespace is destroyed.
351 *
352 *----------------------------------------------------------------------
353 */
354
355 void
356 Tcl_PopCallFrame(
357 Tcl_Interp *interp) /* Interpreter with call frame to pop. */
358 {
359 Interp *iPtr = (Interp *) interp;
360 CallFrame *framePtr = iPtr->framePtr;
361 Namespace *nsPtr;
362
363 /*
364 * It's important to remove the call frame from the interpreter's stack of
365 * call frames before deleting local variables, so that traces invoked by
366 * the variable deletion don't see the partially-deleted frame.
367 */
368
369 if (framePtr->callerPtr) {
370 iPtr->framePtr = framePtr->callerPtr;
371 iPtr->varFramePtr = framePtr->callerVarPtr;
372 } else {
373 /* Tcl_PopCallFrame: trying to pop rootCallFrame! */
374 }
375
376 if (framePtr->varTablePtr != NULL) {
377 TclDeleteVars(iPtr, framePtr->varTablePtr);
378 ckfree(framePtr->varTablePtr);
379 framePtr->varTablePtr = NULL;
380 }
381 if (framePtr->numCompiledLocals > 0) {
382 TclDeleteCompiledLocalVars(iPtr, framePtr);
383 if (framePtr->localCachePtr->refCount-- <= 1) {
384 TclFreeLocalCache(interp, framePtr->localCachePtr);
385 }
386 framePtr->localCachePtr = NULL;
387 }
388
389 /*
390 * Decrement the namespace's count of active call frames. If the namespace
391 * is "dying" and there are no more active call frames, call
392 * Tcl_DeleteNamespace to destroy it.
393 */
394
395 nsPtr = framePtr->nsPtr;
396 if ((--nsPtr->activationCount <= (nsPtr == iPtr->globalNsPtr))
397 && (nsPtr->flags & NS_DYING)) {
398 Tcl_DeleteNamespace((Tcl_Namespace *) nsPtr);
399 }
400 framePtr->nsPtr = NULL;
401
402 if (framePtr->tailcallPtr) {
403 /* Reusing the existing reference count from framePtr->tailcallPtr, so
404 * no need to Tcl_IncrRefCount(framePtr->tailcallPtr)*/
405 TclSetTailcall(interp, framePtr->tailcallPtr);
406 }
407 }
408
409 /*
410 *----------------------------------------------------------------------
411 *
412 * TclPushStackFrame --
413 *
414 * Allocates a new call frame in the interpreter's execution stack, then
415 * pushes it onto the interpreter's Tcl call stack. Called when executing
416 * a Tcl procedure or a "namespace eval" or "namespace inscope" command.
417 *
418 * Results:
419 * Returns TCL_OK if successful, or TCL_ERROR (along with an error
420 * message in the interpreter's result object) if something goes wrong.
421 *
422 * Side effects:
423 * Modifies the interpreter's Tcl call stack.
424 *
425 *----------------------------------------------------------------------
426 */
427
428 int
429 TclPushStackFrame(
430 Tcl_Interp *interp, /* Interpreter in which the new call frame is
431 * to be pushed. */
432 Tcl_CallFrame **framePtrPtr,/* Place to store a pointer to the stack
433 * allocated call frame. */
434 Tcl_Namespace *namespacePtr,/* Points to the namespace in which the frame
435 * will execute. If NULL, the interpreter's
436 * current namespace will be used. */
437 int isProcCallFrame) /* If nonzero, the frame represents a called
438 * Tcl procedure and may have local vars. Vars
439 * will ordinarily be looked up in the frame.
440 * If new variables are created, they will be
441 * created in the frame. If 0, the frame is
442 * for a "namespace eval" or "namespace
443 * inscope" command and var references are
444 * treated as references to namespace
445 * variables. */
446 {
447 *framePtrPtr = (Tcl_CallFrame *)TclStackAlloc(interp, sizeof(CallFrame));
448 return Tcl_PushCallFrame(interp, *framePtrPtr, namespacePtr,
449 isProcCallFrame);
450 }
451
452 void
453 TclPopStackFrame(
454 Tcl_Interp *interp) /* Interpreter with call frame to pop. */
455 {
456 CallFrame *freePtr = ((Interp *) interp)->framePtr;
457
458 Tcl_PopCallFrame(interp);
459 TclStackFree(interp, freePtr);
460 }
461
462 /*
463 *----------------------------------------------------------------------
464 *
465 * EstablishErrorCodeTraces --
466 *
467 * Creates traces on the ::errorCode variable to keep its value
468 * consistent with the expectations of legacy code.
469 *
470 * Results:
471 * None.
472 *
473 * Side effects:
474 * Read and unset traces are established on ::errorCode.
475 *
476 *----------------------------------------------------------------------
477 */
478
479 static char *
480 EstablishErrorCodeTraces(
481 ClientData clientData,
482 Tcl_Interp *interp,
483 const char *name1,
484 const char *name2,
485 int flags)
486 {
487 Tcl_TraceVar2(interp, "errorCode", NULL, TCL_GLOBAL_ONLY|TCL_TRACE_READS,
488 ErrorCodeRead, NULL);
489 Tcl_TraceVar2(interp, "errorCode", NULL, TCL_GLOBAL_ONLY|TCL_TRACE_UNSETS,
490 EstablishErrorCodeTraces, NULL);
491 return NULL;
492 }
493
494 /*
495 *----------------------------------------------------------------------
496 *
497 * ErrorCodeRead --
498 *
499 * Called when the ::errorCode variable is read. Copies the current value
500 * of the interp's errorCode field into ::errorCode.
501 *
502 * Results:
503 * None.
504 *
505 * Side effects:
506 * None.
507 *
508 *----------------------------------------------------------------------
509 */
510
511 static char *
512 ErrorCodeRead(
513 ClientData clientData,
514 Tcl_Interp *interp,
515 const char *name1,
516 const char *name2,
517 int flags)
518 {
519 Interp *iPtr = (Interp *) interp;
520
521 if (Tcl_InterpDeleted(interp) || !(iPtr->flags & ERR_LEGACY_COPY)) {
522 return NULL;
523 }
524 if (iPtr->errorCode) {
525 Tcl_ObjSetVar2(interp, iPtr->ecVar, NULL,
526 iPtr->errorCode, TCL_GLOBAL_ONLY);
527 return NULL;
528 }
529 if (NULL == Tcl_ObjGetVar2(interp, iPtr->ecVar, NULL, TCL_GLOBAL_ONLY)) {
530 Tcl_Obj *objPtr;
531 TclNewObj(objPtr);
532 Tcl_ObjSetVar2(interp, iPtr->ecVar, NULL,
533 objPtr, TCL_GLOBAL_ONLY);
534 }
535 return NULL;
536 }
537
538 /*
539 *----------------------------------------------------------------------
540 *
541 * EstablishErrorInfoTraces --
542 *
543 * Creates traces on the ::errorInfo variable to keep its value
544 * consistent with the expectations of legacy code.
545 *
546 * Results:
547 * None.
548 *
549 * Side effects:
550 * Read and unset traces are established on ::errorInfo.
551 *
552 *----------------------------------------------------------------------
553 */
554
555 static char *
556 EstablishErrorInfoTraces(
557 ClientData clientData,
558 Tcl_Interp *interp,
559 const char *name1,
560 const char *name2,
561 int flags)
562 {
563 Tcl_TraceVar2(interp, "errorInfo", NULL, TCL_GLOBAL_ONLY|TCL_TRACE_READS,
564 ErrorInfoRead, NULL);
565 Tcl_TraceVar2(interp, "errorInfo", NULL, TCL_GLOBAL_ONLY|TCL_TRACE_UNSETS,
566 EstablishErrorInfoTraces, NULL);
567 return NULL;
568 }
569
570 /*
571 *----------------------------------------------------------------------
572 *
573 * ErrorInfoRead --
574 *
575 * Called when the ::errorInfo variable is read. Copies the current value
576 * of the interp's errorInfo field into ::errorInfo.
577 *
578 * Results:
579 * None.
580 *
581 * Side effects:
582 * None.
583 *
584 *----------------------------------------------------------------------
585 */
586
587 static char *
588 ErrorInfoRead(
589 ClientData clientData,
590 Tcl_Interp *interp,
591 const char *name1,
592 const char *name2,
593 int flags)
594 {
595 Interp *iPtr = (Interp *) interp;
596
597 if (Tcl_InterpDeleted(interp) || !(iPtr->flags & ERR_LEGACY_COPY)) {
598 return NULL;
599 }
600 if (iPtr->errorInfo) {
601 Tcl_ObjSetVar2(interp, iPtr->eiVar, NULL,
602 iPtr->errorInfo, TCL_GLOBAL_ONLY);
603 return NULL;
604 }
605 if (NULL == Tcl_ObjGetVar2(interp, iPtr->eiVar, NULL, TCL_GLOBAL_ONLY)) {
606 Tcl_Obj *objPtr;
607 TclNewObj(objPtr);
608 Tcl_ObjSetVar2(interp, iPtr->eiVar, NULL,
609 objPtr, TCL_GLOBAL_ONLY);
610 }
611 return NULL;
612 }
613
614 /*
615 *----------------------------------------------------------------------
616 *
617 * Tcl_CreateNamespace --
618 *
619 * Creates a new namespace with the given name. If there is no active
620 * namespace (i.e., the interpreter is being initialized), the global ::
621 * namespace is created and returned.
622 *
623 * Results:
624 * Returns a pointer to the new namespace if successful. If the namespace
625 * already exists or if another error occurs, this routine returns NULL,
626 * along with an error message in the interpreter's result object.
627 *
628 * Side effects:
629 * If the name contains "::" qualifiers and a parent namespace does not
630 * already exist, it is automatically created.
631 *
632 *----------------------------------------------------------------------
633 */
634
635 Tcl_Namespace *
636 Tcl_CreateNamespace(
637 Tcl_Interp *interp, /* Interpreter in which a new namespace is
638 * being created. Also used for error
639 * reporting. */
640 const char *name, /* Name for the new namespace. May be a
641 * qualified name with names of ancestor
642 * namespaces separated by "::"s. */
643 ClientData clientData, /* One-word value to store with namespace. */
644 Tcl_NamespaceDeleteProc *deleteProc)
645 /* Function called to delete client data when
646 * the namespace is deleted. NULL if no
647 * function should be called. */
648 {
649 Interp *iPtr = (Interp *) interp;
650 Namespace *nsPtr, *ancestorPtr;
651 Namespace *parentPtr, *dummy1Ptr, *dummy2Ptr;
652 Namespace *globalNsPtr = iPtr->globalNsPtr;
653 const char *simpleName;
654 Tcl_HashEntry *entryPtr;
655 Tcl_DString buffer1, buffer2;
656 Tcl_DString *namePtr, *buffPtr;
657 int newEntry;
658 int nameLen;
659 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
660 const char *nameStr;
661 Tcl_DString tmpBuffer;
662
663 Tcl_DStringInit(&tmpBuffer);
664
665 /*
666 * If there is no active namespace, the interpreter is being initialized.
667 */
668
669 if ((globalNsPtr == NULL) && (iPtr->varFramePtr == NULL)) {
670 /*
671 * Treat this namespace as the global namespace, and avoid looking for
672 * a parent.
673 */
674
675 parentPtr = NULL;
676 simpleName = "";
677 goto doCreate;
678 }
679
680 /*
681 * Ensure that there are no trailing colons as that causes chaos when a
682 * deleteProc is specified. [Bug d614d63989]
683 */
684
685 if (deleteProc != NULL) {
686 nameStr = name + strlen(name) - 2;
687 if (nameStr >= name && nameStr[1] == ':' && nameStr[0] == ':') {
688 Tcl_DStringAppend(&tmpBuffer, name, -1);
689 while ((nameLen = Tcl_DStringLength(&tmpBuffer)) > 0
690 && Tcl_DStringValue(&tmpBuffer)[nameLen-1] == ':') {
691 Tcl_DStringSetLength(&tmpBuffer, nameLen-1);
692 }
693 name = Tcl_DStringValue(&tmpBuffer);
694 }
695 }
696
697 /*
698 * If we've ended up with an empty string now, we're attempting to create
699 * the global namespace despite the global namespace existing. That's
700 * naughty!
701 */
702
703 if (*name == '\0') {
704 Tcl_SetObjResult(interp, Tcl_NewStringObj("can't create namespace"
705 " \"\": only global namespace can have empty name", -1));
706 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "NAMESPACE",
707 "CREATEGLOBAL", (char *)NULL);
708 Tcl_DStringFree(&tmpBuffer);
709 return NULL;
710 }
711
712 /*
713 * Find the parent for the new namespace.
714 */
715
716 TclGetNamespaceForQualName(interp, name, NULL, TCL_CREATE_NS_IF_UNKNOWN,
717 &parentPtr, &dummy1Ptr, &dummy2Ptr, &simpleName);
718
719 /*
720 * If the unqualified name at the end is empty, there were trailing "::"s
721 * after the namespace's name which we ignore. The new namespace was
722 * already (recursively) created and is pointed to by parentPtr.
723 */
724
725 if (*simpleName == '\0') {
726 Tcl_DStringFree(&tmpBuffer);
727 return (Tcl_Namespace *) parentPtr;
728 }
729
730 /*
731 * Check for a bad namespace name and make sure that the name does not
732 * already exist in the parent namespace.
733 */
734
735 if (
736 Tcl_FindHashEntry(&parentPtr->childTable, simpleName) != NULL
737 ) {
738 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
739 "can't create namespace \"%s\": already exists", name));
740 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "NAMESPACE",
741 "CREATEEXISTING", (char *)NULL);
742 Tcl_DStringFree(&tmpBuffer);
743 return NULL;
744 }
745
746 /*
747 * Create the new namespace and root it in its parent. Increment the count
748 * of namespaces created.
749 */
750
751 doCreate:
752 nsPtr = (Namespace *)ckalloc(sizeof(Namespace));
753 nameLen = strlen(simpleName) + 1;
754 nsPtr->name = (char *)ckalloc(nameLen);
755 memcpy(nsPtr->name, simpleName, nameLen);
756 nsPtr->fullName = NULL; /* Set below. */
757 nsPtr->clientData = clientData;
758 nsPtr->deleteProc = deleteProc;
759 nsPtr->parentPtr = parentPtr;
760 Tcl_InitHashTable(&nsPtr->childTable, TCL_STRING_KEYS);
761 nsPtr->nsId = ++(tsdPtr->numNsCreated);
762 nsPtr->interp = interp;
763 nsPtr->flags = 0;
764 nsPtr->activationCount = 0;
765 nsPtr->refCount = 0;
766 Tcl_InitHashTable(&nsPtr->cmdTable, TCL_STRING_KEYS);
767 TclInitVarHashTable(&nsPtr->varTable, nsPtr);
768 nsPtr->exportArrayPtr = NULL;
769 nsPtr->numExportPatterns = 0;
770 nsPtr->maxExportPatterns = 0;
771 nsPtr->cmdRefEpoch = 0;
772 nsPtr->resolverEpoch = 0;
773 nsPtr->cmdResProc = NULL;
774 nsPtr->varResProc = NULL;
775 nsPtr->compiledVarResProc = NULL;
776 nsPtr->exportLookupEpoch = 0;
777 nsPtr->ensembles = NULL;
778 nsPtr->unknownHandlerPtr = NULL;
779 nsPtr->commandPathLength = 0;
780 nsPtr->commandPathArray = NULL;
781 nsPtr->commandPathSourceList = NULL;
782 nsPtr->earlyDeleteProc = NULL;
783
784 if (parentPtr != NULL) {
785 entryPtr = Tcl_CreateHashEntry(
786 TclGetNamespaceChildTable((Tcl_Namespace *) parentPtr),
787 simpleName, &newEntry);
788 Tcl_SetHashValue(entryPtr, nsPtr);
789 } else {
790 /*
791 * In the global namespace create traces to maintain the ::errorInfo
792 * and ::errorCode variables.
793 */
794
795 iPtr->globalNsPtr = nsPtr;
796 EstablishErrorInfoTraces(NULL, interp, NULL, NULL, 0);
797 EstablishErrorCodeTraces(NULL, interp, NULL, NULL, 0);
798 }
799
800 /*
801 * Build the fully qualified name for this namespace.
802 */
803
804 Tcl_DStringInit(&buffer1);
805 Tcl_DStringInit(&buffer2);
806 namePtr = &buffer1;
807 buffPtr = &buffer2;
808 for (ancestorPtr = nsPtr; ancestorPtr != NULL;
809 ancestorPtr = ancestorPtr->parentPtr) {
810 if (ancestorPtr != globalNsPtr) {
811 Tcl_DString *tempPtr = namePtr;
812
813 TclDStringAppendLiteral(buffPtr, "::");
814 Tcl_DStringAppend(buffPtr, ancestorPtr->name, -1);
815 TclDStringAppendDString(buffPtr, namePtr);
816
817 /*
818 * Clear the unwanted buffer or we end up appending to previous
819 * results, making the namespace fullNames of nested namespaces
820 * very wrong (and strange).
821 */
822
823 TclDStringClear(namePtr);
824
825 /*
826 * Now swap the buffer pointers so that we build in the other
827 * buffer. This is faster than repeated copying back and forth
828 * between buffers.
829 */
830
831 namePtr = buffPtr;
832 buffPtr = tempPtr;
833 }
834 }
835
836 name = Tcl_DStringValue(namePtr);
837 nameLen = Tcl_DStringLength(namePtr);
838 nsPtr->fullName = (char *)ckalloc(nameLen + 1);
839 memcpy(nsPtr->fullName, name, nameLen + 1);
840
841 Tcl_DStringFree(&buffer1);
842 Tcl_DStringFree(&buffer2);
843 Tcl_DStringFree(&tmpBuffer);
844
845 /*
846 * If compilation of commands originating from the parent NS is
847 * suppressed, suppress it for commands originating in this one too.
848 */
849
850 if (nsPtr->parentPtr != NULL &&
851 nsPtr->parentPtr->flags & NS_SUPPRESS_COMPILATION) {
852 nsPtr->flags |= NS_SUPPRESS_COMPILATION;
853 }
854
855 /*
856 * Return a pointer to the new namespace.
857 */
858
859 return (Tcl_Namespace *) nsPtr;
860 }
861
862 /*
863 *----------------------------------------------------------------------
864 *
865 * Tcl_DeleteNamespace --
866 *
867 * Deletes a namespace and all of the commands, variables, and other
868 * namespaces within it.
869 *
870 * Results:
871 * None.
872 *
873 * Side effects:
874 * When a namespace is deleted, it is automatically removed as a child of
875 * its parent namespace. Also, all its commands, variables and child
876 * namespaces are deleted.
877 *
878 *----------------------------------------------------------------------
879 */
880
881 void
882 Tcl_DeleteNamespace(
883 Tcl_Namespace *namespacePtr)/* Points to the namespace to delete. */
884 {
885 Namespace *nsPtr = (Namespace *) namespacePtr;
886 Tcl_Interp *interp = nsPtr->interp;
887 Namespace *globalNsPtr = (Namespace *) TclGetGlobalNamespace(interp);
888 Tcl_HashEntry *entryPtr;
889 Tcl_HashSearch search;
890 Command *cmdPtr;
891
892 /*
893 * Ensure that this namespace doesn't get deallocated in the meantime.
894 */
895 nsPtr->refCount++;
896
897 /*
898 * Give anyone interested - notably TclOO - a chance to use this namespace
899 * normally despite the fact that the namespace is going to go. Allows the
900 * calling of destructors. Will only be called once (unless re-established
901 * by the called function). [Bug 2950259]
902 *
903 * Note that setting this field requires access to the internal definition
904 * of namespaces, so it should only be accessed by code that knows about
905 * being careful with reentrancy.
906 */
907
908 if (nsPtr->earlyDeleteProc != NULL) {
909 Tcl_NamespaceDeleteProc *earlyDeleteProc = nsPtr->earlyDeleteProc;
910
911 nsPtr->earlyDeleteProc = NULL;
912 nsPtr->activationCount++;
913 earlyDeleteProc(nsPtr->clientData);
914 nsPtr->activationCount--;
915 }
916
917 /*
918 * Delete all coroutine commands now: break the circular ref cycle between
919 * the namespace and the coroutine command [Bug 2724403]. This code is
920 * essentially duplicated in TclTeardownNamespace() for all other
921 * commands. Don't optimize to Tcl_NextHashEntry() because of traces.
922 *
923 * NOTE: we could avoid traversing the ns's command list by keeping a
924 * separate list of coros.
925 */
926
927 for (entryPtr = Tcl_FirstHashEntry(&nsPtr->cmdTable, &search);
928 entryPtr != NULL;) {
929 cmdPtr = (Command *)Tcl_GetHashValue(entryPtr);
930 if (cmdPtr->nreProc == TclNRInterpCoroutine) {
931 Tcl_DeleteCommandFromToken(interp, (Tcl_Command) cmdPtr);
932 entryPtr = Tcl_FirstHashEntry(&nsPtr->cmdTable, &search);
933 } else {
934 entryPtr = Tcl_NextHashEntry(&search);
935 }
936 }
937
938 /*
939 * If the namespace has associated ensemble commands, delete them first.
940 * This leaves the actual contents of the namespace alone (unless they are
941 * linked ensemble commands, of course). Note that this code is actually
942 * reentrant so command delete traces won't purturb things badly.
943 */
944
945 while (nsPtr->ensembles != NULL) {
946 EnsembleConfig *ensemblePtr = (EnsembleConfig *) nsPtr->ensembles;
947
948 /*
949 * Splice out and link to indicate that we've already been killed.
950 */
951
952 nsPtr->ensembles = (Tcl_Ensemble *) ensemblePtr->next;
953 ensemblePtr->next = ensemblePtr;
954 Tcl_DeleteCommandFromToken(interp, ensemblePtr->token);
955 }
956
957 /*
958 * If the namespace has a registered unknown handler (TIP 181), then free
959 * it here.
960 */
961
962 if (nsPtr->unknownHandlerPtr != NULL) {
963 Tcl_DecrRefCount(nsPtr->unknownHandlerPtr);
964 nsPtr->unknownHandlerPtr = NULL;
965 }
966
967 /*
968 * If the namespace is on the call frame stack, it is marked as "dying"
969 * (NS_DYING is OR'd into its flags): Contents of the namespace are
970 * still available and visible until the namespace is later marked as
971 * NS_DEAD, and its commands and variables are still usable by any
972 * active call frames referring to th namespace. When all active call
973 * frames referring to the namespace have been popped from the Tcl
974 * stack, Tcl_PopCallFrame calls Tcl_DeleteNamespace again. If no
975 * nsName objects refer to the namespace (i.e., if its refCount is
976 * zero), its commands and variables are deleted and the storage for
977 * its namespace structure is freed. Otherwise, if its refCount is
978 * nonzero, the namespace's commands and variables are deleted but the
979 * structure isn't freed. Instead, NS_DEAD is OR'd into the structure's
980 * flags to allow the namespace resolution code to recognize that the
981 * namespace is "deleted". The structure's storage is freed by
982 * FreeNsNameInternalRep when its refCount reaches 0.
983 */
984
985 if (nsPtr->activationCount > (nsPtr == globalNsPtr)) {
986 nsPtr->flags |= NS_DYING;
987 if (nsPtr->parentPtr != NULL) {
988 entryPtr = Tcl_FindHashEntry(
989 TclGetNamespaceChildTable((Tcl_Namespace *)
990 nsPtr->parentPtr), nsPtr->name);
991 if (entryPtr != NULL) {
992 Tcl_DeleteHashEntry(entryPtr);
993 }
994 }
995 nsPtr->parentPtr = NULL;
996 } else if (!(nsPtr->flags & NS_KILLED)) {
997 /*
998 * Delete the namespace and everything in it. If this is the global
999 * namespace, then clear it but don't free its storage unless the
1000 * interpreter is being torn down. Set the NS_KILLED flag to avoid
1001 * recursive calls here - if the namespace is really in the process of
1002 * being deleted, ignore any second call.
1003 */
1004
1005 nsPtr->flags |= (NS_DYING | NS_KILLED);
1006
1007 TclTeardownNamespace(nsPtr);
1008
1009 if ((nsPtr != globalNsPtr) || (((Interp *) interp)->flags & DELETED)) {
1010 /*
1011 * If this is the global namespace, then it may have residual
1012 * "errorInfo" and "errorCode" variables for errors that occurred
1013 * while it was being torn down. Try to clear the variable list
1014 * one last time.
1015 */
1016
1017 TclDeleteNamespaceVars(nsPtr);
1018
1019 Tcl_DeleteHashTable(&nsPtr->childTable);
1020 Tcl_DeleteHashTable(&nsPtr->cmdTable);
1021
1022 nsPtr ->flags |= NS_DEAD;
1023 } else {
1024 /*
1025 * Restore the ::errorInfo and ::errorCode traces.
1026 */
1027
1028 EstablishErrorInfoTraces(NULL, interp, NULL, NULL, 0);
1029 EstablishErrorCodeTraces(NULL, interp, NULL, NULL, 0);
1030
1031 /*
1032 * We didn't really kill it, so remove the KILLED marks, so it can
1033 * get killed later, avoiding mem leaks.
1034 */
1035
1036 nsPtr->flags &= ~(NS_DYING|NS_KILLED);
1037 }
1038 }
1039 TclNsDecrRefCount(nsPtr);
1040 }
1041
1042 int
1043 TclNamespaceDeleted(
1044 Namespace *nsPtr)
1045 {
1046 return (nsPtr->flags & NS_DYING) ? 1 : 0;
1047 }
1048
1049 /*
1050 *----------------------------------------------------------------------
1051 *
1052 * TclTeardownNamespace --
1053 *
1054 * Used internally to dismantle and unlink a namespace when it is
1055 * deleted. Divorces the namespace from its parent, and deletes all
1056 * commands, variables, and child namespaces.
1057 *
1058 * This is kept separate from Tcl_DeleteNamespace so that the global
1059 * namespace can be handled specially.
1060 *
1061 * Results:
1062 * None.
1063 *
1064 * Side effects:
1065 * Removes this namespace from its parent's child namespace hashtable.
1066 * Deletes all commands, variables and namespaces in this namespace.
1067 *
1068 *----------------------------------------------------------------------
1069 */
1070
1071 void
1072 TclTeardownNamespace(
1073 Namespace *nsPtr) /* Points to the namespace to be dismantled
1074 * and unlinked from its parent. */
1075 {
1076 Tcl_Interp *interp = nsPtr->interp;
1077 Tcl_HashEntry *entryPtr;
1078 Tcl_HashSearch search;
1079 int i;
1080
1081 /*
1082 * Start by destroying the namespace's variable table, since variables
1083 * might trigger traces. Variable table should be cleared but not freed!
1084 * TclDeleteNamespaceVars frees it, so we reinitialize it afterwards.
1085 */
1086
1087 TclDeleteNamespaceVars(nsPtr);
1088 TclInitVarHashTable(&nsPtr->varTable, nsPtr);
1089
1090 /*
1091 * Delete all commands in this namespace. Be careful when traversing the
1092 * hash table: when each command is deleted, it removes itself from the
1093 * command table. Because of traces (and the desire to avoid the quadratic
1094 * problems of just using Tcl_FirstHashEntry over and over, [Bug
1095 * f97d4ee020]) we copy to a temporary array and then delete all those
1096 * commands.
1097 */
1098
1099 while (nsPtr->cmdTable.numEntries > 0) {
1100 int length = nsPtr->cmdTable.numEntries;
1101 Command **cmds = (Command **)TclStackAlloc(interp,
1102 sizeof(Command *) * length);
1103
1104 i = 0;
1105 for (entryPtr = Tcl_FirstHashEntry(&nsPtr->cmdTable, &search);
1106 entryPtr != NULL;
1107 entryPtr = Tcl_NextHashEntry(&search)) {
1108 cmds[i] = (Command *)Tcl_GetHashValue(entryPtr);
1109 cmds[i]->refCount++;
1110 i++;
1111 }
1112 for (i = 0 ; i < length ; i++) {
1113 Tcl_DeleteCommandFromToken(interp, (Tcl_Command) cmds[i]);
1114 TclCleanupCommandMacro(cmds[i]);
1115 }
1116 TclStackFree(interp, cmds);
1117 }
1118 Tcl_DeleteHashTable(&nsPtr->cmdTable);
1119 Tcl_InitHashTable(&nsPtr->cmdTable, TCL_STRING_KEYS);
1120
1121 /*
1122 * Remove the namespace from its parent's child hashtable.
1123 */
1124
1125 if (nsPtr->parentPtr != NULL) {
1126 entryPtr = Tcl_FindHashEntry(
1127 TclGetNamespaceChildTable((Tcl_Namespace *)
1128 nsPtr->parentPtr), nsPtr->name);
1129 if (entryPtr != NULL) {
1130 Tcl_DeleteHashEntry(entryPtr);
1131 }
1132 }
1133 nsPtr->parentPtr = NULL;
1134
1135 /*
1136 * Delete the namespace path if one is installed.
1137 */
1138
1139 if (nsPtr->commandPathLength != 0) {
1140 UnlinkNsPath(nsPtr);
1141 nsPtr->commandPathLength = 0;
1142 }
1143 if (nsPtr->commandPathSourceList != NULL) {
1144 NamespacePathEntry *nsPathPtr = nsPtr->commandPathSourceList;
1145
1146 do {
1147 if (nsPathPtr->nsPtr != NULL && nsPathPtr->creatorNsPtr != NULL) {
1148 nsPathPtr->creatorNsPtr->cmdRefEpoch++;
1149 }
1150 nsPathPtr->nsPtr = NULL;
1151 nsPathPtr = nsPathPtr->nextPtr;
1152 } while (nsPathPtr != NULL);
1153 nsPtr->commandPathSourceList = NULL;
1154 }
1155
1156 /*
1157 * Delete all the child namespaces.
1158 *
1159 * BE CAREFUL: When each child is deleted, it will divorce itself from its
1160 * parent. You can't traverse a hash table properly if its elements are
1161 * being deleted. Because of traces (and the desire to avoid the
1162 * quadratic problems of just using Tcl_FirstHashEntry over and over, [Bug
1163 * f97d4ee020]) we copy to a temporary array and then delete all those
1164 * namespaces.
1165 *
1166 * Important: leave the hash table itself still live.
1167 */
1168
1169 while (nsPtr->childTable.numEntries > 0) {
1170 int length = nsPtr->childTable.numEntries;
1171 Namespace **children = (Namespace **)TclStackAlloc(interp,
1172 sizeof(Namespace *) * length);
1173
1174 i = 0;
1175 for (entryPtr = Tcl_FirstHashEntry(&nsPtr->childTable, &search);
1176 entryPtr != NULL;
1177 entryPtr = Tcl_NextHashEntry(&search)) {
1178 children[i] = (Namespace *)Tcl_GetHashValue(entryPtr);
1179 children[i]->refCount++;
1180 i++;
1181 }
1182 for (i = 0 ; i < length ; i++) {
1183 Tcl_DeleteNamespace((Tcl_Namespace *) children[i]);
1184 TclNsDecrRefCount(children[i]);
1185 }
1186 TclStackFree(interp, children);
1187 }
1188
1189 /*
1190 * Free the namespace's export pattern array.
1191 */
1192
1193 if (nsPtr->exportArrayPtr != NULL) {
1194 for (i = 0; i < nsPtr->numExportPatterns; i++) {
1195 ckfree(nsPtr->exportArrayPtr[i]);
1196 }
1197 ckfree(nsPtr->exportArrayPtr);
1198 nsPtr->exportArrayPtr = NULL;
1199 nsPtr->numExportPatterns = 0;
1200 nsPtr->maxExportPatterns = 0;
1201 }
1202
1203 /*
1204 * Free any client data associated with the namespace.
1205 */
1206
1207 if (nsPtr->deleteProc != NULL) {
1208 nsPtr->deleteProc(nsPtr->clientData);
1209 }
1210 nsPtr->deleteProc = NULL;
1211 nsPtr->clientData = NULL;
1212
1213 /*
1214 * Reset the namespace's id field to ensure that this namespace won't be
1215 * interpreted as valid by, e.g., the cache validation code for cached
1216 * command references in Tcl_GetCommandFromObj.
1217 */
1218
1219 nsPtr->nsId = 0;
1220 }
1221
1222 /*
1223 *----------------------------------------------------------------------
1224 *
1225 * NamespaceFree --
1226 *
1227 * Called after a namespace has been deleted, when its reference count
1228 * reaches 0. Frees the data structure representing the namespace.
1229 *
1230 * Results:
1231 * None.
1232 *
1233 * Side effects:
1234 * None.
1235 *
1236 *----------------------------------------------------------------------
1237 */
1238
1239 static void
1240 NamespaceFree(
1241 Namespace *nsPtr) /* Points to the namespace to free. */
1242 {
1243 /*
1244 * Most of the namespace's contents are freed when the namespace is
1245 * deleted by Tcl_DeleteNamespace. All that remains is to free its names
1246 * (for error messages), and the structure itself.
1247 */
1248
1249 ckfree(nsPtr->name);
1250 ckfree(nsPtr->fullName);
1251 ckfree(nsPtr);
1252 }
1253
1254 /*
1255 *----------------------------------------------------------------------
1256 *
1257 * TclNsDecrRefCount --
1258 *
1259 * Drops a reference to a namespace and frees it if the namespace has
1260 * been deleted and the last reference has just been dropped.
1261 *
1262 * Results:
1263 * None.
1264 *
1265 * Side effects:
1266 * None.
1267 *
1268 *----------------------------------------------------------------------
1269 */
1270
1271 void
1272 TclNsDecrRefCount(
1273 Namespace *nsPtr)
1274 {
1275 if ((nsPtr->refCount-- <= 1) && (nsPtr->flags & NS_DEAD)) {
1276 NamespaceFree(nsPtr);
1277 }
1278 }
1279
1280 /*
1281 *----------------------------------------------------------------------
1282 *
1283 * Tcl_Export --
1284 *
1285 * Makes all the commands matching a pattern available to later be
1286 * imported from the namespace specified by namespacePtr (or the current
1287 * namespace if namespacePtr is NULL). The specified pattern is appended
1288 * onto the namespace's export pattern list, which is optionally cleared
1289 * beforehand.
1290 *
1291 * Results:
1292 * Returns TCL_OK if successful, or TCL_ERROR (along with an error
1293 * message in the interpreter's result) if something goes wrong.
1294 *
1295 * Side effects:
1296 * Appends the export pattern onto the namespace's export list.
1297 * Optionally reset the namespace's export pattern list.
1298 *
1299 *----------------------------------------------------------------------
1300 */
1301
1302 int
1303 Tcl_Export(
1304 Tcl_Interp *interp, /* Current interpreter. */
1305 Tcl_Namespace *namespacePtr,/* Points to the namespace from which commands
1306 * are to be exported. NULL for the current
1307 * namespace. */
1308 const char *pattern, /* String pattern indicating which commands to
1309 * export. This pattern may not include any
1310 * namespace qualifiers; only commands in the
1311 * specified namespace may be exported. */
1312 int resetListFirst) /* If nonzero, resets the namespace's export
1313 * list before appending. */
1314 {
1315 #define INIT_EXPORT_PATTERNS 5
1316 Namespace *nsPtr, *exportNsPtr, *dummyPtr;
1317 Namespace *currNsPtr = (Namespace *) TclGetCurrentNamespace(interp);
1318 const char *simplePattern;
1319 char *patternCpy;
1320 int neededElems, len, i;
1321
1322 /*
1323 * If the specified namespace is NULL, use the current namespace.
1324 */
1325
1326 if (namespacePtr == NULL) {
1327 nsPtr = (Namespace *) currNsPtr;
1328 } else {
1329 nsPtr = (Namespace *) namespacePtr;
1330 }
1331
1332 /*
1333 * If resetListFirst is true (nonzero), clear the namespace's export
1334 * pattern list.
1335 */
1336
1337 if (resetListFirst) {
1338 if (nsPtr->exportArrayPtr != NULL) {
1339 for (i = 0; i < nsPtr->numExportPatterns; i++) {
1340 ckfree(nsPtr->exportArrayPtr[i]);
1341 }
1342 ckfree(nsPtr->exportArrayPtr);
1343 nsPtr->exportArrayPtr = NULL;
1344 TclInvalidateNsCmdLookup(nsPtr);
1345 nsPtr->numExportPatterns = 0;
1346 nsPtr->maxExportPatterns = 0;
1347 }
1348 }
1349
1350 /*
1351 * Check that the pattern doesn't have namespace qualifiers.
1352 */
1353
1354 TclGetNamespaceForQualName(interp, pattern, nsPtr, TCL_NAMESPACE_ONLY,
1355 &exportNsPtr, &dummyPtr, &dummyPtr, &simplePattern);
1356
1357 if ((exportNsPtr != nsPtr) || (strcmp(pattern, simplePattern) != 0)) {
1358 Tcl_SetObjResult(interp, Tcl_ObjPrintf("invalid export pattern"
1359 " \"%s\": pattern can't specify a namespace", pattern));
1360 Tcl_SetErrorCode(interp, "TCL", "EXPORT", "INVALID", (char *)NULL);
1361 return TCL_ERROR;
1362 }
1363
1364 /*
1365 * Make sure that we don't already have the pattern in the array
1366 */
1367
1368 if (nsPtr->exportArrayPtr != NULL) {
1369 for (i = 0; i < nsPtr->numExportPatterns; i++) {
1370 if (strcmp(pattern, nsPtr->exportArrayPtr[i]) == 0) {
1371 /*
1372 * The pattern already exists in the list.
1373 */
1374
1375 return TCL_OK;
1376 }
1377 }
1378 }
1379
1380 /*
1381 * Make sure there is room in the namespace's pattern array for the new
1382 * pattern.
1383 */
1384
1385 neededElems = nsPtr->numExportPatterns + 1;
1386 if (neededElems > nsPtr->maxExportPatterns) {
1387 nsPtr->maxExportPatterns = nsPtr->maxExportPatterns ?
1388 2 * nsPtr->maxExportPatterns : INIT_EXPORT_PATTERNS;
1389 nsPtr->exportArrayPtr = (char **)ckrealloc(nsPtr->exportArrayPtr,
1390 sizeof(char *) * nsPtr->maxExportPatterns);
1391 }
1392
1393 /*
1394 * Add the pattern to the namespace's array of export patterns.
1395 */
1396
1397 len = strlen(pattern);
1398 patternCpy = (char *)ckalloc(len + 1);
1399 memcpy(patternCpy, pattern, len + 1);
1400
1401 nsPtr->exportArrayPtr[nsPtr->numExportPatterns] = patternCpy;
1402 nsPtr->numExportPatterns++;
1403
1404 /*
1405 * The list of commands actually exported from the namespace might have
1406 * changed (probably will have!) However, we do not need to recompute this
1407 * just yet; next time we need the info will be soon enough.
1408 */
1409
1410 TclInvalidateNsCmdLookup(nsPtr);
1411
1412 return TCL_OK;
1413 #undef INIT_EXPORT_PATTERNS
1414 }
1415
1416 /*
1417 *----------------------------------------------------------------------
1418 *
1419 * Tcl_AppendExportList --
1420 *
1421 * Appends onto the argument object the list of export patterns for the
1422 * specified namespace.
1423 *
1424 * Results:
1425 * The return value is normally TCL_OK; in this case the object
1426 * referenced by objPtr has each export pattern appended to it. If an
1427 * error occurs, TCL_ERROR is returned and the interpreter's result holds
1428 * an error message.
1429 *
1430 * Side effects:
1431 * If necessary, the object referenced by objPtr is converted into a list
1432 * object.
1433 *
1434 *----------------------------------------------------------------------
1435 */
1436
1437 int
1438 Tcl_AppendExportList(
1439 Tcl_Interp *interp, /* Interpreter used for global NS and error
1440 * reporting. */
1441 Tcl_Namespace *namespacePtr,/* Points to the namespace whose export
1442 * pattern list is appended onto objPtr. NULL
1443 * for the current namespace. */
1444 Tcl_Obj *objPtr) /* Points to the Tcl object onto which the
1445 * export pattern list is appended. */
1446 {
1447 Namespace *nsPtr;
1448 int i;
1449 int result;
1450
1451 /*
1452 * If the specified namespace is NULL, use the current namespace.
1453 */
1454
1455 if (namespacePtr == NULL) {
1456 nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
1457 } else {
1458 nsPtr = (Namespace *) namespacePtr;
1459 }
1460
1461 /*
1462 * Append the export pattern list onto objPtr.
1463 */
1464
1465 for (i = 0; i < nsPtr->numExportPatterns; i++) {
1466 result = Tcl_ListObjAppendElement(interp, objPtr,
1467 Tcl_NewStringObj(nsPtr->exportArrayPtr[i], -1));
1468 if (result != TCL_OK) {
1469 return result;
1470 }
1471 }
1472 return TCL_OK;
1473 }
1474
1475 /*
1476 *----------------------------------------------------------------------
1477 *
1478 * Tcl_Import --
1479 *
1480 * Imports all of the commands matching a pattern into the namespace
1481 * specified by namespacePtr (or the current namespace if contextNsPtr is
1482 * NULL). This is done by creating a new command (the "imported command")
1483 * that points to the real command in its original namespace.
1484 *
1485 * If matching commands are on the autoload path but haven't been loaded
1486 * yet, this command forces them to be loaded, then creates the links to
1487 * them.
1488 *
1489 * Results:
1490 * Returns TCL_OK if successful, or TCL_ERROR (along with an error
1491 * message in the interpreter's result) if something goes wrong.
1492 *
1493 * Side effects:
1494 * Creates new commands in the importing namespace. These indirect calls
1495 * back to the real command and are deleted if the real commands are
1496 * deleted.
1497 *
1498 *----------------------------------------------------------------------
1499 */
1500
1501 int
1502 Tcl_Import(
1503 Tcl_Interp *interp, /* Current interpreter. */
1504 Tcl_Namespace *namespacePtr,/* Points to the namespace into which the
1505 * commands are to be imported. NULL for the
1506 * current namespace. */
1507 const char *pattern, /* String pattern indicating which commands to
1508 * import. This pattern should be qualified by
1509 * the name of the namespace from which to
1510 * import the command(s). */
1511 int allowOverwrite) /* If nonzero, allow existing commands to be
1512 * overwritten by imported commands. If 0,
1513 * return an error if an imported cmd
1514 * conflicts with an existing one. */
1515 {
1516 Namespace *nsPtr, *importNsPtr, *dummyPtr;
1517 const char *simplePattern;
1518 Tcl_HashEntry *hPtr;
1519 Tcl_HashSearch search;
1520
1521 /*
1522 * If the specified namespace is NULL, use the current namespace.
1523 */
1524
1525 if (namespacePtr == NULL) {
1526 nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
1527 } else {
1528 nsPtr = (Namespace *) namespacePtr;
1529 }
1530
1531 /*
1532 * First, invoke the "auto_import" command with the pattern being
1533 * imported. This command is part of the Tcl library. It looks for
1534 * imported commands in autoloaded libraries and loads them in. That way,
1535 * they will be found when we try to create links below.
1536 *
1537 * Note that we don't just call Tcl_EvalObjv() directly because we do not
1538 * want absence of the command to be a failure case.
1539 */
1540
1541 if (Tcl_FindCommand(interp, "auto_import", NULL, TCL_GLOBAL_ONLY) != NULL) {
1542 Tcl_Obj *objv[2];
1543 int result;
1544
1545 TclNewLiteralStringObj(objv[0], "auto_import");
1546 objv[1] = Tcl_NewStringObj(pattern, -1);
1547
1548 Tcl_IncrRefCount(objv[0]);
1549 Tcl_IncrRefCount(objv[1]);
1550 result = Tcl_EvalObjv(interp, 2, objv, TCL_GLOBAL_ONLY);
1551 Tcl_DecrRefCount(objv[0]);
1552 Tcl_DecrRefCount(objv[1]);
1553
1554 if (result != TCL_OK) {
1555 return TCL_ERROR;
1556 }
1557 Tcl_ResetResult(interp);
1558 }
1559
1560 /*
1561 * From the pattern, find the namespace from which we are importing and
1562 * get the simple pattern (no namespace qualifiers or ::'s) at the end.
1563 */
1564
1565 if (strlen(pattern) == 0) {
1566 Tcl_SetObjResult(interp, Tcl_NewStringObj("empty import pattern",-1));
1567 Tcl_SetErrorCode(interp, "TCL", "IMPORT", "EMPTY", (char *)NULL);
1568 return TCL_ERROR;
1569 }
1570 TclGetNamespaceForQualName(interp, pattern, nsPtr, TCL_NAMESPACE_ONLY,
1571 &importNsPtr, &dummyPtr, &dummyPtr, &simplePattern);
1572
1573 if (importNsPtr == NULL) {
1574 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1575 "unknown namespace in import pattern \"%s\"", pattern));
1576 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "NAMESPACE", pattern, (char *)NULL);
1577 return TCL_ERROR;
1578 }
1579 if (importNsPtr == nsPtr) {
1580 if (pattern == simplePattern) {
1581 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1582 "no namespace specified in import pattern \"%s\"",
1583 pattern));
1584 Tcl_SetErrorCode(interp, "TCL", "IMPORT", "ORIGIN", (char *)NULL);
1585 } else {
1586 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1587 "import pattern \"%s\" tries to import from namespace"
1588 " \"%s\" into itself", pattern, importNsPtr->name));
1589 Tcl_SetErrorCode(interp, "TCL", "IMPORT", "SELF", (char *)NULL);
1590 }
1591 return TCL_ERROR;
1592 }
1593
1594 /*
1595 * Scan through the command table in the source namespace and look for
1596 * exported commands that match the string pattern. Create an "imported
1597 * command" in the current namespace for each imported command; these
1598 * commands redirect their invocations to the "real" command.
1599 */
1600
1601 if ((simplePattern != NULL) && TclMatchIsTrivial(simplePattern)) {
1602 hPtr = Tcl_FindHashEntry(&importNsPtr->cmdTable, simplePattern);
1603 if (hPtr == NULL) {
1604 return TCL_OK;
1605 }
1606 return DoImport(interp, nsPtr, hPtr, simplePattern, pattern,
1607 importNsPtr, allowOverwrite);
1608 }
1609 for (hPtr = Tcl_FirstHashEntry(&importNsPtr->cmdTable, &search);
1610 (hPtr != NULL); hPtr = Tcl_NextHashEntry(&search)) {
1611 char *cmdName = (char *)Tcl_GetHashKey(&importNsPtr->cmdTable, hPtr);
1612
1613 if (Tcl_StringMatch(cmdName, simplePattern) &&
1614 DoImport(interp, nsPtr, hPtr, cmdName, pattern, importNsPtr,
1615 allowOverwrite) == TCL_ERROR) {
1616 return TCL_ERROR;
1617 }
1618 }
1619 return TCL_OK;
1620 }
1621
1622 /*
1623 *----------------------------------------------------------------------
1624 *
1625 * DoImport --
1626 *
1627 * Import a particular command from one namespace into another. Helper
1628 * for Tcl_Import().
1629 *
1630 * Results:
1631 * Standard Tcl result code. If TCL_ERROR, appends an error message to
1632 * the interpreter result.
1633 *
1634 * Side effects:
1635 * A new command is created in the target namespace unless this is a
1636 * reimport of exactly the same command as before.
1637 *
1638 *----------------------------------------------------------------------
1639 */
1640
1641 static int
1642 DoImport(
1643 Tcl_Interp *interp,
1644 Namespace *nsPtr,
1645 Tcl_HashEntry *hPtr,
1646 const char *cmdName,
1647 const char *pattern,
1648 Namespace *importNsPtr,
1649 int allowOverwrite)
1650 {
1651 int i = 0, exported = 0;
1652 Tcl_HashEntry *found;
1653
1654 /*
1655 * The command cmdName in the source namespace matches the pattern. Check
1656 * whether it was exported. If it wasn't, we ignore it.
1657 */
1658
1659 while (!exported && (i < importNsPtr->numExportPatterns)) {
1660 exported |= Tcl_StringMatch(cmdName,
1661 importNsPtr->exportArrayPtr[i++]);
1662 }
1663 if (!exported) {
1664 return TCL_OK;
1665 }
1666
1667 /*
1668 * Unless there is a name clash, create an imported command in the current
1669 * namespace that refers to cmdPtr.
1670 */
1671
1672 found = Tcl_FindHashEntry(&nsPtr->cmdTable, cmdName);
1673 if ((found == NULL) || allowOverwrite) {
1674 /*
1675 * Create the imported command and its client data. To create the new
1676 * command in the current namespace, generate a fully qualified name
1677 * for it.
1678 */
1679
1680 Tcl_DString ds;
1681 Tcl_Command importedCmd;
1682 ImportedCmdData *dataPtr;
1683 Command *cmdPtr;
1684 ImportRef *refPtr;
1685
1686 Tcl_DStringInit(&ds);
1687 Tcl_DStringAppend(&ds, nsPtr->fullName, -1);
1688 if (nsPtr != ((Interp *) interp)->globalNsPtr) {
1689 TclDStringAppendLiteral(&ds, "::");
1690 }
1691 Tcl_DStringAppend(&ds, cmdName, -1);
1692
1693 /*
1694 * Check whether creating the new imported command in the current
1695 * namespace would create a cycle of imported command references.
1696 */
1697
1698 cmdPtr = (Command *)Tcl_GetHashValue(hPtr);
1699 if (found != NULL && cmdPtr->deleteProc == DeleteImportedCmd) {
1700 Command *overwrite = (Command *)Tcl_GetHashValue(found);
1701 Command *linkCmd = cmdPtr;
1702
1703 while (linkCmd->deleteProc == DeleteImportedCmd) {
1704 dataPtr = (ImportedCmdData *)linkCmd->objClientData;
1705 linkCmd = dataPtr->realCmdPtr;
1706 if (overwrite == linkCmd) {
1707 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1708 "import pattern \"%s\" would create a loop"
1709 " containing command \"%s\"",
1710 pattern, Tcl_DStringValue(&ds)));
1711 Tcl_DStringFree(&ds);
1712 Tcl_SetErrorCode(interp, "TCL", "IMPORT", "LOOP", (char *)NULL);
1713 return TCL_ERROR;
1714 }
1715 }
1716 }
1717
1718 dataPtr = (ImportedCmdData *)ckalloc(sizeof(ImportedCmdData));
1719 importedCmd = Tcl_NRCreateCommand(interp, Tcl_DStringValue(&ds),
1720 InvokeImportedCmd, InvokeImportedNRCmd, dataPtr,
1721 DeleteImportedCmd);
1722 dataPtr->realCmdPtr = cmdPtr;
1723 dataPtr->selfPtr = (Command *) importedCmd;
1724 dataPtr->selfPtr->compileProc = cmdPtr->compileProc;
1725 Tcl_DStringFree(&ds);
1726
1727 /*
1728 * Create an ImportRef structure describing this new import command
1729 * and add it to the import ref list in the "real" command.
1730 */
1731
1732 refPtr = (ImportRef *)ckalloc(sizeof(ImportRef));
1733 refPtr->importedCmdPtr = (Command *) importedCmd;
1734 refPtr->nextPtr = cmdPtr->importRefPtr;
1735 cmdPtr->importRefPtr = refPtr;
1736 } else {
1737 Command *overwrite = (Command *)Tcl_GetHashValue(found);
1738
1739 if (overwrite->deleteProc == DeleteImportedCmd) {
1740 ImportedCmdData *dataPtr = (ImportedCmdData *)overwrite->objClientData;
1741
1742 if (dataPtr->realCmdPtr == Tcl_GetHashValue(hPtr)) {
1743 /*
1744 * Repeated import of same command is acceptable.
1745 */
1746
1747 return TCL_OK;
1748 }
1749 }
1750 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1751 "can't import command \"%s\": already exists", cmdName));
1752 Tcl_SetErrorCode(interp, "TCL", "IMPORT", "OVERWRITE", (char *)NULL);
1753 return TCL_ERROR;
1754 }
1755 return TCL_OK;
1756 }
1757
1758 /*
1759 *----------------------------------------------------------------------
1760 *
1761 * Tcl_ForgetImport --
1762 *
1763 * Deletes commands previously imported into the namespace indicated.
1764 * The by namespacePtr, or the current namespace of interp, when
1765 * namespacePtr is NULL. The pattern controls which imported commands are
1766 * deleted. A simple pattern, one without namespace separators, matches
1767 * the current command names of imported commands in the namespace.
1768 * Matching imported commands are deleted. A qualified pattern is
1769 * interpreted as deletion selection on the basis of where the command is
1770 * imported from. The original command and "first link" command for each
1771 * imported command are determined, and they are matched against the
1772 * pattern. A match leads to deletion of the imported command.
1773 *
1774 * Results:
1775 * Returns TCL_ERROR and records an error message in the interp result if
1776 * a namespace qualified pattern refers to a namespace that does not
1777 * exist. Otherwise, returns TCL_OK.
1778 *
1779 * Side effects:
1780 * May delete commands.
1781 *
1782 *----------------------------------------------------------------------
1783 */
1784
1785 int
1786 Tcl_ForgetImport(
1787 Tcl_Interp *interp, /* Current interpreter. */
1788 Tcl_Namespace *namespacePtr,/* Points to the namespace from which
1789 * previously imported commands should be
1790 * removed. NULL for current namespace. */
1791 const char *pattern) /* String pattern indicating which imported
1792 * commands to remove. */
1793 {
1794 Namespace *nsPtr, *sourceNsPtr, *dummyPtr;
1795 const char *simplePattern;
1796 char *cmdName;
1797 Tcl_HashEntry *hPtr;
1798 Tcl_HashSearch search;
1799
1800 /*
1801 * If the specified namespace is NULL, use the current namespace.
1802 */
1803
1804 if (namespacePtr == NULL) {
1805 nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
1806 } else {
1807 nsPtr = (Namespace *) namespacePtr;
1808 }
1809
1810 /*
1811 * Parse the pattern into its namespace-qualification (if any) and the
1812 * simple pattern.
1813 */
1814
1815 TclGetNamespaceForQualName(interp, pattern, nsPtr, TCL_NAMESPACE_ONLY,
1816 &sourceNsPtr, &dummyPtr, &dummyPtr, &simplePattern);
1817
1818 if (sourceNsPtr == NULL) {
1819 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1820 "unknown namespace in namespace forget pattern \"%s\"",
1821 pattern));
1822 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "NAMESPACE", pattern, (char *)NULL);
1823 return TCL_ERROR;
1824 }
1825
1826 if (strcmp(pattern, simplePattern) == 0) {
1827 /*
1828 * The pattern is simple. Delete any imported commands that match it.
1829 */
1830
1831 if (TclMatchIsTrivial(simplePattern)) {
1832 hPtr = Tcl_FindHashEntry(&nsPtr->cmdTable, simplePattern);
1833 if (hPtr != NULL) {
1834 Command *cmdPtr = (Command *)Tcl_GetHashValue(hPtr);
1835
1836 if (cmdPtr && (cmdPtr->deleteProc == DeleteImportedCmd)) {
1837 Tcl_DeleteCommandFromToken(interp, (Tcl_Command) cmdPtr);
1838 }
1839 }
1840 return TCL_OK;
1841 }
1842 for (hPtr = Tcl_FirstHashEntry(&nsPtr->cmdTable, &search);
1843 (hPtr != NULL); hPtr = Tcl_NextHashEntry(&search)) {
1844 Command *cmdPtr = (Command *)Tcl_GetHashValue(hPtr);
1845
1846 if (cmdPtr->deleteProc != DeleteImportedCmd) {
1847 continue;
1848 }
1849 cmdName = (char *)Tcl_GetHashKey(&nsPtr->cmdTable, hPtr);
1850 if (Tcl_StringMatch(cmdName, simplePattern)) {
1851 Tcl_DeleteCommandFromToken(interp, (Tcl_Command) cmdPtr);
1852 }
1853 }
1854 return TCL_OK;
1855 }
1856
1857 /*
1858 * The pattern was namespace-qualified.
1859 */
1860
1861 for (hPtr = Tcl_FirstHashEntry(&nsPtr->cmdTable, &search); (hPtr != NULL);
1862 hPtr = Tcl_NextHashEntry(&search)) {
1863 Tcl_CmdInfo info;
1864 Tcl_Command token = (Tcl_Command)Tcl_GetHashValue(hPtr);
1865 Tcl_Command origin = TclGetOriginalCommand(token);
1866
1867 if (Tcl_GetCommandInfoFromToken(origin, &info) == 0) {
1868 continue; /* Not an imported command. */
1869 }
1870 if (info.namespacePtr != (Tcl_Namespace *) sourceNsPtr) {
1871 /*
1872 * Original not in namespace we're matching. Check the first link
1873 * in the import chain.
1874 */
1875
1876 Command *cmdPtr = (Command *) token;
1877 ImportedCmdData *dataPtr = (ImportedCmdData *)cmdPtr->objClientData;
1878 Tcl_Command firstToken = (Tcl_Command) dataPtr->realCmdPtr;
1879
1880 if (firstToken == origin) {
1881 continue;
1882 }
1883 Tcl_GetCommandInfoFromToken(firstToken, &info);
1884 if (info.namespacePtr != (Tcl_Namespace *) sourceNsPtr) {
1885 continue;
1886 }
1887 origin = firstToken;
1888 }
1889 if (Tcl_StringMatch(Tcl_GetCommandName(NULL, origin), simplePattern)) {
1890 Tcl_DeleteCommandFromToken(interp, token);
1891 }
1892 }
1893 return TCL_OK;
1894 }
1895
1896 /*
1897 *----------------------------------------------------------------------
1898 *
1899 * TclGetOriginalCommand --
1900 *
1901 * An imported command is created in an namespace when a "real" command
1902 * is imported from another namespace. If the specified command is an
1903 * imported command, this function returns the original command it refers
1904 * to.
1905 *
1906 * Results:
1907 * If the command was imported into a sequence of namespaces a, b,...,n
1908 * where each successive namespace just imports the command from the
1909 * previous namespace, this function returns the Tcl_Command token in the
1910 * first namespace, a. Otherwise, if the specified command is not an
1911 * imported command, the function returns NULL.
1912 *
1913 * Side effects:
1914 * None.
1915 *
1916 *----------------------------------------------------------------------
1917 */
1918
1919 Tcl_Command
1920 TclGetOriginalCommand(
1921 Tcl_Command command) /* The imported command for which the original
1922 * command should be returned. */
1923 {
1924 Command *cmdPtr = (Command *) command;
1925
1926 if (cmdPtr->deleteProc != DeleteImportedCmd) {
1927 return NULL;
1928 }
1929
1930 while (cmdPtr->deleteProc == DeleteImportedCmd) {
1931 ImportedCmdData *dataPtr = (ImportedCmdData *)cmdPtr->objClientData;
1932 cmdPtr = dataPtr->realCmdPtr;
1933 }
1934 return (Tcl_Command) cmdPtr;
1935 }
1936
1937 /*
1938 *----------------------------------------------------------------------
1939 *
1940 * InvokeImportedCmd --
1941 *
1942 * Invoked by Tcl whenever the user calls an imported command that was
1943 * created by Tcl_Import. Finds the "real" command (in another
1944 * namespace), and passes control to it.
1945 *
1946 * Results:
1947 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
1948 *
1949 * Side effects:
1950 * Returns a result in the interpreter's result object. If anything goes
1951 * wrong, the result object is set to an error message.
1952 *
1953 *----------------------------------------------------------------------
1954 */
1955
1956 static int
1957 InvokeImportedNRCmd(
1958 ClientData clientData, /* Points to the imported command's
1959 * ImportedCmdData structure. */
1960 Tcl_Interp *interp, /* Current interpreter. */
1961 int objc, /* Number of arguments. */
1962 Tcl_Obj *const objv[]) /* The argument objects. */
1963 {
1964 ImportedCmdData *dataPtr = (ImportedCmdData *)clientData;
1965 Command *realCmdPtr = dataPtr->realCmdPtr;
1966
1967 TclSkipTailcall(interp);
1968 return TclNREvalObjv(interp, objc, objv, TCL_EVAL_NOERR, realCmdPtr);
1969 }
1970
1971 static int
1972 InvokeImportedCmd(
1973 ClientData clientData, /* Points to the imported command's
1974 * ImportedCmdData structure. */
1975 Tcl_Interp *interp, /* Current interpreter. */
1976 int objc, /* Number of arguments. */
1977 Tcl_Obj *const objv[]) /* The argument objects. */
1978 {
1979 return Tcl_NRCallObjProc(interp, InvokeImportedNRCmd, clientData,
1980 objc, objv);
1981 }
1982
1983 /*
1984 *----------------------------------------------------------------------
1985 *
1986 * DeleteImportedCmd --
1987 *
1988 * Invoked by Tcl whenever an imported command is deleted. The "real"
1989 * command keeps a list of all the imported commands that refer to it, so
1990 * those imported commands can be deleted when the real command is
1991 * deleted. This function removes the imported command reference from the
1992 * real command's list, and frees up the memory associated with the
1993 * imported command.
1994 *
1995 * Results:
1996 * None.
1997 *
1998 * Side effects:
1999 * Removes the imported command from the real command's import list.
2000 *
2001 *----------------------------------------------------------------------
2002 */
2003
2004 static void
2005 DeleteImportedCmd(
2006 ClientData clientData) /* Points to the imported command's
2007 * ImportedCmdData structure. */
2008 {
2009 ImportedCmdData *dataPtr = (ImportedCmdData *)clientData;
2010 Command *realCmdPtr = dataPtr->realCmdPtr;
2011 Command *selfPtr = dataPtr->selfPtr;
2012 ImportRef *refPtr, *prevPtr;
2013
2014 prevPtr = NULL;
2015 for (refPtr = realCmdPtr->importRefPtr; refPtr != NULL;
2016 refPtr = refPtr->nextPtr) {
2017 if (refPtr->importedCmdPtr == selfPtr) {
2018 /*
2019 * Remove *refPtr from real command's list of imported commands
2020 * that refer to it.
2021 */
2022
2023 if (prevPtr == NULL) { /* refPtr is first in list. */
2024 realCmdPtr->importRefPtr = refPtr->nextPtr;
2025 } else {
2026 prevPtr->nextPtr = refPtr->nextPtr;
2027 }
2028 ckfree(refPtr);
2029 ckfree(dataPtr);
2030 return;
2031 }
2032 prevPtr = refPtr;
2033 }
2034
2035 Tcl_Panic("DeleteImportedCmd: did not find cmd in real cmd's list of import references");
2036 }
2037
2038 /*
2039 *----------------------------------------------------------------------
2040 *
2041 * TclGetNamespaceForQualName --
2042 *
2043 * Given a qualified name specifying a command, variable, or namespace,
2044 * and a namespace in which to resolve the name, this function returns a
2045 * pointer to the namespace that contains the item. A qualified name
2046 * consists of the "simple" name of an item qualified by the names of an
2047 * arbitrary number of containing namespace separated by "::"s. If the
2048 * qualified name starts with "::", it is interpreted absolutely from the
2049 * global namespace. Otherwise, it is interpreted relative to the
2050 * namespace specified by cxtNsPtr if it is non-NULL. If cxtNsPtr is
2051 * NULL, the name is interpreted relative to the current namespace.
2052 *
2053 * A relative name like "foo::bar::x" can be found starting in either the
2054 * current namespace or in the global namespace. So each search usually
2055 * follows two tracks, and two possible namespaces are returned. If the
2056 * function sets either *nsPtrPtr or *altNsPtrPtr to NULL, then that path
2057 * failed.
2058 *
2059 * If "flags" contains TCL_GLOBAL_ONLY, the relative qualified name is
2060 * sought only in the global :: namespace. The alternate search (also)
2061 * starting from the global namespace is ignored and *altNsPtrPtr is set
2062 * NULL.
2063 *
2064 * If "flags" contains TCL_NAMESPACE_ONLY, the relative qualified name is
2065 * sought only in the namespace specified by cxtNsPtr. The alternate
2066 * search starting from the global namespace is ignored and *altNsPtrPtr
2067 * is set NULL. If both TCL_GLOBAL_ONLY and TCL_NAMESPACE_ONLY are
2068 * specified, TCL_GLOBAL_ONLY is ignored and the search starts from the
2069 * namespace specified by cxtNsPtr.
2070 *
2071 * If "flags" contains TCL_CREATE_NS_IF_UNKNOWN, all namespace components
2072 * of the qualified name that cannot be found are automatically created
2073 * within their specified parent. This makes sure that functions like
2074 * Tcl_CreateObjCommand always succeed. There is no alternate search path,
2075 * so *altNsPtrPtr is set NULL.
2076 *
2077 * If "flags" contains TCL_FIND_ONLY_NS, the qualified name is treated as
2078 * a reference to a namespace, and the entire qualified name is followed.
2079 * If the name is relative, the namespace is looked up only in the
2080 * current namespace. A pointer to the namespace is stored in *nsPtrPtr
2081 * and NULL is stored in *simpleNamePtr. Otherwise, if TCL_FIND_ONLY_NS
2082 * is not specified, only the leading components are treated as namespace
2083 * names, and a pointer to the simple name of the final component is
2084 * stored in *simpleNamePtr.
2085 *
2086 * Results:
2087 * It sets *nsPtrPtr and *altNsPtrPtr to point to the two possible
2088 * namespaces which represent the last (containing) namespace in the
2089 * qualified name. If the function sets either *nsPtrPtr or *altNsPtrPtr
2090 * to NULL, then the search along that path failed. The function also
2091 * stores a pointer to the simple name of the final component in
2092 * *simpleNamePtr. If the qualified name is "::" or was treated as a
2093 * namespace reference (TCL_FIND_ONLY_NS), the function stores a pointer
2094 * to the namespace in *nsPtrPtr, NULL in *altNsPtrPtr, and sets
2095 * *simpleNamePtr to point to an empty string.
2096 *
2097 * If there is an error, this function returns TCL_ERROR. If "flags"
2098 * contains TCL_LEAVE_ERR_MSG, an error message is returned in the
2099 * interpreter's result object. Otherwise, the interpreter's result
2100 * object is left unchanged.
2101 *
2102 * *actualCxtPtrPtr is set to the actual context namespace. It is set to
2103 * the input context namespace pointer in cxtNsPtr. If cxtNsPtr is NULL,
2104 * it is set to the current namespace context.
2105 *
2106 * For backwards compatibility with the TclPro byte code loader, this
2107 * function always returns TCL_OK.
2108 *
2109 * Side effects:
2110 * If "flags" contains TCL_CREATE_NS_IF_UNKNOWN, new namespaces may be
2111 * created.
2112 *
2113 *----------------------------------------------------------------------
2114 */
2115
2116 int
2117 TclGetNamespaceForQualName(
2118 Tcl_Interp *interp, /* Interpreter in which to find the namespace
2119 * containing qualName. */
2120 const char *qualName, /* A namespace-qualified name of an command,
2121 * variable, or namespace. */
2122 Namespace *cxtNsPtr, /* The namespace in which to start the search
2123 * for qualName's namespace. If NULL start
2124 * from the current namespace. Ignored if
2125 * TCL_GLOBAL_ONLY is set. */
2126 int flags, /* Flags controlling the search: an OR'd
2127 * combination of TCL_GLOBAL_ONLY,
2128 * TCL_NAMESPACE_ONLY, TCL_FIND_ONLY_NS, and
2129 * TCL_CREATE_NS_IF_UNKNOWN. */
2130 Namespace **nsPtrPtr, /* Address where function stores a pointer to
2131 * containing namespace if qualName is found
2132 * starting from *cxtNsPtr or, if
2133 * TCL_GLOBAL_ONLY is set, if qualName is
2134 * found in the global :: namespace. NULL is
2135 * stored otherwise. */
2136 Namespace **altNsPtrPtr, /* Address where function stores a pointer to
2137 * containing namespace if qualName is found
2138 * starting from the global :: namespace.
2139 * NULL is stored if qualName isn't found
2140 * starting from :: or if the TCL_GLOBAL_ONLY,
2141 * TCL_NAMESPACE_ONLY, TCL_FIND_ONLY_NS,
2142 * TCL_CREATE_NS_IF_UNKNOWN flag is set. */
2143 Namespace **actualCxtPtrPtr,/* Address where function stores a pointer to
2144 * the actual namespace from which the search
2145 * started. This is either cxtNsPtr, the ::
2146 * namespace if TCL_GLOBAL_ONLY was specified,
2147 * or the current namespace if cxtNsPtr was
2148 * NULL. */
2149 const char **simpleNamePtr) /* Address where function stores the simple
2150 * name at end of the qualName, or NULL if
2151 * qualName is "::" or the flag
2152 * TCL_FIND_ONLY_NS was specified. */
2153 {
2154 Interp *iPtr = (Interp *) interp;
2155 Namespace *nsPtr = cxtNsPtr, *lastNsPtr = NULL, *lastAltNsPtr = NULL;
2156 Namespace *altNsPtr;
2157 Namespace *globalNsPtr = iPtr->globalNsPtr;
2158 const char *start, *end;
2159 const char *nsName;
2160 Tcl_HashEntry *entryPtr;
2161 Tcl_DString buffer;
2162 int len;
2163
2164 /*
2165 * Determine the context namespace nsPtr in which to start the primary
2166 * search. If the qualName name starts with a "::" or TCL_GLOBAL_ONLY was
2167 * specified, search from the global namespace. Otherwise, use the
2168 * namespace given in cxtNsPtr, or if that is NULL, use the current
2169 * namespace context. Note that we always treat two or more adjacent ":"s
2170 * as a namespace separator.
2171 */
2172
2173 if (flags & TCL_GLOBAL_ONLY) {
2174 nsPtr = globalNsPtr;
2175 } else if (nsPtr == NULL) {
2176 nsPtr = iPtr->varFramePtr->nsPtr;
2177 }
2178
2179 start = qualName; /* Points to start of qualifying
2180 * namespace. */
2181 if ((qualName[0] == ':') && (qualName[1] == ':')) {
2182 start = qualName + 2; /* Skip over the initial :: */
2183 while (start[0] == ':') {
2184 start++; /* Skip over a subsequent : */
2185 }
2186 nsPtr = globalNsPtr;
2187 if (start[0] == '\0') { /* qualName is just two or more
2188 * ":"s. */
2189 *nsPtrPtr = globalNsPtr;
2190 *altNsPtrPtr = NULL;
2191 *actualCxtPtrPtr = globalNsPtr;
2192 *simpleNamePtr = start; /* Points to empty string. */
2193 return TCL_OK;
2194 }
2195 }
2196 *actualCxtPtrPtr = nsPtr;
2197
2198 /*
2199 * Start an alternate search path starting with the global namespace.
2200 * However, if the starting context is the global namespace, or if the
2201 * flag is set to search only the namespace *cxtNsPtr, ignore the
2202 * alternate search path.
2203 */
2204
2205 altNsPtr = globalNsPtr;
2206 if ((nsPtr == globalNsPtr)
2207 || (flags & (TCL_NAMESPACE_ONLY | TCL_FIND_ONLY_NS))) {
2208 altNsPtr = NULL;
2209 }
2210
2211 /*
2212 * Loop to resolve each namespace qualifier in qualName.
2213 */
2214
2215 Tcl_DStringInit(&buffer);
2216 end = start;
2217 while (*start != '\0') {
2218 /*
2219 * Find the next namespace qualifier (i.e., a name ending in "::") or
2220 * the end of the qualified name (i.e., a name ending in "\0"). Set
2221 * len to the number of characters, starting from start, in the name;
2222 * set end to point after the "::"s or at the "\0".
2223 */
2224
2225 len = 0;
2226 for (end = start; *end != '\0'; end++) {
2227 if ((end[0] == ':') && (end[1] == ':')) {
2228 end += 2; /* Skip over the initial :: */
2229 while (*end == ':') {
2230 end++; /* Skip over the subsequent : */
2231 }
2232 break; /* Exit for loop; end is after ::'s */
2233 }
2234 len++;
2235 }
2236
2237 if (end[0]=='\0' && !(end-start>=2 && end[-1]==':' && end[-2]==':')) {
2238 /*
2239 * qualName ended with a simple name at start. If TCL_FIND_ONLY_NS
2240 * was specified, look this up as a namespace. Otherwise, start is
2241 * the name of a cmd or var and we are done.
2242 */
2243
2244 if (flags & TCL_FIND_ONLY_NS) {
2245 nsName = start;
2246 } else {
2247 *simpleNamePtr = start;
2248 goto done;
2249 }
2250 } else {
2251 /*
2252 * start points to the beginning of a namespace qualifier ending
2253 * in "::". end points to the start of a name in that namespace
2254 * that might be empty. Copy the namespace qualifier to a buffer
2255 * so it can be null terminated. We can't modify the incoming
2256 * qualName since it may be a string constant.
2257 */
2258
2259 TclDStringClear(&buffer);
2260 Tcl_DStringAppend(&buffer, start, len);
2261 nsName = Tcl_DStringValue(&buffer);
2262 }
2263
2264 /*
2265 * Look up the namespace qualifier nsName in the current namespace
2266 * context. If it isn't found but TCL_CREATE_NS_IF_UNKNOWN is set,
2267 * create that qualifying namespace. This is needed for functions like
2268 * Tcl_CreateObjCommand that cannot fail.
2269 */
2270
2271 if (nsPtr != NULL) {
2272 entryPtr = Tcl_FindHashEntry(&nsPtr->childTable, nsName);
2273 if (entryPtr != NULL) {
2274 nsPtr = (Namespace *)Tcl_GetHashValue(entryPtr);
2275 } else if (flags & TCL_CREATE_NS_IF_UNKNOWN) {
2276 Tcl_CallFrame *framePtr;
2277
2278 (void) TclPushStackFrame(interp, &framePtr,
2279 (Tcl_Namespace *) nsPtr, /*isProcCallFrame*/ 0);
2280
2281 nsPtr = (Namespace *)
2282 Tcl_CreateNamespace(interp, nsName, NULL, NULL);
2283 TclPopStackFrame(interp);
2284
2285 if (nsPtr == NULL) {
2286 Tcl_Panic("Could not create namespace '%s'", nsName);
2287 }
2288 } else {
2289 /*
2290 * Namespace not found and was not created.
2291 * Remember last found namespace for TCL_FIND_IF_NOT_SIMPLE.
2292 */
2293 lastNsPtr = nsPtr;
2294 nsPtr = NULL;
2295 }
2296 }
2297
2298 /*
2299 * Look up the namespace qualifier in the alternate search path too.
2300 */
2301
2302 if (altNsPtr != NULL) {
2303 entryPtr = Tcl_FindHashEntry(&altNsPtr->childTable, nsName);
2304 if (entryPtr != NULL) {
2305 altNsPtr = (Namespace *)Tcl_GetHashValue(entryPtr);
2306 } else {
2307 /* Remember last found in alternate path */
2308 lastAltNsPtr = altNsPtr;
2309 altNsPtr = NULL;
2310 }
2311 }
2312
2313 /*
2314 * If both search paths have failed, return NULL results.
2315 */
2316
2317 if ((nsPtr == NULL) && (altNsPtr == NULL)) {
2318 if (flags & TCL_FIND_IF_NOT_SIMPLE) {
2319 /*
2320 * return last found NS, regardless simple name or not,
2321 * e. g. ::A::B::C::D -> ::A::B and C::D, if namespace C
2322 * cannot be found in ::A::B
2323 */
2324 nsPtr = lastNsPtr;
2325 altNsPtr = lastAltNsPtr;
2326 *simpleNamePtr = start;
2327 goto done;
2328 }
2329 *simpleNamePtr = NULL;
2330 goto done;
2331 }
2332
2333 start = end;
2334 }
2335
2336 /*
2337 * We ignore trailing "::"s in a namespace name, but in a command or
2338 * variable name, trailing "::"s refer to the cmd or var named {}.
2339 */
2340
2341 if ((flags & TCL_FIND_ONLY_NS) || (end>start && end[-1]!=':')) {
2342 *simpleNamePtr = NULL; /* Found namespace name. */
2343 } else {
2344 *simpleNamePtr = end; /* Found cmd/var: points to empty
2345 * string. */
2346 }
2347
2348 /*
2349 * As a special case, if we are looking for a namespace and qualName is ""
2350 * and the current active namespace (nsPtr) is not the global namespace,
2351 * return NULL (no namespace was found). This is because namespaces can
2352 * not have empty names except for the global namespace.
2353 */
2354
2355 if ((flags & TCL_FIND_ONLY_NS) && (*qualName == '\0')
2356 && (nsPtr != globalNsPtr)) {
2357 nsPtr = NULL;
2358 }
2359
2360 done:
2361 *nsPtrPtr = nsPtr;
2362 *altNsPtrPtr = altNsPtr;
2363 Tcl_DStringFree(&buffer);
2364 return TCL_OK;
2365 }
2366
2367 /*
2368 *----------------------------------------------------------------------
2369 *
2370 * TclEnsureNamespace --
2371 *
2372 * Provide a namespace that is not deleted.
2373 *
2374 * Value
2375 *
2376 * namespacePtr, if it is not scheduled for deletion, or a pointer to a
2377 * new namespace with the same name otherwise.
2378 *
2379 * Effect
2380 * None.
2381 *
2382 *----------------------------------------------------------------------
2383 */
2384 Tcl_Namespace *
2385 TclEnsureNamespace(
2386 Tcl_Interp *interp,
2387 Tcl_Namespace *namespacePtr)
2388 {
2389 Namespace *nsPtr = (Namespace *) namespacePtr;
2390
2391 if (!(nsPtr->flags & NS_DYING)) {
2392 return namespacePtr;
2393 }
2394 /*
2395 * If a new namespace with the same name has been created already,
2396 * return that. Otherwise, create a new one. Bug 24d7f1a695.
2397 */
2398 namespacePtr = Tcl_FindNamespace(interp, nsPtr->fullName, NULL, 0);
2399 if (namespacePtr != NULL) {
2400 return namespacePtr;
2401 }
2402 return Tcl_CreateNamespace(interp, nsPtr->fullName, NULL, NULL);
2403 }
2404
2405 /*
2406 *----------------------------------------------------------------------
2407 *
2408 * Tcl_FindNamespace --
2409 *
2410 * Searches for a namespace.
2411 *
2412 * Results:
2413 * Returns a pointer to the namespace if it is found. Otherwise, returns
2414 * NULL and leaves an error message in the interpreter's result object if
2415 * "flags" contains TCL_LEAVE_ERR_MSG.
2416 *
2417 * Side effects:
2418 * None.
2419 *
2420 *----------------------------------------------------------------------
2421 */
2422
2423 Tcl_Namespace *
2424 Tcl_FindNamespace(
2425 Tcl_Interp *interp, /* The interpreter in which to find the
2426 * namespace. */
2427 const char *name, /* Namespace name. If it starts with "::",
2428 * will be looked up in global namespace.
2429 * Else, looked up first in contextNsPtr
2430 * (current namespace if contextNsPtr is
2431 * NULL), then in global namespace. */
2432 Tcl_Namespace *contextNsPtr,/* Ignored if TCL_GLOBAL_ONLY flag is set or
2433 * if the name starts with "::". Otherwise,
2434 * points to namespace in which to resolve
2435 * name; if NULL, look up name in the current
2436 * namespace. */
2437 int flags) /* Flags controlling namespace lookup: an OR'd
2438 * combination of TCL_GLOBAL_ONLY and
2439 * TCL_LEAVE_ERR_MSG flags. */
2440 {
2441 Namespace *nsPtr, *dummy1Ptr, *dummy2Ptr;
2442 const char *dummy;
2443
2444 /*
2445 * Find the namespace(s) that contain the specified namespace name. Add
2446 * the TCL_FIND_ONLY_NS flag to resolve the name all the way down to its
2447 * last component, a namespace.
2448 */
2449
2450 TclGetNamespaceForQualName(interp, name, (Namespace *) contextNsPtr,
2451 flags|TCL_FIND_ONLY_NS, &nsPtr, &dummy1Ptr, &dummy2Ptr, &dummy);
2452
2453 if (nsPtr != NULL) {
2454 return (Tcl_Namespace *) nsPtr;
2455 }
2456
2457 if (flags & TCL_LEAVE_ERR_MSG) {
2458 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2459 "unknown namespace \"%s\"", name));
2460 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "NAMESPACE", name, (char *)NULL);
2461 }
2462 return NULL;
2463 }
2464
2465 /*
2466 *----------------------------------------------------------------------
2467 *
2468 * Tcl_FindCommand --
2469 *
2470 * Searches for a command.
2471 *
2472 * Results:
2473 * Returns a token for the command if it is found. Otherwise, if it can't
2474 * be found or there is an error, returns NULL and leaves an error
2475 * message in the interpreter's result object if "flags" contains
2476 * TCL_LEAVE_ERR_MSG.
2477 *
2478 * Side effects:
2479 * None.
2480 *
2481 *----------------------------------------------------------------------
2482 */
2483
2484 Tcl_Command
2485 Tcl_FindCommand(
2486 Tcl_Interp *interp, /* The interpreter in which to find the
2487 * command and to report errors. */
2488 const char *name, /* Command's name. If it starts with "::",
2489 * will be looked up in global namespace.
2490 * Else, looked up first in contextNsPtr
2491 * (current namespace if contextNsPtr is
2492 * NULL), then in global namespace. */
2493 Tcl_Namespace *contextNsPtr,/* Ignored if TCL_GLOBAL_ONLY flag set.
2494 * Otherwise, points to namespace in which to
2495 * resolve name. If NULL, look up name in the
2496 * current namespace. */
2497 int flags) /* An OR'd combination of flags:
2498 * TCL_GLOBAL_ONLY (look up name only in
2499 * global namespace), TCL_NAMESPACE_ONLY (look
2500 * up only in contextNsPtr, or the current
2501 * namespace if contextNsPtr is NULL), and
2502 * TCL_LEAVE_ERR_MSG. If both TCL_GLOBAL_ONLY
2503 * and TCL_NAMESPACE_ONLY are given,
2504 * TCL_GLOBAL_ONLY is ignored. */
2505 {
2506 Interp *iPtr = (Interp *) interp;
2507 Namespace *cxtNsPtr;
2508 Tcl_HashEntry *entryPtr;
2509 Command *cmdPtr;
2510 const char *simpleName;
2511 int result;
2512
2513 /*
2514 * If this namespace has a command resolver, then give it first crack at
2515 * the command resolution. If the interpreter has any command resolvers,
2516 * consult them next. The command resolver functions may return a
2517 * Tcl_Command value, they may signal to continue onward, or they may
2518 * signal an error.
2519 */
2520
2521 if ((flags & TCL_GLOBAL_ONLY) || !strncmp(name, "::", 2)) {
2522 cxtNsPtr = (Namespace *) TclGetGlobalNamespace(interp);
2523 } else if (contextNsPtr != NULL) {
2524 cxtNsPtr = (Namespace *) contextNsPtr;
2525 } else {
2526 cxtNsPtr = (Namespace *) TclGetCurrentNamespace(interp);
2527 }
2528
2529 if (cxtNsPtr->cmdResProc != NULL || iPtr->resolverPtr != NULL) {
2530 ResolverScheme *resPtr = iPtr->resolverPtr;
2531 Tcl_Command cmd;
2532
2533 if (cxtNsPtr->cmdResProc) {
2534 result = cxtNsPtr->cmdResProc(interp, name,
2535 (Tcl_Namespace *) cxtNsPtr, flags, &cmd);
2536 } else {
2537 result = TCL_CONTINUE;
2538 }
2539
2540 while (result == TCL_CONTINUE && resPtr) {
2541 if (resPtr->cmdResProc) {
2542 result = resPtr->cmdResProc(interp, name,
2543 (Tcl_Namespace *) cxtNsPtr, flags, &cmd);
2544 }
2545 resPtr = resPtr->nextPtr;
2546 }
2547
2548 if (result == TCL_OK) {
2549 ((Command *)cmd)->flags |= CMD_VIA_RESOLVER;
2550 return cmd;
2551
2552 } else if (result != TCL_CONTINUE) {
2553 return NULL;
2554 }
2555 }
2556
2557 /*
2558 * Find the namespace(s) that contain the command.
2559 */
2560
2561 cmdPtr = NULL;
2562 if (cxtNsPtr->commandPathLength!=0 && strncmp(name, "::", 2)
2563 && !(flags & TCL_NAMESPACE_ONLY)) {
2564 int i;
2565 Namespace *pathNsPtr, *realNsPtr, *dummyNsPtr;
2566
2567 (void) TclGetNamespaceForQualName(interp, name, cxtNsPtr,
2568 TCL_NAMESPACE_ONLY, &realNsPtr, &dummyNsPtr, &dummyNsPtr,
2569 &simpleName);
2570 if ((realNsPtr != NULL) && (simpleName != NULL)) {
2571 if ((cxtNsPtr == realNsPtr)
2572 || !(realNsPtr->flags & NS_DYING)) {
2573 entryPtr = Tcl_FindHashEntry(&realNsPtr->cmdTable, simpleName);
2574 if (entryPtr != NULL) {
2575 cmdPtr = (Command *)Tcl_GetHashValue(entryPtr);
2576 }
2577 }
2578 }
2579
2580 /*
2581 * Next, check along the path.
2582 */
2583
2584 for (i=0 ; (cmdPtr == NULL) && i<cxtNsPtr->commandPathLength ; i++) {
2585 pathNsPtr = cxtNsPtr->commandPathArray[i].nsPtr;
2586 if (pathNsPtr == NULL) {
2587 continue;
2588 }
2589 (void) TclGetNamespaceForQualName(interp, name, pathNsPtr,
2590 TCL_NAMESPACE_ONLY, &realNsPtr, &dummyNsPtr, &dummyNsPtr,
2591 &simpleName);
2592 if ((realNsPtr != NULL) && (simpleName != NULL)
2593 && !(realNsPtr->flags & NS_DYING)) {
2594 entryPtr = Tcl_FindHashEntry(&realNsPtr->cmdTable, simpleName);
2595 if (entryPtr != NULL) {
2596 cmdPtr = (Command *)Tcl_GetHashValue(entryPtr);
2597 }
2598 }
2599 }
2600
2601 /*
2602 * If we've still not found the command, look in the global namespace
2603 * as a last resort.
2604 */
2605
2606 if (cmdPtr == NULL) {
2607 (void) TclGetNamespaceForQualName(interp, name, NULL,
2608 TCL_GLOBAL_ONLY, &realNsPtr, &dummyNsPtr, &dummyNsPtr,
2609 &simpleName);
2610 if ((realNsPtr != NULL) && (simpleName != NULL)
2611 && !(realNsPtr->flags & NS_DYING)) {
2612 entryPtr = Tcl_FindHashEntry(&realNsPtr->cmdTable, simpleName);
2613 if (entryPtr != NULL) {
2614 cmdPtr = (Command *)Tcl_GetHashValue(entryPtr);
2615 }
2616 }
2617 }
2618 } else {
2619 Namespace *nsPtr[2];
2620 int search;
2621
2622 TclGetNamespaceForQualName(interp, name, cxtNsPtr,
2623 flags, &nsPtr[0], &nsPtr[1], &cxtNsPtr, &simpleName);
2624
2625 /*
2626 * Look for the command in the command table of its namespace. Be sure
2627 * to check both possible search paths: from the specified namespace
2628 * context and from the global namespace.
2629 */
2630
2631 for (search = 0; (search < 2) && (cmdPtr == NULL); search++) {
2632 if ((nsPtr[search] != NULL) && (simpleName != NULL)) {
2633 entryPtr = Tcl_FindHashEntry(&nsPtr[search]->cmdTable,
2634 simpleName);
2635 if (entryPtr != NULL) {
2636 cmdPtr = (Command *)Tcl_GetHashValue(entryPtr);
2637 }
2638 }
2639 }
2640 }
2641
2642 if (cmdPtr != NULL) {
2643 cmdPtr->flags &= ~CMD_VIA_RESOLVER;
2644 return (Tcl_Command) cmdPtr;
2645 }
2646
2647 if (flags & TCL_LEAVE_ERR_MSG) {
2648 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2649 "unknown command \"%s\"", name));
2650 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "COMMAND", name, (char *)NULL);
2651 }
2652 return NULL;
2653 }
2654
2655 /*
2656 *----------------------------------------------------------------------
2657 *
2658 * TclResetShadowedCmdRefs --
2659 *
2660 * Called when a command is added to a namespace to check for existing
2661 * command references that the new command may invalidate. Consider the
2662 * following cases that could happen when you add a command "foo" to a
2663 * namespace "b":
2664 * 1. It could shadow a command named "foo" at the global scope. If
2665 * it does, all command references in the namespace "b" are
2666 * suspect.
2667 * 2. Suppose the namespace "b" resides in a namespace "a". Then to
2668 * "a" the new command "b::foo" could shadow another command
2669 * "b::foo" in the global namespace. If so, then all command
2670 * references in "a" * are suspect.
2671 * The same checks are applied to all parent namespaces, until we reach
2672 * the global :: namespace.
2673 *
2674 * Results:
2675 * None.
2676 *
2677 * Side effects:
2678 * If the new command shadows an existing command, the cmdRefEpoch
2679 * counter is incremented in each namespace that sees the shadow. This
2680 * invalidates all command references that were previously cached in that
2681 * namespace. The next time the commands are used, they are resolved from
2682 * scratch.
2683 *
2684 *----------------------------------------------------------------------
2685 */
2686
2687 void
2688 TclResetShadowedCmdRefs(
2689 Tcl_Interp *interp, /* Interpreter containing the new command. */
2690 Command *newCmdPtr) /* Points to the new command. */
2691 {
2692 char *cmdName;
2693 Tcl_HashEntry *hPtr;
2694 Namespace *nsPtr;
2695 Namespace *trailNsPtr, *shadowNsPtr;
2696 Namespace *globalNsPtr = (Namespace *) TclGetGlobalNamespace(interp);
2697 int found, i;
2698 int trailFront = -1;
2699 int trailSize = 5; /* Formerly NUM_TRAIL_ELEMS. */
2700 Namespace **trailPtr = (Namespace **)TclStackAlloc(interp,
2701 trailSize * sizeof(Namespace *));
2702
2703 /*
2704 * Start at the namespace containing the new command, and work up through
2705 * the list of parents. Stop just before the global namespace, since the
2706 * global namespace can't "shadow" its own entries.
2707 *
2708 * The namespace "trail" list we build consists of the names of each
2709 * namespace that encloses the new command, in order from outermost to
2710 * innermost: for example, "a" then "b". Each iteration of this loop
2711 * eventually extends the trail upwards by one namespace, nsPtr. We use
2712 * this trail list to see if nsPtr (e.g. "a" in 2. above) could have
2713 * now-invalid cached command references. This will happen if nsPtr
2714 * (e.g. "a") contains a sequence of child namespaces (e.g. "b") such that
2715 * there is a identically-named sequence of child namespaces starting from
2716 * :: (e.g. "::b") whose tail namespace contains a command also named
2717 * cmdName.
2718 */
2719
2720 cmdName = (char *)Tcl_GetHashKey(newCmdPtr->hPtr->tablePtr, newCmdPtr->hPtr);
2721 for (nsPtr=newCmdPtr->nsPtr ; (nsPtr!=NULL) && (nsPtr!=globalNsPtr) ;
2722 nsPtr=nsPtr->parentPtr) {
2723 /*
2724 * Find the maximal sequence of child namespaces contained in nsPtr
2725 * such that there is a identically-named sequence of child namespaces
2726 * starting from ::. shadowNsPtr will be the tail of this sequence, or
2727 * the deepest namespace under :: that might contain a command now
2728 * shadowed by cmdName. We check below if shadowNsPtr actually
2729 * contains a command cmdName.
2730 */
2731
2732 found = 1;
2733 shadowNsPtr = globalNsPtr;
2734
2735 for (i = trailFront; i >= 0; i--) {
2736 trailNsPtr = trailPtr[i];
2737 hPtr = Tcl_FindHashEntry(&shadowNsPtr->childTable,
2738 trailNsPtr->name);
2739 if (hPtr != NULL) {
2740 shadowNsPtr = (Namespace *)Tcl_GetHashValue(hPtr);
2741 } else {
2742 found = 0;
2743 break;
2744 }
2745 }
2746
2747 /*
2748 * If shadowNsPtr contains a command named cmdName, we invalidate all
2749 * of the command refs cached in nsPtr. As a boundary case,
2750 * shadowNsPtr is initially :: and we check for case 1. above.
2751 */
2752
2753 if (found) {
2754 hPtr = Tcl_FindHashEntry(&shadowNsPtr->cmdTable, cmdName);
2755 if (hPtr != NULL) {
2756 nsPtr->cmdRefEpoch++;
2757 TclInvalidateNsPath(nsPtr);
2758
2759 /*
2760 * If the shadowed command was compiled to bytecodes, we
2761 * invalidate all the bytecodes in nsPtr, to force a new
2762 * compilation. We use the resolverEpoch to signal the need
2763 * for a fresh compilation of every bytecode.
2764 */
2765
2766 if (((Command *)Tcl_GetHashValue(hPtr))->compileProc != NULL){
2767 nsPtr->resolverEpoch++;
2768 }
2769 }
2770 }
2771
2772 /*
2773 * Insert nsPtr at the front of the trail list: i.e., at the end of
2774 * the trailPtr array.
2775 */
2776
2777 trailFront++;
2778 if (trailFront == trailSize) {
2779 int newSize = 2 * trailSize;
2780
2781 trailPtr = (Namespace **)TclStackRealloc(interp, trailPtr,
2782 newSize * sizeof(Namespace *));
2783 trailSize = newSize;
2784 }
2785 trailPtr[trailFront] = nsPtr;
2786 }
2787 TclStackFree(interp, trailPtr);
2788 }
2789
2790 /*
2791 *----------------------------------------------------------------------
2792 *
2793 * TclGetNamespaceFromObj, GetNamespaceFromObj --
2794 *
2795 * Gets the namespace specified by the name in a Tcl_Obj.
2796 *
2797 * Results:
2798 * Returns TCL_OK if the namespace was resolved successfully, and stores
2799 * a pointer to the namespace in the location specified by nsPtrPtr. If
2800 * the namespace can't be found, or anything else goes wrong, this
2801 * function returns TCL_ERROR and writes an error message to interp,
2802 * if non-NULL.
2803 *
2804 * Side effects:
2805 * May update the internal representation for the object, caching the
2806 * namespace reference. The next time this function is called, the
2807 * namespace value can be found quickly.
2808 *
2809 *----------------------------------------------------------------------
2810 */
2811
2812 int
2813 TclGetNamespaceFromObj(
2814 Tcl_Interp *interp, /* The current interpreter. */
2815 Tcl_Obj *objPtr, /* The object to be resolved as the name of a
2816 * namespace. */
2817 Tcl_Namespace **nsPtrPtr) /* Result namespace pointer goes here. */
2818 {
2819 if (GetNamespaceFromObj(interp, objPtr, nsPtrPtr) == TCL_ERROR) {
2820 const char *name = TclGetString(objPtr);
2821
2822 if ((name[0] == ':') && (name[1] == ':')) {
2823 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2824 "namespace \"%s\" not found", name));
2825 } else {
2826 /*
2827 * Get the current namespace name.
2828 */
2829
2830 NamespaceCurrentCmd(NULL, interp, 1, NULL);
2831 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2832 "namespace \"%s\" not found in \"%s\"", name,
2833 Tcl_GetStringResult(interp)));
2834 }
2835 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "NAMESPACE", name, (char *)NULL);
2836 return TCL_ERROR;
2837 }
2838 return TCL_OK;
2839 }
2840
2841 static int
2842 GetNamespaceFromObj(
2843 Tcl_Interp *interp, /* The current interpreter. */
2844 Tcl_Obj *objPtr, /* The object to be resolved as the name of a
2845 * namespace. */
2846 Tcl_Namespace **nsPtrPtr) /* Result namespace pointer goes here. */
2847 {
2848 ResolvedNsName *resNamePtr;
2849 Namespace *nsPtr, *refNsPtr;
2850
2851 if (objPtr->typePtr == &nsNameType) {
2852 /*
2853 * Check that the ResolvedNsName is still valid; avoid letting the ref
2854 * cross interps.
2855 */
2856
2857 resNamePtr = (ResolvedNsName *)objPtr->internalRep.twoPtrValue.ptr1;
2858 nsPtr = resNamePtr->nsPtr;
2859 refNsPtr = resNamePtr->refNsPtr;
2860 if (!(nsPtr->flags & NS_DYING) && (interp == nsPtr->interp)
2861 && (!refNsPtr || ((interp == refNsPtr->interp) &&
2862 (refNsPtr == (Namespace *)Tcl_GetCurrentNamespace(interp))))){
2863 *nsPtrPtr = (Tcl_Namespace *)nsPtr;
2864 return TCL_OK;
2865 }
2866 }
2867 if (SetNsNameFromAny(interp, objPtr) == TCL_OK) {
2868 resNamePtr = (ResolvedNsName *)objPtr->internalRep.twoPtrValue.ptr1;
2869 *nsPtrPtr = (Tcl_Namespace *)resNamePtr->nsPtr;
2870 return TCL_OK;
2871 }
2872 return TCL_ERROR;
2873 }
2874
2875 /*
2876 *----------------------------------------------------------------------
2877 *
2878 * TclInitNamespaceCmd --
2879 *
2880 * This function is called to create the "namespace" Tcl command. See the
2881 * user documentation for details on what it does.
2882 *
2883 * Results:
2884 * Handle for the namespace command, or NULL on failure.
2885 *
2886 * Side effects:
2887 * none
2888 *
2889 *----------------------------------------------------------------------
2890 */
2891
2892 Tcl_Command
2893 TclInitNamespaceCmd(
2894 Tcl_Interp *interp) /* Current interpreter. */
2895 {
2896 return TclMakeEnsemble(interp, "namespace", defaultNamespaceMap);
2897 }
2898
2899 /*
2900 *----------------------------------------------------------------------
2901 *
2902 * NamespaceChildrenCmd --
2903 *
2904 * Invoked to implement the "namespace children" command that returns a
2905 * list containing the fully-qualified names of the child namespaces of a
2906 * given namespace. Handles the following syntax:
2907 *
2908 * namespace children ?name? ?pattern?
2909 *
2910 * Results:
2911 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
2912 *
2913 * Side effects:
2914 * Returns a result in the interpreter's result object. If anything goes
2915 * wrong, the result is an error message.
2916 *
2917 *----------------------------------------------------------------------
2918 */
2919
2920 static int
2921 NamespaceChildrenCmd(
2922 ClientData dummy, /* Not used. */
2923 Tcl_Interp *interp, /* Current interpreter. */
2924 int objc, /* Number of arguments. */
2925 Tcl_Obj *const objv[]) /* Argument objects. */
2926 {
2927 Tcl_Namespace *namespacePtr;
2928 Namespace *nsPtr, *childNsPtr;
2929 Namespace *globalNsPtr = (Namespace *) TclGetGlobalNamespace(interp);
2930 const char *pattern = NULL;
2931 Tcl_DString buffer;
2932 Tcl_HashEntry *entryPtr;
2933 Tcl_HashSearch search;
2934 Tcl_Obj *listPtr, *elemPtr;
2935
2936 /*
2937 * Get a pointer to the specified namespace, or the current namespace.
2938 */
2939
2940 if (objc == 1) {
2941 nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
2942 } else if ((objc == 2) || (objc == 3)) {
2943 if (TclGetNamespaceFromObj(interp, objv[1], &namespacePtr) != TCL_OK) {
2944 return TCL_ERROR;
2945 }
2946 nsPtr = (Namespace *) namespacePtr;
2947 } else {
2948 Tcl_WrongNumArgs(interp, 1, objv, "?name? ?pattern?");
2949 return TCL_ERROR;
2950 }
2951
2952 /*
2953 * Get the glob-style pattern, if any, used to narrow the search.
2954 */
2955
2956 Tcl_DStringInit(&buffer);
2957 if (objc == 3) {
2958 const char *name = TclGetString(objv[2]);
2959
2960 if ((name[0] == ':') && (name[1] == ':')) {
2961 pattern = name;
2962 } else {
2963 Tcl_DStringAppend(&buffer, nsPtr->fullName, -1);
2964 if (nsPtr != globalNsPtr) {
2965 TclDStringAppendLiteral(&buffer, "::");
2966 }
2967 Tcl_DStringAppend(&buffer, name, -1);
2968 pattern = Tcl_DStringValue(&buffer);
2969 }
2970 }
2971
2972 /*
2973 * Create a list containing the full names of all child namespaces whose
2974 * names match the specified pattern, if any.
2975 */
2976
2977 listPtr = Tcl_NewListObj(0, NULL);
2978 if ((pattern != NULL) && TclMatchIsTrivial(pattern)) {
2979 size_t length = strlen(nsPtr->fullName);
2980
2981 if (strncmp(pattern, nsPtr->fullName, length) != 0) {
2982 goto searchDone;
2983 }
2984 /*
2985 * Global namespace members are prefixed with "::", others not. Ticket [63449c0514]
2986 */
2987 if (
2988 Tcl_FindHashEntry(&nsPtr->childTable, (nsPtr != globalNsPtr ? 2 : 0) + pattern+length) != NULL
2989 ) {
2990 Tcl_ListObjAppendElement(interp, listPtr,
2991 Tcl_NewStringObj(pattern, -1));
2992 }
2993 goto searchDone;
2994 }
2995 entryPtr = Tcl_FirstHashEntry(&nsPtr->childTable, &search);
2996 while (entryPtr != NULL) {
2997 childNsPtr = (Namespace *)Tcl_GetHashValue(entryPtr);
2998 if ((pattern == NULL)
2999 || Tcl_StringMatch(childNsPtr->fullName, pattern)) {
3000 elemPtr = Tcl_NewStringObj(childNsPtr->fullName, -1);
3001 Tcl_ListObjAppendElement(interp, listPtr, elemPtr);
3002 }
3003 entryPtr = Tcl_NextHashEntry(&search);
3004 }
3005
3006 searchDone:
3007 Tcl_SetObjResult(interp, listPtr);
3008 Tcl_DStringFree(&buffer);
3009 return TCL_OK;
3010 }
3011
3012 /*
3013 *----------------------------------------------------------------------
3014 *
3015 * NamespaceCodeCmd --
3016 *
3017 * Invoked to implement the "namespace code" command to capture the
3018 * namespace context of a command. Handles the following syntax:
3019 *
3020 * namespace code arg
3021 *
3022 * Here "arg" can be a list. "namespace code arg" produces a result
3023 * equivalent to that produced by the command
3024 *
3025 * list ::namespace inscope [namespace current] $arg
3026 *
3027 * However, if "arg" is itself a scoped value starting with "::namespace
3028 * inscope", then the result is just "arg".
3029 *
3030 * Results:
3031 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3032 *
3033 * Side effects:
3034 * If anything goes wrong, this function returns an error message as the
3035 * result in the interpreter's result object.
3036 *
3037 *----------------------------------------------------------------------
3038 */
3039
3040 static int
3041 NamespaceCodeCmd(
3042 ClientData dummy, /* Not used. */
3043 Tcl_Interp *interp, /* Current interpreter. */
3044 int objc, /* Number of arguments. */
3045 Tcl_Obj *const objv[]) /* Argument objects. */
3046 {
3047 Namespace *currNsPtr;
3048 Tcl_Obj *listPtr, *objPtr;
3049 const char *arg;
3050 int length;
3051
3052 if (objc != 2) {
3053 Tcl_WrongNumArgs(interp, 1, objv, "arg");
3054 return TCL_ERROR;
3055 }
3056
3057 /*
3058 * If "arg" is already a scoped value, then return it directly.
3059 * Take care to only check for scoping in precisely the style that
3060 * [::namespace code] generates it. Anything more forgiving can have
3061 * the effect of failing in namespaces that contain their own custom
3062 " "namespace" command. [Bug 3202171].
3063 */
3064
3065 arg = TclGetStringFromObj(objv[1], &length);
3066 if (*arg==':' && length > 20
3067 && strncmp(arg, "::namespace inscope ", 20) == 0) {
3068 Tcl_SetObjResult(interp, objv[1]);
3069 return TCL_OK;
3070 }
3071
3072 /*
3073 * Otherwise, construct a scoped command by building a list with
3074 * "namespace inscope", the full name of the current namespace, and the
3075 * argument "arg". By constructing a list, we ensure that scoped commands
3076 * are interpreted properly when they are executed later, by the
3077 * "namespace inscope" command.
3078 */
3079
3080 TclNewObj(listPtr);
3081 TclNewLiteralStringObj(objPtr, "::namespace");
3082 Tcl_ListObjAppendElement(interp, listPtr, objPtr);
3083 TclNewLiteralStringObj(objPtr, "inscope");
3084 Tcl_ListObjAppendElement(interp, listPtr, objPtr);
3085
3086 currNsPtr = (Namespace *) TclGetCurrentNamespace(interp);
3087 if (currNsPtr == (Namespace *) TclGetGlobalNamespace(interp)) {
3088 TclNewLiteralStringObj(objPtr, "::");
3089 } else {
3090 objPtr = Tcl_NewStringObj(currNsPtr->fullName, -1);
3091 }
3092 Tcl_ListObjAppendElement(interp, listPtr, objPtr);
3093
3094 Tcl_ListObjAppendElement(interp, listPtr, objv[1]);
3095
3096 Tcl_SetObjResult(interp, listPtr);
3097 return TCL_OK;
3098 }
3099
3100 /*
3101 *----------------------------------------------------------------------
3102 *
3103 * NamespaceCurrentCmd --
3104 *
3105 * Invoked to implement the "namespace current" command which returns the
3106 * fully-qualified name of the current namespace. Handles the following
3107 * syntax:
3108 *
3109 * namespace current
3110 *
3111 * Results:
3112 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3113 *
3114 * Side effects:
3115 * Returns a result in the interpreter's result object. If anything goes
3116 * wrong, the result is an error message.
3117 *
3118 *----------------------------------------------------------------------
3119 */
3120
3121 static int
3122 NamespaceCurrentCmd(
3123 ClientData dummy, /* Not used. */
3124 Tcl_Interp *interp, /* Current interpreter. */
3125 int objc, /* Number of arguments. */
3126 Tcl_Obj *const objv[]) /* Argument objects. */
3127 {
3128 Namespace *currNsPtr;
3129
3130 if (objc != 1) {
3131 Tcl_WrongNumArgs(interp, 1, objv, NULL);
3132 return TCL_ERROR;
3133 }
3134
3135 /*
3136 * The "real" name of the global namespace ("::") is the null string, but
3137 * we return "::" for it as a convenience to programmers. Note that "" and
3138 * "::" are treated as synonyms by the namespace code so that it is still
3139 * easy to do things like:
3140 *
3141 * namespace [namespace current]::bar { ... }
3142 */
3143
3144 currNsPtr = (Namespace *) TclGetCurrentNamespace(interp);
3145 if (currNsPtr == (Namespace *) TclGetGlobalNamespace(interp)) {
3146 Tcl_SetObjResult(interp, Tcl_NewStringObj("::", 2));
3147 } else {
3148 Tcl_SetObjResult(interp, Tcl_NewStringObj(currNsPtr->fullName, -1));
3149 }
3150 return TCL_OK;
3151 }
3152
3153 /*
3154 *----------------------------------------------------------------------
3155 *
3156 * NamespaceDeleteCmd --
3157 *
3158 * Invoked to implement the "namespace delete" command to delete
3159 * namespace(s). Handles the following syntax:
3160 *
3161 * namespace delete ?name name...?
3162 *
3163 * Each name identifies a namespace. It may include a sequence of
3164 * namespace qualifiers separated by "::"s. If a namespace is found, it
3165 * is deleted: all variables and procedures contained in that namespace
3166 * are deleted. If that namespace is being used on the call stack, it is
3167 * kept alive (but logically deleted) until it is removed from the call
3168 * stack: that is, it can no longer be referenced by name but any
3169 * currently executing procedure that refers to it is allowed to do so
3170 * until the procedure returns. If the namespace can't be found, this
3171 * function returns an error. If no namespaces are specified, this
3172 * command does nothing.
3173 *
3174 * Results:
3175 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3176 *
3177 * Side effects:
3178 * Deletes the specified namespaces. If anything goes wrong, this
3179 * function returns an error message in the interpreter's result object.
3180 *
3181 *----------------------------------------------------------------------
3182 */
3183
3184 static int
3185 NamespaceDeleteCmd(
3186 ClientData dummy, /* Not used. */
3187 Tcl_Interp *interp, /* Current interpreter. */
3188 int objc, /* Number of arguments. */
3189 Tcl_Obj *const objv[]) /* Argument objects. */
3190 {
3191 Tcl_Namespace *namespacePtr;
3192 const char *name;
3193 int i;
3194
3195 if (objc < 1) {
3196 Tcl_WrongNumArgs(interp, 1, objv, "?name name...?");
3197 return TCL_ERROR;
3198 }
3199
3200 /*
3201 * Destroying one namespace may cause another to be destroyed. Break this
3202 * into two passes: first check to make sure that all namespaces on the
3203 * command line are valid, and report any errors.
3204 */
3205
3206 for (i = 1; i < objc; i++) {
3207 name = TclGetString(objv[i]);
3208 namespacePtr = Tcl_FindNamespace(interp, name, NULL, /*flags*/ 0);
3209 if ((namespacePtr == NULL)
3210 || (((Namespace *) namespacePtr)->flags & NS_KILLED)) {
3211 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3212 "unknown namespace \"%s\" in namespace delete command",
3213 TclGetString(objv[i])));
3214 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "NAMESPACE",
3215 TclGetString(objv[i]), (char *)NULL);
3216 return TCL_ERROR;
3217 }
3218 }
3219
3220 /*
3221 * Okay, now delete each namespace.
3222 */
3223
3224 for (i = 1; i < objc; i++) {
3225 name = TclGetString(objv[i]);
3226 namespacePtr = Tcl_FindNamespace(interp, name, NULL, /* flags */ 0);
3227 if (namespacePtr) {
3228 Tcl_DeleteNamespace(namespacePtr);
3229 }
3230 }
3231 return TCL_OK;
3232 }
3233
3234 /*
3235 *----------------------------------------------------------------------
3236 *
3237 * NamespaceEvalCmd --
3238 *
3239 * Invoked to implement the "namespace eval" command. Executes commands
3240 * in a namespace. If the namespace does not already exist, it is
3241 * created. Handles the following syntax:
3242 *
3243 * namespace eval name arg ?arg...?
3244 *
3245 * If more than one arg argument is specified, the command that is
3246 * executed is the result of concatenating the arguments together with a
3247 * space between each argument.
3248 *
3249 * Results:
3250 * Returns TCL_OK if the namespace is found and the commands are executed
3251 * successfully. Returns TCL_ERROR if anything goes wrong.
3252 *
3253 * Side effects:
3254 * Returns the result of the command in the interpreter's result object.
3255 * If anything goes wrong, this function returns an error message as the
3256 * result.
3257 *
3258 *----------------------------------------------------------------------
3259 */
3260
3261 static int
3262 NamespaceEvalCmd(
3263 ClientData clientData, /* Arbitrary value passed to cmd. */
3264 Tcl_Interp *interp, /* Current interpreter. */
3265 int objc, /* Number of arguments. */
3266 Tcl_Obj *const objv[]) /* Argument objects. */
3267 {
3268 return Tcl_NRCallObjProc(interp, NRNamespaceEvalCmd, clientData, objc,
3269 objv);
3270 }
3271
3272 static int
3273 NRNamespaceEvalCmd(
3274 ClientData dummy, /* Not used. */
3275 Tcl_Interp *interp, /* Current interpreter. */
3276 int objc, /* Number of arguments. */
3277 Tcl_Obj *const objv[]) /* Argument objects. */
3278 {
3279 Interp *iPtr = (Interp *) interp;
3280 CmdFrame *invoker;
3281 int word;
3282 Tcl_Namespace *namespacePtr;
3283 CallFrame *framePtr, **framePtrPtr;
3284 Tcl_Obj *objPtr;
3285 int result;
3286
3287 if (objc < 3) {
3288 Tcl_WrongNumArgs(interp, 1, objv, "name arg ?arg...?");
3289 return TCL_ERROR;
3290 }
3291
3292 /*
3293 * Try to resolve the namespace reference, caching the result in the
3294 * namespace object along the way.
3295 */
3296
3297 result = GetNamespaceFromObj(interp, objv[1], &namespacePtr);
3298
3299 /*
3300 * If the namespace wasn't found, try to create it.
3301 */
3302
3303 if (result == TCL_ERROR) {
3304 const char *name = TclGetString(objv[1]);
3305
3306 namespacePtr = Tcl_CreateNamespace(interp, name, NULL, NULL);
3307 if (namespacePtr == NULL) {
3308 return TCL_ERROR;
3309 }
3310 }
3311
3312 /*
3313 * Make the specified namespace the current namespace and evaluate the
3314 * command(s).
3315 */
3316
3317 /* This is needed to satisfy GCC 3.3's strict aliasing rules */
3318 framePtrPtr = &framePtr;
3319 (void) TclPushStackFrame(interp, (Tcl_CallFrame **) framePtrPtr,
3320 namespacePtr, /*isProcCallFrame*/ 0);
3321
3322 framePtr->objv = TclFetchEnsembleRoot(interp, objv, objc, &framePtr->objc);
3323
3324 if (objc == 3) {
3325 /*
3326 * TIP #280: Make actual argument location available to eval'd script.
3327 */
3328
3329 objPtr = objv[2];
3330 invoker = iPtr->cmdFramePtr;
3331 word = 3;
3332 TclArgumentGet(interp, objPtr, &invoker, &word);
3333 } else {
3334 /*
3335 * More than one argument: concatenate them together with spaces
3336 * between, then evaluate the result. Tcl_EvalObjEx will delete the
3337 * object when it decrements its refcount after eval'ing it.
3338 */
3339
3340 objPtr = Tcl_ConcatObj(objc-2, objv+2);
3341 invoker = NULL;
3342 word = 0;
3343 }
3344
3345 /*
3346 * TIP #280: Make invoking context available to eval'd script.
3347 */
3348
3349 TclNRAddCallback(interp, NsEval_Callback, namespacePtr, "eval",
3350 NULL, NULL);
3351 return TclNREvalObjEx(interp, objPtr, 0, invoker, word);
3352 }
3353
3354 static int
3355 NsEval_Callback(
3356 ClientData data[],
3357 Tcl_Interp *interp,
3358 int result)
3359 {
3360 Tcl_Namespace *namespacePtr = (Tcl_Namespace *)data[0];
3361
3362 if (result == TCL_ERROR) {
3363 int length = strlen(namespacePtr->fullName);
3364 int limit = 200;
3365 int overflow = (length > limit);
3366 char *cmd = (char *)data[1];
3367
3368 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
3369 "\n (in namespace %s \"%.*s%s\" script line %d)",
3370 cmd,
3371 (overflow ? limit : length), namespacePtr->fullName,
3372 (overflow ? "..." : ""), Tcl_GetErrorLine(interp)));
3373 }
3374
3375 /*
3376 * Restore the previous "current" namespace.
3377 */
3378
3379 TclPopStackFrame(interp);
3380 return result;
3381 }
3382
3383 /*
3384 *----------------------------------------------------------------------
3385 *
3386 * NamespaceExistsCmd --
3387 *
3388 * Invoked to implement the "namespace exists" command that returns true
3389 * if the given namespace currently exists, and false otherwise. Handles
3390 * the following syntax:
3391 *
3392 * namespace exists name
3393 *
3394 * Results:
3395 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3396 *
3397 * Side effects:
3398 * Returns a result in the interpreter's result object. If anything goes
3399 * wrong, the result is an error message.
3400 *
3401 *----------------------------------------------------------------------
3402 */
3403
3404 static int
3405 NamespaceExistsCmd(
3406 ClientData dummy, /* Not used. */
3407 Tcl_Interp *interp, /* Current interpreter. */
3408 int objc, /* Number of arguments. */
3409 Tcl_Obj *const objv[]) /* Argument objects. */
3410 {
3411 Tcl_Namespace *namespacePtr;
3412
3413 if (objc != 2) {
3414 Tcl_WrongNumArgs(interp, 1, objv, "name");
3415 return TCL_ERROR;
3416 }
3417
3418 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(
3419 GetNamespaceFromObj(interp, objv[1], &namespacePtr) == TCL_OK));
3420 return TCL_OK;
3421 }
3422
3423 /*
3424 *----------------------------------------------------------------------
3425 *
3426 * NamespaceExportCmd --
3427 *
3428 * Invoked to implement the "namespace export" command that specifies
3429 * which commands are exported from a namespace. The exported commands
3430 * are those that can be imported into another namespace using "namespace
3431 * import". Both commands defined in a namespace and commands the
3432 * namespace has imported can be exported by a namespace. This command
3433 * has the following syntax:
3434 *
3435 * namespace export ?-clear? ?pattern pattern...?
3436 *
3437 * Each pattern may contain "string match"-style pattern matching special
3438 * characters, but the pattern may not include any namespace qualifiers:
3439 * that is, the pattern must specify commands in the current (exporting)
3440 * namespace. The specified patterns are appended onto the namespace's
3441 * list of export patterns.
3442 *
3443 * To reset the namespace's export pattern list, specify the "-clear"
3444 * flag.
3445 *
3446 * If there are no export patterns and the "-clear" flag isn't given,
3447 * this command returns the namespace's current export list.
3448 *
3449 * Results:
3450 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3451 *
3452 * Side effects:
3453 * Returns a result in the interpreter's result object. If anything goes
3454 * wrong, the result is an error message.
3455 *
3456 *----------------------------------------------------------------------
3457 */
3458
3459 static int
3460 NamespaceExportCmd(
3461 ClientData dummy, /* Not used. */
3462 Tcl_Interp *interp, /* Current interpreter. */
3463 int objc, /* Number of arguments. */
3464 Tcl_Obj *const objv[]) /* Argument objects. */
3465 {
3466 int firstArg, i;
3467
3468 if (objc < 1) {
3469 Tcl_WrongNumArgs(interp, 1, objv, "?-clear? ?pattern pattern...?");
3470 return TCL_ERROR;
3471 }
3472
3473 /*
3474 * If no pattern arguments are given, and "-clear" isn't specified, return
3475 * the namespace's current export pattern list.
3476 */
3477
3478 if (objc == 1) {
3479 Tcl_Obj *listPtr;
3480
3481 TclNewObj(listPtr);
3482 (void)Tcl_AppendExportList(interp, NULL, listPtr);
3483 Tcl_SetObjResult(interp, listPtr);
3484 return TCL_OK;
3485 }
3486
3487 /*
3488 * Process the optional "-clear" argument.
3489 */
3490
3491 firstArg = 1;
3492 if (strcmp("-clear", TclGetString(objv[firstArg])) == 0) {
3493 Tcl_Export(interp, NULL, "::", 1);
3494 Tcl_ResetResult(interp);
3495 firstArg++;
3496 }
3497
3498 /*
3499 * Add each pattern to the namespace's export pattern list.
3500 */
3501
3502 for (i = firstArg; i < objc; i++) {
3503 int result = Tcl_Export(interp, NULL, TclGetString(objv[i]), 0);
3504 if (result != TCL_OK) {
3505 return result;
3506 }
3507 }
3508 return TCL_OK;
3509 }
3510
3511 /*
3512 *----------------------------------------------------------------------
3513 *
3514 * NamespaceForgetCmd --
3515 *
3516 * Invoked to implement the "namespace forget" command to remove imported
3517 * commands from a namespace. Handles the following syntax:
3518 *
3519 * namespace forget ?pattern pattern...?
3520 *
3521 * Each pattern is a name like "foo::*" or "a::b::x*". That is, the
3522 * pattern may include the special pattern matching characters recognized
3523 * by the "string match" command, but only in the command name at the end
3524 * of the qualified name; the special pattern characters may not appear
3525 * in a namespace name. All of the commands that match that pattern are
3526 * checked to see if they have an imported command in the current
3527 * namespace that refers to the matched command. If there is an alias, it
3528 * is removed.
3529 *
3530 * Results:
3531 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3532 *
3533 * Side effects:
3534 * Imported commands are removed from the current namespace. If anything
3535 * goes wrong, this function returns an error message in the
3536 * interpreter's result object.
3537 *
3538 *----------------------------------------------------------------------
3539 */
3540
3541 static int
3542 NamespaceForgetCmd(
3543 ClientData dummy, /* Not used. */
3544 Tcl_Interp *interp, /* Current interpreter. */
3545 int objc, /* Number of arguments. */
3546 Tcl_Obj *const objv[]) /* Argument objects. */
3547 {
3548 const char *pattern;
3549 int i, result;
3550
3551 if (objc < 1) {
3552 Tcl_WrongNumArgs(interp, 1, objv, "?pattern pattern...?");
3553 return TCL_ERROR;
3554 }
3555
3556 for (i = 1; i < objc; i++) {
3557 pattern = TclGetString(objv[i]);
3558 result = Tcl_ForgetImport(interp, NULL, pattern);
3559 if (result != TCL_OK) {
3560 return result;
3561 }
3562 }
3563 return TCL_OK;
3564 }
3565
3566 /*
3567 *----------------------------------------------------------------------
3568 *
3569 * NamespaceImportCmd --
3570 *
3571 * Invoked to implement the "namespace import" command that imports
3572 * commands into a namespace. Handles the following syntax:
3573 *
3574 * namespace import ?-force? ?pattern pattern...?
3575 *
3576 * Each pattern is a namespace-qualified name like "foo::*", "a::b::x*",
3577 * or "bar::p". That is, the pattern may include the special pattern
3578 * matching characters recognized by the "string match" command, but only
3579 * in the command name at the end of the qualified name; the special
3580 * pattern characters may not appear in a namespace name. All of the
3581 * commands that match the pattern and which are exported from their
3582 * namespace are made accessible from the current namespace context. This
3583 * is done by creating a new "imported command" in the current namespace
3584 * that points to the real command in its original namespace; when the
3585 * imported command is called, it invokes the real command.
3586 *
3587 * If an imported command conflicts with an existing command, it is
3588 * treated as an error. But if the "-force" option is included, then
3589 * existing commands are overwritten by the imported commands.
3590 *
3591 * If there are no pattern arguments and the "-force" flag isn't given,
3592 * this command returns the list of commands currently imported in
3593 * the current namespace.
3594 *
3595 * Results:
3596 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3597 *
3598 * Side effects:
3599 * Adds imported commands to the current namespace. If anything goes
3600 * wrong, this function returns an error message in the interpreter's
3601 * result object.
3602 *
3603 *----------------------------------------------------------------------
3604 */
3605
3606 static int
3607 NamespaceImportCmd(
3608 ClientData dummy, /* Not used. */
3609 Tcl_Interp *interp, /* Current interpreter. */
3610 int objc, /* Number of arguments. */
3611 Tcl_Obj *const objv[]) /* Argument objects. */
3612 {
3613 int allowOverwrite = 0;
3614 const char *string, *pattern;
3615 int i, result;
3616 int firstArg;
3617
3618 if (objc < 1) {
3619 Tcl_WrongNumArgs(interp, 1, objv, "?-force? ?pattern pattern...?");
3620 return TCL_ERROR;
3621 }
3622
3623 /*
3624 * Skip over the optional "-force" as the first argument.
3625 */
3626
3627 firstArg = 1;
3628 if (firstArg < objc) {
3629 string = TclGetString(objv[firstArg]);
3630 if ((*string == '-') && (strcmp(string, "-force") == 0)) {
3631 allowOverwrite = 1;
3632 firstArg++;
3633 }
3634 } else {
3635 /*
3636 * When objc == 1, command is just [namespace import]. Introspection
3637 * form to return list of imported commands.
3638 */
3639
3640 Tcl_HashEntry *hPtr;
3641 Tcl_HashSearch search;
3642 Namespace *nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
3643 Tcl_Obj *listPtr;
3644
3645 TclNewObj(listPtr);
3646 for (hPtr = Tcl_FirstHashEntry(&nsPtr->cmdTable, &search);
3647 hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) {
3648 Command *cmdPtr = (Command *)Tcl_GetHashValue(hPtr);
3649
3650 if (cmdPtr->deleteProc == DeleteImportedCmd) {
3651 Tcl_ListObjAppendElement(NULL, listPtr, Tcl_NewStringObj(
3652 (char *)Tcl_GetHashKey(&nsPtr->cmdTable, hPtr), -1));
3653 }
3654 }
3655 Tcl_SetObjResult(interp, listPtr);
3656 return TCL_OK;
3657 }
3658
3659 /*
3660 * Handle the imports for each of the patterns.
3661 */
3662
3663 for (i = firstArg; i < objc; i++) {
3664 pattern = TclGetString(objv[i]);
3665 result = Tcl_Import(interp, NULL, pattern, allowOverwrite);
3666 if (result != TCL_OK) {
3667 return result;
3668 }
3669 }
3670 return TCL_OK;
3671 }
3672
3673 /*
3674 *----------------------------------------------------------------------
3675 *
3676 * NamespaceInscopeCmd --
3677 *
3678 * Invoked to implement the "namespace inscope" command that executes a
3679 * script in the context of a particular namespace. This command is not
3680 * expected to be used directly by programmers; calls to it are generated
3681 * implicitly when programs use "namespace code" commands to register
3682 * callback scripts. Handles the following syntax:
3683 *
3684 * namespace inscope name arg ?arg...?
3685 *
3686 * The "namespace inscope" command is much like the "namespace eval"
3687 * command except that it has lappend semantics and the namespace must
3688 * already exist. It treats the first argument as a list, and appends any
3689 * arguments after the first onto the end as proper list elements. For
3690 * example,
3691 *
3692 * namespace inscope ::foo {a b} c d e
3693 *
3694 * is equivalent to
3695 *
3696 * namespace eval ::foo [concat {a b} [list c d e]]
3697 *
3698 * This lappend semantics is important because many callback scripts are
3699 * actually prefixes.
3700 *
3701 * Results:
3702 * Returns TCL_OK to indicate success, or TCL_ERROR to indicate failure.
3703 *
3704 * Side effects:
3705 * Returns a result in the Tcl interpreter's result object.
3706 *
3707 *----------------------------------------------------------------------
3708 */
3709
3710 static int
3711 NamespaceInscopeCmd(
3712 ClientData clientData, /* Arbitrary value passed to cmd. */
3713 Tcl_Interp *interp, /* Current interpreter. */
3714 int objc, /* Number of arguments. */
3715 Tcl_Obj *const objv[]) /* Argument objects. */
3716 {
3717 return Tcl_NRCallObjProc(interp, NRNamespaceInscopeCmd, clientData, objc,
3718 objv);
3719 }
3720
3721 static int
3722 NRNamespaceInscopeCmd(
3723 ClientData dummy, /* Not used. */
3724 Tcl_Interp *interp, /* Current interpreter. */
3725 int objc, /* Number of arguments. */
3726 Tcl_Obj *const objv[]) /* Argument objects. */
3727 {
3728 Tcl_Namespace *namespacePtr;
3729 CallFrame *framePtr, **framePtrPtr;
3730 int i;
3731 Tcl_Obj *cmdObjPtr;
3732
3733 if (objc < 3) {
3734 Tcl_WrongNumArgs(interp, 1, objv, "name arg ?arg...?");
3735 return TCL_ERROR;
3736 }
3737
3738 /*
3739 * Resolve the namespace reference.
3740 */
3741
3742 if (TclGetNamespaceFromObj(interp, objv[1], &namespacePtr) != TCL_OK) {
3743 return TCL_ERROR;
3744 }
3745
3746 /*
3747 * Make the specified namespace the current namespace.
3748 */
3749
3750 framePtrPtr = &framePtr; /* This is needed to satisfy GCC's
3751 * strict aliasing rules. */
3752 (void) TclPushStackFrame(interp, (Tcl_CallFrame **) framePtrPtr,
3753 namespacePtr, /*isProcCallFrame*/ 0);
3754
3755 framePtr->objv = TclFetchEnsembleRoot(interp, objv, objc, &framePtr->objc);
3756
3757 /*
3758 * Execute the command. If there is just one argument, just treat it as a
3759 * script and evaluate it. Otherwise, create a list from the arguments
3760 * after the first one, then concatenate the first argument and the list
3761 * of extra arguments to form the command to evaluate.
3762 */
3763
3764 if (objc == 3) {
3765 cmdObjPtr = objv[2];
3766 } else {
3767 Tcl_Obj *concatObjv[2];
3768 Tcl_Obj *listPtr;
3769
3770 listPtr = Tcl_NewListObj(0, NULL);
3771 for (i = 3; i < objc; i++) {
3772 if (Tcl_ListObjAppendElement(interp, listPtr, objv[i]) != TCL_OK){
3773 Tcl_DecrRefCount(listPtr); /* Free unneeded obj. */
3774 return TCL_ERROR;
3775 }
3776 }
3777
3778 concatObjv[0] = objv[2];
3779 concatObjv[1] = listPtr;
3780 cmdObjPtr = Tcl_ConcatObj(2, concatObjv);
3781 Tcl_DecrRefCount(listPtr); /* We're done with the list object. */
3782 }
3783
3784 TclNRAddCallback(interp, NsEval_Callback, namespacePtr, "inscope",
3785 NULL, NULL);
3786 return TclNREvalObjEx(interp, cmdObjPtr, 0, NULL, 0);
3787 }
3788
3789 /*
3790 *----------------------------------------------------------------------
3791 *
3792 * NamespaceOriginCmd --
3793 *
3794 * Invoked to implement the "namespace origin" command to return the
3795 * fully-qualified name of the "real" command to which the specified
3796 * "imported command" refers. Handles the following syntax:
3797 *
3798 * namespace origin name
3799 *
3800 * Results:
3801 * An imported command is created in an namespace when that namespace
3802 * imports a command from another namespace. If a command is imported
3803 * into a sequence of namespaces a, b,...,n where each successive
3804 * namespace just imports the command from the previous namespace, this
3805 * command returns the fully-qualified name of the original command in
3806 * the first namespace, a. If "name" does not refer to an alias, its
3807 * fully-qualified name is returned. The returned name is stored in the
3808 * interpreter's result object. This function returns TCL_OK if
3809 * successful, and TCL_ERROR if anything goes wrong.
3810 *
3811 * Side effects:
3812 * If anything goes wrong, this function returns an error message in the
3813 * interpreter's result object.
3814 *
3815 *----------------------------------------------------------------------
3816 */
3817
3818 static int
3819 NamespaceOriginCmd(
3820 ClientData dummy, /* Not used. */
3821 Tcl_Interp *interp, /* Current interpreter. */
3822 int objc, /* Number of arguments. */
3823 Tcl_Obj *const objv[]) /* Argument objects. */
3824 {
3825 Tcl_Command cmd, origCmd;
3826 Tcl_Obj *resultPtr;
3827
3828 if (objc != 2) {
3829 Tcl_WrongNumArgs(interp, 1, objv, "name");
3830 return TCL_ERROR;
3831 }
3832
3833 cmd = Tcl_GetCommandFromObj(interp, objv[1]);
3834 if (cmd == NULL) {
3835 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3836 "invalid command name \"%s\"", TclGetString(objv[1])));
3837 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "COMMAND",
3838 TclGetString(objv[1]), (char *)NULL);
3839 return TCL_ERROR;
3840 }
3841 origCmd = TclGetOriginalCommand(cmd);
3842 TclNewObj(resultPtr);
3843 if (origCmd == NULL) {
3844 /*
3845 * The specified command isn't an imported command. Return the
3846 * command's name qualified by the full name of the namespace it was
3847 * defined in.
3848 */
3849
3850 Tcl_GetCommandFullName(interp, cmd, resultPtr);
3851 } else {
3852 Tcl_GetCommandFullName(interp, origCmd, resultPtr);
3853 }
3854 Tcl_SetObjResult(interp, resultPtr);
3855 return TCL_OK;
3856 }
3857
3858 /*
3859 *----------------------------------------------------------------------
3860 *
3861 * NamespaceParentCmd --
3862 *
3863 * Invoked to implement the "namespace parent" command that returns the
3864 * fully-qualified name of the parent namespace for a specified
3865 * namespace. Handles the following syntax:
3866 *
3867 * namespace parent ?name?
3868 *
3869 * Results:
3870 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
3871 *
3872 * Side effects:
3873 * Returns a result in the interpreter's result object. If anything goes
3874 * wrong, the result is an error message.
3875 *
3876 *----------------------------------------------------------------------
3877 */
3878
3879 static int
3880 NamespaceParentCmd(
3881 ClientData dummy, /* Not used. */
3882 Tcl_Interp *interp, /* Current interpreter. */
3883 int objc, /* Number of arguments. */
3884 Tcl_Obj *const objv[]) /* Argument objects. */
3885 {
3886 Tcl_Namespace *nsPtr;
3887
3888 if (objc == 1) {
3889 nsPtr = TclGetCurrentNamespace(interp);
3890 } else if (objc == 2) {
3891 if (TclGetNamespaceFromObj(interp, objv[1], &nsPtr) != TCL_OK) {
3892 return TCL_ERROR;
3893 }
3894 } else {
3895 Tcl_WrongNumArgs(interp, 1, objv, "?name?");
3896 return TCL_ERROR;
3897 }
3898
3899 /*
3900 * Report the parent of the specified namespace.
3901 */
3902
3903 if (nsPtr->parentPtr != NULL) {
3904 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3905 nsPtr->parentPtr->fullName, -1));
3906 }
3907 return TCL_OK;
3908 }
3909
3910 /*
3911 *----------------------------------------------------------------------
3912 *
3913 * NamespacePathCmd --
3914 *
3915 * Invoked to implement the "namespace path" command that reads and
3916 * writes the current namespace's command resolution path. Has one
3917 * optional argument: if present, it is a list of named namespaces to set
3918 * the path to, and if absent, the current path should be returned.
3919 * Handles the following syntax:
3920 *
3921 * namespace path ?nsList?
3922 *
3923 * Results:
3924 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong
3925 * (most notably if the namespace list contains the name of something
3926 * other than a namespace). In the successful-exit case, may set the
3927 * interpreter result to the list of names of the namespaces on the
3928 * current namespace's path.
3929 *
3930 * Side effects:
3931 * May update the namespace path (triggering a recomputing of all command
3932 * names that depend on the namespace for resolution).
3933 *
3934 *----------------------------------------------------------------------
3935 */
3936
3937 static int
3938 NamespacePathCmd(
3939 ClientData dummy, /* Not used. */
3940 Tcl_Interp *interp, /* Current interpreter. */
3941 int objc, /* Number of arguments. */
3942 Tcl_Obj *const objv[]) /* Argument objects. */
3943 {
3944 Namespace *nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
3945 int nsObjc, i;
3946 int result = TCL_ERROR;
3947 Tcl_Obj **nsObjv;
3948 Tcl_Namespace **namespaceList = NULL;
3949
3950 if (objc > 2) {
3951 Tcl_WrongNumArgs(interp, 1, objv, "?pathList?");
3952 return TCL_ERROR;
3953 }
3954
3955 /*
3956 * If no path is given, return the current path.
3957 */
3958
3959 if (objc == 1) {
3960 Tcl_Obj *resultObj;
3961
3962 TclNewObj(resultObj);
3963 for (i=0 ; i<nsPtr->commandPathLength ; i++) {
3964 if (nsPtr->commandPathArray[i].nsPtr != NULL) {
3965 Tcl_ListObjAppendElement(NULL, resultObj, Tcl_NewStringObj(
3966 nsPtr->commandPathArray[i].nsPtr->fullName, -1));
3967 }
3968 }
3969 Tcl_SetObjResult(interp, resultObj);
3970 return TCL_OK;
3971 }
3972
3973 /*
3974 * There is a path given, so parse it into an array of namespace pointers.
3975 */
3976
3977 if (TclListObjGetElements(interp, objv[1], &nsObjc, &nsObjv) != TCL_OK) {
3978 goto badNamespace;
3979 }
3980 if (nsObjc != 0) {
3981 namespaceList = (Tcl_Namespace **)
3982 TclStackAlloc(interp, sizeof(Tcl_Namespace *) * nsObjc);
3983
3984 for (i = 0; i < nsObjc; i++) {
3985 if (TclGetNamespaceFromObj(interp, nsObjv[i],
3986 &namespaceList[i]) != TCL_OK) {
3987 goto badNamespace;
3988 }
3989 }
3990 }
3991
3992 /*
3993 * Now we have the list of valid namespaces, install it as the path.
3994 */
3995
3996 TclSetNsPath(nsPtr, nsObjc, namespaceList);
3997
3998 result = TCL_OK;
3999 badNamespace:
4000 if (namespaceList != NULL) {
4001 TclStackFree(interp, namespaceList);
4002 }
4003 return result;
4004 }
4005
4006 /*
4007 *----------------------------------------------------------------------
4008 *
4009 * TclSetNsPath --
4010 *
4011 * Sets the namespace command name resolution path to the given list of
4012 * namespaces. If the list is empty (of zero length) the path is set to
4013 * empty and the default old-style behaviour of command name resolution
4014 * is used.
4015 *
4016 * Results:
4017 * nothing
4018 *
4019 * Side effects:
4020 * Invalidates the command name resolution caches for any command
4021 * resolved in the given namespace.
4022 *
4023 *----------------------------------------------------------------------
4024 */
4025
4026 void
4027 TclSetNsPath(
4028 Namespace *nsPtr, /* Namespace whose path is to be set. */
4029 int pathLength, /* Length of pathAry. */
4030 Tcl_Namespace *pathAry[]) /* Array of namespaces that are the path. */
4031 {
4032 if (pathLength != 0) {
4033 NamespacePathEntry *tmpPathArray = (NamespacePathEntry *)
4034 ckalloc(sizeof(NamespacePathEntry) * pathLength);
4035 int i;
4036
4037 for (i=0 ; i<pathLength ; i++) {
4038 tmpPathArray[i].nsPtr = (Namespace *) pathAry[i];
4039 tmpPathArray[i].creatorNsPtr = nsPtr;
4040 tmpPathArray[i].prevPtr = NULL;
4041 tmpPathArray[i].nextPtr =
4042 tmpPathArray[i].nsPtr->commandPathSourceList;
4043 if (tmpPathArray[i].nextPtr != NULL) {
4044 tmpPathArray[i].nextPtr->prevPtr = &tmpPathArray[i];
4045 }
4046 tmpPathArray[i].nsPtr->commandPathSourceList = &tmpPathArray[i];
4047 }
4048 if (nsPtr->commandPathLength != 0) {
4049 UnlinkNsPath(nsPtr);
4050 }
4051 nsPtr->commandPathArray = tmpPathArray;
4052 } else {
4053 if (nsPtr->commandPathLength != 0) {
4054 UnlinkNsPath(nsPtr);
4055 }
4056 }
4057
4058 nsPtr->commandPathLength = pathLength;
4059 nsPtr->cmdRefEpoch++;
4060 nsPtr->resolverEpoch++;
4061 }
4062
4063 /*
4064 *----------------------------------------------------------------------
4065 *
4066 * UnlinkNsPath --
4067 *
4068 * Delete the given namespace's command name resolution path. Only call
4069 * if the path is non-empty. Caller must reset the counter containing the
4070 * path size.
4071 *
4072 * Results:
4073 * nothing
4074 *
4075 * Side effects:
4076 * Deletes the array of path entries and unlinks those path entries from
4077 * the target namespace's list of interested namespaces.
4078 *
4079 *----------------------------------------------------------------------
4080 */
4081
4082 static void
4083 UnlinkNsPath(
4084 Namespace *nsPtr)
4085 {
4086 int i;
4087 for (i=0 ; i<nsPtr->commandPathLength ; i++) {
4088 NamespacePathEntry *nsPathPtr = &nsPtr->commandPathArray[i];
4089
4090 if (nsPathPtr->prevPtr != NULL) {
4091 nsPathPtr->prevPtr->nextPtr = nsPathPtr->nextPtr;
4092 }
4093 if (nsPathPtr->nextPtr != NULL) {
4094 nsPathPtr->nextPtr->prevPtr = nsPathPtr->prevPtr;
4095 }
4096 if (nsPathPtr->nsPtr != NULL) {
4097 if (nsPathPtr->nsPtr->commandPathSourceList == nsPathPtr) {
4098 nsPathPtr->nsPtr->commandPathSourceList = nsPathPtr->nextPtr;
4099 }
4100 }
4101 }
4102 ckfree(nsPtr->commandPathArray);
4103 }
4104
4105 /*
4106 *----------------------------------------------------------------------
4107 *
4108 * TclInvalidateNsPath --
4109 *
4110 * Invalidate the name resolution caches for all names looked up in
4111 * namespaces whose name path includes the given namespace.
4112 *
4113 * Results:
4114 * nothing
4115 *
4116 * Side effects:
4117 * Increments the command reference epoch in each namespace whose path
4118 * includes the given namespace. This causes any cached resolved names
4119 * whose root caching context starts at that namespace to be recomputed
4120 * the next time they are used.
4121 *
4122 *----------------------------------------------------------------------
4123 */
4124
4125 void
4126 TclInvalidateNsPath(
4127 Namespace *nsPtr)
4128 {
4129 NamespacePathEntry *nsPathPtr = nsPtr->commandPathSourceList;
4130
4131 while (nsPathPtr != NULL) {
4132 if (nsPathPtr->nsPtr != NULL) {
4133 nsPathPtr->creatorNsPtr->cmdRefEpoch++;
4134 }
4135 nsPathPtr = nsPathPtr->nextPtr;
4136 }
4137 }
4138
4139 /*
4140 *----------------------------------------------------------------------
4141 *
4142 * NamespaceQualifiersCmd --
4143 *
4144 * Invoked to implement the "namespace qualifiers" command that returns
4145 * any leading namespace qualifiers in a string. These qualifiers are
4146 * namespace names separated by "::"s. For example, for "::foo::p" this
4147 * command returns "::foo", and for "::" it returns "". This command is
4148 * the complement of the "namespace tail" command. Note that this command
4149 * does not check whether the "namespace" names are, in fact, the names
4150 * of currently defined namespaces. Handles the following syntax:
4151 *
4152 * namespace qualifiers string
4153 *
4154 * Results:
4155 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
4156 *
4157 * Side effects:
4158 * Returns a result in the interpreter's result object. If anything goes
4159 * wrong, the result is an error message.
4160 *
4161 *----------------------------------------------------------------------
4162 */
4163
4164 static int
4165 NamespaceQualifiersCmd(
4166 ClientData dummy, /* Not used. */
4167 Tcl_Interp *interp, /* Current interpreter. */
4168 int objc, /* Number of arguments. */
4169 Tcl_Obj *const objv[]) /* Argument objects. */
4170 {
4171 const char *name, *p;
4172 int length;
4173
4174 if (objc != 2) {
4175 Tcl_WrongNumArgs(interp, 1, objv, "string");
4176 return TCL_ERROR;
4177 }
4178
4179 /*
4180 * Find the end of the string, then work backward and find the start of
4181 * the last "::" qualifier.
4182 */
4183
4184 name = TclGetString(objv[1]);
4185 for (p = name; p[0] != '\0'; p++) {
4186 /* empty body */
4187 }
4188 while (--p >= name) {
4189 if ((p[0] == ':') && (p > name) && (p[-1] == ':')) {
4190 p -= 2; /* Back up over the :: */
4191 while ((p >= name) && (p[0] == ':')) {
4192 p--; /* Back up over the preceding : */
4193 }
4194 break;
4195 }
4196 }
4197
4198 if (p >= name) {
4199 length = p-name+1;
4200 Tcl_SetObjResult(interp, Tcl_NewStringObj(name, length));
4201 }
4202 return TCL_OK;
4203 }
4204
4205 /*
4206 *----------------------------------------------------------------------
4207 *
4208 * NamespaceUnknownCmd --
4209 *
4210 * Invoked to implement the "namespace unknown" command (TIP 181) that
4211 * sets or queries a per-namespace unknown command handler. This handler
4212 * is called when command lookup fails (current and global ns). The
4213 * default handler for the global namespace is ::unknown. The default
4214 * handler for other namespaces is to call the global namespace unknown
4215 * handler. Passing an empty list results in resetting the handler to its
4216 * default.
4217 *
4218 * namespace unknown ?handler?
4219 *
4220 * Results:
4221 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
4222 *
4223 * Side effects:
4224 * If no handler is specified, returns a result in the interpreter's
4225 * result object, otherwise it sets the unknown handler pointer in the
4226 * current namespace to the script fragment provided. If anything goes
4227 * wrong, the result is an error message.
4228 *
4229 *----------------------------------------------------------------------
4230 */
4231
4232 static int
4233 NamespaceUnknownCmd(
4234 ClientData dummy, /* Not used. */
4235 Tcl_Interp *interp, /* Current interpreter. */
4236 int objc, /* Number of arguments. */
4237 Tcl_Obj *const objv[]) /* Argument objects. */
4238 {
4239 Tcl_Namespace *currNsPtr;
4240 Tcl_Obj *resultPtr;
4241 int rc;
4242
4243 if (objc > 2) {
4244 Tcl_WrongNumArgs(interp, 1, objv, "?script?");
4245 return TCL_ERROR;
4246 }
4247
4248 currNsPtr = TclGetCurrentNamespace(interp);
4249
4250 if (objc == 1) {
4251 /*
4252 * Introspection - return the current namespace handler.
4253 */
4254
4255 resultPtr = Tcl_GetNamespaceUnknownHandler(interp, currNsPtr);
4256 if (resultPtr == NULL) {
4257 TclNewObj(resultPtr);
4258 }
4259 Tcl_SetObjResult(interp, resultPtr);
4260 } else {
4261 rc = Tcl_SetNamespaceUnknownHandler(interp, currNsPtr, objv[1]);
4262 if (rc == TCL_OK) {
4263 Tcl_SetObjResult(interp, objv[1]);
4264 }
4265 return rc;
4266 }
4267 return TCL_OK;
4268 }
4269
4270 /*
4271 *----------------------------------------------------------------------
4272 *
4273 * Tcl_GetNamespaceUnknownHandler --
4274 *
4275 * Returns the unknown command handler registered for the given
4276 * namespace.
4277 *
4278 * Results:
4279 * Returns the current unknown command handler, or NULL if none exists
4280 * for the namespace.
4281 *
4282 * Side effects:
4283 * None.
4284 *
4285 *----------------------------------------------------------------------
4286 */
4287
4288 Tcl_Obj *
4289 Tcl_GetNamespaceUnknownHandler(
4290 Tcl_Interp *interp, /* The interpreter in which the namespace
4291 * exists. */
4292 Tcl_Namespace *nsPtr) /* The namespace. */
4293 {
4294 Namespace *currNsPtr = (Namespace *) nsPtr;
4295
4296 if (currNsPtr->unknownHandlerPtr == NULL &&
4297 currNsPtr == ((Interp *) interp)->globalNsPtr) {
4298 /*
4299 * Default handler for global namespace is "::unknown". For all other
4300 * namespaces, it is NULL (which falls back on the global unknown
4301 * handler).
4302 */
4303
4304 TclNewLiteralStringObj(currNsPtr->unknownHandlerPtr, "::unknown");
4305 Tcl_IncrRefCount(currNsPtr->unknownHandlerPtr);
4306 }
4307 return currNsPtr->unknownHandlerPtr;
4308 }
4309
4310 /*
4311 *----------------------------------------------------------------------
4312 *
4313 * Tcl_SetNamespaceUnknownHandler --
4314 *
4315 * Sets the unknown command handler for the given namespace to the
4316 * command prefix passed.
4317 *
4318 * Results:
4319 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
4320 *
4321 * Side effects:
4322 * Sets the namespace unknown command handler. If the passed in handler
4323 * is NULL or an empty list, then the handler is reset to its default. If
4324 * an error occurs, then an error message is left in the interpreter
4325 * result.
4326 *
4327 *----------------------------------------------------------------------
4328 */
4329
4330 int
4331 Tcl_SetNamespaceUnknownHandler(
4332 Tcl_Interp *interp, /* Interpreter in which the namespace
4333 * exists. */
4334 Tcl_Namespace *nsPtr, /* Namespace which is being updated. */
4335 Tcl_Obj *handlerPtr) /* The new handler, or NULL to reset. */
4336 {
4337 int lstlen = 0;
4338 Namespace *currNsPtr = (Namespace *) nsPtr;
4339
4340 /*
4341 * Ensure that we check for errors *first* before we change anything.
4342 */
4343
4344 if (handlerPtr != NULL) {
4345 if (TclListObjLength(interp, handlerPtr, &lstlen) != TCL_OK) {
4346 /*
4347 * Not a list.
4348 */
4349
4350 return TCL_ERROR;
4351 }
4352 if (lstlen > 0) {
4353 /*
4354 * We are going to be saving this handler. Increment the reference
4355 * count before decrementing the refcount on the previous handler,
4356 * so that nothing strange can happen if we are told to set the
4357 * handler to the previous value.
4358 */
4359
4360 Tcl_IncrRefCount(handlerPtr);
4361 }
4362 }
4363
4364 /*
4365 * Remove old handler next.
4366 */
4367
4368 if (currNsPtr->unknownHandlerPtr != NULL) {
4369 Tcl_DecrRefCount(currNsPtr->unknownHandlerPtr);
4370 }
4371
4372 /*
4373 * Install the new handler.
4374 */
4375
4376 if (lstlen > 0) {
4377 /*
4378 * Just store the handler. It already has the correct reference count.
4379 */
4380
4381 currNsPtr->unknownHandlerPtr = handlerPtr;
4382 } else {
4383 /*
4384 * If NULL or an empty list is passed, this resets to the default
4385 * handler.
4386 */
4387
4388 currNsPtr->unknownHandlerPtr = NULL;
4389 }
4390 return TCL_OK;
4391 }
4392
4393 /*
4394 *----------------------------------------------------------------------
4395 *
4396 * NamespaceTailCmd --
4397 *
4398 * Invoked to implement the "namespace tail" command that returns the
4399 * trailing name at the end of a string with "::" namespace qualifiers.
4400 * These qualifiers are namespace names separated by "::"s. For example,
4401 * for "::foo::p" this command returns "p", and for "::" it returns "".
4402 * This command is the complement of the "namespace qualifiers" command.
4403 * Note that this command does not check whether the "namespace" names
4404 * are, in fact, the names of currently defined namespaces. Handles the
4405 * following syntax:
4406 *
4407 * namespace tail string
4408 *
4409 * Results:
4410 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
4411 *
4412 * Side effects:
4413 * Returns a result in the interpreter's result object. If anything goes
4414 * wrong, the result is an error message.
4415 *
4416 *----------------------------------------------------------------------
4417 */
4418
4419 static int
4420 NamespaceTailCmd(
4421 ClientData dummy, /* Not used. */
4422 Tcl_Interp *interp, /* Current interpreter. */
4423 int objc, /* Number of arguments. */
4424 Tcl_Obj *const objv[]) /* Argument objects. */
4425 {
4426 const char *name, *p;
4427
4428 if (objc != 2) {
4429 Tcl_WrongNumArgs(interp, 1, objv, "string");
4430 return TCL_ERROR;
4431 }
4432
4433 /*
4434 * Find the end of the string, then work backward and find the last "::"
4435 * qualifier.
4436 */
4437
4438 name = TclGetString(objv[1]);
4439 for (p = name; *p != '\0'; p++) {
4440 /* empty body */
4441 }
4442 while (--p > name) {
4443 if ((p[0] == ':') && (p[-1] == ':')) {
4444 p++; /* Just after the last "::" */
4445 break;
4446 }
4447 }
4448
4449 if (p >= name) {
4450 Tcl_SetObjResult(interp, Tcl_NewStringObj(p, -1));
4451 }
4452 return TCL_OK;
4453 }
4454
4455 /*
4456 *----------------------------------------------------------------------
4457 *
4458 * NamespaceUpvarCmd --
4459 *
4460 * Invoked to implement the "namespace upvar" command, that creates
4461 * variables in the current scope linked to variables in another
4462 * namespace. Handles the following syntax:
4463 *
4464 * namespace upvar ns otherVar myVar ?otherVar myVar ...?
4465 *
4466 * Results:
4467 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
4468 *
4469 * Side effects:
4470 * Creates new variables in the current scope, linked to the
4471 * corresponding variables in the stipulated namespace. If anything goes
4472 * wrong, the result is an error message.
4473 *
4474 *----------------------------------------------------------------------
4475 */
4476
4477 static int
4478 NamespaceUpvarCmd(
4479 ClientData dummy, /* Not used. */
4480 Tcl_Interp *interp, /* Current interpreter. */
4481 int objc, /* Number of arguments. */
4482 Tcl_Obj *const objv[]) /* Argument objects. */
4483 {
4484 Interp *iPtr = (Interp *) interp;
4485 Tcl_Namespace *nsPtr, *savedNsPtr;
4486 Var *otherPtr, *arrayPtr;
4487 const char *myName;
4488
4489 if (objc < 2 || (objc & 1)) {
4490 Tcl_WrongNumArgs(interp, 1, objv, "ns ?otherVar myVar ...?");
4491 return TCL_ERROR;
4492 }
4493
4494 if (TclGetNamespaceFromObj(interp, objv[1], &nsPtr) != TCL_OK) {
4495 return TCL_ERROR;
4496 }
4497
4498 objc -= 2;
4499 objv += 2;
4500
4501 for (; objc>0 ; objc-=2, objv+=2) {
4502 /*
4503 * Locate the other variable.
4504 */
4505
4506 savedNsPtr = (Tcl_Namespace *) iPtr->varFramePtr->nsPtr;
4507 iPtr->varFramePtr->nsPtr = (Namespace *) nsPtr;
4508 otherPtr = TclObjLookupVarEx(interp, objv[0], NULL,
4509 (TCL_NAMESPACE_ONLY|TCL_LEAVE_ERR_MSG|TCL_AVOID_RESOLVERS),
4510 "access", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr);
4511 iPtr->varFramePtr->nsPtr = (Namespace *) savedNsPtr;
4512 if (otherPtr == NULL) {
4513 return TCL_ERROR;
4514 }
4515
4516 /*
4517 * Create the new variable and link it to otherPtr.
4518 */
4519
4520 myName = TclGetString(objv[1]);
4521 if (TclPtrMakeUpvar(interp, otherPtr, myName, 0, -1) != TCL_OK) {
4522 return TCL_ERROR;
4523 }
4524 }
4525
4526 return TCL_OK;
4527 }
4528
4529 /*
4530 *----------------------------------------------------------------------
4531 *
4532 * NamespaceWhichCmd --
4533 *
4534 * Invoked to implement the "namespace which" command that returns the
4535 * fully-qualified name of a command or variable. If the specified
4536 * command or variable does not exist, it returns "". Handles the
4537 * following syntax:
4538 *
4539 * namespace which ?-command? ?-variable? name
4540 *
4541 * Results:
4542 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
4543 *
4544 * Side effects:
4545 * Returns a result in the interpreter's result object. If anything goes
4546 * wrong, the result is an error message.
4547 *
4548 *----------------------------------------------------------------------
4549 */
4550
4551 static int
4552 NamespaceWhichCmd(
4553 ClientData dummy, /* Not used. */
4554 Tcl_Interp *interp, /* Current interpreter. */
4555 int objc, /* Number of arguments. */
4556 Tcl_Obj *const objv[]) /* Argument objects. */
4557 {
4558 static const char *const opts[] = {
4559 "-command", "-variable", NULL
4560 };
4561 int lookupType = 0;
4562 Tcl_Obj *resultPtr;
4563
4564 if (objc < 2 || objc > 3) {
4565 badArgs:
4566 Tcl_WrongNumArgs(interp, 1, objv, "?-command? ?-variable? name");
4567 return TCL_ERROR;
4568 } else if (objc == 3) {
4569 /*
4570 * Look for a flag controlling the lookup.
4571 */
4572
4573 if (Tcl_GetIndexFromObj(interp, objv[1], opts, "option", 0,
4574 &lookupType) != TCL_OK) {
4575 /*
4576 * Preserve old style of error message!
4577 */
4578
4579 Tcl_ResetResult(interp);
4580 goto badArgs;
4581 }
4582 }
4583
4584 TclNewObj(resultPtr);
4585 switch (lookupType) {
4586 case 0: { /* -command */
4587 Tcl_Command cmd = Tcl_GetCommandFromObj(interp, objv[objc-1]);
4588
4589 if (cmd != NULL) {
4590 Tcl_GetCommandFullName(interp, cmd, resultPtr);
4591 }
4592 break;
4593 }
4594 case 1: { /* -variable */
4595 Tcl_Var var = Tcl_FindNamespaceVar(interp,
4596 TclGetString(objv[objc-1]), NULL, /*flags*/ 0);
4597
4598 if (var != NULL) {
4599 Tcl_GetVariableFullName(interp, var, resultPtr);
4600 }
4601 break;
4602 }
4603 }
4604 Tcl_SetObjResult(interp, resultPtr);
4605 return TCL_OK;
4606 }
4607
4608 /*
4609 *----------------------------------------------------------------------
4610 *
4611 * FreeNsNameInternalRep --
4612 *
4613 * Frees the resources associated with a nsName object's internal
4614 * representation.
4615 *
4616 * Results:
4617 * None.
4618 *
4619 * Side effects:
4620 * Decrements the ref count of any Namespace structure pointed to by the
4621 * nsName's internal representation. If there are no more references to
4622 * the namespace, it's structure will be freed.
4623 *
4624 *----------------------------------------------------------------------
4625 */
4626
4627 static void
4628 FreeNsNameInternalRep(
4629 Tcl_Obj *objPtr) /* nsName object with internal representation
4630 * to free. */
4631 {
4632 ResolvedNsName *resNamePtr = (ResolvedNsName *)objPtr->internalRep.twoPtrValue.ptr1;
4633
4634 /*
4635 * Decrement the reference count of the namespace. If there are no more
4636 * references, free it up.
4637 */
4638
4639 if (resNamePtr->refCount-- <= 1) {
4640 /*
4641 * Decrement the reference count for the cached namespace. If the
4642 * namespace is dead, and there are no more references to it, free
4643 * it.
4644 */
4645
4646 TclNsDecrRefCount(resNamePtr->nsPtr);
4647 ckfree(resNamePtr);
4648 }
4649 objPtr->typePtr = NULL;
4650 }
4651
4652 /*
4653 *----------------------------------------------------------------------
4654 *
4655 * DupNsNameInternalRep --
4656 *
4657 * Initializes the internal representation of a nsName object to a copy
4658 * of the internal representation of another nsName object.
4659 *
4660 * Results:
4661 * None.
4662 *
4663 * Side effects:
4664 * copyPtr's internal rep is set to refer to the same namespace
4665 * referenced by srcPtr's internal rep. Increments the ref count of the
4666 * ResolvedNsName structure used to hold the namespace reference.
4667 *
4668 *----------------------------------------------------------------------
4669 */
4670
4671 static void
4672 DupNsNameInternalRep(
4673 Tcl_Obj *srcPtr, /* Object with internal rep to copy. */
4674 Tcl_Obj *copyPtr) /* Object with internal rep to set. */
4675 {
4676 ResolvedNsName *resNamePtr = (ResolvedNsName *)srcPtr->internalRep.twoPtrValue.ptr1;
4677
4678 copyPtr->internalRep.twoPtrValue.ptr1 = resNamePtr;
4679 resNamePtr->refCount++;
4680 copyPtr->typePtr = &nsNameType;
4681 }
4682
4683 /*
4684 *----------------------------------------------------------------------
4685 *
4686 * SetNsNameFromAny --
4687 *
4688 * Attempt to generate a nsName internal representation for a Tcl object.
4689 *
4690 * Results:
4691 * Returns TCL_OK if the value could be converted to a proper namespace
4692 * reference. Otherwise, it returns TCL_ERROR, along with an error
4693 * message in the interpreter's result object.
4694 *
4695 * Side effects:
4696 * If successful, the object is made a nsName object. Its internal rep is
4697 * set to point to a ResolvedNsName, which contains a cached pointer to
4698 * the Namespace. Reference counts are kept on both the ResolvedNsName
4699 * and the Namespace, so we can keep track of their usage and free them
4700 * when appropriate.
4701 *
4702 *----------------------------------------------------------------------
4703 */
4704
4705 static int
4706 SetNsNameFromAny(
4707 Tcl_Interp *interp, /* Points to the namespace in which to resolve
4708 * name. Also used for error reporting if not
4709 * NULL. */
4710 Tcl_Obj *objPtr) /* The object to convert. */
4711 {
4712 const char *dummy;
4713 Namespace *nsPtr, *dummy1Ptr, *dummy2Ptr;
4714 ResolvedNsName *resNamePtr;
4715 const char *name;
4716
4717 if (interp == NULL) {
4718 return TCL_ERROR;
4719 }
4720
4721 name = TclGetString(objPtr);
4722 TclGetNamespaceForQualName(interp, name, NULL, TCL_FIND_ONLY_NS,
4723 &nsPtr, &dummy1Ptr, &dummy2Ptr, &dummy);
4724
4725 /*
4726 * If we found a namespace, then create a new ResolvedNsName structure
4727 * that holds a reference to it.
4728 */
4729
4730 if ((nsPtr == NULL) || (nsPtr->flags & NS_DYING)) {
4731 /*
4732 * Our failed lookup proves any previously cached nsName internalrep is no
4733 * longer valid. Get rid of it so we no longer waste memory storing
4734 * it, nor time determining its invalidity again and again.
4735 */
4736
4737 if (objPtr->typePtr == &nsNameType) {
4738 TclFreeIntRep(objPtr);
4739 }
4740 return TCL_ERROR;
4741 }
4742
4743 nsPtr->refCount++;
4744 resNamePtr = (ResolvedNsName *)ckalloc(sizeof(ResolvedNsName));
4745 resNamePtr->nsPtr = nsPtr;
4746 if ((name[0] == ':') && (name[1] == ':')) {
4747 resNamePtr->refNsPtr = NULL;
4748 } else {
4749 resNamePtr->refNsPtr = (Namespace *)Tcl_GetCurrentNamespace(interp);
4750 }
4751 resNamePtr->refCount = 1;
4752 TclFreeIntRep(objPtr);
4753 objPtr->internalRep.twoPtrValue.ptr1 = resNamePtr;
4754 objPtr->typePtr = &nsNameType;
4755 return TCL_OK;
4756 }
4757
4758 /*
4759 *----------------------------------------------------------------------
4760 *
4761 * TclGetNamespaceCommandTable --
4762 *
4763 * Returns the hash table of commands.
4764 *
4765 * Results:
4766 * Pointer to the hash table.
4767 *
4768 * Side effects:
4769 * None.
4770 *
4771 *----------------------------------------------------------------------
4772 */
4773
4774 Tcl_HashTable *
4775 TclGetNamespaceCommandTable(
4776 Tcl_Namespace *nsPtr)
4777 {
4778 return &((Namespace *) nsPtr)->cmdTable;
4779 }
4780
4781 /*
4782 *----------------------------------------------------------------------
4783 *
4784 * TclGetNamespaceChildTable --
4785 *
4786 * Returns the hash table of child namespaces.
4787 *
4788 * Results:
4789 * Pointer to the hash table.
4790 *
4791 * Side effects:
4792 * Might allocate memory.
4793 *
4794 *----------------------------------------------------------------------
4795 */
4796
4797 Tcl_HashTable *
4798 TclGetNamespaceChildTable(
4799 Tcl_Namespace *nsPtr)
4800 {
4801 Namespace *nPtr = (Namespace *) nsPtr;
4802 return &nPtr->childTable;
4803 }
4804
4805 /*
4806 *----------------------------------------------------------------------
4807 *
4808 * TclLogCommandInfo --
4809 *
4810 * Invoked after an error occurs in an interpreter.
4811 * Adds information to iPtr->errorInfo/errorStack fields to describe the
4812 * command that was being executed when the error occurred. When pc and
4813 * tosPtr are non-NULL, conveying a bytecode execution "inner context",
4814 * and the offending instruction is suitable, and that inner context is
4815 * recorded in errorStack.
4816 *
4817 * Results:
4818 * None.
4819 *
4820 * Side effects:
4821 * Information about the command is added to errorInfo/errorStack and the
4822 * line number stored internally in the interpreter is set.
4823 *
4824 *----------------------------------------------------------------------
4825 */
4826
4827 void
4828 TclLogCommandInfo(
4829 Tcl_Interp *interp, /* Interpreter in which to log information. */
4830 const char *script, /* First character in script containing
4831 * command (must be <= command). */
4832 const char *command, /* First character in command that generated
4833 * the error. */
4834 int length, /* Number of bytes in command (-1 means use
4835 * all bytes up to first null byte). */
4836 const unsigned char *pc, /* Current pc of bytecode execution context */
4837 Tcl_Obj **tosPtr) /* Current stack of bytecode execution
4838 * context */
4839 {
4840 const char *p;
4841 Interp *iPtr = (Interp *) interp;
4842 int overflow, limit = 150;
4843 Var *varPtr, *arrayPtr;
4844
4845 if (iPtr->flags & ERR_ALREADY_LOGGED) {
4846 /*
4847 * Someone else has already logged error information for this command.
4848 * Don't add anything more.
4849 */
4850
4851 return;
4852 }
4853
4854 if (command != NULL) {
4855 /*
4856 * Compute the line number where the error occurred.
4857 */
4858
4859 iPtr->errorLine = 1;
4860 for (p = script; p != command; p++) {
4861 if (*p == '\n') {
4862 iPtr->errorLine++;
4863 }
4864 }
4865
4866 if (length < 0) {
4867 length = strlen(command);
4868 }
4869 overflow = (length > limit);
4870 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
4871 "\n %s\n\"%.*s%s\"", ((iPtr->errorInfo == NULL)
4872 ? "while executing" : "invoked from within"),
4873 (overflow ? limit : length), command,
4874 (overflow ? "..." : "")));
4875
4876 varPtr = TclObjLookupVarEx(interp, iPtr->eiVar, NULL, TCL_GLOBAL_ONLY,
4877 NULL, 0, 0, &arrayPtr);
4878 if ((varPtr == NULL) || !TclIsVarTraced(varPtr)) {
4879 /*
4880 * Should not happen.
4881 */
4882
4883 return;
4884 } else {
4885 Tcl_HashEntry *hPtr
4886 = Tcl_FindHashEntry(&iPtr->varTraces, (char *)varPtr);
4887 VarTrace *tracePtr = (VarTrace *)Tcl_GetHashValue(hPtr);
4888
4889 if (tracePtr->traceProc != EstablishErrorInfoTraces) {
4890 /*
4891 * The most recent trace set on ::errorInfo is not the one the
4892 * core itself puts on last. This means some other code is
4893 * tracing the variable, and the additional trace(s) might be
4894 * write traces that expect the timing of writes to
4895 * ::errorInfo that existed Tcl releases before 8.5. To
4896 * satisfy that compatibility need, we write the current
4897 * -errorinfo value to the ::errorInfo variable.
4898 */
4899
4900 Tcl_ObjSetVar2(interp, iPtr->eiVar, NULL, iPtr->errorInfo,
4901 TCL_GLOBAL_ONLY);
4902 }
4903 }
4904 }
4905
4906 /*
4907 * TIP #348
4908 */
4909
4910 if (Tcl_IsShared(iPtr->errorStack)) {
4911 Tcl_Obj *newObj;
4912
4913 newObj = Tcl_DuplicateObj(iPtr->errorStack);
4914 Tcl_DecrRefCount(iPtr->errorStack);
4915 Tcl_IncrRefCount(newObj);
4916 iPtr->errorStack = newObj;
4917 }
4918 if (iPtr->resetErrorStack) {
4919 int len;
4920
4921 iPtr->resetErrorStack = 0;
4922 TclListObjLength(interp, iPtr->errorStack, &len);
4923
4924 /*
4925 * Reset while keeping the list internalrep as much as possible.
4926 */
4927
4928 Tcl_ListObjReplace(interp, iPtr->errorStack, 0, len, 0, NULL);
4929 if (pc != NULL) {
4930 Tcl_Obj *innerContext;
4931
4932 innerContext = TclGetInnerContext(interp, pc, tosPtr);
4933 if (innerContext != NULL) {
4934 Tcl_ListObjAppendElement(NULL, iPtr->errorStack,
4935 iPtr->innerLiteral);
4936 Tcl_ListObjAppendElement(NULL, iPtr->errorStack, innerContext);
4937 }
4938 } else if (command != NULL) {
4939 Tcl_ListObjAppendElement(NULL, iPtr->errorStack,
4940 iPtr->innerLiteral);
4941 Tcl_ListObjAppendElement(NULL, iPtr->errorStack,
4942 Tcl_NewStringObj(command, length));
4943 }
4944 }
4945
4946 if (!iPtr->framePtr->objc) {
4947 /*
4948 * Special frame, nothing to report.
4949 */
4950 } else if (iPtr->varFramePtr != iPtr->framePtr) {
4951 /*
4952 * uplevel case, [lappend errorstack UP $relativelevel]
4953 */
4954
4955 Tcl_ListObjAppendElement(NULL, iPtr->errorStack, iPtr->upLiteral);
4956 Tcl_ListObjAppendElement(NULL, iPtr->errorStack, Tcl_NewIntObj(
4957 iPtr->framePtr->level - iPtr->varFramePtr->level));
4958 } else if (iPtr->framePtr != iPtr->rootFramePtr) {
4959 /*
4960 * normal case, [lappend errorstack CALL [info level 0]]
4961 */
4962
4963 Tcl_ListObjAppendElement(NULL, iPtr->errorStack, iPtr->callLiteral);
4964 Tcl_ListObjAppendElement(NULL, iPtr->errorStack, Tcl_NewListObj(
4965 iPtr->framePtr->objc, iPtr->framePtr->objv));
4966 }
4967 }
4968
4969 /*
4970 *----------------------------------------------------------------------
4971 *
4972 * TclErrorStackResetIf --
4973 *
4974 * The TIP 348 reset/no-bc part of TLCI, for specific use by
4975 * TclCompileSyntaxError.
4976 *
4977 * Results:
4978 * None.
4979 *
4980 * Side effects:
4981 * Reset errorstack if it needs be, and in that case remember the
4982 * passed-in error message as inner context.
4983 *
4984 *----------------------------------------------------------------------
4985 */
4986
4987 void
4988 TclErrorStackResetIf(
4989 Tcl_Interp *interp,
4990 const char *msg,
4991 int length)
4992 {
4993 Interp *iPtr = (Interp *) interp;
4994
4995 if (Tcl_IsShared(iPtr->errorStack)) {
4996 Tcl_Obj *newObj;
4997
4998 newObj = Tcl_DuplicateObj(iPtr->errorStack);
4999 Tcl_DecrRefCount(iPtr->errorStack);
5000 Tcl_IncrRefCount(newObj);
5001 iPtr->errorStack = newObj;
5002 }
5003 if (iPtr->resetErrorStack) {
5004 int len;
5005
5006 iPtr->resetErrorStack = 0;
5007 TclListObjLength(interp, iPtr->errorStack, &len);
5008
5009 /*
5010 * Reset while keeping the list internalrep as much as possible.
5011 */
5012
5013 Tcl_ListObjReplace(interp, iPtr->errorStack, 0, len, 0, NULL);
5014 Tcl_ListObjAppendElement(NULL, iPtr->errorStack, iPtr->innerLiteral);
5015 Tcl_ListObjAppendElement(NULL, iPtr->errorStack,
5016 Tcl_NewStringObj(msg, length));
5017 }
5018 }
5019
5020 /*
5021 *----------------------------------------------------------------------
5022 *
5023 * Tcl_LogCommandInfo --
5024 *
5025 * This function is invoked after an error occurs in an interpreter. It
5026 * adds information to iPtr->errorInfo/errorStack fields to describe the
5027 * command that was being executed when the error occurred.
5028 *
5029 * Results:
5030 * None.
5031 *
5032 * Side effects:
5033 * Information about the command is added to errorInfo/errorStack and the
5034 * line number stored internally in the interpreter is set.
5035 *
5036 *----------------------------------------------------------------------
5037 */
5038
5039 void
5040 Tcl_LogCommandInfo(
5041 Tcl_Interp *interp, /* Interpreter in which to log information. */
5042 const char *script, /* First character in script containing
5043 * command (must be <= command). */
5044 const char *command, /* First character in command that generated
5045 * the error. */
5046 int length) /* Number of bytes in command (-1 means use
5047 * all bytes up to first null byte). */
5048 {
5049 TclLogCommandInfo(interp, script, command, length, NULL, NULL);
5050 }
5051
5052 /*
5053 * Local Variables:
5054 * mode: c
5055 * c-basic-offset: 4
5056 * fill-column: 78
5057 * tab-width: 8
5058 * End:
5059 */