Debian Codegraph @

generic/tclVar.c

raw
1 /*
2 * tclVar.c --
3 *
4 * This file contains routines that implement Tcl variables (both scalars
5 * and arrays).
6 *
7 * The implementation of arrays is modelled after an initial
8 * implementation by Mark Diekhans and Karl Lehenbauer.
9 *
10 * Copyright (c) 1987-1994 The Regents of the University of California.
11 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
12 * Copyright (c) 1998-1999 Scriptics Corporation.
13 * Copyright (c) 2001 Kevin B. Kenny. All rights reserved.
14 * Copyright (c) 2007 Miguel Sofer
15 *
16 * See the file "license.terms" for information on usage and redistribution of
17 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
18 */
19
20 #include "tclInt.h"
21 #include "tclOOInt.h"
22
23 /*
24 * Prototypes for the variable hash key methods.
25 */
26
27 static Tcl_HashEntry * AllocVarEntry(Tcl_HashTable *tablePtr, void *keyPtr);
28 static void FreeVarEntry(Tcl_HashEntry *hPtr);
29 static int CompareVarKeys(void *keyPtr, Tcl_HashEntry *hPtr);
30
31 static const Tcl_HashKeyType tclVarHashKeyType = {
32 TCL_HASH_KEY_TYPE_VERSION, /* version */
33 TCL_HASH_KEY_DIRECT_COMPARE,/* allows compare keys by pointers */
34 TclHashObjKey, /* hashKeyProc */
35 CompareVarKeys, /* compareKeysProc */
36 AllocVarEntry, /* allocEntryProc */
37 FreeVarEntry /* freeEntryProc */
38 };
39
40 static inline Var * VarHashCreateVar(TclVarHashTable *tablePtr,
41 Tcl_Obj *key, int *newPtr);
42 static inline Var * VarHashFirstVar(TclVarHashTable *tablePtr,
43 Tcl_HashSearch *searchPtr);
44 static inline Var * VarHashNextVar(Tcl_HashSearch *searchPtr);
45 static inline void CleanupVar(Var *varPtr, Var *arrayPtr);
46
47 #define VarHashGetValue(hPtr) \
48 ((Var *) ((char *)hPtr - TclOffset(VarInHash, entry)))
49
50 /*
51 * NOTE: VarHashCreateVar increments the recount of its key argument.
52 * All callers that will call Tcl_DecrRefCount on that argument must
53 * call Tcl_IncrRefCount on it before passing it in. This requirement
54 * can bubble up to callers of callers .... etc.
55 */
56
57 static inline Var *
58 VarHashCreateVar(
59 TclVarHashTable *tablePtr,
60 Tcl_Obj *key,
61 int *newPtr)
62 {
63 Tcl_HashEntry *hPtr = Tcl_CreateHashEntry(&tablePtr->table,
64 key, newPtr);
65
66 if (!hPtr) {
67 return NULL;
68 }
69 return VarHashGetValue(hPtr);
70 }
71
72 #define VarHashFindVar(tablePtr, key) \
73 VarHashCreateVar((tablePtr), (key), NULL)
74
75 #define VarHashInvalidateEntry(varPtr) \
76 ((varPtr)->flags |= VAR_DEAD_HASH)
77
78 #define VarHashDeleteEntry(varPtr) \
79 Tcl_DeleteHashEntry(&(((VarInHash *) varPtr)->entry))
80
81 #define VarHashFirstEntry(tablePtr, searchPtr) \
82 Tcl_FirstHashEntry(&(tablePtr)->table, (searchPtr))
83
84 #define VarHashNextEntry(searchPtr) \
85 Tcl_NextHashEntry((searchPtr))
86
87 static inline Var *
88 VarHashFirstVar(
89 TclVarHashTable *tablePtr,
90 Tcl_HashSearch *searchPtr)
91 {
92 Tcl_HashEntry *hPtr = VarHashFirstEntry(tablePtr, searchPtr);
93
94 if (!hPtr) {
95 return NULL;
96 }
97 return VarHashGetValue(hPtr);
98 }
99
100 static inline Var *
101 VarHashNextVar(
102 Tcl_HashSearch *searchPtr)
103 {
104 Tcl_HashEntry *hPtr = VarHashNextEntry(searchPtr);
105
106 if (!hPtr) {
107 return NULL;
108 }
109 return VarHashGetValue(hPtr);
110 }
111
112 #define VarHashGetKey(varPtr) \
113 (((VarInHash *)(varPtr))->entry.key.objPtr)
114
115 #define VarHashDeleteTable(tablePtr) \
116 Tcl_DeleteHashTable(&(tablePtr)->table)
117
118 /*
119 * The strings below are used to indicate what went wrong when a variable
120 * access is denied.
121 */
122
123 static const char NOSUCHVAR[] = "no such variable";
124 static const char ISARRAY[] = "variable is array";
125 static const char NEEDARRAY[] = "variable isn't array";
126 static const char NOSUCHELEMENT[] = "no such element in array";
127 static const char DANGLINGELEMENT[] =
128 "upvar refers to element in deleted array";
129 static const char DANGLINGVAR[] =
130 "upvar refers to variable in deleted namespace";
131 static const char BADNAMESPACE[] = "parent namespace doesn't exist";
132 static const char MISSINGNAME[] = "missing variable name";
133 static const char ISARRAYELEMENT[] =
134 "name refers to an element in an array";
135
136 /*
137 * A test to see if we are in a call frame that has local variables. This is
138 * true if we are inside a procedure body.
139 */
140
141 #define HasLocalVars(framePtr) ((framePtr)->isProcCallFrame & FRAME_IS_PROC)
142
143 /*
144 * The following structure describes an enumerative search in progress on an
145 * array variable; this are invoked with options to the "array" command.
146 */
147
148 typedef struct ArraySearch {
149 int id; /* Integer id used to distinguish among
150 * multiple concurrent searches for the same
151 * array. */
152 struct Var *varPtr; /* Pointer to array variable that's being
153 * searched. */
154 Tcl_HashSearch search; /* Info kept by the hash module about progress
155 * through the array. */
156 Tcl_HashEntry *nextEntry; /* Non-null means this is the next element to
157 * be enumerated (it's leftover from the
158 * Tcl_FirstHashEntry call or from an "array
159 * anymore" command). NULL means must call
160 * Tcl_NextHashEntry to get value to
161 * return. */
162 struct ArraySearch *nextPtr;/* Next in list of all active searches for
163 * this variable, or NULL if this is the last
164 * one. */
165 } ArraySearch;
166
167 /*
168 * Forward references to functions defined later in this file:
169 */
170
171 static void AppendLocals(Tcl_Interp *interp, Tcl_Obj *listPtr,
172 Tcl_Obj *patternPtr, int includeLinks);
173 static void DeleteSearches(Interp *iPtr, Var *arrayVarPtr);
174 static void DeleteArray(Interp *iPtr, Tcl_Obj *arrayNamePtr,
175 Var *varPtr, int flags, int index);
176 static int LocateArray(Tcl_Interp *interp, Tcl_Obj *name,
177 Var **varPtrPtr, int *isArrayPtr);
178 static int NotArrayError(Tcl_Interp *interp, Tcl_Obj *name);
179 static Tcl_Var ObjFindNamespaceVar(Tcl_Interp *interp,
180 Tcl_Obj *namePtr, Tcl_Namespace *contextNsPtr,
181 int flags);
182 static int ObjMakeUpvar(Tcl_Interp *interp,
183 CallFrame *framePtr, Tcl_Obj *otherP1Ptr,
184 const char *otherP2, int otherFlags,
185 Tcl_Obj *myNamePtr, int myFlags, int index);
186 static ArraySearch * ParseSearchId(Tcl_Interp *interp, const Var *varPtr,
187 Tcl_Obj *varNamePtr, Tcl_Obj *handleObj);
188 static void UnsetVarStruct(Var *varPtr, Var *arrayPtr,
189 Interp *iPtr, Tcl_Obj *part1Ptr,
190 Tcl_Obj *part2Ptr, int flags, int index);
191 static int SetArraySearchObj(Tcl_Interp *interp,
192 Tcl_Obj *objPtr);
193
194 /*
195 * Functions defined in this file that may be exported in the future for use
196 * by the bytecode compiler and engine or to the public interface.
197 */
198
199 MODULE_SCOPE Var * TclLookupSimpleVar(Tcl_Interp *interp,
200 Tcl_Obj *varNamePtr, int flags, int create,
201 const char **errMsgPtr, int *indexPtr);
202
203 static Tcl_DupInternalRepProc DupLocalVarName;
204 static Tcl_FreeInternalRepProc FreeLocalVarName;
205 static Tcl_UpdateStringProc PanicOnUpdateVarName;
206
207 static Tcl_FreeInternalRepProc FreeParsedVarName;
208 static Tcl_DupInternalRepProc DupParsedVarName;
209 static Tcl_UpdateStringProc UpdateParsedVarName;
210
211 static Tcl_UpdateStringProc PanicOnUpdateVarName;
212 static Tcl_SetFromAnyProc PanicOnSetVarName;
213
214 /*
215 * Types of Tcl_Objs used to cache variable lookups.
216 *
217 * localVarName - INTERNALREP DEFINITION:
218 * twoPtrValue.ptr1: pointer to name obj in varFramePtr->localCache
219 * or NULL if it is this same obj
220 * twoPtrValue.ptr2: index into locals table
221 *
222 * parsedVarName - INTERNALREP DEFINITION:
223 * twoPtrValue.ptr1: pointer to the array name Tcl_Obj, or NULL if it is a
224 * scalar variable
225 * twoPtrValue.ptr2: pointer to the element name string (owned by this
226 * Tcl_Obj), or NULL if it is a scalar variable
227 */
228
229 static const Tcl_ObjType localVarNameType = {
230 "localVarName",
231 FreeLocalVarName, DupLocalVarName, PanicOnUpdateVarName, PanicOnSetVarName
232 };
233
234 static const Tcl_ObjType tclParsedVarNameType = {
235 "parsedVarName",
236 FreeParsedVarName, DupParsedVarName, UpdateParsedVarName, PanicOnSetVarName
237 };
238
239 /*
240 * Type of Tcl_Objs used to speed up array searches.
241 *
242 * INTERNALREP DEFINITION:
243 * twoPtrValue.ptr1: searchIdNumber (cast to pointer)
244 * twoPtrValue.ptr2: variableNameStartInString (cast to pointer)
245 *
246 * Note that the value stored in ptr2 is the offset into the string of the
247 * start of the variable name and not the address of the variable name itself,
248 * as this can be safely copied.
249 */
250
251 const Tcl_ObjType tclArraySearchType = {
252 "array search",
253 NULL, NULL, NULL, SetArraySearchObj
254 };
255
256 Var *
257 TclVarHashCreateVar(
258 TclVarHashTable *tablePtr,
259 const char *key,
260 int *newPtr)
261 {
262 Tcl_Obj *keyPtr;
263 Var *varPtr;
264
265 keyPtr = Tcl_NewStringObj(key, -1);
266 Tcl_IncrRefCount(keyPtr);
267 varPtr = VarHashCreateVar(tablePtr, keyPtr, newPtr);
268 Tcl_DecrRefCount(keyPtr);
269
270 return varPtr;
271 }
272
273 static int
274 LocateArray(
275 Tcl_Interp *interp,
276 Tcl_Obj *name,
277 Var **varPtrPtr,
278 int *isArrayPtr)
279 {
280 Var *arrayPtr, *varPtr = TclObjLookupVarEx(interp, name, NULL, /*flags*/ 0,
281 /*msg*/ 0, /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr);
282
283 if (TclCheckArrayTraces(interp, varPtr, arrayPtr, name, -1) == TCL_ERROR) {
284 return TCL_ERROR;
285 }
286 if (varPtrPtr) {
287 *varPtrPtr = varPtr;
288 }
289 if (isArrayPtr) {
290 *isArrayPtr = varPtr && !TclIsVarUndefined(varPtr)
291 && TclIsVarArray(varPtr);
292 }
293 return TCL_OK;
294 }
295
296 static int
297 NotArrayError(
298 Tcl_Interp *interp,
299 Tcl_Obj *name)
300 {
301 const char *nameStr = TclGetString(name);
302
303 Tcl_SetObjResult(interp,
304 Tcl_ObjPrintf("\"%s\" isn't an array", nameStr));
305 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "ARRAY", nameStr, (char *)NULL);
306 return TCL_ERROR;
307 }
308
309 /*
310 *----------------------------------------------------------------------
311 *
312 * TclCleanupVar --
313 *
314 * This function is called when it looks like it may be OK to free up a
315 * variable's storage. If the variable is in a hashtable, its Var
316 * structure and hash table entry will be freed along with those of its
317 * containing array, if any. This function is called, for example, when
318 * a trace on a variable deletes a variable.
319 *
320 * Results:
321 * None.
322 *
323 * Side effects:
324 * If the variable (or its containing array) really is dead and in a
325 * hashtable, then its Var structure, and possibly its hash table entry,
326 * is freed up.
327 *
328 *----------------------------------------------------------------------
329 */
330
331 static inline void
332 CleanupVar(
333 Var *varPtr, /* Pointer to variable that may be a candidate
334 * for being expunged. */
335 Var *arrayPtr) /* Array that contains the variable, or NULL
336 * if this variable isn't an array element. */
337 {
338 if (TclIsVarUndefined(varPtr) && TclIsVarInHash(varPtr)
339 && !TclIsVarTraced(varPtr)
340 && (VarHashRefCount(varPtr) == !TclIsVarDeadHash(varPtr))) {
341 if (VarHashRefCount(varPtr) == 0) {
342 ckfree(varPtr);
343 } else {
344 VarHashDeleteEntry(varPtr);
345 }
346 }
347 if (arrayPtr != NULL && TclIsVarUndefined(arrayPtr) &&
348 TclIsVarInHash(arrayPtr) && !TclIsVarTraced(arrayPtr) &&
349 (VarHashRefCount(arrayPtr) == !TclIsVarDeadHash(arrayPtr))) {
350 if (VarHashRefCount(arrayPtr) == 0) {
351 ckfree(arrayPtr);
352 } else {
353 VarHashDeleteEntry(arrayPtr);
354 }
355 }
356 }
357
358 void
359 TclCleanupVar(
360 Var *varPtr, /* Pointer to variable that may be a candidate
361 * for being expunged. */
362 Var *arrayPtr) /* Array that contains the variable, or NULL
363 * if this variable isn't an array element. */
364 {
365 CleanupVar(varPtr, arrayPtr);
366 }
367
368 /*
369 *----------------------------------------------------------------------
370 *
371 * TclLookupVar --
372 *
373 * This function is used to locate a variable given its name(s). It has
374 * been mostly superseded by TclObjLookupVar, it is now only used by the
375 * trace code. It is kept in tcl8.5 mainly because it is in the internal
376 * stubs table, so that some extension may be calling it.
377 *
378 * Results:
379 * The return value is a pointer to the variable structure indicated by
380 * part1 and part2, or NULL if the variable couldn't be found. If the
381 * variable is found, *arrayPtrPtr is filled in with the address of the
382 * variable structure for the array that contains the variable (or NULL
383 * if the variable is a scalar). If the variable can't be found and
384 * either createPart1 or createPart2 are 1, a new as-yet-undefined
385 * (VAR_UNDEFINED) variable structure is created, entered into a hash
386 * table, and returned.
387 *
388 * If the variable isn't found and creation wasn't specified, or some
389 * other error occurs, NULL is returned and an error message is left in
390 * the interp's result if TCL_LEAVE_ERR_MSG is set in flags.
391 *
392 * Note: it's possible for the variable returned to be VAR_UNDEFINED even
393 * if createPart1 or createPart2 are 1 (these only cause the hash table
394 * entry or array to be created). For example, the variable might be a
395 * global that has been unset but is still referenced by a procedure, or
396 * a variable that has been unset but it only being kept in existence (if
397 * VAR_UNDEFINED) by a trace.
398 *
399 * Side effects:
400 * New hashtable entries may be created if createPart1 or createPart2
401 * are 1.
402 *
403 *----------------------------------------------------------------------
404 */
405
406 Var *
407 TclLookupVar(
408 Tcl_Interp *interp, /* Interpreter to use for lookup. */
409 const char *part1, /* If part2 isn't NULL, this is the name of an
410 * array. Otherwise, this is a full variable
411 * name that could include a parenthesized
412 * array element. */
413 const char *part2, /* Name of element within array, or NULL. */
414 int flags, /* Only TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
415 * and TCL_LEAVE_ERR_MSG bits matter. */
416 const char *msg, /* Verb to use in error messages, e.g. "read"
417 * or "set". Only needed if TCL_LEAVE_ERR_MSG
418 * is set in flags. */
419 int createPart1, /* If 1, create hash table entry for part 1 of
420 * name, if it doesn't already exist. If 0,
421 * return error if it doesn't exist. */
422 int createPart2, /* If 1, create hash table entry for part 2 of
423 * name, if it doesn't already exist. If 0,
424 * return error if it doesn't exist. */
425 Var **arrayPtrPtr) /* If the name refers to an element of an
426 * array, *arrayPtrPtr gets filled in with
427 * address of array variable. Otherwise this
428 * is set to NULL. */
429 {
430 Var *varPtr;
431 Tcl_Obj *part1Ptr = Tcl_NewStringObj(part1, -1);
432
433 if (createPart1) {
434 Tcl_IncrRefCount(part1Ptr);
435 }
436
437 varPtr = TclObjLookupVar(interp, part1Ptr, part2, flags, msg,
438 createPart1, createPart2, arrayPtrPtr);
439
440 TclDecrRefCount(part1Ptr);
441 return varPtr;
442 }
443
444 /*
445 *----------------------------------------------------------------------
446 *
447 * TclObjLookupVar, TclObjLookupVarEx --
448 *
449 * This function is used by virtually all of the variable code to locate
450 * a variable given its name(s). The parsing into array/element
451 * components and (if possible) the lookup results are cached in
452 * part1Ptr, which is converted to one of the varNameTypes.
453 *
454 * Results:
455 * The return value is a pointer to the variable structure indicated by
456 * part1Ptr and part2, or NULL if the variable couldn't be found. If *
457 * the variable is found, *arrayPtrPtr is filled with the address of the
458 * variable structure for the array that contains the variable (or NULL
459 * if the variable is a scalar). If the variable can't be found and
460 * either createPart1 or createPart2 are 1, a new as-yet-undefined
461 * (VAR_UNDEFINED) variable structure is created, entered into a hash
462 * table, and returned.
463 *
464 * If the variable isn't found and creation wasn't specified, or some
465 * other error occurs, NULL is returned and an error message is left in
466 * the interp's result if TCL_LEAVE_ERR_MSG is set in flags.
467 *
468 * Note: it's possible for the variable returned to be VAR_UNDEFINED even
469 * if createPart1 or createPart2 are 1 (these only cause the hash table
470 * entry or array to be created). For example, the variable might be a
471 * global that has been unset but is still referenced by a procedure, or
472 * a variable that has been unset but it only being kept in existence (if
473 * VAR_UNDEFINED) by a trace.
474 *
475 * Side effects:
476 * New hashtable entries may be created if createPart1 or createPart2
477 * are 1. The object part1Ptr is converted to one of localVarNameType,
478 * tclNsVarNameType or tclParsedVarNameType and caches as much of the
479 * lookup as it can.
480 * When createPart1 is 1, callers must IncrRefCount part1Ptr if they
481 * plan to DecrRefCount it.
482 *
483 *----------------------------------------------------------------------
484 */
485
486 Var *
487 TclObjLookupVar(
488 Tcl_Interp *interp, /* Interpreter to use for lookup. */
489 Tcl_Obj *part1Ptr, /* If part2 isn't NULL, this is the name of an
490 * array. Otherwise, this is a full variable
491 * name that could include a parenthesized
492 * array element. */
493 const char *part2, /* Name of element within array, or NULL. */
494 int flags, /* Only TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
495 * and TCL_LEAVE_ERR_MSG bits matter. */
496 const char *msg, /* Verb to use in error messages, e.g. "read"
497 * or "set". Only needed if TCL_LEAVE_ERR_MSG
498 * is set in flags. */
499 int createPart1, /* If 1, create hash table entry for part 1 of
500 * name, if it doesn't already exist. If 0,
501 * return error if it doesn't exist. */
502 int createPart2, /* If 1, create hash table entry for part 2 of
503 * name, if it doesn't already exist. If 0,
504 * return error if it doesn't exist. */
505 Var **arrayPtrPtr) /* If the name refers to an element of an
506 * array, *arrayPtrPtr gets filled in with
507 * address of array variable. Otherwise this
508 * is set to NULL. */
509 {
510 Tcl_Obj *part2Ptr = NULL;
511 Var *resPtr;
512
513 if (part2) {
514 part2Ptr = Tcl_NewStringObj(part2, -1);
515 if (createPart2) {
516 Tcl_IncrRefCount(part2Ptr);
517 }
518 }
519
520 resPtr = TclObjLookupVarEx(interp, part1Ptr, part2Ptr,
521 flags, msg, createPart1, createPart2, arrayPtrPtr);
522
523 if (part2Ptr) {
524 Tcl_DecrRefCount(part2Ptr);
525 }
526
527 return resPtr;
528 }
529
530 /*
531 * When createPart1 is 1, callers must IncrRefCount part1Ptr if they
532 * plan to DecrRefCount it.
533 * When createPart2 is 1, callers must IncrRefCount part2Ptr if they
534 * plan to DecrRefCount it.
535 */
536 Var *
537 TclObjLookupVarEx(
538 Tcl_Interp *interp, /* Interpreter to use for lookup. */
539 Tcl_Obj *part1Ptr, /* If part2Ptr isn't NULL, this is the name of
540 * an array. Otherwise, this is a full
541 * variable name that could include a
542 * parenthesized array element. */
543 Tcl_Obj *part2Ptr, /* Name of element within array, or NULL. */
544 int flags, /* Only TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
545 * and TCL_LEAVE_ERR_MSG bits matter. */
546 const char *msg, /* Verb to use in error messages, e.g. "read"
547 * or "set". Only needed if TCL_LEAVE_ERR_MSG
548 * is set in flags. */
549 int createPart1, /* If 1, create hash table entry for part 1 of
550 * name, if it doesn't already exist. If 0,
551 * return error if it doesn't exist. */
552 int createPart2, /* If 1, create hash table entry for part 2 of
553 * name, if it doesn't already exist. If 0,
554 * return error if it doesn't exist. */
555 Var **arrayPtrPtr) /* If the name refers to an element of an
556 * array, *arrayPtrPtr gets filled in with
557 * address of array variable. Otherwise this
558 * is set to NULL. */
559 {
560 Interp *iPtr = (Interp *) interp;
561 Var *varPtr; /* Points to the variable's in-frame Var
562 * structure. */
563 const char *part1;
564 int index, len1, len2;
565 int parsed = 0;
566 Tcl_Obj *objPtr;
567 const Tcl_ObjType *typePtr = part1Ptr->typePtr;
568 const char *errMsg = NULL;
569 CallFrame *varFramePtr = iPtr->varFramePtr;
570 const char *part2 = part2Ptr? TclGetString(part2Ptr):NULL;
571 char *newPart2 = NULL;
572 *arrayPtrPtr = NULL;
573
574 if (typePtr == &localVarNameType) {
575 int localIndex;
576
577 localVarNameTypeHandling:
578 localIndex = PTR2INT(part1Ptr->internalRep.twoPtrValue.ptr2);
579 if (HasLocalVars(varFramePtr)
580 && !(flags & (TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY))
581 && (localIndex < varFramePtr->numCompiledLocals)) {
582 /*
583 * Use the cached index if the names coincide.
584 */
585
586 Tcl_Obj *namePtr = part1Ptr->internalRep.twoPtrValue.ptr1;
587 Tcl_Obj *checkNamePtr = localName(iPtr->varFramePtr, localIndex);
588
589 if ((!namePtr && (checkNamePtr == part1Ptr)) ||
590 (namePtr && (checkNamePtr == namePtr))) {
591 varPtr = (Var *) &(varFramePtr->compiledLocals[localIndex]);
592 goto donePart1;
593 }
594 }
595 goto doneParsing;
596 }
597
598 /*
599 * If part1Ptr is a tclParsedVarNameType, separate it into the preparsed
600 * parts.
601 */
602
603 if (typePtr == &tclParsedVarNameType) {
604 if (part1Ptr->internalRep.twoPtrValue.ptr1 != NULL) {
605 if (part2Ptr != NULL) {
606 /*
607 * ERROR: part1Ptr is already an array element, cannot specify
608 * a part2.
609 */
610
611 if (flags & TCL_LEAVE_ERR_MSG) {
612 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, msg,
613 NOSUCHVAR, -1);
614 Tcl_SetErrorCode(interp, "TCL", "VALUE", "VARNAME", (char *)NULL);
615 }
616 return NULL;
617 }
618 part2 = newPart2 = part1Ptr->internalRep.twoPtrValue.ptr2;
619 if (newPart2) {
620 part2Ptr = Tcl_NewStringObj(newPart2, -1);
621 if (createPart2) {
622 Tcl_IncrRefCount(part2Ptr);
623 }
624 }
625 part1Ptr = part1Ptr->internalRep.twoPtrValue.ptr1;
626 typePtr = part1Ptr->typePtr;
627 if (typePtr == &localVarNameType) {
628 goto localVarNameTypeHandling;
629 }
630 }
631 parsed = 1;
632 }
633 part1 = TclGetStringFromObj(part1Ptr, &len1);
634
635 if (!parsed && len1 && (*(part1 + len1 - 1) == ')')) {
636 /*
637 * part1Ptr is possibly an unparsed array element.
638 */
639
640 int i;
641
642 len2 = -1;
643 for (i = 0; i < len1; i++) {
644 if (*(part1 + i) == '(') {
645 if (part2Ptr != NULL) {
646 if (flags & TCL_LEAVE_ERR_MSG) {
647 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, msg,
648 NEEDARRAY, -1);
649 Tcl_SetErrorCode(interp, "TCL", "VALUE", "VARNAME",
650 (char *)NULL);
651 }
652 return NULL;
653 }
654
655 /*
656 * part1Ptr points to an array element; first copy the element
657 * name to a new string part2.
658 */
659
660 part2 = part1 + i + 1;
661 len2 = len1 - i - 2;
662 len1 = i;
663
664 newPart2 = ckalloc(len2 + 1);
665 memcpy(newPart2, part2, len2);
666 *(newPart2+len2) = '\0';
667 part2 = newPart2;
668 part2Ptr = Tcl_NewStringObj(newPart2, -1);
669 if (createPart2) {
670 Tcl_IncrRefCount(part2Ptr);
671 }
672
673 /*
674 * Free the internal rep of the original part1Ptr, now renamed
675 * objPtr, and set it to tclParsedVarNameType.
676 */
677
678 objPtr = part1Ptr;
679 TclFreeIntRep(objPtr);
680 objPtr->typePtr = &tclParsedVarNameType;
681
682 /*
683 * Define a new string object to hold the new part1Ptr, i.e.,
684 * the array name. Set the internal rep of objPtr, reset
685 * typePtr and part1 to contain the references to the array
686 * name.
687 */
688
689 TclNewStringObj(part1Ptr, part1, len1);
690 Tcl_IncrRefCount(part1Ptr);
691
692 objPtr->internalRep.twoPtrValue.ptr1 = part1Ptr;
693 objPtr->internalRep.twoPtrValue.ptr2 = (void *) part2;
694
695 typePtr = part1Ptr->typePtr;
696 part1 = TclGetString(part1Ptr);
697 break;
698 }
699 }
700 }
701
702 doneParsing:
703 /*
704 * part1Ptr is not an array element; look it up, and convert it to one of
705 * the cached types if possible.
706 */
707
708 TclFreeIntRep(part1Ptr);
709
710 varPtr = TclLookupSimpleVar(interp, part1Ptr, flags, createPart1,
711 &errMsg, &index);
712 if (varPtr == NULL) {
713 if ((errMsg != NULL) && (flags & TCL_LEAVE_ERR_MSG)) {
714 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, msg, errMsg, -1);
715 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
716 TclGetString(part1Ptr), (char *)NULL);
717 }
718 if (newPart2) {
719 Tcl_DecrRefCount(part2Ptr);
720 }
721 return NULL;
722 }
723
724 /*
725 * Cache the newly found variable if possible.
726 */
727
728 if (index >= 0) {
729 /*
730 * An indexed local variable.
731 */
732 Tcl_Obj *cachedNamePtr = localName(iPtr->varFramePtr, index);
733
734 part1Ptr->typePtr = &localVarNameType;
735 if (part1Ptr != cachedNamePtr) {
736 part1Ptr->internalRep.twoPtrValue.ptr1 = cachedNamePtr;
737 Tcl_IncrRefCount(cachedNamePtr);
738 if (cachedNamePtr->typePtr != &localVarNameType
739 || cachedNamePtr->internalRep.twoPtrValue.ptr1 != NULL) {
740 TclFreeIntRep(cachedNamePtr);
741 }
742 } else {
743 part1Ptr->internalRep.twoPtrValue.ptr1 = NULL;
744 }
745 part1Ptr->internalRep.twoPtrValue.ptr2 = INT2PTR(index);
746 } else {
747 /*
748 * At least mark part1Ptr as already parsed.
749 */
750
751 part1Ptr->typePtr = &tclParsedVarNameType;
752 part1Ptr->internalRep.twoPtrValue.ptr1 = NULL;
753 part1Ptr->internalRep.twoPtrValue.ptr2 = NULL;
754 }
755
756 donePart1:
757 while (TclIsVarLink(varPtr)) {
758 varPtr = varPtr->value.linkPtr;
759 }
760
761 if (part2Ptr != NULL) {
762 /*
763 * Array element sought: look it up.
764 */
765
766 *arrayPtrPtr = varPtr;
767 varPtr = TclLookupArrayElement(interp, part1Ptr, part2Ptr, flags, msg,
768 createPart1, createPart2, varPtr, -1);
769 if (newPart2) {
770 Tcl_DecrRefCount(part2Ptr);
771 }
772 }
773 return varPtr;
774 }
775
776 /*
777 *----------------------------------------------------------------------
778 *
779 * TclLookupSimpleVar --
780 *
781 * This function is used by to locate a simple variable (i.e., not an
782 * array element) given its name.
783 *
784 * Results:
785 * The return value is a pointer to the variable structure indicated by
786 * varName, or NULL if the variable couldn't be found. If the variable
787 * can't be found and create is 1, a new as-yet-undefined (VAR_UNDEFINED)
788 * variable structure is created, entered into a hash table, and
789 * returned.
790 *
791 * If the current CallFrame corresponds to a proc and the variable found
792 * is one of the compiledLocals, its index is placed in *indexPtr.
793 * Otherwise, *indexPtr will be set to (according to the needs of
794 * TclObjLookupVar):
795 * -1 a global reference
796 * -2 a reference to a namespace variable
797 * -3 a non-cacheable reference, i.e., one of:
798 * . non-indexed local var
799 * . a reference of unknown origin;
800 * . resolution by a namespace or interp resolver
801 *
802 * If the variable isn't found and creation wasn't specified, or some
803 * other error occurs, NULL is returned and the corresponding error
804 * message is left in *errMsgPtr.
805 *
806 * Note: it's possible for the variable returned to be VAR_UNDEFINED even
807 * if create is 1 (this only causes the hash table entry to be created).
808 * For example, the variable might be a global that has been unset but is
809 * still referenced by a procedure, or a variable that has been unset but
810 * it only being kept in existence (if VAR_UNDEFINED) by a trace.
811 *
812 * Side effects:
813 * A new hashtable entry may be created if create is 1.
814 * Callers must Incr varNamePtr if they plan to Decr it if create is 1.
815 *
816 *----------------------------------------------------------------------
817 */
818
819 Var *
820 TclLookupSimpleVar(
821 Tcl_Interp *interp, /* Interpreter to use for lookup. */
822 Tcl_Obj *varNamePtr, /* This is a simple variable name that could
823 * represent a scalar or an array. */
824 int flags, /* Only TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
825 * TCL_AVOID_RESOLVERS and TCL_LEAVE_ERR_MSG
826 * bits matter. */
827 int create, /* If 1, create hash table entry for varname,
828 * if it doesn't already exist. If 0, return
829 * error if it doesn't exist. */
830 const char **errMsgPtr,
831 int *indexPtr)
832 {
833 Interp *iPtr = (Interp *) interp;
834 CallFrame *varFramePtr = iPtr->varFramePtr;
835 /* Points to the procedure call frame whose
836 * variables are currently in use. Same as the
837 * current procedure's frame, if any, unless
838 * an "uplevel" is executing. */
839 TclVarHashTable *tablePtr; /* Points to the hashtable, if any, in which
840 * to look up the variable. */
841 Tcl_Var var; /* Used to search for global names. */
842 Var *varPtr; /* Points to the Var structure returned for
843 * the variable. */
844 Namespace *varNsPtr, *cxtNsPtr, *dummy1Ptr, *dummy2Ptr;
845 ResolverScheme *resPtr;
846 int isNew, i, result, varLen;
847 const char *varName = TclGetStringFromObj(varNamePtr, &varLen);
848
849 varPtr = NULL;
850 varNsPtr = NULL; /* Set non-NULL if a nonlocal variable. */
851 *indexPtr = -3;
852
853 if (flags & TCL_GLOBAL_ONLY) {
854 cxtNsPtr = iPtr->globalNsPtr;
855 } else {
856 cxtNsPtr = iPtr->varFramePtr->nsPtr;
857 }
858
859 /*
860 * If this namespace has a variable resolver, then give it first crack at
861 * the variable resolution. It may return a Tcl_Var value, it may signal
862 * to continue onward, or it may signal an error.
863 */
864
865 if ((cxtNsPtr->varResProc != NULL || iPtr->resolverPtr != NULL)
866 && !(flags & TCL_AVOID_RESOLVERS)) {
867 resPtr = iPtr->resolverPtr;
868 if (cxtNsPtr->varResProc) {
869 result = cxtNsPtr->varResProc(interp, varName,
870 (Tcl_Namespace *) cxtNsPtr, flags, &var);
871 } else {
872 result = TCL_CONTINUE;
873 }
874
875 while (result == TCL_CONTINUE && resPtr) {
876 if (resPtr->varResProc) {
877 result = resPtr->varResProc(interp, varName,
878 (Tcl_Namespace *) cxtNsPtr, flags, &var);
879 }
880 resPtr = resPtr->nextPtr;
881 }
882
883 if (result == TCL_OK) {
884 return (Var *) var;
885 } else if (result != TCL_CONTINUE) {
886 return NULL;
887 }
888 }
889
890 /*
891 * Look up varName. Look it up as either a namespace variable or as a
892 * local variable in a procedure call frame (varFramePtr). Interpret
893 * varName as a namespace variable if:
894 * 1) so requested by a TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY flag,
895 * 2) there is no active frame (we're at the global :: scope),
896 * 3) the active frame was pushed to define the namespace context for a
897 * "namespace eval" or "namespace inscope" command,
898 * 4) the name has namespace qualifiers ("::"s).
899 * Otherwise, if varName is a local variable, search first in the frame's
900 * array of compiler-allocated local variables, then in its hashtable for
901 * runtime-created local variables.
902 *
903 * If create and the variable isn't found, create the variable and, if
904 * necessary, create varFramePtr's local var hashtable.
905 */
906
907 if (((flags & (TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY)) != 0)
908 || !HasLocalVars(varFramePtr)
909 || (strstr(varName, "::") != NULL)) {
910 const char *tail;
911 int lookGlobal = (flags & TCL_GLOBAL_ONLY)
912 || (cxtNsPtr == iPtr->globalNsPtr)
913 || ((*varName == ':') && (*(varName+1) == ':'));
914
915 if (lookGlobal) {
916 *indexPtr = -1;
917 flags = (flags | TCL_GLOBAL_ONLY) & ~TCL_NAMESPACE_ONLY;
918 } else {
919 if (flags & TCL_AVOID_RESOLVERS) {
920 flags = (flags | TCL_NAMESPACE_ONLY);
921 }
922 if (flags & TCL_NAMESPACE_ONLY) {
923 *indexPtr = -2;
924 }
925 }
926
927 /*
928 * Don't pass TCL_LEAVE_ERR_MSG, we may yet create the variable, or
929 * otherwise generate our own error!
930 */
931
932 varPtr = (Var *) ObjFindNamespaceVar(interp, varNamePtr,
933 (Tcl_Namespace *) cxtNsPtr,
934 (flags | TCL_AVOID_RESOLVERS) & ~TCL_LEAVE_ERR_MSG);
935 if (varPtr == NULL) {
936 Tcl_Obj *tailPtr;
937
938 if (create) { /* Var wasn't found so create it. */
939 TclGetNamespaceForQualName(interp, varName, cxtNsPtr,
940 flags, &varNsPtr, &dummy1Ptr, &dummy2Ptr, &tail);
941 if (varNsPtr == NULL) {
942 *errMsgPtr = BADNAMESPACE;
943 return NULL;
944 } else if (tail == NULL) {
945 *errMsgPtr = MISSINGNAME;
946 return NULL;
947 }
948 if (tail != varName) {
949 tailPtr = Tcl_NewStringObj(tail, -1);
950 } else {
951 tailPtr = varNamePtr;
952 }
953 varPtr = VarHashCreateVar(&varNsPtr->varTable, tailPtr,
954 &isNew);
955 if (lookGlobal) {
956 /*
957 * The variable was created starting from the global
958 * namespace: a global reference is returned even if it
959 * wasn't explicitly requested.
960 */
961
962 *indexPtr = -1;
963 } else {
964 *indexPtr = -2;
965 }
966 } else { /* Var wasn't found and not to create it. */
967 *errMsgPtr = NOSUCHVAR;
968 return NULL;
969 }
970 }
971 } else { /* Local var: look in frame varFramePtr. */
972 int localCt = varFramePtr->numCompiledLocals;
973
974 if (localCt > 0) {
975 Tcl_Obj **objPtrPtr = &varFramePtr->localCachePtr->varName0;
976 const char *localNameStr;
977 int localLen;
978
979 for (i=0 ; i<localCt ; i++, objPtrPtr++) {
980 Tcl_Obj *objPtr = *objPtrPtr;
981
982 if (objPtr) {
983 localNameStr = TclGetStringFromObj(objPtr, &localLen);
984
985 if ((varLen == localLen) && (varName[0] == localNameStr[0])
986 && !memcmp(varName, localNameStr, varLen)) {
987 *indexPtr = i;
988 return (Var *) &varFramePtr->compiledLocals[i];
989 }
990 }
991 }
992 }
993 tablePtr = varFramePtr->varTablePtr;
994 if (create) {
995 if (tablePtr == NULL) {
996 tablePtr = (TclVarHashTable *)ckalloc(sizeof(TclVarHashTable));
997 TclInitVarHashTable(tablePtr, NULL);
998 varFramePtr->varTablePtr = tablePtr;
999 }
1000 varPtr = VarHashCreateVar(tablePtr, varNamePtr, &isNew);
1001 } else {
1002 varPtr = NULL;
1003 if (tablePtr != NULL) {
1004 varPtr = VarHashFindVar(tablePtr, varNamePtr);
1005 }
1006 if (varPtr == NULL) {
1007 *errMsgPtr = NOSUCHVAR;
1008 }
1009 }
1010 }
1011 return varPtr;
1012 }
1013
1014 /*
1015 *----------------------------------------------------------------------
1016 *
1017 * TclLookupArrayElement --
1018 *
1019 * This function is used to locate a variable which is in an array's
1020 * hashtable given a pointer to the array's Var structure and the
1021 * element's name.
1022 *
1023 * Results:
1024 * The return value is a pointer to the variable structure , or NULL if
1025 * the variable couldn't be found.
1026 *
1027 * If arrayPtr points to a variable that isn't an array and createPart1
1028 * is 1, the corresponding variable will be converted to an array.
1029 * Otherwise, NULL is returned and an error message is left in the
1030 * interp's result if TCL_LEAVE_ERR_MSG is set in flags.
1031 *
1032 * If the variable is not found and createPart2 is 1, the variable is
1033 * created. Otherwise, NULL is returned and an error message is left in
1034 * the interp's result if TCL_LEAVE_ERR_MSG is set in flags.
1035 *
1036 * Note: it's possible for the variable returned to be VAR_UNDEFINED even
1037 * if createPart1 or createPart2 are 1 (these only cause the hash table
1038 * entry or array to be created). For example, the variable might be a
1039 * global that has been unset but is still referenced by a procedure, or
1040 * a variable that has been unset but it only being kept in existence (if
1041 * VAR_UNDEFINED) by a trace.
1042 *
1043 * Side effects:
1044 * The variable at arrayPtr may be converted to be an array if
1045 * createPart1 is 1. A new hashtable entry may be created if createPart2
1046 * is 1.
1047 * When createElem is 1, callers must incr elNamePtr if they plan
1048 * to decr it.
1049 *
1050 *----------------------------------------------------------------------
1051 */
1052
1053 Var *
1054 TclLookupArrayElement(
1055 Tcl_Interp *interp, /* Interpreter to use for lookup. */
1056 Tcl_Obj *arrayNamePtr, /* This is the name of the array, or NULL if
1057 * index>= 0. */
1058 Tcl_Obj *elNamePtr, /* Name of element within array. */
1059 int flags, /* Only TCL_LEAVE_ERR_MSG bit matters. */
1060 const char *msg, /* Verb to use in error messages, e.g. "read"
1061 * or "set". Only needed if TCL_LEAVE_ERR_MSG
1062 * is set in flags. */
1063 int createArray, /* If 1, transform arrayName to be an array if
1064 * it isn't one yet and the transformation is
1065 * possible. If 0, return error if it isn't
1066 * already an array. */
1067 int createElem, /* If 1, create hash table entry for the
1068 * element, if it doesn't already exist. If 0,
1069 * return error if it doesn't exist. */
1070 Var *arrayPtr, /* Pointer to the array's Var structure. */
1071 int index) /* If >=0, the index of the local array. */
1072 {
1073 int isNew;
1074 Var *varPtr;
1075 TclVarHashTable *tablePtr;
1076 Namespace *nsPtr;
1077
1078 /*
1079 * We're dealing with an array element. Make sure the variable is an array
1080 * and look up the element (create the element if desired).
1081 */
1082
1083 if (TclIsVarUndefined(arrayPtr) && !TclIsVarArrayElement(arrayPtr)) {
1084 if (!createArray) {
1085 if (flags & TCL_LEAVE_ERR_MSG) {
1086 TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg,
1087 NOSUCHVAR, index);
1088 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
1089 arrayNamePtr?TclGetString(arrayNamePtr):NULL, (char *)NULL);
1090 }
1091 return NULL;
1092 }
1093
1094 /*
1095 * Make sure we are not resurrecting a namespace variable from a
1096 * deleted namespace!
1097 */
1098
1099 if (TclIsVarDeadHash(arrayPtr)) {
1100 if (flags & TCL_LEAVE_ERR_MSG) {
1101 TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg,
1102 DANGLINGVAR, index);
1103 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
1104 arrayNamePtr?TclGetString(arrayNamePtr):NULL, (char *)NULL);
1105 }
1106 return NULL;
1107 }
1108
1109 TclSetVarArray(arrayPtr);
1110 tablePtr = ckalloc(sizeof(TclVarHashTable));
1111 arrayPtr->value.tablePtr = tablePtr;
1112
1113 if (TclIsVarInHash(arrayPtr) && TclGetVarNsPtr(arrayPtr)) {
1114 nsPtr = TclGetVarNsPtr(arrayPtr);
1115 } else {
1116 nsPtr = NULL;
1117 }
1118 TclInitVarHashTable(arrayPtr->value.tablePtr, nsPtr);
1119 } else if (!TclIsVarArray(arrayPtr)) {
1120 if (flags & TCL_LEAVE_ERR_MSG) {
1121 TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg, NEEDARRAY,
1122 index);
1123 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
1124 arrayNamePtr?TclGetString(arrayNamePtr):NULL, (char *)NULL);
1125 }
1126 return NULL;
1127 }
1128
1129 if (createElem) {
1130 varPtr = VarHashCreateVar(arrayPtr->value.tablePtr, elNamePtr,
1131 &isNew);
1132 if (isNew) {
1133 if (arrayPtr->flags & VAR_SEARCH_ACTIVE) {
1134 DeleteSearches((Interp *) interp, arrayPtr);
1135 }
1136 TclSetVarArrayElement(varPtr);
1137 }
1138 } else {
1139 varPtr = VarHashFindVar(arrayPtr->value.tablePtr, elNamePtr);
1140 if (varPtr == NULL) {
1141 if (flags & TCL_LEAVE_ERR_MSG) {
1142 TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg,
1143 NOSUCHELEMENT, index);
1144 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "ELEMENT",
1145 TclGetString(elNamePtr), (char *)NULL);
1146 }
1147 }
1148 }
1149 return varPtr;
1150 }
1151
1152 /*
1153 *----------------------------------------------------------------------
1154 *
1155 * Tcl_GetVar --
1156 *
1157 * Return the value of a Tcl variable as a string.
1158 *
1159 * Results:
1160 * The return value points to the current value of varName as a string.
1161 * If the variable is not defined or can't be read because of a clash in
1162 * array usage then a NULL pointer is returned and an error message is
1163 * left in the interp's result if the TCL_LEAVE_ERR_MSG flag is set.
1164 * Note: the return value is only valid up until the next change to the
1165 * variable; if you depend on the value lasting longer than that, then
1166 * make yourself a private copy.
1167 *
1168 * Side effects:
1169 * None.
1170 *
1171 *----------------------------------------------------------------------
1172 */
1173
1174 #undef Tcl_GetVar
1175 const char *
1176 Tcl_GetVar(
1177 Tcl_Interp *interp, /* Command interpreter in which varName is to
1178 * be looked up. */
1179 const char *varName, /* Name of a variable in interp. */
1180 int flags) /* OR-ed combination of TCL_GLOBAL_ONLY,
1181 * TCL_NAMESPACE_ONLY or TCL_LEAVE_ERR_MSG
1182 * bits. */
1183 {
1184 Tcl_Obj *varNamePtr = Tcl_NewStringObj(varName, -1);
1185 Tcl_Obj *resultPtr = Tcl_ObjGetVar2(interp, varNamePtr, NULL, flags);
1186
1187 TclDecrRefCount(varNamePtr);
1188
1189 if (resultPtr == NULL) {
1190 return NULL;
1191 }
1192 return TclGetString(resultPtr);
1193 }
1194
1195 /*
1196 *----------------------------------------------------------------------
1197 *
1198 * Tcl_GetVar2 --
1199 *
1200 * Return the value of a Tcl variable as a string, given a two-part name
1201 * consisting of array name and element within array.
1202 *
1203 * Results:
1204 * The return value points to the current value of the variable given by
1205 * part1 and part2 as a string. If the specified variable doesn't exist,
1206 * or if there is a clash in array usage, then NULL is returned and a
1207 * message will be left in the interp's result if the TCL_LEAVE_ERR_MSG
1208 * flag is set. Note: the return value is only valid up until the next
1209 * change to the variable; if you depend on the value lasting longer than
1210 * that, then make yourself a private copy.
1211 *
1212 * Side effects:
1213 * None.
1214 *
1215 *----------------------------------------------------------------------
1216 */
1217
1218 const char *
1219 Tcl_GetVar2(
1220 Tcl_Interp *interp, /* Command interpreter in which variable is to
1221 * be looked up. */
1222 const char *part1, /* Name of an array (if part2 is non-NULL) or
1223 * the name of a variable. */
1224 const char *part2, /* If non-NULL, gives the name of an element
1225 * in the array part1. */
1226 int flags) /* OR-ed combination of TCL_GLOBAL_ONLY,
1227 * TCL_NAMESPACE_ONLY and TCL_LEAVE_ERR_MSG *
1228 * bits. */
1229 {
1230 Tcl_Obj *resultPtr;
1231 Tcl_Obj *part2Ptr = NULL, *part1Ptr = Tcl_NewStringObj(part1, -1);
1232
1233 if (part2) {
1234 part2Ptr = Tcl_NewStringObj(part2, -1);
1235 Tcl_IncrRefCount(part2Ptr);
1236 }
1237
1238 resultPtr = Tcl_ObjGetVar2(interp, part1Ptr, part2Ptr, flags);
1239
1240 Tcl_DecrRefCount(part1Ptr);
1241 if (part2Ptr) {
1242 Tcl_DecrRefCount(part2Ptr);
1243 }
1244 if (resultPtr == NULL) {
1245 return NULL;
1246 }
1247 return TclGetString(resultPtr);
1248 }
1249
1250 /*
1251 *----------------------------------------------------------------------
1252 *
1253 * Tcl_GetVar2Ex --
1254 *
1255 * Return the value of a Tcl variable as a Tcl object, given a two-part
1256 * name consisting of array name and element within array.
1257 *
1258 * Results:
1259 * The return value points to the current object value of the variable
1260 * given by part1Ptr and part2Ptr. If the specified variable doesn't
1261 * exist, or if there is a clash in array usage, then NULL is returned
1262 * and a message will be left in the interpreter's result if the
1263 * TCL_LEAVE_ERR_MSG flag is set.
1264 *
1265 * Side effects:
1266 * The ref count for the returned object is _not_ incremented to reflect
1267 * the returned reference; if you want to keep a reference to the object
1268 * you must increment its ref count yourself.
1269 *
1270 *----------------------------------------------------------------------
1271 */
1272
1273 Tcl_Obj *
1274 Tcl_GetVar2Ex(
1275 Tcl_Interp *interp, /* Command interpreter in which variable is to
1276 * be looked up. */
1277 const char *part1, /* Name of an array (if part2 is non-NULL) or
1278 * the name of a variable. */
1279 const char *part2, /* If non-NULL, gives the name of an element
1280 * in the array part1. */
1281 int flags) /* OR-ed combination of TCL_GLOBAL_ONLY, and
1282 * TCL_LEAVE_ERR_MSG bits. */
1283 {
1284 Tcl_Obj *resPtr, *part2Ptr = NULL, *part1Ptr = Tcl_NewStringObj(part1, -1);
1285
1286 if (part2) {
1287 part2Ptr = Tcl_NewStringObj(part2, -1);
1288 Tcl_IncrRefCount(part2Ptr);
1289 }
1290
1291 resPtr = Tcl_ObjGetVar2(interp, part1Ptr, part2Ptr, flags);
1292
1293 Tcl_DecrRefCount(part1Ptr);
1294 if (part2Ptr) {
1295 Tcl_DecrRefCount(part2Ptr);
1296 }
1297
1298 return resPtr;
1299 }
1300
1301 /*
1302 *----------------------------------------------------------------------
1303 *
1304 * Tcl_ObjGetVar2 --
1305 *
1306 * Return the value of a Tcl variable as a Tcl object, given a two-part
1307 * name consisting of array name and element within array.
1308 *
1309 * Results:
1310 * The return value points to the current object value of the variable
1311 * given by part1Ptr and part2Ptr. If the specified variable doesn't
1312 * exist, or if there is a clash in array usage, then NULL is returned
1313 * and a message will be left in the interpreter's result if the
1314 * TCL_LEAVE_ERR_MSG flag is set.
1315 *
1316 * Side effects:
1317 * The ref count for the returned object is _not_ incremented to reflect
1318 * the returned reference; if you want to keep a reference to the object
1319 * you must increment its ref count yourself.
1320 *
1321 * Callers must incr part2Ptr if they plan to decr it.
1322 *
1323 *----------------------------------------------------------------------
1324 */
1325
1326 Tcl_Obj *
1327 Tcl_ObjGetVar2(
1328 Tcl_Interp *interp, /* Command interpreter in which variable is to
1329 * be looked up. */
1330 Tcl_Obj *part1Ptr, /* Points to an object holding the name of an
1331 * array (if part2 is non-NULL) or the name of
1332 * a variable. */
1333 Tcl_Obj *part2Ptr, /* If non-null, points to an object holding
1334 * the name of an element in the array
1335 * part1Ptr. */
1336 int flags) /* OR-ed combination of TCL_GLOBAL_ONLY and
1337 * TCL_LEAVE_ERR_MSG bits. */
1338 {
1339 Var *varPtr, *arrayPtr;
1340
1341 /*
1342 * Filter to pass through only the flags this interface supports.
1343 */
1344
1345 flags &= (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY|TCL_LEAVE_ERR_MSG);
1346 varPtr = TclObjLookupVarEx(interp, part1Ptr, part2Ptr, flags, "read",
1347 /*createPart1*/ 0, /*createPart2*/ 1, &arrayPtr);
1348 if (varPtr == NULL) {
1349 return NULL;
1350 }
1351
1352 return TclPtrGetVarIdx(interp, varPtr, arrayPtr, part1Ptr, part2Ptr,
1353 flags, -1);
1354 }
1355
1356 /*
1357 *----------------------------------------------------------------------
1358 *
1359 * TclPtrGetVar --
1360 *
1361 * Return the value of a Tcl variable as a Tcl object, given the pointers
1362 * to the variable's (and possibly containing array's) VAR structure.
1363 *
1364 * Results:
1365 * The return value points to the current object value of the variable
1366 * given by varPtr. If the specified variable doesn't exist, or if there
1367 * is a clash in array usage, then NULL is returned and a message will be
1368 * left in the interpreter's result if the TCL_LEAVE_ERR_MSG flag is set.
1369 *
1370 * Side effects:
1371 * The ref count for the returned object is _not_ incremented to reflect
1372 * the returned reference; if you want to keep a reference to the object
1373 * you must increment its ref count yourself.
1374 *
1375 *----------------------------------------------------------------------
1376 */
1377
1378 Tcl_Obj *
1379 TclPtrGetVar(
1380 Tcl_Interp *interp, /* Command interpreter in which variable is to
1381 * be looked up. */
1382 Tcl_Var varPtr, /* The variable to be read.*/
1383 Tcl_Var arrayPtr, /* NULL for scalar variables, pointer to the
1384 * containing array otherwise. */
1385 Tcl_Obj *part1Ptr, /* Name of an array (if part2 is non-NULL) or
1386 * the name of a variable. */
1387 Tcl_Obj *part2Ptr, /* If non-NULL, gives the name of an element
1388 * in the array part1. */
1389 int flags) /* OR-ed combination of TCL_GLOBAL_ONLY, and
1390 * TCL_LEAVE_ERR_MSG bits. */
1391 {
1392 if (varPtr == NULL) {
1393 Tcl_Panic("varPtr must not be NULL");
1394 }
1395 if (part1Ptr == NULL) {
1396 Tcl_Panic("part1Ptr must not be NULL");
1397 }
1398 return TclPtrGetVarIdx(interp, (Var *) varPtr, (Var *) arrayPtr,
1399 part1Ptr, part2Ptr, flags, -1);
1400 }
1401
1402 /*
1403 *----------------------------------------------------------------------
1404 *
1405 * TclPtrGetVarIdx --
1406 *
1407 * Return the value of a Tcl variable as a Tcl object, given the pointers
1408 * to the variable's (and possibly containing array's) VAR structure.
1409 *
1410 * Results:
1411 * The return value points to the current object value of the variable
1412 * given by varPtr. If the specified variable doesn't exist, or if there
1413 * is a clash in array usage, then NULL is returned and a message will be
1414 * left in the interpreter's result if the TCL_LEAVE_ERR_MSG flag is set.
1415 *
1416 * Side effects:
1417 * The ref count for the returned object is _not_ incremented to reflect
1418 * the returned reference; if you want to keep a reference to the object
1419 * you must increment its ref count yourself.
1420 *
1421 *----------------------------------------------------------------------
1422 */
1423
1424 Tcl_Obj *
1425 TclPtrGetVarIdx(
1426 Tcl_Interp *interp, /* Command interpreter in which variable is to
1427 * be looked up. */
1428 Var *varPtr, /* The variable to be read.*/
1429 Var *arrayPtr, /* NULL for scalar variables, pointer to the
1430 * containing array otherwise. */
1431 Tcl_Obj *part1Ptr, /* Name of an array (if part2 is non-NULL) or
1432 * the name of a variable. */
1433 Tcl_Obj *part2Ptr, /* If non-NULL, gives the name of an element
1434 * in the array part1. */
1435 int flags, /* OR-ed combination of TCL_GLOBAL_ONLY, and
1436 * TCL_LEAVE_ERR_MSG bits. */
1437 int index) /* Index into the local variable table of the
1438 * variable, or -1. Only used when part1Ptr is
1439 * NULL. */
1440 {
1441 Interp *iPtr = (Interp *) interp;
1442 const char *msg;
1443
1444 /*
1445 * Invoke any read traces that have been set for the variable.
1446 */
1447
1448 if ((varPtr->flags & VAR_TRACED_READ)
1449 || (arrayPtr && (arrayPtr->flags & VAR_TRACED_READ))) {
1450 if (TCL_ERROR == TclObjCallVarTraces(iPtr, arrayPtr, varPtr,
1451 part1Ptr, part2Ptr,
1452 (flags & (TCL_NAMESPACE_ONLY|TCL_GLOBAL_ONLY))
1453 | TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG), index)) {
1454 goto errorReturn;
1455 }
1456 }
1457
1458 /*
1459 * Return the element if it's an existing scalar variable.
1460 */
1461
1462 if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr)) {
1463 return varPtr->value.objPtr;
1464 }
1465
1466 if (flags & TCL_LEAVE_ERR_MSG) {
1467 if (TclIsVarUndefined(varPtr) && arrayPtr
1468 && !TclIsVarUndefined(arrayPtr)) {
1469 msg = NOSUCHELEMENT;
1470 } else if (TclIsVarArray(varPtr)) {
1471 msg = ISARRAY;
1472 } else {
1473 msg = NOSUCHVAR;
1474 }
1475 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "read", msg, index);
1476 }
1477
1478 /*
1479 * An error. If the variable doesn't exist anymore and no-one's using it,
1480 * then free up the relevant structures and hash table entries.
1481 */
1482
1483 errorReturn:
1484 Tcl_SetErrorCode(interp, "TCL", "READ", "VARNAME", (char *)NULL);
1485 if (TclIsVarUndefined(varPtr)) {
1486 TclCleanupVar(varPtr, arrayPtr);
1487 }
1488 return NULL;
1489 }
1490
1491 /*
1492 *----------------------------------------------------------------------
1493 *
1494 * Tcl_SetObjCmd --
1495 *
1496 * This function is invoked to process the "set" Tcl command. See the
1497 * user documentation for details on what it does.
1498 *
1499 * Results:
1500 * A standard Tcl result value.
1501 *
1502 * Side effects:
1503 * A variable's value may be changed.
1504 *
1505 *----------------------------------------------------------------------
1506 */
1507
1508 int
1509 Tcl_SetObjCmd(
1510 ClientData dummy, /* Not used. */
1511 Tcl_Interp *interp,/* Current interpreter. */
1512 int objc, /* Number of arguments. */
1513 Tcl_Obj *const objv[]) /* Argument objects. */
1514 {
1515 Tcl_Obj *varValueObj;
1516
1517 if (objc == 2) {
1518 varValueObj = Tcl_ObjGetVar2(interp, objv[1], NULL,TCL_LEAVE_ERR_MSG);
1519 if (varValueObj == NULL) {
1520 return TCL_ERROR;
1521 }
1522 Tcl_SetObjResult(interp, varValueObj);
1523 return TCL_OK;
1524 } else if (objc == 3) {
1525 varValueObj = Tcl_ObjSetVar2(interp, objv[1], NULL, objv[2],
1526 TCL_LEAVE_ERR_MSG);
1527 if (varValueObj == NULL) {
1528 return TCL_ERROR;
1529 }
1530 Tcl_SetObjResult(interp, varValueObj);
1531 return TCL_OK;
1532 } else {
1533 Tcl_WrongNumArgs(interp, 1, objv, "varName ?newValue?");
1534 return TCL_ERROR;
1535 }
1536 }
1537
1538 /*
1539 *----------------------------------------------------------------------
1540 *
1541 * Tcl_SetVar --
1542 *
1543 * Change the value of a variable.
1544 *
1545 * Results:
1546 * Returns a pointer to the malloc'ed string which is the character
1547 * representation of the variable's new value. The caller must not modify
1548 * this string. If the write operation was disallowed then NULL is
1549 * returned; if the TCL_LEAVE_ERR_MSG flag is set, then an explanatory
1550 * message will be left in the interp's result. Note that the returned
1551 * string may not be the same as newValue; this is because variable
1552 * traces may modify the variable's value.
1553 *
1554 * Side effects:
1555 * If varName is defined as a local or global variable in interp, its
1556 * value is changed to newValue. If varName isn't currently defined, then
1557 * a new global variable by that name is created.
1558 *
1559 *----------------------------------------------------------------------
1560 */
1561
1562 #undef Tcl_SetVar
1563 const char *
1564 Tcl_SetVar(
1565 Tcl_Interp *interp, /* Command interpreter in which varName is to
1566 * be looked up. */
1567 const char *varName, /* Name of a variable in interp. */
1568 const char *newValue, /* New value for varName. */
1569 int flags) /* Various flags that tell how to set value:
1570 * any of TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
1571 * TCL_APPEND_VALUE, TCL_LIST_ELEMENT,
1572 * TCL_LEAVE_ERR_MSG. */
1573 {
1574 Tcl_Obj *varValuePtr, *varNamePtr = Tcl_NewStringObj(varName, -1);
1575
1576 Tcl_IncrRefCount(varNamePtr);
1577 varValuePtr = Tcl_ObjSetVar2(interp, varNamePtr, NULL,
1578 Tcl_NewStringObj(newValue, -1), flags);
1579 Tcl_DecrRefCount(varNamePtr);
1580
1581 if (varValuePtr == NULL) {
1582 return NULL;
1583 }
1584 return TclGetString(varValuePtr);
1585 }
1586
1587 /*
1588 *----------------------------------------------------------------------
1589 *
1590 * Tcl_SetVar2 --
1591 *
1592 * Given a two-part variable name, which may refer either to a scalar
1593 * variable or an element of an array, change the value of the variable.
1594 * If the named scalar or array or element doesn't exist then create one.
1595 *
1596 * Results:
1597 * Returns a pointer to the malloc'ed string which is the character
1598 * representation of the variable's new value. The caller must not modify
1599 * this string. If the write operation was disallowed because an array
1600 * was expected but not found (or vice versa), then NULL is returned; if
1601 * the TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will be
1602 * left in the interp's result. Note that the returned string may not be
1603 * the same as newValue; this is because variable traces may modify the
1604 * variable's value.
1605 *
1606 * Side effects:
1607 * The value of the given variable is set. If either the array or the
1608 * entry didn't exist then a new one is created.
1609 *
1610 *----------------------------------------------------------------------
1611 */
1612
1613 const char *
1614 Tcl_SetVar2(
1615 Tcl_Interp *interp, /* Command interpreter in which variable is to
1616 * be looked up. */
1617 const char *part1, /* If part2 is NULL, this is name of scalar
1618 * variable. Otherwise it is the name of an
1619 * array. */
1620 const char *part2, /* Name of an element within an array, or
1621 * NULL. */
1622 const char *newValue, /* New value for variable. */
1623 int flags) /* Various flags that tell how to set value:
1624 * any of TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
1625 * TCL_APPEND_VALUE, TCL_LIST_ELEMENT, or
1626 * TCL_LEAVE_ERR_MSG. */
1627 {
1628 Tcl_Obj *varValuePtr = Tcl_SetVar2Ex(interp, part1, part2,
1629 Tcl_NewStringObj(newValue, -1), flags);
1630
1631 if (varValuePtr == NULL) {
1632 return NULL;
1633 }
1634 return TclGetString(varValuePtr);
1635 }
1636
1637 /*
1638 *----------------------------------------------------------------------
1639 *
1640 * Tcl_SetVar2Ex --
1641 *
1642 * Given a two-part variable name, which may refer either to a scalar
1643 * variable or an element of an array, change the value of the variable
1644 * to a new Tcl object value. If the named scalar or array or element
1645 * doesn't exist then create one.
1646 *
1647 * Results:
1648 * Returns a pointer to the Tcl_Obj holding the new value of the
1649 * variable. If the write operation was disallowed because an array was
1650 * expected but not found (or vice versa), then NULL is returned; if the
1651 * TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will be
1652 * left in the interpreter's result. Note that the returned object may
1653 * not be the same one referenced by newValuePtr; this is because
1654 * variable traces may modify the variable's value.
1655 *
1656 * Side effects:
1657 * The value of the given variable is set. If either the array or the
1658 * entry didn't exist then a new variable is created.
1659 *
1660 * The reference count is decremented for any old value of the variable
1661 * and incremented for its new value. If the new value for the variable
1662 * is not the same one referenced by newValuePtr (perhaps as a result of
1663 * a variable trace), then newValuePtr's ref count is left unchanged by
1664 * Tcl_SetVar2Ex. newValuePtr's ref count is also left unchanged if we
1665 * are appending it as a string value: that is, if "flags" includes
1666 * TCL_APPEND_VALUE but not TCL_LIST_ELEMENT.
1667 *
1668 * The reference count for the returned object is _not_ incremented: if
1669 * you want to keep a reference to the object you must increment its ref
1670 * count yourself.
1671 *
1672 *----------------------------------------------------------------------
1673 */
1674
1675 Tcl_Obj *
1676 Tcl_SetVar2Ex(
1677 Tcl_Interp *interp, /* Command interpreter in which variable is to
1678 * be found. */
1679 const char *part1, /* Name of an array (if part2 is non-NULL) or
1680 * the name of a variable. */
1681 const char *part2, /* If non-NULL, gives the name of an element
1682 * in the array part1. */
1683 Tcl_Obj *newValuePtr, /* New value for variable. */
1684 int flags) /* Various flags that tell how to set value:
1685 * any of TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
1686 * TCL_APPEND_VALUE, TCL_LIST_ELEMENT or
1687 * TCL_LEAVE_ERR_MSG. */
1688 {
1689 Tcl_Obj *resPtr, *part2Ptr = NULL, *part1Ptr = Tcl_NewStringObj(part1, -1);
1690
1691 Tcl_IncrRefCount(part1Ptr);
1692 if (part2) {
1693 part2Ptr = Tcl_NewStringObj(part2, -1);
1694 Tcl_IncrRefCount(part2Ptr);
1695 }
1696
1697 resPtr = Tcl_ObjSetVar2(interp, part1Ptr, part2Ptr, newValuePtr, flags);
1698
1699 Tcl_DecrRefCount(part1Ptr);
1700 if (part2Ptr) {
1701 Tcl_DecrRefCount(part2Ptr);
1702 }
1703
1704 return resPtr;
1705 }
1706
1707 /*
1708 *----------------------------------------------------------------------
1709 *
1710 * Tcl_ObjSetVar2 --
1711 *
1712 * This function is the same as Tcl_SetVar2Ex above, except the variable
1713 * names are passed in Tcl object instead of strings.
1714 *
1715 * Results:
1716 * Returns a pointer to the Tcl_Obj holding the new value of the
1717 * variable. If the write operation was disallowed because an array was
1718 * expected but not found (or vice versa), then NULL is returned; if the
1719 * TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will be
1720 * left in the interpreter's result. Note that the returned object may
1721 * not be the same one referenced by newValuePtr; this is because
1722 * variable traces may modify the variable's value.
1723 *
1724 * Side effects:
1725 * The value of the given variable is set. If either the array or the
1726 * entry didn't exist then a new variable is created.
1727 * Callers must Incr part1Ptr if they plan to Decr it.
1728 * Callers must Incr part2Ptr if they plan to Decr it.
1729 *
1730 *----------------------------------------------------------------------
1731 */
1732
1733 Tcl_Obj *
1734 Tcl_ObjSetVar2(
1735 Tcl_Interp *interp, /* Command interpreter in which variable is to
1736 * be found. */
1737 Tcl_Obj *part1Ptr, /* Points to an object holding the name of an
1738 * array (if part2 is non-NULL) or the name of
1739 * a variable. */
1740 Tcl_Obj *part2Ptr, /* If non-NULL, points to an object holding
1741 * the name of an element in the array
1742 * part1Ptr. */
1743 Tcl_Obj *newValuePtr, /* New value for variable. */
1744 int flags) /* Various flags that tell how to set value:
1745 * any of TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
1746 * TCL_APPEND_VALUE, TCL_LIST_ELEMENT, or
1747 * TCL_LEAVE_ERR_MSG. */
1748 {
1749 Var *varPtr, *arrayPtr;
1750
1751 /*
1752 * Filter to pass through only the flags this interface supports.
1753 */
1754
1755 flags &= (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY|TCL_LEAVE_ERR_MSG
1756 |TCL_APPEND_VALUE|TCL_LIST_ELEMENT);
1757 varPtr = TclObjLookupVarEx(interp, part1Ptr, part2Ptr, flags, "set",
1758 /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr);
1759 if (varPtr == NULL) {
1760 if (newValuePtr->refCount == 0) {
1761 Tcl_DecrRefCount(newValuePtr);
1762 }
1763 return NULL;
1764 }
1765
1766 return TclPtrSetVarIdx(interp, varPtr, arrayPtr, part1Ptr, part2Ptr,
1767 newValuePtr, flags, -1);
1768 }
1769
1770 /*
1771 *----------------------------------------------------------------------
1772 *
1773 * TclPtrSetVar --
1774 *
1775 * This function is the same as Tcl_SetVar2Ex above, except that it
1776 * requires pointers to the variable's Var structs in addition to the
1777 * variable names.
1778 *
1779 * Results:
1780 * Returns a pointer to the Tcl_Obj holding the new value of the
1781 * variable. If the write operation was disallowed because an array was
1782 * expected but not found (or vice versa), then NULL is returned; if the
1783 * TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will be
1784 * left in the interpreter's result. Note that the returned object may
1785 * not be the same one referenced by newValuePtr; this is because
1786 * variable traces may modify the variable's value.
1787 *
1788 * Side effects:
1789 * The value of the given variable is set. If either the array or the
1790 * entry didn't exist then a new variable is created.
1791 *
1792 *----------------------------------------------------------------------
1793 */
1794
1795 Tcl_Obj *
1796 TclPtrSetVar(
1797 Tcl_Interp *interp, /* Command interpreter in which variable is to
1798 * be looked up. */
1799 Tcl_Var varPtr, /* Reference to the variable to set. */
1800 Tcl_Var arrayPtr, /* Reference to the array containing the
1801 * variable, or NULL if the variable is a
1802 * scalar. */
1803 Tcl_Obj *part1Ptr, /* Name of an array (if part2 is non-NULL) or
1804 * the name of a variable. */
1805 Tcl_Obj *part2Ptr, /* If non-NULL, gives the name of an element
1806 * in the array part1. */
1807 Tcl_Obj *newValuePtr, /* New value for variable. */
1808 int flags) /* OR-ed combination of TCL_GLOBAL_ONLY, and
1809 * TCL_LEAVE_ERR_MSG bits. */
1810 {
1811 if (varPtr == NULL) {
1812 Tcl_Panic("varPtr must not be NULL");
1813 }
1814 if (part1Ptr == NULL) {
1815 Tcl_Panic("part1Ptr must not be NULL");
1816 }
1817 if (newValuePtr == NULL) {
1818 Tcl_Panic("newValuePtr must not be NULL");
1819 }
1820 return TclPtrSetVarIdx(interp, (Var *) varPtr, (Var *) arrayPtr,
1821 part1Ptr, part2Ptr, newValuePtr, flags, -1);
1822 }
1823
1824 /*
1825 *----------------------------------------------------------------------
1826 *
1827 * TclPtrSetVarIdx --
1828 *
1829 * This function is the same as Tcl_SetVar2Ex above, except that it
1830 * requires pointers to the variable's Var structs in addition to the
1831 * variable names.
1832 *
1833 * Results:
1834 * Returns a pointer to the Tcl_Obj holding the new value of the
1835 * variable. If the write operation was disallowed because an array was
1836 * expected but not found (or vice versa), then NULL is returned; if the
1837 * TCL_LEAVE_ERR_MSG flag is set, then an explanatory message will be
1838 * left in the interpreter's result. Note that the returned object may
1839 * not be the same one referenced by newValuePtr; this is because
1840 * variable traces may modify the variable's value.
1841 *
1842 * Side effects:
1843 * The value of the given variable is set. If either the array or the
1844 * entry didn't exist then a new variable is created.
1845 *
1846 *----------------------------------------------------------------------
1847 */
1848
1849 Tcl_Obj *
1850 TclPtrSetVarIdx(
1851 Tcl_Interp *interp, /* Command interpreter in which variable is to
1852 * be looked up. */
1853 Var *varPtr, /* Reference to the variable to set. */
1854 Var *arrayPtr, /* Reference to the array containing the
1855 * variable, or NULL if the variable is a
1856 * scalar. */
1857 Tcl_Obj *part1Ptr, /* Name of an array (if part2 is non-NULL) or
1858 * the name of a variable. NULL if the 'index'
1859 * parameter is >= 0 */
1860 Tcl_Obj *part2Ptr, /* If non-NULL, gives the name of an element
1861 * in the array part1. */
1862 Tcl_Obj *newValuePtr, /* New value for variable. */
1863 int flags, /* OR-ed combination of TCL_GLOBAL_ONLY, and
1864 * TCL_LEAVE_ERR_MSG bits. */
1865 int index) /* Index of local var where part1 is to be
1866 * found. */
1867 {
1868 Interp *iPtr = (Interp *) interp;
1869 Tcl_Obj *oldValuePtr;
1870 Tcl_Obj *resultPtr = NULL;
1871 int result;
1872 int cleanupOnEarlyError = (newValuePtr->refCount == 0);
1873
1874 /*
1875 * If the variable is in a hashtable and its hPtr field is NULL, then we
1876 * may have an upvar to an array element where the array was deleted or an
1877 * upvar to a namespace variable whose namespace was deleted. Generate an
1878 * error (allowing the variable to be reset would screw up our storage
1879 * allocation and is meaningless anyway).
1880 */
1881
1882 if (TclIsVarDeadHash(varPtr)) {
1883 if (flags & TCL_LEAVE_ERR_MSG) {
1884 if (TclIsVarArrayElement(varPtr)) {
1885 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "set",
1886 DANGLINGELEMENT, index);
1887 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "ELEMENT", (char *)NULL);
1888 } else {
1889 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "set",
1890 DANGLINGVAR, index);
1891 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME", (char *)NULL);
1892 }
1893 }
1894 goto earlyError;
1895 }
1896
1897 /*
1898 * It's an error to try to set an array variable itself.
1899 */
1900
1901 if (TclIsVarArray(varPtr)) {
1902 if (flags & TCL_LEAVE_ERR_MSG) {
1903 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "set", ISARRAY,index);
1904 Tcl_SetErrorCode(interp, "TCL", "WRITE", "ARRAY", (char *)NULL);
1905 }
1906 goto earlyError;
1907 }
1908
1909 /*
1910 * Invoke any read traces that have been set for the variable if it is
1911 * requested. This was done for INST_LAPPEND_* but that was inconsistent
1912 * with the non-bc instruction, and would cause failures trying to
1913 * lappend to any non-existing ::env var, which is inconsistent with
1914 * documented behavior. [Bug #3057639].
1915 */
1916
1917 if ((flags & TCL_TRACE_READS) && ((varPtr->flags & VAR_TRACED_READ)
1918 || (arrayPtr && (arrayPtr->flags & VAR_TRACED_READ)))) {
1919 if (TCL_ERROR == TclObjCallVarTraces(iPtr, arrayPtr, varPtr,
1920 part1Ptr, part2Ptr,
1921 TCL_TRACE_READS, (flags & TCL_LEAVE_ERR_MSG), index)) {
1922 goto earlyError;
1923 }
1924 }
1925
1926 /*
1927 * Set the variable's new value. If appending, append the new value to the
1928 * variable, either as a list element or as a string. Also, if appending,
1929 * then if the variable's old value is unshared we can modify it directly,
1930 * otherwise we must create a new copy to modify: this is "copy on write".
1931 */
1932
1933 oldValuePtr = varPtr->value.objPtr;
1934 if (flags & TCL_LIST_ELEMENT && !(flags & TCL_APPEND_VALUE)) {
1935 varPtr->value.objPtr = NULL;
1936 }
1937 if (flags & (TCL_APPEND_VALUE|TCL_LIST_ELEMENT)) {
1938 if (flags & TCL_LIST_ELEMENT) { /* Append list element. */
1939 if (oldValuePtr == NULL) {
1940 TclNewObj(oldValuePtr);
1941 varPtr->value.objPtr = oldValuePtr;
1942 Tcl_IncrRefCount(oldValuePtr); /* Since var is referenced. */
1943 } else if (Tcl_IsShared(oldValuePtr)) {
1944 varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr);
1945 TclDecrRefCount(oldValuePtr);
1946 oldValuePtr = varPtr->value.objPtr;
1947 Tcl_IncrRefCount(oldValuePtr); /* Since var is referenced. */
1948 }
1949 result = Tcl_ListObjAppendElement(interp, oldValuePtr,
1950 newValuePtr);
1951 if (result != TCL_OK) {
1952 goto earlyError;
1953 }
1954 } else { /* Append string. */
1955 /*
1956 * We append newValuePtr's bytes but don't change its ref count.
1957 */
1958
1959 if (oldValuePtr == NULL) {
1960 varPtr->value.objPtr = newValuePtr;
1961 Tcl_IncrRefCount(newValuePtr);
1962 } else {
1963 if (Tcl_IsShared(oldValuePtr)) { /* Append to copy. */
1964 varPtr->value.objPtr = Tcl_DuplicateObj(oldValuePtr);
1965
1966 TclContinuationsCopy(varPtr->value.objPtr, oldValuePtr);
1967
1968 TclDecrRefCount(oldValuePtr);
1969 oldValuePtr = varPtr->value.objPtr;
1970 Tcl_IncrRefCount(oldValuePtr); /* Since var is ref */
1971 }
1972 Tcl_AppendObjToObj(oldValuePtr, newValuePtr);
1973 if (newValuePtr->refCount == 0) {
1974 Tcl_DecrRefCount(newValuePtr);
1975 }
1976 }
1977 }
1978 } else if (newValuePtr != oldValuePtr) {
1979 /*
1980 * In this case we are replacing the value, so we don't need to do
1981 * more than swap the objects.
1982 */
1983
1984 varPtr->value.objPtr = newValuePtr;
1985 Tcl_IncrRefCount(newValuePtr); /* Var is another ref. */
1986 if (oldValuePtr != NULL) {
1987 TclDecrRefCount(oldValuePtr); /* Discard old value. */
1988 }
1989 }
1990
1991 /*
1992 * Invoke any write traces for the variable.
1993 */
1994
1995 if ((varPtr->flags & VAR_TRACED_WRITE)
1996 || (arrayPtr && (arrayPtr->flags & VAR_TRACED_WRITE))) {
1997 if (TCL_ERROR == TclObjCallVarTraces(iPtr, arrayPtr, varPtr, part1Ptr,
1998 part2Ptr, (flags & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY))
1999 | TCL_TRACE_WRITES, (flags & TCL_LEAVE_ERR_MSG), index)) {
2000 goto cleanup;
2001 }
2002 }
2003
2004 /*
2005 * Return the variable's value unless the variable was changed in some
2006 * gross way by a trace (e.g. it was unset and then recreated as an
2007 * array).
2008 */
2009
2010 if (TclIsVarScalar(varPtr) && !TclIsVarUndefined(varPtr)) {
2011 return varPtr->value.objPtr;
2012 }
2013
2014 /*
2015 * A trace changed the value in some gross way. Return an empty string
2016 * object.
2017 */
2018
2019 resultPtr = iPtr->emptyObjPtr;
2020
2021 /*
2022 * If the variable doesn't exist anymore and no-one's using it, then free
2023 * up the relevant structures and hash table entries.
2024 */
2025
2026 cleanup:
2027 if (resultPtr == NULL) {
2028 Tcl_SetErrorCode(interp, "TCL", "WRITE", "VARNAME", (char *)NULL);
2029 }
2030 if (TclIsVarUndefined(varPtr)) {
2031 TclCleanupVar(varPtr, arrayPtr);
2032 }
2033 return resultPtr;
2034
2035 earlyError:
2036 if (cleanupOnEarlyError) {
2037 Tcl_DecrRefCount(newValuePtr);
2038 }
2039 goto cleanup;
2040 }
2041
2042 /*
2043 *----------------------------------------------------------------------
2044 *
2045 * TclIncrObjVar2 --
2046 *
2047 * Given a two-part variable name, which may refer either to a scalar
2048 * variable or an element of an array, increment the Tcl object value of
2049 * the variable by a specified Tcl_Obj increment value.
2050 *
2051 * Results:
2052 * Returns a pointer to the Tcl_Obj holding the new value of the
2053 * variable. If the specified variable doesn't exist, or there is a clash
2054 * in array usage, or an error occurs while executing variable traces,
2055 * then NULL is returned and a message will be left in the interpreter's
2056 * result.
2057 *
2058 * Side effects:
2059 * The value of the given variable is incremented by the specified
2060 * amount. If either the array or the entry didn't exist then a new
2061 * variable is created. The ref count for the returned object is _not_
2062 * incremented to reflect the returned reference; if you want to keep a
2063 * reference to the object you must increment its ref count yourself.
2064 * Callers must Incr part1Ptr if they plan to Decr it.
2065 * Callers must Incr part2Ptr if they plan to Decr it.
2066 *
2067 *----------------------------------------------------------------------
2068 */
2069
2070 Tcl_Obj *
2071 TclIncrObjVar2(
2072 Tcl_Interp *interp, /* Command interpreter in which variable is to
2073 * be found. */
2074 Tcl_Obj *part1Ptr, /* Points to an object holding the name of an
2075 * array (if part2 is non-NULL) or the name of
2076 * a variable. */
2077 Tcl_Obj *part2Ptr, /* If non-null, points to an object holding
2078 * the name of an element in the array
2079 * part1Ptr. */
2080 Tcl_Obj *incrPtr, /* Amount to be added to variable. */
2081 int flags) /* Various flags that tell how to incr value:
2082 * any of TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
2083 * TCL_APPEND_VALUE, TCL_LIST_ELEMENT,
2084 * TCL_LEAVE_ERR_MSG. */
2085 {
2086 Var *varPtr, *arrayPtr;
2087
2088 varPtr = TclObjLookupVarEx(interp, part1Ptr, part2Ptr, flags, "read",
2089 1, 1, &arrayPtr);
2090 if (varPtr == NULL) {
2091 Tcl_AddErrorInfo(interp,
2092 "\n (reading value of variable to increment)");
2093 return NULL;
2094 }
2095 return TclPtrIncrObjVarIdx(interp, varPtr, arrayPtr, part1Ptr, part2Ptr,
2096 incrPtr, flags, -1);
2097 }
2098
2099 /*
2100 *----------------------------------------------------------------------
2101 *
2102 * TclPtrIncrObjVar --
2103 *
2104 * Given the pointers to a variable and possible containing array,
2105 * increment the Tcl object value of the variable by a Tcl_Obj increment.
2106 *
2107 * Results:
2108 * Returns a pointer to the Tcl_Obj holding the new value of the
2109 * variable. If the specified variable doesn't exist, or there is a clash
2110 * in array usage, or an error occurs while executing variable traces,
2111 * then NULL is returned and a message will be left in the interpreter's
2112 * result.
2113 *
2114 * Side effects:
2115 * The value of the given variable is incremented by the specified
2116 * amount. If either the array or the entry didn't exist then a new
2117 * variable is created. The ref count for the returned object is _not_
2118 * incremented to reflect the returned reference; if you want to keep a
2119 * reference to the object you must increment its ref count yourself.
2120 *
2121 *----------------------------------------------------------------------
2122 */
2123
2124 Tcl_Obj *
2125 TclPtrIncrObjVar(
2126 Tcl_Interp *interp, /* Command interpreter in which variable is to
2127 * be found. */
2128 Tcl_Var varPtr, /* Reference to the variable to set. */
2129 Tcl_Var arrayPtr, /* Reference to the array containing the
2130 * variable, or NULL if the variable is a
2131 * scalar. */
2132 Tcl_Obj *part1Ptr, /* Points to an object holding the name of an
2133 * array (if part2 is non-NULL) or the name of
2134 * a variable. */
2135 Tcl_Obj *part2Ptr, /* If non-null, points to an object holding
2136 * the name of an element in the array
2137 * part1Ptr. */
2138 Tcl_Obj *incrPtr, /* Increment value. */
2139 /* TODO: Which of these flag values really make sense? */
2140 int flags) /* Various flags that tell how to incr value:
2141 * any of TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
2142 * TCL_APPEND_VALUE, TCL_LIST_ELEMENT,
2143 * TCL_LEAVE_ERR_MSG. */
2144 {
2145 if (varPtr == NULL) {
2146 Tcl_Panic("varPtr must not be NULL");
2147 }
2148 if (part1Ptr == NULL) {
2149 Tcl_Panic("part1Ptr must not be NULL");
2150 }
2151 return TclPtrIncrObjVarIdx(interp, (Var *) varPtr, (Var *) arrayPtr,
2152 part1Ptr, part2Ptr, incrPtr, flags, -1);
2153 }
2154
2155 /*
2156 *----------------------------------------------------------------------
2157 *
2158 * TclPtrIncrObjVarIdx --
2159 *
2160 * Given the pointers to a variable and possible containing array,
2161 * increment the Tcl object value of the variable by a Tcl_Obj increment.
2162 *
2163 * Results:
2164 * Returns a pointer to the Tcl_Obj holding the new value of the
2165 * variable. If the specified variable doesn't exist, or there is a clash
2166 * in array usage, or an error occurs while executing variable traces,
2167 * then NULL is returned and a message will be left in the interpreter's
2168 * result.
2169 *
2170 * Side effects:
2171 * The value of the given variable is incremented by the specified
2172 * amount. If either the array or the entry didn't exist then a new
2173 * variable is created. The ref count for the returned object is _not_
2174 * incremented to reflect the returned reference; if you want to keep a
2175 * reference to the object you must increment its ref count yourself.
2176 *
2177 *----------------------------------------------------------------------
2178 */
2179
2180 Tcl_Obj *
2181 TclPtrIncrObjVarIdx(
2182 Tcl_Interp *interp, /* Command interpreter in which variable is to
2183 * be found. */
2184 Var *varPtr, /* Reference to the variable to set. */
2185 Var *arrayPtr, /* Reference to the array containing the
2186 * variable, or NULL if the variable is a
2187 * scalar. */
2188 Tcl_Obj *part1Ptr, /* Points to an object holding the name of an
2189 * array (if part2 is non-NULL) or the name of
2190 * a variable. */
2191 Tcl_Obj *part2Ptr, /* If non-null, points to an object holding
2192 * the name of an element in the array
2193 * part1Ptr. */
2194 Tcl_Obj *incrPtr, /* Increment value. */
2195 /* TODO: Which of these flag values really make sense? */
2196 int flags, /* Various flags that tell how to incr value:
2197 * any of TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
2198 * TCL_APPEND_VALUE, TCL_LIST_ELEMENT,
2199 * TCL_LEAVE_ERR_MSG. */
2200 int index) /* Index into the local variable table of the
2201 * variable, or -1. Only used when part1Ptr is
2202 * NULL. */
2203 {
2204 Tcl_Obj *varValuePtr;
2205
2206 if (TclIsVarInHash(varPtr)) {
2207 VarHashRefCount(varPtr)++;
2208 }
2209 varValuePtr = TclPtrGetVarIdx(interp, varPtr, arrayPtr, part1Ptr,
2210 part2Ptr, flags, index);
2211 if (TclIsVarInHash(varPtr)) {
2212 VarHashRefCount(varPtr)--;
2213 }
2214 if (varValuePtr == NULL) {
2215 TclNewIntObj(varValuePtr, 0);
2216 }
2217 if (Tcl_IsShared(varValuePtr)) {
2218 /* Copy on write */
2219 varValuePtr = Tcl_DuplicateObj(varValuePtr);
2220
2221 if (TCL_OK == TclIncrObj(interp, varValuePtr, incrPtr)) {
2222 return TclPtrSetVarIdx(interp, varPtr, arrayPtr, part1Ptr,
2223 part2Ptr, varValuePtr, flags, index);
2224 } else {
2225 Tcl_DecrRefCount(varValuePtr);
2226 return NULL;
2227 }
2228 } else {
2229 /* Unshared - can Incr in place */
2230 if (TCL_OK == TclIncrObj(interp, varValuePtr, incrPtr)) {
2231 /*
2232 * This seems dumb to write the incremeted value into the var
2233 * after we just adjusted the value in place, but the spec for
2234 * [incr] requires that write traces fire, and making this call
2235 * is the way to make that happen.
2236 */
2237
2238 return TclPtrSetVarIdx(interp, varPtr, arrayPtr, part1Ptr,
2239 part2Ptr, varValuePtr, flags, index);
2240 } else {
2241 return NULL;
2242 }
2243 }
2244 }
2245
2246 /*
2247 *----------------------------------------------------------------------
2248 *
2249 * Tcl_UnsetVar --
2250 *
2251 * Delete a variable, so that it may not be accessed anymore.
2252 *
2253 * Results:
2254 * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR if
2255 * the variable can't be unset. In the event of an error, if the
2256 * TCL_LEAVE_ERR_MSG flag is set then an error message is left in the
2257 * interp's result.
2258 *
2259 * Side effects:
2260 * If varName is defined as a local or global variable in interp, it is
2261 * deleted.
2262 *
2263 *----------------------------------------------------------------------
2264 */
2265
2266 #undef Tcl_UnsetVar
2267 int
2268 Tcl_UnsetVar(
2269 Tcl_Interp *interp, /* Command interpreter in which varName is to
2270 * be looked up. */
2271 const char *varName, /* Name of a variable in interp. May be either
2272 * a scalar name or an array name or an
2273 * element in an array. */
2274 int flags) /* OR-ed combination of any of
2275 * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY or
2276 * TCL_LEAVE_ERR_MSG. */
2277 {
2278 int result;
2279 Tcl_Obj *varNamePtr;
2280
2281 varNamePtr = Tcl_NewStringObj(varName, -1);
2282 Tcl_IncrRefCount(varNamePtr);
2283
2284 /*
2285 * Filter to pass through only the flags this interface supports.
2286 */
2287
2288 flags &= (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY|TCL_LEAVE_ERR_MSG);
2289 result = TclObjUnsetVar2(interp, varNamePtr, NULL, flags);
2290
2291 Tcl_DecrRefCount(varNamePtr);
2292 return result;
2293 }
2294
2295 /*
2296 *----------------------------------------------------------------------
2297 *
2298 * Tcl_UnsetVar2 --
2299 *
2300 * Delete a variable, given a 2-part name.
2301 *
2302 * Results:
2303 * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR if
2304 * the variable can't be unset. In the event of an error, if the
2305 * TCL_LEAVE_ERR_MSG flag is set then an error message is left in the
2306 * interp's result.
2307 *
2308 * Side effects:
2309 * If part1 and part2 indicate a local or global variable in interp, it
2310 * is deleted. If part1 is an array name and part2 is NULL, then the
2311 * whole array is deleted.
2312 *
2313 *----------------------------------------------------------------------
2314 */
2315
2316 int
2317 Tcl_UnsetVar2(
2318 Tcl_Interp *interp, /* Command interpreter in which varName is to
2319 * be looked up. */
2320 const char *part1, /* Name of variable or array. */
2321 const char *part2, /* Name of element within array or NULL. */
2322 int flags) /* OR-ed combination of any of
2323 * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
2324 * TCL_LEAVE_ERR_MSG. */
2325 {
2326 int result;
2327 Tcl_Obj *part2Ptr = NULL, *part1Ptr = Tcl_NewStringObj(part1, -1);
2328
2329 if (part2) {
2330 part2Ptr = Tcl_NewStringObj(part2, -1);
2331 }
2332
2333 /*
2334 * Filter to pass through only the flags this interface supports.
2335 */
2336
2337 flags &= (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY|TCL_LEAVE_ERR_MSG);
2338 result = TclObjUnsetVar2(interp, part1Ptr, part2Ptr, flags);
2339
2340 Tcl_DecrRefCount(part1Ptr);
2341 if (part2Ptr) {
2342 Tcl_DecrRefCount(part2Ptr);
2343 }
2344 return result;
2345 }
2346
2347 /*
2348 *----------------------------------------------------------------------
2349 *
2350 * TclObjUnsetVar2 --
2351 *
2352 * Delete a variable, given a 2-object name.
2353 *
2354 * Results:
2355 * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR if
2356 * the variable can't be unset. In the event of an error, if the
2357 * TCL_LEAVE_ERR_MSG flag is set then an error message is left in the
2358 * interp's result.
2359 *
2360 * Side effects:
2361 * If part1ptr and part2Ptr indicate a local or global variable in
2362 * interp, it is deleted. If part1Ptr is an array name and part2Ptr is
2363 * NULL, then the whole array is deleted.
2364 *
2365 *----------------------------------------------------------------------
2366 */
2367
2368 int
2369 TclObjUnsetVar2(
2370 Tcl_Interp *interp, /* Command interpreter in which varName is to
2371 * be looked up. */
2372 Tcl_Obj *part1Ptr, /* Name of variable or array. */
2373 Tcl_Obj *part2Ptr, /* Name of element within array or NULL. */
2374 int flags) /* OR-ed combination of any of
2375 * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
2376 * TCL_LEAVE_ERR_MSG. */
2377 {
2378 Var *varPtr, *arrayPtr;
2379
2380 varPtr = TclObjLookupVarEx(interp, part1Ptr, part2Ptr, flags, "unset",
2381 /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr);
2382 if (varPtr == NULL) {
2383 return TCL_ERROR;
2384 }
2385
2386 return TclPtrUnsetVarIdx(interp, varPtr, arrayPtr, part1Ptr, part2Ptr,
2387 flags, -1);
2388 }
2389
2390 /*
2391 *----------------------------------------------------------------------
2392 *
2393 * TclPtrUnsetVar --
2394 *
2395 * Delete a variable, given the pointers to the variable's (and possibly
2396 * containing array's) VAR structure.
2397 *
2398 * Results:
2399 * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR if
2400 * the variable can't be unset. In the event of an error, if the
2401 * TCL_LEAVE_ERR_MSG flag is set then an error message is left in the
2402 * interp's result.
2403 *
2404 * Side effects:
2405 * If varPtr and arrayPtr indicate a local or global variable in interp,
2406 * it is deleted. If varPtr is an array reference and part2Ptr is NULL,
2407 * then the whole array is deleted.
2408 *
2409 *----------------------------------------------------------------------
2410 */
2411
2412 int
2413 TclPtrUnsetVar(
2414 Tcl_Interp *interp, /* Command interpreter in which varName is to
2415 * be looked up. */
2416 Tcl_Var varPtr, /* The variable to be unset. */
2417 Tcl_Var arrayPtr, /* NULL for scalar variables, pointer to the
2418 * containing array otherwise. */
2419 Tcl_Obj *part1Ptr, /* Name of an array (if part2 is non-NULL) or
2420 * the name of a variable. */
2421 Tcl_Obj *part2Ptr, /* If non-NULL, gives the name of an element
2422 * in the array part1. */
2423 int flags) /* OR-ed combination of any of
2424 * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
2425 * TCL_LEAVE_ERR_MSG. */
2426 {
2427 if (varPtr == NULL) {
2428 Tcl_Panic("varPtr must not be NULL");
2429 }
2430 if (part1Ptr == NULL) {
2431 Tcl_Panic("part1Ptr must not be NULL");
2432 }
2433 return TclPtrUnsetVarIdx(interp, (Var *) varPtr, (Var *) arrayPtr,
2434 part1Ptr, part2Ptr, flags, -1);
2435 }
2436
2437 /*
2438 *----------------------------------------------------------------------
2439 *
2440 * TclPtrUnsetVarIdx --
2441 *
2442 * Delete a variable, given the pointers to the variable's (and possibly
2443 * containing array's) VAR structure.
2444 *
2445 * Results:
2446 * Returns TCL_OK if the variable was successfully deleted, TCL_ERROR if
2447 * the variable can't be unset. In the event of an error, if the
2448 * TCL_LEAVE_ERR_MSG flag is set then an error message is left in the
2449 * interp's result.
2450 *
2451 * Side effects:
2452 * If varPtr and arrayPtr indicate a local or global variable in interp,
2453 * it is deleted. If varPtr is an array reference and part2Ptr is NULL,
2454 * then the whole array is deleted.
2455 *
2456 *----------------------------------------------------------------------
2457 */
2458
2459 int
2460 TclPtrUnsetVarIdx(
2461 Tcl_Interp *interp, /* Command interpreter in which varName is to
2462 * be looked up. */
2463 Var *varPtr, /* The variable to be unset. */
2464 Var *arrayPtr, /* NULL for scalar variables, pointer to the
2465 * containing array otherwise. */
2466 Tcl_Obj *part1Ptr, /* Name of an array (if part2 is non-NULL) or
2467 * the name of a variable. */
2468 Tcl_Obj *part2Ptr, /* If non-NULL, gives the name of an element
2469 * in the array part1. */
2470 int flags, /* OR-ed combination of any of
2471 * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY,
2472 * TCL_LEAVE_ERR_MSG. */
2473 int index) /* Index into the local variable table of the
2474 * variable, or -1. Only used when part1Ptr is
2475 * NULL. */
2476 {
2477 Interp *iPtr = (Interp *) interp;
2478 int result = (TclIsVarUndefined(varPtr)? TCL_ERROR : TCL_OK);
2479
2480 /*
2481 * Keep the variable alive until we're done with it. We used to
2482 * increase/decrease the refCount for each operation, making it hard to
2483 * find [Bug 735335] - caused by unsetting the variable whose value was
2484 * the variable's name.
2485 */
2486
2487 if (TclIsVarInHash(varPtr)) {
2488 VarHashRefCount(varPtr)++;
2489 }
2490
2491 UnsetVarStruct(varPtr, arrayPtr, iPtr, part1Ptr, part2Ptr, flags, index);
2492
2493 /*
2494 * It's an error to unset an undefined variable.
2495 */
2496
2497 if (result != TCL_OK) {
2498 if (flags & TCL_LEAVE_ERR_MSG) {
2499 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "unset",
2500 ((arrayPtr == NULL) ? NOSUCHVAR : NOSUCHELEMENT), index);
2501 Tcl_SetErrorCode(interp, "TCL", "UNSET", "VARNAME", (char *)NULL);
2502 }
2503 }
2504
2505 /*
2506 * Finally, if the variable is truly not in use then free up its Var
2507 * structure and remove it from its hash table, if any. The ref count of
2508 * its value object, if any, was decremented above.
2509 */
2510
2511 if (TclIsVarInHash(varPtr)) {
2512 VarHashRefCount(varPtr)--;
2513 CleanupVar(varPtr, arrayPtr);
2514 }
2515 return result;
2516 }
2517
2518 /*
2519 *----------------------------------------------------------------------
2520 *
2521 * UnsetVarStruct --
2522 *
2523 * Unset and delete a variable. This does the internal work for
2524 * TclObjUnsetVar2 and TclDeleteNamespaceVars, which call here for each
2525 * variable to be unset and deleted.
2526 *
2527 * Results:
2528 * None.
2529 *
2530 * Side effects:
2531 * If the arguments indicate a local or global variable in iPtr, it is
2532 * unset and deleted.
2533 *
2534 *----------------------------------------------------------------------
2535 */
2536
2537 static void
2538 UnsetVarStruct(
2539 Var *varPtr,
2540 Var *arrayPtr,
2541 Interp *iPtr,
2542 Tcl_Obj *part1Ptr,
2543 Tcl_Obj *part2Ptr,
2544 int flags,
2545 int index)
2546 {
2547 Var dummyVar;
2548 int traced = TclIsVarTraced(varPtr)
2549 || (arrayPtr && (arrayPtr->flags & VAR_TRACED_UNSET));
2550
2551 if (arrayPtr && (arrayPtr->flags & VAR_SEARCH_ACTIVE)) {
2552 DeleteSearches(iPtr, arrayPtr);
2553 } else if (varPtr->flags & VAR_SEARCH_ACTIVE) {
2554 DeleteSearches(iPtr, varPtr);
2555 }
2556
2557 /*
2558 * The code below is tricky, because of the possibility that a trace
2559 * function might try to access a variable being deleted. To handle this
2560 * situation gracefully, do things in three steps:
2561 * 1. Copy the contents of the variable to a dummy variable structure, and
2562 * mark the original Var structure as undefined.
2563 * 2. Invoke traces and clean up the variable, using the dummy copy.
2564 * 3. If at the end of this the original variable is still undefined and
2565 * has no outstanding references, then delete it (but it could have
2566 * gotten recreated by a trace).
2567 */
2568
2569 dummyVar = *varPtr;
2570 dummyVar.flags &= ~VAR_ALL_HASH;
2571 TclSetVarUndefined(varPtr);
2572
2573 /*
2574 * Call trace functions for the variable being deleted. Then delete its
2575 * traces. Be sure to abort any other traces for the variable that are
2576 * still pending. Special tricks:
2577 * 1. We need to increment varPtr's refCount around this: TclCallVarTraces
2578 * will use dummyVar so it won't increment varPtr's refCount itself.
2579 * 2. Turn off the VAR_TRACE_ACTIVE flag in dummyVar: we want to call
2580 * unset traces even if other traces are pending.
2581 */
2582
2583 if (traced) {
2584 VarTrace *tracePtr = NULL;
2585 Tcl_HashEntry *tPtr;
2586
2587 if (TclIsVarTraced(&dummyVar)) {
2588 /*
2589 * Transfer any existing traces on var, IF there are unset traces.
2590 * Otherwise just delete them.
2591 */
2592
2593 int isNew;
2594
2595 tPtr = Tcl_FindHashEntry(&iPtr->varTraces, varPtr);
2596 tracePtr = (VarTrace *)Tcl_GetHashValue(tPtr);
2597 varPtr->flags &= ~VAR_ALL_TRACES;
2598 Tcl_DeleteHashEntry(tPtr);
2599 if (dummyVar.flags & VAR_TRACED_UNSET) {
2600 tPtr = Tcl_CreateHashEntry(&iPtr->varTraces,
2601 &dummyVar, &isNew);
2602 Tcl_SetHashValue(tPtr, tracePtr);
2603 }
2604 }
2605
2606 if ((dummyVar.flags & VAR_TRACED_UNSET)
2607 || (arrayPtr && (arrayPtr->flags & VAR_TRACED_UNSET))) {
2608 dummyVar.flags &= ~VAR_TRACE_ACTIVE;
2609 TclObjCallVarTraces(iPtr, arrayPtr, &dummyVar, part1Ptr, part2Ptr,
2610 (flags & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY))
2611 | TCL_TRACE_UNSETS,
2612 /* leaveErrMsg */ 0, index);
2613
2614 /*
2615 * The traces that we just called may have triggered a change in
2616 * the set of traces. If so, reload the traces to manipulate.
2617 */
2618
2619 tracePtr = NULL;
2620 if (TclIsVarTraced(&dummyVar)) {
2621 tPtr = Tcl_FindHashEntry(&iPtr->varTraces, &dummyVar);
2622 if (tPtr) {
2623 tracePtr = (VarTrace *)Tcl_GetHashValue(tPtr);
2624 Tcl_DeleteHashEntry(tPtr);
2625 }
2626 }
2627 }
2628
2629 if (tracePtr) {
2630 ActiveVarTrace *activePtr;
2631
2632 while (tracePtr) {
2633 VarTrace *prevPtr = tracePtr;
2634
2635 tracePtr = tracePtr->nextPtr;
2636 prevPtr->nextPtr = NULL;
2637 Tcl_EventuallyFree(prevPtr, TCL_DYNAMIC);
2638 }
2639 for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL;
2640 activePtr = activePtr->nextPtr) {
2641 if (activePtr->varPtr == varPtr) {
2642 activePtr->nextTracePtr = NULL;
2643 }
2644 }
2645 dummyVar.flags &= ~VAR_ALL_TRACES;
2646 }
2647 }
2648
2649 if (TclIsVarScalar(&dummyVar) && (dummyVar.value.objPtr != NULL)) {
2650 /*
2651 * Decrement the ref count of the var's value.
2652 */
2653
2654 Tcl_Obj *objPtr = dummyVar.value.objPtr;
2655
2656 TclDecrRefCount(objPtr);
2657 } else if (TclIsVarArray(&dummyVar)) {
2658 /*
2659 * If the variable is an array, delete all of its elements. This must
2660 * be done after calling and deleting the traces on the array, above
2661 * (that's the way traces are defined). If the array name is not
2662 * present and is required for a trace on some element, it will be
2663 * computed at DeleteArray.
2664 */
2665
2666 DeleteArray(iPtr, part1Ptr, (Var *) &dummyVar, (flags
2667 & (TCL_GLOBAL_ONLY|TCL_NAMESPACE_ONLY)) | TCL_TRACE_UNSETS,
2668 index);
2669 } else if (TclIsVarLink(&dummyVar)) {
2670 /*
2671 * For global/upvar variables referenced in procedures, decrement the
2672 * reference count on the variable referred to, and free the
2673 * referenced variable if it's no longer needed.
2674 */
2675
2676 Var *linkPtr = dummyVar.value.linkPtr;
2677
2678 if (TclIsVarInHash(linkPtr)) {
2679 VarHashRefCount(linkPtr)--;
2680 CleanupVar(linkPtr, NULL);
2681 }
2682 }
2683
2684 /*
2685 * If the variable was a namespace variable, decrement its reference
2686 * count.
2687 */
2688
2689 TclClearVarNamespaceVar(varPtr);
2690 }
2691
2692 /*
2693 *----------------------------------------------------------------------
2694 *
2695 * Tcl_UnsetObjCmd --
2696 *
2697 * This object-based function is invoked to process the "unset" Tcl
2698 * command. See the user documentation for details on what it does.
2699 *
2700 * Results:
2701 * A standard Tcl object result value.
2702 *
2703 * Side effects:
2704 * See the user documentation.
2705 *
2706 *----------------------------------------------------------------------
2707 */
2708
2709 int
2710 Tcl_UnsetObjCmd(
2711 ClientData dummy, /* Not used. */
2712 Tcl_Interp *interp, /* Current interpreter. */
2713 int objc, /* Number of arguments. */
2714 Tcl_Obj *const objv[]) /* Argument objects. */
2715 {
2716 int i, flags = TCL_LEAVE_ERR_MSG;
2717 const char *name;
2718
2719 if (objc == 1) {
2720 /*
2721 * Do nothing if no arguments supplied, so as to match command
2722 * documentation.
2723 */
2724
2725 return TCL_OK;
2726 }
2727
2728 /*
2729 * Simple, restrictive argument parsing. The only options are -- and
2730 * -nocomplain (which must come first and be given exactly to be an
2731 * option).
2732 */
2733
2734 i = 1;
2735 name = TclGetString(objv[i]);
2736 if (name[0] == '-') {
2737 if (strcmp("-nocomplain", name) == 0) {
2738 i++;
2739 if (i == objc) {
2740 return TCL_OK;
2741 }
2742 flags = 0;
2743 name = TclGetString(objv[i]);
2744 }
2745 if (strcmp("--", name) == 0) {
2746 i++;
2747 }
2748 }
2749
2750 for (; i < objc; i++) {
2751 if ((TclObjUnsetVar2(interp, objv[i], NULL, flags) != TCL_OK)
2752 && (flags == TCL_LEAVE_ERR_MSG)) {
2753 return TCL_ERROR;
2754 }
2755 }
2756 return TCL_OK;
2757 }
2758
2759 /*
2760 *----------------------------------------------------------------------
2761 *
2762 * Tcl_AppendObjCmd --
2763 *
2764 * This object-based function is invoked to process the "append" Tcl
2765 * command. See the user documentation for details on what it does.
2766 *
2767 * Results:
2768 * A standard Tcl object result value.
2769 *
2770 * Side effects:
2771 * A variable's value may be changed.
2772 *
2773 *----------------------------------------------------------------------
2774 */
2775
2776 int
2777 Tcl_AppendObjCmd(
2778 ClientData dummy, /* Not used. */
2779 Tcl_Interp *interp, /* Current interpreter. */
2780 int objc, /* Number of arguments. */
2781 Tcl_Obj *const objv[]) /* Argument objects. */
2782 {
2783 Var *varPtr, *arrayPtr;
2784 Tcl_Obj *varValuePtr = NULL;
2785 /* Initialized to avoid compiler warning. */
2786 int i;
2787
2788 if (objc < 2) {
2789 Tcl_WrongNumArgs(interp, 1, objv, "varName ?value ...?");
2790 return TCL_ERROR;
2791 }
2792
2793 if (objc == 2) {
2794 varValuePtr = Tcl_ObjGetVar2(interp, objv[1], NULL,TCL_LEAVE_ERR_MSG);
2795 if (varValuePtr == NULL) {
2796 return TCL_ERROR;
2797 }
2798 } else {
2799 varPtr = TclObjLookupVarEx(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG,
2800 "set", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr);
2801 if (varPtr == NULL) {
2802 return TCL_ERROR;
2803 }
2804 for (i=2 ; i<objc ; i++) {
2805 /*
2806 * Note that we do not need to increase the refCount of the Var
2807 * pointers: should a trace delete the variable, the return value
2808 * of TclPtrSetVarIdx will be NULL or emptyObjPtr, and we will not
2809 * access the variable again.
2810 */
2811
2812 varValuePtr = TclPtrSetVarIdx(interp, varPtr, arrayPtr, objv[1],
2813 NULL, objv[i], TCL_APPEND_VALUE|TCL_LEAVE_ERR_MSG, -1);
2814 if ((varValuePtr == NULL) ||
2815 (varValuePtr == ((Interp *) interp)->emptyObjPtr)) {
2816 return TCL_ERROR;
2817 }
2818 }
2819 }
2820 Tcl_SetObjResult(interp, varValuePtr);
2821 return TCL_OK;
2822 }
2823
2824 /*
2825 *----------------------------------------------------------------------
2826 *
2827 * Tcl_LappendObjCmd --
2828 *
2829 * This object-based function is invoked to process the "lappend" Tcl
2830 * command. See the user documentation for details on what it does.
2831 *
2832 * Results:
2833 * A standard Tcl object result value.
2834 *
2835 * Side effects:
2836 * A variable's value may be changed.
2837 *
2838 *----------------------------------------------------------------------
2839 */
2840
2841 int
2842 Tcl_LappendObjCmd(
2843 ClientData dummy, /* Not used. */
2844 Tcl_Interp *interp, /* Current interpreter. */
2845 int objc, /* Number of arguments. */
2846 Tcl_Obj *const objv[]) /* Argument objects. */
2847 {
2848 Tcl_Obj *varValuePtr, *newValuePtr;
2849 int numElems, createdNewObj;
2850 Var *varPtr, *arrayPtr;
2851 int result;
2852
2853 if (objc < 2) {
2854 Tcl_WrongNumArgs(interp, 1, objv, "varName ?value ...?");
2855 return TCL_ERROR;
2856 }
2857 if (objc == 2) {
2858 newValuePtr = Tcl_ObjGetVar2(interp, objv[1], NULL, 0);
2859 if (newValuePtr == NULL) {
2860 /*
2861 * The variable doesn't exist yet. Just create it with an empty
2862 * initial value.
2863 */
2864
2865 TclNewObj(varValuePtr);
2866 newValuePtr = Tcl_ObjSetVar2(interp, objv[1], NULL, varValuePtr,
2867 TCL_LEAVE_ERR_MSG);
2868 if (newValuePtr == NULL) {
2869 return TCL_ERROR;
2870 }
2871 } else {
2872 result = TclListObjLength(interp, newValuePtr, &numElems);
2873 if (result != TCL_OK) {
2874 return result;
2875 }
2876 }
2877 } else {
2878 /*
2879 * We have arguments to append. We used to call Tcl_SetVar2 to append
2880 * each argument one at a time to ensure that traces were run for each
2881 * append step. We now append the arguments all at once because it's
2882 * faster. Note that a read trace and a write trace for the variable
2883 * will now each only be called once. Also, if the variable's old
2884 * value is unshared we modify it directly, otherwise we create a new
2885 * copy to modify: this is "copy on write".
2886 */
2887
2888 createdNewObj = 0;
2889
2890 /*
2891 * Protect the variable pointers around the TclPtrGetVarIdx call
2892 * to insure that they remain valid even if the variable was undefined
2893 * and unused.
2894 */
2895
2896 varPtr = TclObjLookupVarEx(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG,
2897 "set", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr);
2898 if (varPtr == NULL) {
2899 return TCL_ERROR;
2900 }
2901 if (TclIsVarInHash(varPtr)) {
2902 VarHashRefCount(varPtr)++;
2903 }
2904 if (arrayPtr && TclIsVarInHash(arrayPtr)) {
2905 VarHashRefCount(arrayPtr)++;
2906 }
2907 varValuePtr = TclPtrGetVarIdx(interp, varPtr, arrayPtr, objv[1], NULL,
2908 TCL_LEAVE_ERR_MSG, -1);
2909 if (TclIsVarInHash(varPtr)) {
2910 VarHashRefCount(varPtr)--;
2911 }
2912 if (arrayPtr && TclIsVarInHash(arrayPtr)) {
2913 VarHashRefCount(arrayPtr)--;
2914 }
2915
2916 if (varValuePtr == NULL) {
2917 /*
2918 * We couldn't read the old value: either the var doesn't yet
2919 * exist or it's an array element. If it's new, we will try to
2920 * create it with Tcl_ObjSetVar2 below.
2921 */
2922
2923 TclNewObj(varValuePtr);
2924 createdNewObj = 1;
2925 } else if (Tcl_IsShared(varValuePtr)) {
2926 varValuePtr = Tcl_DuplicateObj(varValuePtr);
2927 createdNewObj = 1;
2928 }
2929
2930 result = TclListObjLength(interp, varValuePtr, &numElems);
2931 if (result == TCL_OK) {
2932 result = Tcl_ListObjReplace(interp, varValuePtr, numElems, 0,
2933 (objc-2), (objv+2));
2934 }
2935 if (result != TCL_OK) {
2936 if (createdNewObj) {
2937 TclDecrRefCount(varValuePtr); /* Free unneeded obj. */
2938 }
2939 return result;
2940 }
2941
2942 /*
2943 * Now store the list object back into the variable. If there is an
2944 * error setting the new value, decrement its ref count if it was new
2945 * and we didn't create the variable.
2946 */
2947
2948 newValuePtr = TclPtrSetVarIdx(interp, varPtr, arrayPtr, objv[1], NULL,
2949 varValuePtr, TCL_LEAVE_ERR_MSG, -1);
2950 if (newValuePtr == NULL) {
2951 return TCL_ERROR;
2952 }
2953 }
2954
2955 /*
2956 * Set the interpreter's object result to refer to the variable's value
2957 * object.
2958 */
2959
2960 Tcl_SetObjResult(interp, newValuePtr);
2961 return TCL_OK;
2962 }
2963
2964 /*
2965 *----------------------------------------------------------------------
2966 *
2967 * ArrayStartSearchCmd --
2968 *
2969 * This object-based function is invoked to process the "array
2970 * startsearch" Tcl command. See the user documentation for details on
2971 * what it does.
2972 *
2973 * Results:
2974 * A standard Tcl result object.
2975 *
2976 * Side effects:
2977 * See the user documentation.
2978 *
2979 *----------------------------------------------------------------------
2980 */
2981
2982 static int
2983 ArrayStartSearchCmd(
2984 ClientData clientData,
2985 Tcl_Interp *interp,
2986 int objc,
2987 Tcl_Obj *const objv[])
2988 {
2989 Interp *iPtr = (Interp *)interp;
2990 Var *varPtr;
2991 Tcl_HashEntry *hPtr;
2992 int isNew, isArray;
2993 ArraySearch *searchPtr;
2994 const char *varName;
2995
2996 if (objc != 2) {
2997 Tcl_WrongNumArgs(interp, 1, objv, "arrayName");
2998 return TCL_ERROR;
2999 }
3000
3001 if (TCL_ERROR == LocateArray(interp, objv[1], &varPtr, &isArray)) {
3002 return TCL_ERROR;
3003 }
3004
3005 if (!isArray) {
3006 return NotArrayError(interp, objv[1]);
3007 }
3008
3009 /*
3010 * Make a new array search with a free name.
3011 */
3012
3013 varName = TclGetString(objv[1]);
3014 searchPtr = ckalloc(sizeof(ArraySearch));
3015 hPtr = Tcl_CreateHashEntry(&iPtr->varSearches, varPtr, &isNew);
3016 if (isNew) {
3017 searchPtr->id = 1;
3018 varPtr->flags |= VAR_SEARCH_ACTIVE;
3019 searchPtr->nextPtr = NULL;
3020 } else {
3021 searchPtr->id = ((ArraySearch *) Tcl_GetHashValue(hPtr))->id + 1;
3022 searchPtr->nextPtr = Tcl_GetHashValue(hPtr);
3023 }
3024 searchPtr->varPtr = varPtr;
3025 searchPtr->nextEntry = VarHashFirstEntry(varPtr->value.tablePtr,
3026 &searchPtr->search);
3027 Tcl_SetHashValue(hPtr, searchPtr);
3028 Tcl_SetObjResult(interp,
3029 Tcl_ObjPrintf("s-%d-%s", searchPtr->id, varName));
3030 return TCL_OK;
3031 }
3032
3033 /*
3034 *----------------------------------------------------------------------
3035 *
3036 * ArrayAnyMoreCmd --
3037 *
3038 * This object-based function is invoked to process the "array anymore"
3039 * Tcl command. See the user documentation for details on what it does.
3040 *
3041 * Results:
3042 * A standard Tcl result object.
3043 *
3044 * Side effects:
3045 * See the user documentation.
3046 *
3047 *----------------------------------------------------------------------
3048 */
3049
3050 static int
3051 ArrayAnyMoreCmd(
3052 ClientData clientData,
3053 Tcl_Interp *interp,
3054 int objc,
3055 Tcl_Obj *const objv[])
3056 {
3057 Interp *iPtr = (Interp *)interp;
3058 Var *varPtr;
3059 Tcl_Obj *varNameObj, *searchObj;
3060 int gotValue, isArray;
3061 ArraySearch *searchPtr;
3062
3063 if (objc != 3) {
3064 Tcl_WrongNumArgs(interp, 1, objv, "arrayName searchId");
3065 return TCL_ERROR;
3066 }
3067 varNameObj = objv[1];
3068 searchObj = objv[2];
3069
3070 if (TCL_ERROR == LocateArray(interp, varNameObj, &varPtr, &isArray)) {
3071 return TCL_ERROR;
3072 }
3073
3074 if (!isArray) {
3075 return NotArrayError(interp, varNameObj);
3076 }
3077
3078 /*
3079 * Get the search.
3080 */
3081
3082 searchPtr = ParseSearchId(interp, varPtr, varNameObj, searchObj);
3083 if (searchPtr == NULL) {
3084 return TCL_ERROR;
3085 }
3086
3087 /*
3088 * Scan forward to find if there are any further elements in the array
3089 * that are defined.
3090 */
3091
3092 while (1) {
3093 if (searchPtr->nextEntry != NULL) {
3094 varPtr = VarHashGetValue(searchPtr->nextEntry);
3095 if (!TclIsVarUndefined(varPtr)) {
3096 gotValue = 1;
3097 break;
3098 }
3099 }
3100 searchPtr->nextEntry = Tcl_NextHashEntry(&searchPtr->search);
3101 if (searchPtr->nextEntry == NULL) {
3102 gotValue = 0;
3103 break;
3104 }
3105 }
3106 Tcl_SetObjResult(interp, iPtr->execEnvPtr->constants[gotValue]);
3107 return TCL_OK;
3108 }
3109
3110 /*
3111 *----------------------------------------------------------------------
3112 *
3113 * ArrayNextElementCmd --
3114 *
3115 * This object-based function is invoked to process the "array
3116 * nextelement" Tcl command. See the user documentation for details on
3117 * what it does.
3118 *
3119 * Results:
3120 * A standard Tcl result object.
3121 *
3122 * Side effects:
3123 * See the user documentation.
3124 *
3125 *----------------------------------------------------------------------
3126 */
3127
3128 static int
3129 ArrayNextElementCmd(
3130 ClientData clientData,
3131 Tcl_Interp *interp,
3132 int objc,
3133 Tcl_Obj *const objv[])
3134 {
3135 Var *varPtr;
3136 Tcl_Obj *varNameObj, *searchObj;
3137 ArraySearch *searchPtr;
3138 int isArray;
3139
3140 if (objc != 3) {
3141 Tcl_WrongNumArgs(interp, 1, objv, "arrayName searchId");
3142 return TCL_ERROR;
3143 }
3144 varNameObj = objv[1];
3145 searchObj = objv[2];
3146
3147 if (TCL_ERROR == LocateArray(interp, varNameObj, &varPtr, &isArray)) {
3148 return TCL_ERROR;
3149 }
3150
3151 if (!isArray) {
3152 return NotArrayError(interp, varNameObj);
3153 }
3154
3155 /*
3156 * Get the search.
3157 */
3158
3159 searchPtr = ParseSearchId(interp, varPtr, varNameObj, searchObj);
3160 if (searchPtr == NULL) {
3161 return TCL_ERROR;
3162 }
3163
3164 /*
3165 * Get the next element from the search, or the empty string on
3166 * exhaustion. Note that the [array anymore] command may well have already
3167 * pulled a value from the hash enumeration, so we have to check the cache
3168 * there first.
3169 */
3170
3171 while (1) {
3172 Tcl_HashEntry *hPtr = searchPtr->nextEntry;
3173
3174 if (hPtr == NULL) {
3175 hPtr = Tcl_NextHashEntry(&searchPtr->search);
3176 if (hPtr == NULL) {
3177 return TCL_OK;
3178 }
3179 } else {
3180 searchPtr->nextEntry = NULL;
3181 }
3182 varPtr = VarHashGetValue(hPtr);
3183 if (!TclIsVarUndefined(varPtr)) {
3184 Tcl_SetObjResult(interp, VarHashGetKey(varPtr));
3185 return TCL_OK;
3186 }
3187 }
3188 }
3189
3190 /*
3191 *----------------------------------------------------------------------
3192 *
3193 * ArrayDoneSearchCmd --
3194 *
3195 * This object-based function is invoked to process the "array
3196 * donesearch" Tcl command. See the user documentation for details on
3197 * what it does.
3198 *
3199 * Results:
3200 * A standard Tcl result object.
3201 *
3202 * Side effects:
3203 * See the user documentation.
3204 *
3205 *----------------------------------------------------------------------
3206 */
3207
3208 static int
3209 ArrayDoneSearchCmd(
3210 ClientData clientData,
3211 Tcl_Interp *interp,
3212 int objc,
3213 Tcl_Obj *const objv[])
3214 {
3215 Interp *iPtr = (Interp *)interp;
3216 Var *varPtr;
3217 Tcl_HashEntry *hPtr;
3218 Tcl_Obj *varNameObj, *searchObj;
3219 ArraySearch *searchPtr, *prevPtr;
3220 int isArray;
3221
3222 if (objc != 3) {
3223 Tcl_WrongNumArgs(interp, 1, objv, "arrayName searchId");
3224 return TCL_ERROR;
3225 }
3226 varNameObj = objv[1];
3227 searchObj = objv[2];
3228
3229 if (TCL_ERROR == LocateArray(interp, varNameObj, &varPtr, &isArray)) {
3230 return TCL_ERROR;
3231 }
3232
3233 if (!isArray) {
3234 return NotArrayError(interp, varNameObj);
3235 }
3236
3237 /*
3238 * Get the search.
3239 */
3240
3241 searchPtr = ParseSearchId(interp, varPtr, varNameObj, searchObj);
3242 if (searchPtr == NULL) {
3243 return TCL_ERROR;
3244 }
3245
3246 /*
3247 * Unhook the search from the list of searches associated with the
3248 * variable.
3249 */
3250
3251 hPtr = Tcl_FindHashEntry(&iPtr->varSearches, varPtr);
3252 if (searchPtr == Tcl_GetHashValue(hPtr)) {
3253 if (searchPtr->nextPtr) {
3254 Tcl_SetHashValue(hPtr, searchPtr->nextPtr);
3255 } else {
3256 varPtr->flags &= ~VAR_SEARCH_ACTIVE;
3257 Tcl_DeleteHashEntry(hPtr);
3258 }
3259 } else {
3260 for (prevPtr=Tcl_GetHashValue(hPtr) ;; prevPtr=prevPtr->nextPtr) {
3261 if (prevPtr->nextPtr == searchPtr) {
3262 prevPtr->nextPtr = searchPtr->nextPtr;
3263 break;
3264 }
3265 }
3266 }
3267 ckfree(searchPtr);
3268 return TCL_OK;
3269 }
3270
3271 /*
3272 *----------------------------------------------------------------------
3273 *
3274 * ArrayExistsCmd --
3275 *
3276 * This object-based function is invoked to process the "array exists"
3277 * Tcl command. See the user documentation for details on what it does.
3278 *
3279 * Results:
3280 * A standard Tcl result object.
3281 *
3282 * Side effects:
3283 * See the user documentation.
3284 *
3285 *----------------------------------------------------------------------
3286 */
3287
3288 static int
3289 ArrayExistsCmd(
3290 ClientData clientData,
3291 Tcl_Interp *interp,
3292 int objc,
3293 Tcl_Obj *const objv[])
3294 {
3295 Interp *iPtr = (Interp *)interp;
3296 int isArray;
3297
3298 if (objc != 2) {
3299 Tcl_WrongNumArgs(interp, 1, objv, "arrayName");
3300 return TCL_ERROR;
3301 }
3302
3303 if (TCL_ERROR == LocateArray(interp, objv[1], NULL, &isArray)) {
3304 return TCL_ERROR;
3305 }
3306
3307 Tcl_SetObjResult(interp, iPtr->execEnvPtr->constants[isArray]);
3308 return TCL_OK;
3309 }
3310
3311 /*
3312 *----------------------------------------------------------------------
3313 *
3314 * ArrayGetCmd --
3315 *
3316 * This object-based function is invoked to process the "array get" Tcl
3317 * command. See the user documentation for details on what it does.
3318 *
3319 * Results:
3320 * A standard Tcl result object.
3321 *
3322 * Side effects:
3323 * See the user documentation.
3324 *
3325 *----------------------------------------------------------------------
3326 */
3327
3328 static int
3329 ArrayGetCmd(
3330 ClientData clientData,
3331 Tcl_Interp *interp,
3332 int objc,
3333 Tcl_Obj *const objv[])
3334 {
3335 Var *varPtr, *varPtr2;
3336 Tcl_Obj *varNameObj, *nameObj, *valueObj, *nameLstObj, *tmpResObj;
3337 Tcl_Obj **nameObjPtr, *patternObj;
3338 Tcl_HashSearch search;
3339 const char *pattern;
3340 int i, count, result, isArray;
3341
3342 switch (objc) {
3343 case 2:
3344 varNameObj = objv[1];
3345 patternObj = NULL;
3346 break;
3347 case 3:
3348 varNameObj = objv[1];
3349 patternObj = objv[2];
3350 break;
3351 default:
3352 Tcl_WrongNumArgs(interp, 1, objv, "arrayName ?pattern?");
3353 return TCL_ERROR;
3354 }
3355
3356 if (TCL_ERROR == LocateArray(interp, varNameObj, &varPtr, &isArray)) {
3357 return TCL_ERROR;
3358 }
3359
3360 /* If not an array, it's an empty result. */
3361 if (!isArray) {
3362 return TCL_OK;
3363 }
3364
3365 pattern = (patternObj ? TclGetString(patternObj) : NULL);
3366
3367 /*
3368 * Store the array names in a new object.
3369 */
3370
3371 TclNewObj(nameLstObj);
3372 Tcl_IncrRefCount(nameLstObj);
3373 if ((patternObj != NULL) && TclMatchIsTrivial(pattern)) {
3374 varPtr2 = VarHashFindVar(varPtr->value.tablePtr, patternObj);
3375 if (varPtr2 == NULL) {
3376 goto searchDone;
3377 }
3378 if (TclIsVarUndefined(varPtr2)) {
3379 goto searchDone;
3380 }
3381 result = Tcl_ListObjAppendElement(interp, nameLstObj,
3382 VarHashGetKey(varPtr2));
3383 if (result != TCL_OK) {
3384 TclDecrRefCount(nameLstObj);
3385 return result;
3386 }
3387 goto searchDone;
3388 }
3389
3390 for (varPtr2 = VarHashFirstVar(varPtr->value.tablePtr, &search);
3391 varPtr2; varPtr2 = VarHashNextVar(&search)) {
3392 if (TclIsVarUndefined(varPtr2)) {
3393 continue;
3394 }
3395 nameObj = VarHashGetKey(varPtr2);
3396 if (patternObj && !Tcl_StringMatch(TclGetString(nameObj), pattern)) {
3397 continue; /* Element name doesn't match pattern. */
3398 }
3399
3400 result = Tcl_ListObjAppendElement(interp, nameLstObj, nameObj);
3401 if (result != TCL_OK) {
3402 TclDecrRefCount(nameLstObj);
3403 return result;
3404 }
3405 }
3406
3407 /*
3408 * Make sure the Var structure of the array is not removed by a trace
3409 * while we're working.
3410 */
3411
3412 searchDone:
3413 if (TclIsVarInHash(varPtr)) {
3414 VarHashRefCount(varPtr)++;
3415 }
3416
3417 /*
3418 * Get the array values corresponding to each element name.
3419 */
3420
3421 TclNewObj(tmpResObj);
3422 result = TclListObjGetElements(interp, nameLstObj, &count, &nameObjPtr);
3423 if (result != TCL_OK) {
3424 goto errorInArrayGet;
3425 }
3426
3427 for (i=0 ; i<count ; i++) {
3428 nameObj = *nameObjPtr++;
3429 valueObj = Tcl_ObjGetVar2(interp, varNameObj, nameObj,
3430 TCL_LEAVE_ERR_MSG);
3431 if (valueObj == NULL) {
3432 /*
3433 * Some trace played a trick on us; we need to diagnose to adapt
3434 * our behaviour: was the array element unset, or did the
3435 * modification modify the complete array?
3436 */
3437
3438 if (TclIsVarArray(varPtr)) {
3439 /*
3440 * The array itself looks OK, the variable was undefined:
3441 * forget it.
3442 */
3443
3444 continue;
3445 }
3446 result = TCL_ERROR;
3447 goto errorInArrayGet;
3448 }
3449 result = Tcl_DictObjPut(interp, tmpResObj, nameObj, valueObj);
3450 if (result != TCL_OK) {
3451 goto errorInArrayGet;
3452 }
3453 }
3454 if (TclIsVarInHash(varPtr)) {
3455 VarHashRefCount(varPtr)--;
3456 }
3457 Tcl_SetObjResult(interp, tmpResObj);
3458 TclDecrRefCount(nameLstObj);
3459 return TCL_OK;
3460
3461 errorInArrayGet:
3462 if (TclIsVarInHash(varPtr)) {
3463 VarHashRefCount(varPtr)--;
3464 }
3465 TclDecrRefCount(nameLstObj);
3466 TclDecrRefCount(tmpResObj); /* Free unneeded temp result. */
3467 return result;
3468 }
3469
3470 /*
3471 *----------------------------------------------------------------------
3472 *
3473 * ArrayNamesCmd --
3474 *
3475 * This object-based function is invoked to process the "array names" Tcl
3476 * command. See the user documentation for details on what it does.
3477 *
3478 * Results:
3479 * A standard Tcl result object.
3480 *
3481 * Side effects:
3482 * See the user documentation.
3483 *
3484 *----------------------------------------------------------------------
3485 */
3486
3487 static int
3488 ArrayNamesCmd(
3489 ClientData clientData,
3490 Tcl_Interp *interp,
3491 int objc,
3492 Tcl_Obj *const objv[])
3493 {
3494 static const char *const options[] = {
3495 "-exact", "-glob", "-regexp", NULL
3496 };
3497 enum arrayNamesOptionsEnum { OPT_EXACT, OPT_GLOB, OPT_REGEXP };
3498 Var *varPtr, *varPtr2;
3499 Tcl_Obj *nameObj, *resultObj, *patternObj;
3500 Tcl_HashSearch search;
3501 const char *pattern = NULL;
3502 int isArray, mode = OPT_GLOB;
3503
3504 if ((objc < 2) || (objc > 4)) {
3505 Tcl_WrongNumArgs(interp, 1, objv, "arrayName ?mode? ?pattern?");
3506 return TCL_ERROR;
3507 }
3508 patternObj = (objc > 2 ? objv[objc-1] : NULL);
3509
3510 if (TCL_ERROR == LocateArray(interp, objv[1], &varPtr, &isArray)) {
3511 return TCL_ERROR;
3512 }
3513
3514 /*
3515 * Finish parsing the arguments.
3516 */
3517
3518 if ((objc == 4) && Tcl_GetIndexFromObj(interp, objv[2], options, "option",
3519 0, &mode) != TCL_OK) {
3520 return TCL_ERROR;
3521 }
3522
3523 /* If not an array, the result is empty. */
3524
3525 if (!isArray) {
3526 return TCL_OK;
3527 }
3528
3529 /*
3530 * Check for the trivial cases where we can use a direct lookup.
3531 */
3532
3533 TclNewObj(resultObj);
3534 if (patternObj) {
3535 pattern = TclGetString(patternObj);
3536 }
3537 if ((mode==OPT_GLOB && patternObj && TclMatchIsTrivial(pattern))
3538 || (mode==OPT_EXACT)) {
3539 varPtr2 = VarHashFindVar(varPtr->value.tablePtr, patternObj);
3540 if ((varPtr2 != NULL) && !TclIsVarUndefined(varPtr2)) {
3541 /*
3542 * This can't fail; lappending to an empty object always works.
3543 */
3544
3545 Tcl_ListObjAppendElement(NULL, resultObj, VarHashGetKey(varPtr2));
3546 }
3547 Tcl_SetObjResult(interp, resultObj);
3548 return TCL_OK;
3549 }
3550
3551 /*
3552 * Must scan the array to select the elements.
3553 */
3554
3555 for (varPtr2=VarHashFirstVar(varPtr->value.tablePtr, &search);
3556 varPtr2!=NULL ; varPtr2=VarHashNextVar(&search)) {
3557 if (TclIsVarUndefined(varPtr2)) {
3558 continue;
3559 }
3560 nameObj = VarHashGetKey(varPtr2);
3561 if (patternObj) {
3562 const char *name = TclGetString(nameObj);
3563 int matched = 0;
3564
3565 switch ((enum arrayNamesOptionsEnum) mode) {
3566 case OPT_EXACT:
3567 Tcl_Panic("exact matching shouldn't get here");
3568 case OPT_GLOB:
3569 matched = Tcl_StringMatch(name, pattern);
3570 break;
3571 case OPT_REGEXP:
3572 matched = Tcl_RegExpMatchObj(interp, nameObj, patternObj);
3573 if (matched < 0) {
3574 TclDecrRefCount(resultObj);
3575 return TCL_ERROR;
3576 }
3577 break;
3578 }
3579 if (matched == 0) {
3580 continue;
3581 }
3582 }
3583
3584 Tcl_ListObjAppendElement(NULL, resultObj, nameObj);
3585 }
3586 Tcl_SetObjResult(interp, resultObj);
3587 return TCL_OK;
3588 }
3589
3590 /*
3591 *----------------------------------------------------------------------
3592 *
3593 * TclFindArrayPtrElements --
3594 *
3595 * Fill out a hash table (which *must* use Tcl_Obj* keys) with an entry
3596 * for each existing element of the given array. The provided hash table
3597 * is assumed to be initially empty.
3598 *
3599 * Result:
3600 * none
3601 *
3602 * Side effects:
3603 * The keys of the array gain an extra reference. The supplied hash table
3604 * has elements added to it.
3605 *
3606 *----------------------------------------------------------------------
3607 */
3608
3609 void
3610 TclFindArrayPtrElements(
3611 Var *arrayPtr,
3612 Tcl_HashTable *tablePtr)
3613 {
3614 Var *varPtr;
3615 Tcl_HashSearch search;
3616
3617 if ((arrayPtr == NULL) || !TclIsVarArray(arrayPtr)
3618 || TclIsVarUndefined(arrayPtr)) {
3619 return;
3620 }
3621
3622 for (varPtr=VarHashFirstVar(arrayPtr->value.tablePtr, &search);
3623 varPtr!=NULL ; varPtr=VarHashNextVar(&search)) {
3624 Tcl_HashEntry *hPtr;
3625 Tcl_Obj *nameObj;
3626 int dummy;
3627
3628 if (TclIsVarUndefined(varPtr)) {
3629 continue;
3630 }
3631 nameObj = VarHashGetKey(varPtr);
3632 hPtr = Tcl_CreateHashEntry(tablePtr, (char *) nameObj, &dummy);
3633 Tcl_SetHashValue(hPtr, nameObj);
3634 }
3635 }
3636
3637 /*
3638 *----------------------------------------------------------------------
3639 *
3640 * ArraySetCmd --
3641 *
3642 * This object-based function is invoked to process the "array set" Tcl
3643 * command. See the user documentation for details on what it does.
3644 *
3645 * Results:
3646 * A standard Tcl result object.
3647 *
3648 * Side effects:
3649 * See the user documentation.
3650 *
3651 *----------------------------------------------------------------------
3652 */
3653
3654 static int
3655 ArraySetCmd(
3656 ClientData clientData,
3657 Tcl_Interp *interp,
3658 int objc,
3659 Tcl_Obj *const objv[])
3660 {
3661 Tcl_Obj *arrayNameObj;
3662 Tcl_Obj *arrayElemObj;
3663 Var *varPtr, *arrayPtr;
3664 int result, i;
3665
3666 if (objc != 3) {
3667 Tcl_WrongNumArgs(interp, 1, objv, "arrayName list");
3668 return TCL_ERROR;
3669 }
3670
3671 if (TCL_ERROR == LocateArray(interp, objv[1], NULL, NULL)) {
3672 return TCL_ERROR;
3673 }
3674
3675 arrayNameObj = objv[1];
3676 varPtr = TclObjLookupVarEx(interp, arrayNameObj, NULL,
3677 /*flags*/ TCL_LEAVE_ERR_MSG, /*msg*/ "set", /*createPart1*/ 1,
3678 /*createPart2*/ 1, &arrayPtr);
3679 if (varPtr == NULL) {
3680 return TCL_ERROR;
3681 }
3682 if (arrayPtr) {
3683 CleanupVar(varPtr, arrayPtr);
3684 TclObjVarErrMsg(interp, arrayNameObj, NULL, "set", NEEDARRAY, -1);
3685 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
3686 TclGetString(arrayNameObj), (char *)NULL);
3687 return TCL_ERROR;
3688 }
3689
3690 /*
3691 * Install the contents of the dictionary or list into the array.
3692 */
3693
3694 arrayElemObj = objv[2];
3695 if (arrayElemObj->typePtr == &tclDictType && arrayElemObj->bytes == NULL) {
3696 Tcl_Obj *keyPtr, *valuePtr;
3697 Tcl_DictSearch search;
3698 int done;
3699
3700 if (Tcl_DictObjSize(interp, arrayElemObj, &done) != TCL_OK) {
3701 return TCL_ERROR;
3702 }
3703 if (done == 0) {
3704 /*
3705 * Empty, so we'll just force the array to be properly existing
3706 * instead.
3707 */
3708
3709 goto ensureArray;
3710 }
3711
3712 /*
3713 * Don't need to look at result of Tcl_DictObjFirst as we've just
3714 * successfully used a dictionary operation on the same object.
3715 */
3716
3717 for (Tcl_DictObjFirst(interp, arrayElemObj, &search,
3718 &keyPtr, &valuePtr, &done) ; !done ;
3719 Tcl_DictObjNext(&search, &keyPtr, &valuePtr, &done)) {
3720 /*
3721 * At this point, it would be nice if the key was directly usable
3722 * by the array. This isn't the case though.
3723 */
3724
3725 Var *elemVarPtr = TclLookupArrayElement(interp, arrayNameObj,
3726 keyPtr, TCL_LEAVE_ERR_MSG, "set", 1, 1, varPtr, -1);
3727
3728 if ((elemVarPtr == NULL) ||
3729 (TclPtrSetVarIdx(interp, elemVarPtr, varPtr, arrayNameObj,
3730 keyPtr, valuePtr, TCL_LEAVE_ERR_MSG, -1) == NULL)) {
3731 Tcl_DictObjDone(&search);
3732 return TCL_ERROR;
3733 }
3734 }
3735 return TCL_OK;
3736 } else {
3737 /*
3738 * Not a dictionary, so assume (and convert to, for backward-
3739 * -compatibility reasons) a list.
3740 */
3741
3742 int elemLen;
3743 Tcl_Obj **elemPtrs, *copyListObj;
3744
3745 result = TclListObjGetElements(interp, arrayElemObj,
3746 &elemLen, &elemPtrs);
3747 if (result != TCL_OK) {
3748 return result;
3749 }
3750 if (elemLen & 1) {
3751 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3752 "list must have an even number of elements", -1));
3753 Tcl_SetErrorCode(interp, "TCL", "ARGUMENT", "FORMAT", (char *)NULL);
3754 return TCL_ERROR;
3755 }
3756 if (elemLen == 0) {
3757 goto ensureArray;
3758 }
3759
3760 /*
3761 * We needn't worry about traces invalidating arrayPtr: should that be
3762 * the case, TclPtrSetVarIdx will return NULL so that we break out of
3763 * the loop and return an error.
3764 */
3765
3766 copyListObj = TclListObjCopy(NULL, arrayElemObj);
3767 for (i=0 ; i<elemLen ; i+=2) {
3768 Var *elemVarPtr = TclLookupArrayElement(interp, arrayNameObj,
3769 elemPtrs[i], TCL_LEAVE_ERR_MSG, "set", 1, 1, varPtr, -1);
3770
3771 if ((elemVarPtr == NULL) ||
3772 (TclPtrSetVarIdx(interp, elemVarPtr, varPtr, arrayNameObj,
3773 elemPtrs[i], elemPtrs[i+1], TCL_LEAVE_ERR_MSG,
3774 -1) == NULL)) {
3775 result = TCL_ERROR;
3776 break;
3777 }
3778 }
3779 Tcl_DecrRefCount(copyListObj);
3780 return result;
3781 }
3782
3783 /*
3784 * The list is empty make sure we have an array, or create one if
3785 * necessary.
3786 */
3787
3788 ensureArray:
3789 if (varPtr != NULL) {
3790 if (TclIsVarArray(varPtr)) {
3791 /*
3792 * Already an array, done.
3793 */
3794
3795 return TCL_OK;
3796 }
3797 if (TclIsVarArrayElement(varPtr) || !TclIsVarUndefined(varPtr)) {
3798 /*
3799 * Either an array element, or a scalar: lose!
3800 */
3801
3802 TclObjVarErrMsg(interp, arrayNameObj, NULL, "array set",
3803 NEEDARRAY, -1);
3804 Tcl_SetErrorCode(interp, "TCL", "WRITE", "ARRAY", (char *)NULL);
3805 return TCL_ERROR;
3806 }
3807 }
3808 TclSetVarArray(varPtr);
3809 varPtr->value.tablePtr = ckalloc(sizeof(TclVarHashTable));
3810 TclInitVarHashTable(varPtr->value.tablePtr, TclGetVarNsPtr(varPtr));
3811 return TCL_OK;
3812 }
3813
3814 /*
3815 *----------------------------------------------------------------------
3816 *
3817 * ArraySizeCmd --
3818 *
3819 * This object-based function is invoked to process the "array size" Tcl
3820 * command. See the user documentation for details on what it does.
3821 *
3822 * Results:
3823 * A standard Tcl result object.
3824 *
3825 * Side effects:
3826 * See the user documentation.
3827 *
3828 *----------------------------------------------------------------------
3829 */
3830
3831 static int
3832 ArraySizeCmd(
3833 ClientData clientData,
3834 Tcl_Interp *interp,
3835 int objc,
3836 Tcl_Obj *const objv[])
3837 {
3838 Var *varPtr;
3839 Tcl_HashSearch search;
3840 Var *varPtr2;
3841 int isArray, size = 0;
3842
3843 if (objc != 2) {
3844 Tcl_WrongNumArgs(interp, 1, objv, "arrayName");
3845 return TCL_ERROR;
3846 }
3847
3848 if (TCL_ERROR == LocateArray(interp, objv[1], &varPtr, &isArray)) {
3849 return TCL_ERROR;
3850 }
3851
3852 /* We can only iterate over the array if it exists... */
3853
3854 if (isArray) {
3855 /*
3856 * Must iterate in order to get chance to check for present but
3857 * "undefined" entries.
3858 */
3859
3860 for (varPtr2=VarHashFirstVar(varPtr->value.tablePtr, &search);
3861 varPtr2!=NULL ; varPtr2=VarHashNextVar(&search)) {
3862 if (!TclIsVarUndefined(varPtr2)) {
3863 size++;
3864 }
3865 }
3866 }
3867
3868 Tcl_SetObjResult(interp, Tcl_NewIntObj(size));
3869 return TCL_OK;
3870 }
3871
3872 /*
3873 *----------------------------------------------------------------------
3874 *
3875 * ArrayStatsCmd --
3876 *
3877 * This object-based function is invoked to process the "array
3878 * statistics" Tcl command. See the user documentation for details on
3879 * what it does.
3880 *
3881 * Results:
3882 * A standard Tcl result object.
3883 *
3884 * Side effects:
3885 * See the user documentation.
3886 *
3887 *----------------------------------------------------------------------
3888 */
3889
3890 static int
3891 ArrayStatsCmd(
3892 ClientData clientData,
3893 Tcl_Interp *interp,
3894 int objc,
3895 Tcl_Obj *const objv[])
3896 {
3897 Var *varPtr;
3898 Tcl_Obj *varNameObj;
3899 char *stats;
3900 int isArray;
3901
3902 if (objc != 2) {
3903 Tcl_WrongNumArgs(interp, 1, objv, "arrayName");
3904 return TCL_ERROR;
3905 }
3906 varNameObj = objv[1];
3907
3908 if (TCL_ERROR == LocateArray(interp, varNameObj, &varPtr, &isArray)) {
3909 return TCL_ERROR;
3910 }
3911
3912 if (!isArray) {
3913 return NotArrayError(interp, varNameObj);
3914 }
3915
3916 stats = Tcl_HashStats((Tcl_HashTable *) varPtr->value.tablePtr);
3917 if (stats == NULL) {
3918 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3919 "error reading array statistics", -1));
3920 return TCL_ERROR;
3921 }
3922 Tcl_SetObjResult(interp, Tcl_NewStringObj(stats, -1));
3923 ckfree(stats);
3924 return TCL_OK;
3925 }
3926
3927 /*
3928 *----------------------------------------------------------------------
3929 *
3930 * ArrayUnsetCmd --
3931 *
3932 * This object-based function is invoked to process the "array unset" Tcl
3933 * command. See the user documentation for details on what it does.
3934 *
3935 * Results:
3936 * A standard Tcl result object.
3937 *
3938 * Side effects:
3939 * See the user documentation.
3940 *
3941 *----------------------------------------------------------------------
3942 */
3943
3944 static int
3945 ArrayUnsetCmd(
3946 ClientData clientData,
3947 Tcl_Interp *interp,
3948 int objc,
3949 Tcl_Obj *const objv[])
3950 {
3951 Var *varPtr, *varPtr2, *protectedVarPtr;
3952 Tcl_Obj *varNameObj, *patternObj, *nameObj;
3953 Tcl_HashSearch search;
3954 const char *pattern;
3955 int unsetFlags = 0; /* Should this be TCL_LEAVE_ERR_MSG? */
3956 int isArray;
3957
3958 switch (objc) {
3959 case 2:
3960 varNameObj = objv[1];
3961 patternObj = NULL;
3962 break;
3963 case 3:
3964 varNameObj = objv[1];
3965 patternObj = objv[2];
3966 break;
3967 default:
3968 Tcl_WrongNumArgs(interp, 1, objv, "arrayName ?pattern?");
3969 return TCL_ERROR;
3970 }
3971
3972 if (TCL_ERROR == LocateArray(interp, varNameObj, &varPtr, &isArray)) {
3973 return TCL_ERROR;
3974 }
3975
3976 if (!isArray) {
3977 return TCL_OK;
3978 }
3979
3980 if (!patternObj) {
3981 /*
3982 * When no pattern is given, just unset the whole array.
3983 */
3984
3985 return TclObjUnsetVar2(interp, varNameObj, NULL, 0);
3986 }
3987
3988 /*
3989 * With a trivial pattern, we can just unset.
3990 */
3991
3992 pattern = TclGetString(patternObj);
3993 if (TclMatchIsTrivial(pattern)) {
3994 varPtr2 = VarHashFindVar(varPtr->value.tablePtr, patternObj);
3995 if (!varPtr2 || TclIsVarUndefined(varPtr2)) {
3996 return TCL_OK;
3997 }
3998 return TclPtrUnsetVarIdx(interp, varPtr2, varPtr, varNameObj,
3999 patternObj, unsetFlags, -1);
4000 }
4001
4002 /*
4003 * Non-trivial case (well, deeply tricky really). We peek inside the hash
4004 * iterator in order to allow us to guarantee that the following element
4005 * in the array will not be scrubbed until we have dealt with it. This
4006 * stops the overall iterator from ending up pointing into deallocated
4007 * memory. [Bug 2939073]
4008 */
4009
4010 protectedVarPtr = NULL;
4011 for (varPtr2=VarHashFirstVar(varPtr->value.tablePtr, &search);
4012 varPtr2!=NULL ; varPtr2=VarHashNextVar(&search)) {
4013 /*
4014 * Drop the extra ref immediately. We don't need to free it at this
4015 * point though; we'll be unsetting it if necessary soon.
4016 */
4017
4018 if (varPtr2 == protectedVarPtr) {
4019 VarHashRefCount(varPtr2)--;
4020 }
4021
4022 /*
4023 * Guard the next (peeked) item in the search chain by incrementing
4024 * its refcount. This guarantees that the hash table iterator won't be
4025 * dangling on the next time through the loop.
4026 */
4027
4028 if (search.nextEntryPtr != NULL) {
4029 protectedVarPtr = VarHashGetValue(search.nextEntryPtr);
4030 VarHashRefCount(protectedVarPtr)++;
4031 } else {
4032 protectedVarPtr = NULL;
4033 }
4034
4035 /*
4036 * If the variable is undefined, clean it out as it has been hit by
4037 * something else (i.e., an unset trace).
4038 */
4039
4040 if (TclIsVarUndefined(varPtr2)) {
4041 CleanupVar(varPtr2, varPtr);
4042 continue;
4043 }
4044
4045 nameObj = VarHashGetKey(varPtr2);
4046 if (Tcl_StringMatch(TclGetString(nameObj), pattern)
4047 && TclPtrUnsetVarIdx(interp, varPtr2, varPtr, varNameObj,
4048 nameObj, unsetFlags, -1) != TCL_OK) {
4049 /*
4050 * If we incremented a refcount, we must decrement it here as we
4051 * will not be coming back properly due to the error.
4052 */
4053
4054 if (protectedVarPtr) {
4055 VarHashRefCount(protectedVarPtr)--;
4056 CleanupVar(protectedVarPtr, varPtr);
4057 }
4058 return TCL_ERROR;
4059 }
4060 }
4061 return TCL_OK;
4062 }
4063
4064 /*
4065 *----------------------------------------------------------------------
4066 *
4067 * TclInitArrayCmd --
4068 *
4069 * This creates the ensemble for the "array" command.
4070 *
4071 * Results:
4072 * The handle for the created ensemble.
4073 *
4074 * Side effects:
4075 * Creates a command in the global namespace.
4076 *
4077 *----------------------------------------------------------------------
4078 */
4079
4080 Tcl_Command
4081 TclInitArrayCmd(
4082 Tcl_Interp *interp) /* Current interpreter. */
4083 {
4084 static const EnsembleImplMap arrayImplMap[] = {
4085 {"anymore", ArrayAnyMoreCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0},
4086 {"donesearch", ArrayDoneSearchCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0},
4087 {"exists", ArrayExistsCmd, TclCompileArrayExistsCmd, NULL, NULL, 0},
4088 {"get", ArrayGetCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0},
4089 {"names", ArrayNamesCmd, TclCompileBasic1To3ArgCmd, NULL, NULL, 0},
4090 {"nextelement", ArrayNextElementCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0},
4091 {"set", ArraySetCmd, TclCompileArraySetCmd, NULL, NULL, 0},
4092 {"size", ArraySizeCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
4093 {"startsearch", ArrayStartSearchCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
4094 {"statistics", ArrayStatsCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
4095 {"unset", ArrayUnsetCmd, TclCompileArrayUnsetCmd, NULL, NULL, 0},
4096 {NULL, NULL, NULL, NULL, NULL, 0}
4097 };
4098
4099 return TclMakeEnsemble(interp, "array", arrayImplMap);
4100 }
4101
4102 /*
4103 *----------------------------------------------------------------------
4104 *
4105 * ObjMakeUpvar --
4106 *
4107 * This function does all of the work of the "global" and "upvar"
4108 * commands.
4109 *
4110 * Results:
4111 * A standard Tcl completion code. If an error occurs then an error
4112 * message is left in interp.
4113 *
4114 * Side effects:
4115 * The variable given by myName is linked to the variable in framePtr
4116 * given by otherP1 and otherP2, so that references to myName are
4117 * redirected to the other variable like a symbolic link.
4118 * Callers must Incr myNamePtr if they plan to Decr it.
4119 * Callers must Incr otherP1Ptr if they plan to Decr it.
4120 *
4121 *----------------------------------------------------------------------
4122 */
4123
4124 static int
4125 ObjMakeUpvar(
4126 Tcl_Interp *interp, /* Interpreter containing variables. Used for
4127 * error messages, too. */
4128 CallFrame *framePtr, /* Call frame containing "other" variable.
4129 * NULL means use global :: context. */
4130 Tcl_Obj *otherP1Ptr,
4131 const char *otherP2, /* Two-part name of variable in framePtr. */
4132 int otherFlags, /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY:
4133 * indicates scope of "other" variable. */
4134 Tcl_Obj *myNamePtr, /* Name of variable which will refer to
4135 * otherP1/otherP2. Must be a scalar. */
4136 int myFlags, /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY:
4137 * indicates scope of myName. */
4138 int index) /* If the variable to be linked is an indexed
4139 * scalar, this is its index. Otherwise, -1 */
4140 {
4141 Interp *iPtr = (Interp *) interp;
4142 Var *otherPtr, *arrayPtr;
4143 CallFrame *varFramePtr;
4144
4145 /*
4146 * Find "other" in "framePtr". If not looking up other in just the current
4147 * namespace, temporarily replace the current var frame pointer in the
4148 * interpreter in order to use TclObjLookupVar.
4149 */
4150
4151 if (framePtr == NULL) {
4152 framePtr = iPtr->rootFramePtr;
4153 }
4154
4155 varFramePtr = iPtr->varFramePtr;
4156 if (!(otherFlags & TCL_NAMESPACE_ONLY)) {
4157 iPtr->varFramePtr = framePtr;
4158 }
4159 otherPtr = TclObjLookupVar(interp, otherP1Ptr, otherP2,
4160 (otherFlags | TCL_LEAVE_ERR_MSG), "access",
4161 /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr);
4162 if (!(otherFlags & TCL_NAMESPACE_ONLY)) {
4163 iPtr->varFramePtr = varFramePtr;
4164 }
4165 if (otherPtr == NULL) {
4166 return TCL_ERROR;
4167 }
4168
4169 /*
4170 * Check that we are not trying to create a namespace var linked to a
4171 * local variable in a procedure. If we allowed this, the local
4172 * variable in the shorter-lived procedure frame could go away leaving
4173 * the namespace var's reference invalid.
4174 */
4175
4176 if (index < 0) {
4177 if (!(arrayPtr != NULL
4178 ? (TclIsVarInHash(arrayPtr) && TclGetVarNsPtr(arrayPtr))
4179 : (TclIsVarInHash(otherPtr) && TclGetVarNsPtr(otherPtr)))
4180 && ((myFlags & (TCL_GLOBAL_ONLY | TCL_NAMESPACE_ONLY))
4181 || (varFramePtr == NULL)
4182 || !HasLocalVars(varFramePtr)
4183 || (strstr(TclGetString(myNamePtr), "::") != NULL))) {
4184 Tcl_SetObjResult((Tcl_Interp *) iPtr, Tcl_ObjPrintf(
4185 "bad variable name \"%s\": can't create namespace "
4186 "variable that refers to procedure variable",
4187 TclGetString(myNamePtr)));
4188 Tcl_SetErrorCode(interp, "TCL", "UPVAR", "INVERTED", (char *)NULL);
4189 return TCL_ERROR;
4190 }
4191 }
4192
4193 return TclPtrObjMakeUpvarIdx(interp, otherPtr, myNamePtr, myFlags, index);
4194 }
4195
4196 /*
4197 *----------------------------------------------------------------------
4198 *
4199 * TclPtrMakeUpvar --
4200 *
4201 * This procedure does all of the work of the "global" and "upvar"
4202 * commands.
4203 *
4204 * Results:
4205 * A standard Tcl completion code. If an error occurs then an error
4206 * message is left in interp.
4207 *
4208 * Side effects:
4209 * The variable given by myName is linked to the variable in framePtr
4210 * given by otherP1 and otherP2, so that references to myName are
4211 * redirected to the other variable like a symbolic link.
4212 *
4213 *----------------------------------------------------------------------
4214 */
4215
4216 int
4217 TclPtrMakeUpvar(
4218 Tcl_Interp *interp, /* Interpreter containing variables. Used for
4219 * error messages, too. */
4220 Var *otherPtr, /* Pointer to the variable being linked-to. */
4221 const char *myName, /* Name of variable which will refer to
4222 * otherP1/otherP2. Must be a scalar. */
4223 int myFlags, /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY:
4224 * indicates scope of myName. */
4225 int index) /* If the variable to be linked is an indexed
4226 * scalar, this is its index. Otherwise, -1 */
4227 {
4228 Tcl_Obj *myNamePtr = NULL;
4229 int result;
4230
4231 if (myName) {
4232 myNamePtr = Tcl_NewStringObj(myName, -1);
4233 Tcl_IncrRefCount(myNamePtr);
4234 }
4235 result = TclPtrObjMakeUpvarIdx(interp, otherPtr, myNamePtr, myFlags,
4236 index);
4237 if (myNamePtr) {
4238 Tcl_DecrRefCount(myNamePtr);
4239 }
4240 return result;
4241 }
4242
4243 int
4244 TclPtrObjMakeUpvar(
4245 Tcl_Interp *interp, /* Interpreter containing variables. Used for
4246 * error messages, too. */
4247 Tcl_Var otherPtr, /* Pointer to the variable being linked-to. */
4248 Tcl_Obj *myNamePtr, /* Name of variable which will refer to
4249 * otherP1/otherP2. Must be a scalar. */
4250 int myFlags) /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY:
4251 * indicates scope of myName. */
4252 {
4253 return TclPtrObjMakeUpvarIdx(interp, (Var *) otherPtr, myNamePtr, myFlags,
4254 -1);
4255 }
4256
4257 /* Callers must Incr myNamePtr if they plan to Decr it. */
4258
4259 int
4260 TclPtrObjMakeUpvarIdx(
4261 Tcl_Interp *interp, /* Interpreter containing variables. Used for
4262 * error messages, too. */
4263 Var *otherPtr, /* Pointer to the variable being linked-to. */
4264 Tcl_Obj *myNamePtr, /* Name of variable which will refer to
4265 * otherP1/otherP2. Must be a scalar. */
4266 int myFlags, /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY:
4267 * indicates scope of myName. */
4268 int index) /* If the variable to be linked is an indexed
4269 * scalar, this is its index. Otherwise, -1 */
4270 {
4271 Interp *iPtr = (Interp *) interp;
4272 CallFrame *varFramePtr = iPtr->varFramePtr;
4273 const char *errMsg, *p, *myName;
4274 Var *varPtr;
4275
4276 if (index >= 0) {
4277 if (!HasLocalVars(varFramePtr)) {
4278 Tcl_Panic("ObjMakeUpvar called with an index outside from a proc");
4279 }
4280 varPtr = (Var *) &(varFramePtr->compiledLocals[index]);
4281 myNamePtr = localName(iPtr->varFramePtr, index);
4282 myName = myNamePtr? TclGetString(myNamePtr) : NULL;
4283 } else {
4284 /*
4285 * Do not permit the new variable to look like an array reference, as
4286 * it will not be reachable in that case [Bug 600812, TIP 184]. The
4287 * "definition" of what "looks like an array reference" is consistent
4288 * (and must remain consistent) with the code in TclObjLookupVar().
4289 */
4290
4291 myName = TclGetString(myNamePtr);
4292 p = strstr(myName, "(");
4293 if (p != NULL) {
4294 p += strlen(p)-1;
4295 if (*p == ')') {
4296 /*
4297 * myName looks like an array reference.
4298 */
4299
4300 Tcl_SetObjResult((Tcl_Interp *) iPtr, Tcl_ObjPrintf(
4301 "bad variable name \"%s\": can't create a scalar "
4302 "variable that looks like an array element", myName));
4303 Tcl_SetErrorCode(interp, "TCL", "UPVAR", "LOCAL_ELEMENT",
4304 (char *)NULL);
4305 return TCL_ERROR;
4306 }
4307 }
4308
4309 /*
4310 * Lookup and eventually create the new variable. Set the flag bit
4311 * TCL_AVOID_RESOLVERS to indicate the special resolution rules for
4312 * upvar purposes:
4313 * - Bug #696893 - variable is either proc-local or in the current
4314 * namespace; never follow the second (global) resolution path.
4315 * - Bug #631741 - do not use special namespace or interp resolvers.
4316 */
4317
4318 varPtr = TclLookupSimpleVar(interp, myNamePtr,
4319 myFlags|TCL_AVOID_RESOLVERS, /* create */ 1, &errMsg, &index);
4320 if (varPtr == NULL) {
4321 TclObjVarErrMsg(interp, myNamePtr, NULL, "create", errMsg, -1);
4322 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
4323 TclGetString(myNamePtr), (char *)NULL);
4324 return TCL_ERROR;
4325 }
4326 }
4327
4328 if (varPtr == otherPtr) {
4329 Tcl_SetObjResult((Tcl_Interp *) iPtr, Tcl_NewStringObj(
4330 "can't upvar from variable to itself", -1));
4331 Tcl_SetErrorCode(interp, "TCL", "UPVAR", "SELF", (char *)NULL);
4332 return TCL_ERROR;
4333 }
4334
4335 if (TclIsVarTraced(varPtr)) {
4336 Tcl_SetObjResult((Tcl_Interp *) iPtr, Tcl_ObjPrintf(
4337 "variable \"%s\" has traces: can't use for upvar", myName));
4338 Tcl_SetErrorCode(interp, "TCL", "UPVAR", "TRACED", (char *)NULL);
4339 return TCL_ERROR;
4340 } else if (!TclIsVarUndefined(varPtr)) {
4341 Var *linkPtr;
4342
4343 /*
4344 * The variable already existed. Make sure this variable "varPtr"
4345 * isn't the same as "otherPtr" (avoid circular links). Also, if it's
4346 * not an upvar then it's an error. If it is an upvar, then just
4347 * disconnect it from the thing it currently refers to.
4348 */
4349
4350 if (!TclIsVarLink(varPtr)) {
4351 Tcl_SetObjResult((Tcl_Interp *) iPtr, Tcl_ObjPrintf(
4352 "variable \"%s\" already exists", myName));
4353 Tcl_SetErrorCode(interp, "TCL", "UPVAR", "EXISTS", (char *)NULL);
4354 return TCL_ERROR;
4355 }
4356
4357 linkPtr = varPtr->value.linkPtr;
4358 if (linkPtr == otherPtr) {
4359 return TCL_OK;
4360 }
4361 if (TclIsVarInHash(linkPtr)) {
4362 VarHashRefCount(linkPtr)--;
4363 if (TclIsVarUndefined(linkPtr)) {
4364 CleanupVar(linkPtr, NULL);
4365 }
4366 }
4367 }
4368 TclSetVarLink(varPtr);
4369 varPtr->value.linkPtr = otherPtr;
4370 if (TclIsVarInHash(otherPtr)) {
4371 VarHashRefCount(otherPtr)++;
4372 }
4373 return TCL_OK;
4374 }
4375
4376 /*
4377 *----------------------------------------------------------------------
4378 *
4379 * Tcl_UpVar --
4380 *
4381 * This function links one variable to another, just like the "upvar"
4382 * command.
4383 *
4384 * Results:
4385 * A standard Tcl completion code. If an error occurs then an error
4386 * message is left in the interp's result.
4387 *
4388 * Side effects:
4389 * The variable in frameName whose name is given by varName becomes
4390 * accessible under the name localNameStr, so that references to
4391 * localNameStr are redirected to the other variable like a symbolic
4392 * link.
4393 *
4394 *----------------------------------------------------------------------
4395 */
4396
4397 #undef Tcl_UpVar
4398 int
4399 Tcl_UpVar(
4400 Tcl_Interp *interp, /* Command interpreter in which varName is to
4401 * be looked up. */
4402 const char *frameName, /* Name of the frame containing the source
4403 * variable, such as "1" or "#0". */
4404 const char *varName, /* Name of a variable in interp to link to.
4405 * May be either a scalar name or an element
4406 * in an array. */
4407 const char *localNameStr, /* Name of link variable. */
4408 int flags) /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY:
4409 * indicates scope of localNameStr. */
4410 {
4411 int result;
4412 CallFrame *framePtr;
4413 Tcl_Obj *varNamePtr, *localNamePtr;
4414
4415 if (TclGetFrame(interp, frameName, &framePtr) == -1) {
4416 return TCL_ERROR;
4417 }
4418
4419 varNamePtr = Tcl_NewStringObj(varName, -1);
4420 Tcl_IncrRefCount(varNamePtr);
4421 localNamePtr = Tcl_NewStringObj(localNameStr, -1);
4422 Tcl_IncrRefCount(localNamePtr);
4423
4424 result = ObjMakeUpvar(interp, framePtr, varNamePtr, NULL, 0,
4425 localNamePtr, flags, -1);
4426 Tcl_DecrRefCount(varNamePtr);
4427 Tcl_DecrRefCount(localNamePtr);
4428 return result;
4429 }
4430
4431 /*
4432 *----------------------------------------------------------------------
4433 *
4434 * Tcl_UpVar2 --
4435 *
4436 * This function links one variable to another, just like the "upvar"
4437 * command.
4438 *
4439 * Results:
4440 * A standard Tcl completion code. If an error occurs then an error
4441 * message is left in the interp's result.
4442 *
4443 * Side effects:
4444 * The variable in frameName whose name is given by part1 and part2
4445 * becomes accessible under the name localNameStr, so that references to
4446 * localNameStr are redirected to the other variable like a symbolic
4447 * link.
4448 *
4449 *----------------------------------------------------------------------
4450 */
4451
4452 int
4453 Tcl_UpVar2(
4454 Tcl_Interp *interp, /* Interpreter containing variables. Used for
4455 * error messages too. */
4456 const char *frameName, /* Name of the frame containing the source
4457 * variable, such as "1" or "#0". */
4458 const char *part1,
4459 const char *part2, /* Two parts of source variable name to link
4460 * to. */
4461 const char *localNameStr, /* Name of link variable. */
4462 int flags) /* 0, TCL_GLOBAL_ONLY or TCL_NAMESPACE_ONLY:
4463 * indicates scope of localNameStr. */
4464 {
4465 int result;
4466 CallFrame *framePtr;
4467 Tcl_Obj *part1Ptr, *localNamePtr;
4468
4469 if (TclGetFrame(interp, frameName, &framePtr) == -1) {
4470 return TCL_ERROR;
4471 }
4472
4473 part1Ptr = Tcl_NewStringObj(part1, -1);
4474 Tcl_IncrRefCount(part1Ptr);
4475 localNamePtr = Tcl_NewStringObj(localNameStr, -1);
4476 Tcl_IncrRefCount(localNamePtr);
4477
4478 result = ObjMakeUpvar(interp, framePtr, part1Ptr, part2, 0,
4479 localNamePtr, flags, -1);
4480 Tcl_DecrRefCount(part1Ptr);
4481 Tcl_DecrRefCount(localNamePtr);
4482 return result;
4483 }
4484
4485 /*
4486 *----------------------------------------------------------------------
4487 *
4488 * Tcl_GetVariableFullName --
4489 *
4490 * Given a Tcl_Var token returned by Tcl_FindNamespaceVar, this function
4491 * appends to an object the namespace variable's full name, qualified by
4492 * a sequence of parent namespace names.
4493 *
4494 * Results:
4495 * None.
4496 *
4497 * Side effects:
4498 * The variable's fully-qualified name is appended to the string
4499 * representation of objPtr.
4500 *
4501 *----------------------------------------------------------------------
4502 */
4503
4504 void
4505 Tcl_GetVariableFullName(
4506 Tcl_Interp *interp, /* Interpreter containing the variable. */
4507 Tcl_Var variable, /* Token for the variable returned by a
4508 * previous call to Tcl_FindNamespaceVar. */
4509 Tcl_Obj *objPtr) /* Points to the object onto which the
4510 * variable's full name is appended. */
4511 {
4512 Interp *iPtr = (Interp *) interp;
4513 Var *varPtr = (Var *) variable;
4514 Tcl_Obj *namePtr;
4515 Namespace *nsPtr;
4516
4517 if (!varPtr || TclIsVarArrayElement(varPtr)) {
4518 return;
4519 }
4520
4521 /*
4522 * Add the full name of the containing namespace (if any), followed by the
4523 * "::" separator, then the variable name.
4524 */
4525
4526 nsPtr = TclGetVarNsPtr(varPtr);
4527 if (nsPtr) {
4528 Tcl_AppendToObj(objPtr, nsPtr->fullName, -1);
4529 if (nsPtr != iPtr->globalNsPtr) {
4530 Tcl_AppendToObj(objPtr, "::", 2);
4531 }
4532 }
4533 if (TclIsVarInHash(varPtr)) {
4534 if (!TclIsVarDeadHash(varPtr)) {
4535 namePtr = VarHashGetKey(varPtr);
4536 Tcl_AppendObjToObj(objPtr, namePtr);
4537 }
4538 } else if (iPtr->varFramePtr->procPtr) {
4539 int index = varPtr - iPtr->varFramePtr->compiledLocals;
4540
4541 if (index >= 0 && index < iPtr->varFramePtr->numCompiledLocals) {
4542 namePtr = localName(iPtr->varFramePtr, index);
4543 Tcl_AppendObjToObj(objPtr, namePtr);
4544 }
4545 }
4546 }
4547
4548 /*
4549 *----------------------------------------------------------------------
4550 *
4551 * Tcl_GlobalObjCmd --
4552 *
4553 * This object-based function is invoked to process the "global" Tcl
4554 * command. See the user documentation for details on what it does.
4555 *
4556 * Results:
4557 * A standard Tcl object result value.
4558 *
4559 * Side effects:
4560 * See the user documentation.
4561 *
4562 *----------------------------------------------------------------------
4563 */
4564
4565 int
4566 Tcl_GlobalObjCmd(
4567 ClientData dummy, /* Not used. */
4568 Tcl_Interp *interp, /* Current interpreter. */
4569 int objc, /* Number of arguments. */
4570 Tcl_Obj *const objv[]) /* Argument objects. */
4571 {
4572 Interp *iPtr = (Interp *) interp;
4573 Tcl_Obj *objPtr, *tailPtr;
4574 const char *varName;
4575 const char *tail;
4576 int result, i;
4577
4578 /*
4579 * If we are not executing inside a Tcl procedure, just return.
4580 */
4581
4582 if (!HasLocalVars(iPtr->varFramePtr)) {
4583 return TCL_OK;
4584 }
4585
4586 for (i=1 ; i<objc ; i++) {
4587 /*
4588 * Make a local variable linked to its counterpart in the global ::
4589 * namespace.
4590 */
4591
4592 objPtr = objv[i];
4593 varName = TclGetString(objPtr);
4594
4595 /*
4596 * The variable name might have a scope qualifier, but the name for
4597 * the local "link" variable must be the simple name at the tail.
4598 */
4599
4600 for (tail=varName ; *tail!='\0' ; tail++) {
4601 /* empty body */
4602 }
4603 while ((tail > varName) && ((*tail != ':') || (*(tail-1) != ':'))) {
4604 tail--;
4605 }
4606 if ((*tail == ':') && (tail > varName)) {
4607 tail++;
4608 }
4609
4610 if (tail == varName) {
4611 tailPtr = objPtr;
4612 } else {
4613 tailPtr = Tcl_NewStringObj(tail, -1);
4614 Tcl_IncrRefCount(tailPtr);
4615 }
4616
4617 /*
4618 * Link to the variable "varName" in the global :: namespace.
4619 */
4620
4621 result = ObjMakeUpvar(interp, NULL, objPtr, NULL,
4622 TCL_GLOBAL_ONLY, /*myName*/ tailPtr, /*myFlags*/ 0, -1);
4623
4624 if (tail != varName) {
4625 Tcl_DecrRefCount(tailPtr);
4626 }
4627
4628 if (result != TCL_OK) {
4629 return result;
4630 }
4631 }
4632 return TCL_OK;
4633 }
4634
4635 /*
4636 *----------------------------------------------------------------------
4637 *
4638 * Tcl_VariableObjCmd --
4639 *
4640 * Invoked to implement the "variable" command that creates one or more
4641 * global variables. Handles the following syntax:
4642 *
4643 * variable ?name value...? name ?value?
4644 *
4645 * One or more variables can be created. The variables are initialized
4646 * with the specified values. The value for the last variable is
4647 * optional.
4648 *
4649 * If the variable does not exist, it is created and given the optional
4650 * value. If it already exists, it is simply set to the optional value.
4651 * Normally, "name" is an unqualified name, so it is created in the
4652 * current namespace. If it includes namespace qualifiers, it can be
4653 * created in another namespace.
4654 *
4655 * If the variable command is executed inside a Tcl procedure, it creates
4656 * a local variable linked to the newly-created namespace variable.
4657 *
4658 * Results:
4659 * Returns TCL_OK if the variable is found or created. Returns TCL_ERROR
4660 * if anything goes wrong.
4661 *
4662 * Side effects:
4663 * If anything goes wrong, this function returns an error message as the
4664 * result in the interpreter's result object.
4665 *
4666 *----------------------------------------------------------------------
4667 */
4668
4669 int
4670 Tcl_VariableObjCmd(
4671 ClientData dummy, /* Not used. */
4672 Tcl_Interp *interp, /* Current interpreter. */
4673 int objc, /* Number of arguments. */
4674 Tcl_Obj *const objv[]) /* Argument objects. */
4675 {
4676 Interp *iPtr = (Interp *) interp;
4677 const char *varName, *tail, *cp;
4678 Var *varPtr, *arrayPtr;
4679 Tcl_Obj *varValuePtr;
4680 int i, result;
4681 Tcl_Obj *varNamePtr, *tailPtr;
4682
4683 for (i=1 ; i<objc ; i+=2) {
4684 /*
4685 * Look up each variable in the current namespace context, creating it
4686 * if necessary.
4687 */
4688
4689 varNamePtr = objv[i];
4690 varName = TclGetString(varNamePtr);
4691 varPtr = TclObjLookupVarEx(interp, varNamePtr, NULL,
4692 (TCL_NAMESPACE_ONLY | TCL_LEAVE_ERR_MSG), "define",
4693 /*createPart1*/ 1, /*createPart2*/ 0, &arrayPtr);
4694
4695 if (arrayPtr != NULL) {
4696 /*
4697 * Variable cannot be an element in an array. If arrayPtr is
4698 * non-NULL, it is, so throw up an error and return.
4699 */
4700
4701 TclObjVarErrMsg(interp, varNamePtr, NULL, "define",
4702 ISARRAYELEMENT, -1);
4703 Tcl_SetErrorCode(interp, "TCL", "UPVAR", "LOCAL_ELEMENT", (char *)NULL);
4704 return TCL_ERROR;
4705 }
4706
4707 if (varPtr == NULL) {
4708 return TCL_ERROR;
4709 }
4710
4711 /*
4712 * Mark the variable as a namespace variable and increment its
4713 * reference count so that it will persist until its namespace is
4714 * destroyed or until the variable is unset.
4715 */
4716
4717 TclSetVarNamespaceVar(varPtr);
4718
4719 /*
4720 * If a value was specified, set the variable to that value.
4721 * Otherwise, if the variable is new, leave it undefined. (If the
4722 * variable already exists and no value was specified, leave its value
4723 * unchanged; just create the local link if we're in a Tcl procedure).
4724 */
4725
4726 if (i+1 < objc) { /* A value was specified. */
4727 varValuePtr = TclPtrSetVarIdx(interp, varPtr, arrayPtr,
4728 varNamePtr, NULL, objv[i+1],
4729 (TCL_NAMESPACE_ONLY | TCL_LEAVE_ERR_MSG), -1);
4730 if (varValuePtr == NULL) {
4731 return TCL_ERROR;
4732 }
4733 }
4734
4735 /*
4736 * If we are executing inside a Tcl procedure, create a local variable
4737 * linked to the new namespace variable "varName".
4738 */
4739
4740 if (HasLocalVars(iPtr->varFramePtr)) {
4741 /*
4742 * varName might have a scope qualifier, but the name for the
4743 * local "link" variable must be the simple name at the tail.
4744 *
4745 * Locate tail in one pass: drop any prefix after two *or more*
4746 * consecutive ":" characters).
4747 */
4748
4749 for (tail=cp=varName ; *cp!='\0' ;) {
4750 if (*cp++ == ':') {
4751 while (*cp == ':') {
4752 tail = ++cp;
4753 }
4754 }
4755 }
4756
4757 /*
4758 * Create a local link "tail" to the variable "varName" in the
4759 * current namespace.
4760 */
4761
4762 if (tail == varName) {
4763 tailPtr = varNamePtr;
4764 } else {
4765 tailPtr = Tcl_NewStringObj(tail, -1);
4766 Tcl_IncrRefCount(tailPtr);
4767 }
4768
4769 result = ObjMakeUpvar(interp, NULL, varNamePtr, /*otherP2*/ NULL,
4770 /*otherFlags*/ TCL_NAMESPACE_ONLY,
4771 /*myName*/ tailPtr, /*myFlags*/ 0, -1);
4772
4773 if (tail != varName) {
4774 Tcl_DecrRefCount(tailPtr);
4775 }
4776
4777 if (result != TCL_OK) {
4778 return result;
4779 }
4780 }
4781 }
4782 return TCL_OK;
4783 }
4784
4785 /*
4786 *----------------------------------------------------------------------
4787 *
4788 * Tcl_UpvarObjCmd --
4789 *
4790 * This object-based function is invoked to process the "upvar" Tcl
4791 * command. See the user documentation for details on what it does.
4792 *
4793 * Results:
4794 * A standard Tcl object result value.
4795 *
4796 * Side effects:
4797 * See the user documentation.
4798 *
4799 *----------------------------------------------------------------------
4800 */
4801
4802 int
4803 Tcl_UpvarObjCmd(
4804 ClientData dummy, /* Not used. */
4805 Tcl_Interp *interp, /* Current interpreter. */
4806 int objc, /* Number of arguments. */
4807 Tcl_Obj *const objv[]) /* Argument objects. */
4808 {
4809 CallFrame *framePtr;
4810 int result, hasLevel;
4811 Tcl_Obj *levelObj;
4812
4813 if (objc < 3) {
4814 Tcl_WrongNumArgs(interp, 1, objv,
4815 "?level? otherVar localVar ?otherVar localVar ...?");
4816 return TCL_ERROR;
4817 }
4818
4819 if (objc & 1) {
4820 /*
4821 * Even number of arguments, so use the default level of "1" by
4822 * passing NULL to TclObjGetFrame.
4823 */
4824
4825 levelObj = NULL;
4826 hasLevel = 0;
4827 } else {
4828 /*
4829 * Odd number of arguments, so objv[1] must contain the level.
4830 */
4831
4832 levelObj = objv[1];
4833 hasLevel = 1;
4834 }
4835
4836 /*
4837 * Find the call frame containing each of the "other variables" to be
4838 * linked to.
4839 */
4840
4841 result = TclObjGetFrame(interp, levelObj, &framePtr);
4842 if (result == -1) {
4843 return TCL_ERROR;
4844 }
4845 if ((result == 0) && hasLevel) {
4846 /*
4847 * Synthesize an error message since TclObjGetFrame doesn't do this
4848 * for this particular case.
4849 */
4850
4851 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4852 "bad level \"%s\"", TclGetString(levelObj)));
4853 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "LEVEL",
4854 TclGetString(levelObj), (char *)NULL);
4855 return TCL_ERROR;
4856 }
4857
4858 /*
4859 * We've now finished with parsing levels; skip to the variable names.
4860 */
4861
4862 objc -= hasLevel + 1;
4863 objv += hasLevel + 1;
4864
4865 /*
4866 * Iterate over each (other variable, local variable) pair. Divide the
4867 * other variable name into two parts, then call MakeUpvar to do all the
4868 * work of linking it to the local variable.
4869 */
4870
4871 for (; objc>0 ; objc-=2, objv+=2) {
4872 result = ObjMakeUpvar(interp, framePtr, /* othervarName */ objv[0],
4873 NULL, 0, /* myVarName */ objv[1], /*flags*/ 0, -1);
4874 if (result != TCL_OK) {
4875 return TCL_ERROR;
4876 }
4877 }
4878 return TCL_OK;
4879 }
4880
4881 /*
4882 *----------------------------------------------------------------------
4883 *
4884 * SetArraySearchObj --
4885 *
4886 * This function converts the given tcl object into one that has the
4887 * "array search" internal type.
4888 *
4889 * Results:
4890 * TCL_OK if the conversion succeeded, and TCL_ERROR if it failed (when
4891 * an error message will be placed in the interpreter's result.)
4892 *
4893 * Side effects:
4894 * Updates the internal type and representation of the object to make
4895 * this an array-search object. See the tclArraySearchType declaration
4896 * above for details of the internal representation.
4897 *
4898 *----------------------------------------------------------------------
4899 */
4900
4901 static int
4902 SetArraySearchObj(
4903 Tcl_Interp *interp,
4904 Tcl_Obj *objPtr)
4905 {
4906 const char *string;
4907 char *end; /* Can't be const due to strtoul defn. */
4908 int id;
4909 size_t offset;
4910
4911 /*
4912 * Get the string representation. Make it up-to-date if necessary.
4913 */
4914
4915 string = TclGetString(objPtr);
4916
4917 /*
4918 * Parse the id into the three parts separated by dashes.
4919 */
4920
4921 if ((string[0] != 's') || (string[1] != '-')) {
4922 goto syntax;
4923 }
4924 id = strtoul(string+2, &end, 10);
4925 if ((end == (string+2)) || (*end != '-')) {
4926 goto syntax;
4927 }
4928
4929 /*
4930 * Can't perform value check in this context, so place reference to place
4931 * in string to use for the check in the object instead.
4932 */
4933
4934 end++;
4935 offset = end - string;
4936
4937 TclFreeIntRep(objPtr);
4938 objPtr->typePtr = &tclArraySearchType;
4939 objPtr->internalRep.twoPtrValue.ptr1 = INT2PTR(id);
4940 objPtr->internalRep.twoPtrValue.ptr2 = INT2PTR(offset);
4941 return TCL_OK;
4942
4943 syntax:
4944 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4945 "illegal search identifier \"%s\"", string));
4946 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "ARRAYSEARCH", string, (char *)NULL);
4947 return TCL_ERROR;
4948 }
4949
4950 /*
4951 *----------------------------------------------------------------------
4952 *
4953 * ParseSearchId --
4954 *
4955 * This function translates from a tcl object to a pointer to an active
4956 * array search (if there is one that matches the string).
4957 *
4958 * Results:
4959 * The return value is a pointer to the array search indicated by string,
4960 * or NULL if there isn't one. If NULL is returned, the interp's result
4961 * contains an error message.
4962 *
4963 * Side effects:
4964 * The tcl object might have its internal type and representation
4965 * modified.
4966 *
4967 *----------------------------------------------------------------------
4968 */
4969
4970 static ArraySearch *
4971 ParseSearchId(
4972 Tcl_Interp *interp, /* Interpreter containing variable. */
4973 const Var *varPtr, /* Array variable search is for. */
4974 Tcl_Obj *varNamePtr, /* Name of array variable that search is
4975 * supposed to be for. */
4976 Tcl_Obj *handleObj) /* Object containing id of search. Must have
4977 * form "search-num-var" where "num" is a
4978 * decimal number and "var" is a variable
4979 * name. */
4980 {
4981 Interp *iPtr = (Interp *) interp;
4982 const char *string;
4983 size_t offset;
4984 int id;
4985 ArraySearch *searchPtr;
4986 const char *varName = TclGetString(varNamePtr);
4987
4988 /*
4989 * Parse the id.
4990 */
4991
4992 if ((handleObj->typePtr != &tclArraySearchType)
4993 && (SetArraySearchObj(interp, handleObj) != TCL_OK)) {
4994 return NULL;
4995 }
4996
4997 /*
4998 * Extract the information out of the Tcl_Obj.
4999 */
5000
5001 id = PTR2INT(handleObj->internalRep.twoPtrValue.ptr1);
5002 string = TclGetString(handleObj);
5003 offset = PTR2INT(handleObj->internalRep.twoPtrValue.ptr2);
5004
5005 /*
5006 * This test cannot be placed inside the Tcl_Obj machinery, since it is
5007 * dependent on the variable context.
5008 */
5009
5010 if (strcmp(string+offset, varName) != 0) {
5011 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
5012 "search identifier \"%s\" isn't for variable \"%s\"",
5013 string, varName));
5014 goto badLookup;
5015 }
5016
5017 /*
5018 * Search through the list of active searches on the interpreter to see if
5019 * the desired one exists.
5020 *
5021 * Note that we cannot store the searchPtr directly in the Tcl_Obj as that
5022 * would run into trouble when DeleteSearches() was called so we must scan
5023 * this list every time.
5024 */
5025
5026 if (varPtr->flags & VAR_SEARCH_ACTIVE) {
5027 Tcl_HashEntry *hPtr =
5028 Tcl_FindHashEntry(&iPtr->varSearches, varPtr);
5029
5030 for (searchPtr = Tcl_GetHashValue(hPtr); searchPtr != NULL;
5031 searchPtr = searchPtr->nextPtr) {
5032 if (searchPtr->id == id) {
5033 return searchPtr;
5034 }
5035 }
5036 }
5037 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
5038 "couldn't find search \"%s\"", string));
5039 badLookup:
5040 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "ARRAYSEARCH", string, (char *)NULL);
5041 return NULL;
5042 }
5043
5044 /*
5045 *----------------------------------------------------------------------
5046 *
5047 * DeleteSearches --
5048 *
5049 * This function is called to free up all of the searches associated
5050 * with an array variable.
5051 *
5052 * Results:
5053 * None.
5054 *
5055 * Side effects:
5056 * Memory is released to the storage allocator.
5057 *
5058 *----------------------------------------------------------------------
5059 */
5060
5061 static void
5062 DeleteSearches(
5063 Interp *iPtr,
5064 Var *arrayVarPtr) /* Variable whose searches are to be
5065 * deleted. */
5066 {
5067 ArraySearch *searchPtr, *nextPtr;
5068 Tcl_HashEntry *sPtr;
5069
5070 if (arrayVarPtr->flags & VAR_SEARCH_ACTIVE) {
5071 sPtr = Tcl_FindHashEntry(&iPtr->varSearches, arrayVarPtr);
5072 for (searchPtr = (ArraySearch *)Tcl_GetHashValue(sPtr); searchPtr != NULL;
5073 searchPtr = nextPtr) {
5074 nextPtr = searchPtr->nextPtr;
5075 ckfree(searchPtr);
5076 }
5077 arrayVarPtr->flags &= ~VAR_SEARCH_ACTIVE;
5078 Tcl_DeleteHashEntry(sPtr);
5079 }
5080 }
5081
5082 /*
5083 *----------------------------------------------------------------------
5084 *
5085 * TclDeleteNamespaceVars --
5086 *
5087 * This function is called to recycle all the storage space associated
5088 * with a namespace's table of variables.
5089 *
5090 * Results:
5091 * None.
5092 *
5093 * Side effects:
5094 * Variables are deleted and trace functions are invoked, if any are
5095 * declared.
5096 *
5097 *----------------------------------------------------------------------
5098 */
5099
5100 void
5101 TclDeleteNamespaceVars(
5102 Namespace *nsPtr)
5103 {
5104 TclVarHashTable *tablePtr = &nsPtr->varTable;
5105 Tcl_Interp *interp = nsPtr->interp;
5106 Interp *iPtr = (Interp *)interp;
5107 Tcl_HashSearch search;
5108 int flags = 0;
5109 Var *varPtr;
5110
5111 /*
5112 * Determine what flags to pass to the trace callback functions.
5113 */
5114
5115 if (nsPtr == iPtr->globalNsPtr) {
5116 flags = TCL_GLOBAL_ONLY;
5117 } else if (nsPtr == (Namespace *) TclGetCurrentNamespace(interp)) {
5118 flags = TCL_NAMESPACE_ONLY;
5119 }
5120
5121 for (varPtr = VarHashFirstVar(tablePtr, &search); varPtr != NULL;
5122 varPtr = VarHashFirstVar(tablePtr, &search)) {
5123 Tcl_Obj *objPtr;
5124 TclNewObj(objPtr);
5125 VarHashRefCount(varPtr)++; /* Make sure we get to remove from
5126 * hash. */
5127 Tcl_GetVariableFullName(interp, (Tcl_Var) varPtr, objPtr);
5128 UnsetVarStruct(varPtr, NULL, iPtr, /* part1 */ objPtr,
5129 NULL, flags, -1);
5130
5131 /*
5132 * We just unset the variable. However, an unset trace might
5133 * have re-set it, or might have re-established traces on it.
5134 * This namespace and its vartable are going away unconditionally,
5135 * so we cannot let such things linger. That would be a leak.
5136 *
5137 * First we destroy all traces. ...
5138 */
5139
5140 if (TclIsVarTraced(varPtr)) {
5141 Tcl_HashEntry *tPtr = Tcl_FindHashEntry(&iPtr->varTraces, varPtr);
5142 VarTrace *tracePtr = (VarTrace *)Tcl_GetHashValue(tPtr);
5143 ActiveVarTrace *activePtr;
5144
5145 while (tracePtr) {
5146 VarTrace *prevPtr = tracePtr;
5147
5148 tracePtr = tracePtr->nextPtr;
5149 prevPtr->nextPtr = NULL;
5150 Tcl_EventuallyFree(prevPtr, TCL_DYNAMIC);
5151 }
5152 Tcl_DeleteHashEntry(tPtr);
5153 varPtr->flags &= ~VAR_ALL_TRACES;
5154 for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL;
5155 activePtr = activePtr->nextPtr) {
5156 if (activePtr->varPtr == varPtr) {
5157 activePtr->nextTracePtr = NULL;
5158 }
5159 }
5160 }
5161
5162 /*
5163 * ...and then, if the variable still holds a value, we unset it
5164 * again. This time with no traces left, we're sure it goes away.
5165 */
5166
5167 if (!TclIsVarUndefined(varPtr)) {
5168 UnsetVarStruct(varPtr, NULL, iPtr, /* part1 */ objPtr,
5169 NULL, flags, -1);
5170 }
5171 Tcl_DecrRefCount(objPtr); /* free no longer needed obj */
5172 VarHashRefCount(varPtr)--;
5173 VarHashDeleteEntry(varPtr);
5174 }
5175 VarHashDeleteTable(tablePtr);
5176 }
5177
5178 /*
5179 *----------------------------------------------------------------------
5180 *
5181 * TclDeleteVars --
5182 *
5183 * This function is called to recycle all the storage space associated
5184 * with a table of variables. For this function to work correctly, it
5185 * must not be possible for any of the variables in the table to be
5186 * accessed from Tcl commands (e.g. from trace functions).
5187 *
5188 * Results:
5189 * None.
5190 *
5191 * Side effects:
5192 * Variables are deleted and trace functions are invoked, if any are
5193 * declared.
5194 *
5195 *----------------------------------------------------------------------
5196 */
5197
5198 void
5199 TclDeleteVars(
5200 Interp *iPtr, /* Interpreter to which variables belong. */
5201 TclVarHashTable *tablePtr) /* Hash table containing variables to
5202 * delete. */
5203 {
5204 Tcl_Interp *interp = (Tcl_Interp *) iPtr;
5205 Tcl_HashSearch search;
5206 Var *varPtr;
5207 int flags;
5208 Namespace *currNsPtr = (Namespace *) TclGetCurrentNamespace(interp);
5209
5210 /*
5211 * Determine what flags to pass to the trace callback functions.
5212 */
5213
5214 flags = TCL_TRACE_UNSETS;
5215 if (tablePtr == &iPtr->globalNsPtr->varTable) {
5216 flags |= TCL_GLOBAL_ONLY;
5217 } else if (tablePtr == &currNsPtr->varTable) {
5218 flags |= TCL_NAMESPACE_ONLY;
5219 }
5220
5221 for (varPtr = VarHashFirstVar(tablePtr, &search); varPtr != NULL;
5222 varPtr = VarHashFirstVar(tablePtr, &search)) {
5223 UnsetVarStruct(varPtr, NULL, iPtr, VarHashGetKey(varPtr), NULL, flags,
5224 -1);
5225 VarHashDeleteEntry(varPtr);
5226 }
5227 VarHashDeleteTable(tablePtr);
5228 }
5229
5230 /*
5231 *----------------------------------------------------------------------
5232 *
5233 * TclDeleteCompiledLocalVars --
5234 *
5235 * This function is called to recycle storage space associated with the
5236 * compiler-allocated array of local variables in a procedure call frame.
5237 * This function resembles TclDeleteVars above except that each variable
5238 * is stored in a call frame and not a hash table. For this function to
5239 * work correctly, it must not be possible for any of the variable in the
5240 * table to be accessed from Tcl commands (e.g. from trace functions).
5241 *
5242 * Results:
5243 * None.
5244 *
5245 * Side effects:
5246 * Variables are deleted and trace functions are invoked, if any are
5247 * declared.
5248 *
5249 *----------------------------------------------------------------------
5250 */
5251
5252 void
5253 TclDeleteCompiledLocalVars(
5254 Interp *iPtr, /* Interpreter to which variables belong. */
5255 CallFrame *framePtr) /* Procedure call frame containing compiler-
5256 * assigned local variables to delete. */
5257 {
5258 Var *varPtr;
5259 int numLocals, i;
5260 Tcl_Obj **namePtrPtr;
5261
5262 numLocals = framePtr->numCompiledLocals;
5263 varPtr = framePtr->compiledLocals;
5264 namePtrPtr = &localName(framePtr, 0);
5265 for (i=0 ; i<numLocals ; i++, namePtrPtr++, varPtr++) {
5266 UnsetVarStruct(varPtr, NULL, iPtr, *namePtrPtr, NULL,
5267 TCL_TRACE_UNSETS, i);
5268 }
5269 framePtr->numCompiledLocals = 0;
5270 }
5271
5272 /*
5273 *----------------------------------------------------------------------
5274 *
5275 * DeleteArray --
5276 *
5277 * This function is called to free up everything in an array variable.
5278 * It's the caller's responsibility to make sure that the array is no
5279 * longer accessible before this function is called.
5280 *
5281 * Results:
5282 * None.
5283 *
5284 * Side effects:
5285 * All storage associated with varPtr's array elements is deleted
5286 * (including the array's hash table). Deletion trace functions for
5287 * array elements are invoked, then deleted. Any pending traces for array
5288 * elements are also deleted.
5289 *
5290 *----------------------------------------------------------------------
5291 */
5292
5293 static void
5294 DeleteArray(
5295 Interp *iPtr, /* Interpreter containing array. */
5296 Tcl_Obj *arrayNamePtr, /* Name of array (used for trace callbacks),
5297 * or NULL if it is to be computed on
5298 * demand. */
5299 Var *varPtr, /* Pointer to variable structure. */
5300 int flags, /* Flags to pass to TclCallVarTraces:
5301 * TCL_TRACE_UNSETS and sometimes
5302 * TCL_NAMESPACE_ONLY or TCL_GLOBAL_ONLY. */
5303 int index)
5304 {
5305 Tcl_HashSearch search;
5306 Tcl_HashEntry *tPtr;
5307 Var *elPtr;
5308 ActiveVarTrace *activePtr;
5309 Tcl_Obj *objPtr;
5310 VarTrace *tracePtr;
5311
5312 for (elPtr = VarHashFirstVar(varPtr->value.tablePtr, &search);
5313 elPtr != NULL; elPtr = VarHashNextVar(&search)) {
5314 if (TclIsVarScalar(elPtr) && (elPtr->value.objPtr != NULL)) {
5315 objPtr = elPtr->value.objPtr;
5316 TclDecrRefCount(objPtr);
5317 elPtr->value.objPtr = NULL;
5318 }
5319
5320 /*
5321 * Lie about the validity of the hashtable entry. In this way the
5322 * variables will be deleted by VarHashDeleteTable.
5323 */
5324
5325 VarHashInvalidateEntry(elPtr);
5326 if (TclIsVarTraced(elPtr)) {
5327 /*
5328 * Compute the array name if it was not supplied.
5329 */
5330
5331 if (elPtr->flags & VAR_TRACED_UNSET) {
5332 Tcl_Obj *elNamePtr = VarHashGetKey(elPtr);
5333
5334 elPtr->flags &= ~VAR_TRACE_ACTIVE;
5335 TclObjCallVarTraces(iPtr, NULL, elPtr, arrayNamePtr,
5336 elNamePtr, flags,/* leaveErrMsg */ 0, index);
5337 }
5338 tPtr = Tcl_FindHashEntry(&iPtr->varTraces, elPtr);
5339 tracePtr = (VarTrace *)Tcl_GetHashValue(tPtr);
5340 while (tracePtr) {
5341 VarTrace *prevPtr = tracePtr;
5342
5343 tracePtr = tracePtr->nextPtr;
5344 prevPtr->nextPtr = NULL;
5345 Tcl_EventuallyFree(prevPtr, TCL_DYNAMIC);
5346 }
5347 Tcl_DeleteHashEntry(tPtr);
5348 elPtr->flags &= ~VAR_ALL_TRACES;
5349 for (activePtr = iPtr->activeVarTracePtr; activePtr != NULL;
5350 activePtr = activePtr->nextPtr) {
5351 if (activePtr->varPtr == elPtr) {
5352 activePtr->nextTracePtr = NULL;
5353 }
5354 }
5355 }
5356 TclSetVarUndefined(elPtr);
5357
5358 /*
5359 * Even though array elements are not supposed to be namespace
5360 * variables, some combinations of [upvar] and [variable] may create
5361 * such beasts - see [Bug 604239]. This is necessary to avoid leaking
5362 * the corresponding Var struct, and is otherwise harmless.
5363 */
5364
5365 TclClearVarNamespaceVar(elPtr);
5366 }
5367 VarHashDeleteTable(varPtr->value.tablePtr);
5368 ckfree(varPtr->value.tablePtr);
5369 }
5370
5371 /*
5372 *----------------------------------------------------------------------
5373 *
5374 * TclObjVarErrMsg --
5375 *
5376 * Generate a reasonable error message describing why a variable
5377 * operation failed.
5378 *
5379 * Results:
5380 * None.
5381 *
5382 * Side effects:
5383 * The interp's result is set to hold a message identifying the variable
5384 * given by part1 and part2 and describing why the variable operation
5385 * failed.
5386 *
5387 *----------------------------------------------------------------------
5388 */
5389
5390 void
5391 TclVarErrMsg(
5392 Tcl_Interp *interp, /* Interpreter in which to record message. */
5393 const char *part1,
5394 const char *part2, /* Variable's two-part name. */
5395 const char *operation, /* String describing operation that failed,
5396 * e.g. "read", "set", or "unset". */
5397 const char *reason) /* String describing why operation failed. */
5398 {
5399 Tcl_Obj *part2Ptr = NULL, *part1Ptr = Tcl_NewStringObj(part1, -1);
5400
5401 if (part2) {
5402 part2Ptr = Tcl_NewStringObj(part2, -1);
5403 }
5404
5405 TclObjVarErrMsg(interp, part1Ptr, part2Ptr, operation, reason, -1);
5406
5407 Tcl_DecrRefCount(part1Ptr);
5408 if (part2Ptr) {
5409 Tcl_DecrRefCount(part2Ptr);
5410 }
5411 }
5412
5413 void
5414 TclObjVarErrMsg(
5415 Tcl_Interp *interp, /* Interpreter in which to record message. */
5416 Tcl_Obj *part1Ptr, /* (may be NULL, if index >= 0) */
5417 Tcl_Obj *part2Ptr, /* Variable's two-part name. */
5418 const char *operation, /* String describing operation that failed,
5419 * e.g. "read", "set", or "unset". */
5420 const char *reason, /* String describing why operation failed. */
5421 int index) /* Index into the local variable table of the
5422 * variable, or -1. Only used when part1Ptr is
5423 * NULL. */
5424 {
5425 if (!part1Ptr) {
5426 if (index == -1) {
5427 Tcl_Panic("invalid part1Ptr and invalid index together");
5428 }
5429 part1Ptr = localName(((Interp *)interp)->varFramePtr, index);
5430 }
5431 Tcl_SetObjResult(interp, Tcl_ObjPrintf("can't %s \"%s%s%s%s\": %s",
5432 operation, TclGetString(part1Ptr), (part2Ptr ? "(" : ""),
5433 (part2Ptr ? TclGetString(part2Ptr) : ""), (part2Ptr ? ")" : ""),
5434 reason));
5435 }
5436
5437 /*
5438 *----------------------------------------------------------------------
5439 *
5440 * Internal functions for variable name object types --
5441 *
5442 *----------------------------------------------------------------------
5443 */
5444
5445 /*
5446 * Panic functions that should never be called in normal operation.
5447 */
5448
5449 static void
5450 PanicOnUpdateVarName(
5451 Tcl_Obj *objPtr)
5452 {
5453 Tcl_Panic("%s of type %s should not be called", "updateStringProc",
5454 objPtr->typePtr->name);
5455 }
5456
5457 static int
5458 PanicOnSetVarName(
5459 Tcl_Interp *interp,
5460 Tcl_Obj *objPtr)
5461 {
5462 Tcl_Panic("%s of type %s should not be called", "setFromAnyProc",
5463 objPtr->typePtr->name);
5464 return TCL_ERROR;
5465 }
5466
5467 /*
5468 * localVarName -
5469 *
5470 * INTERNALREP DEFINITION:
5471 * twoPtrValue.ptr1: pointer to name obj in varFramePtr->localCache
5472 * or NULL if it is this same obj
5473 * twoPtrValue.ptr2: index into locals table
5474 */
5475
5476 static void
5477 FreeLocalVarName(
5478 Tcl_Obj *objPtr)
5479 {
5480 Tcl_Obj *namePtr = (Tcl_Obj *)objPtr->internalRep.twoPtrValue.ptr1;
5481
5482 if (namePtr) {
5483 Tcl_DecrRefCount(namePtr);
5484 }
5485 objPtr->typePtr = NULL;
5486 }
5487
5488 static void
5489 DupLocalVarName(
5490 Tcl_Obj *srcPtr,
5491 Tcl_Obj *dupPtr)
5492 {
5493 Tcl_Obj *namePtr = srcPtr->internalRep.twoPtrValue.ptr1;
5494
5495 if (!namePtr) {
5496 namePtr = srcPtr;
5497 }
5498 dupPtr->internalRep.twoPtrValue.ptr1 = namePtr;
5499 Tcl_IncrRefCount(namePtr);
5500
5501 dupPtr->internalRep.twoPtrValue.ptr2 =
5502 srcPtr->internalRep.twoPtrValue.ptr2;
5503 dupPtr->typePtr = &localVarNameType;
5504 }
5505
5506 /*
5507 * parsedVarName -
5508 *
5509 * INTERNALREP DEFINITION:
5510 * twoPtrValue.ptr1 = pointer to the array name Tcl_Obj (NULL if scalar)
5511 * twoPtrValue.ptr2 = pointer to the element name string (owned by this
5512 * Tcl_Obj), or NULL if it is a scalar variable
5513 */
5514
5515 static void
5516 FreeParsedVarName(
5517 Tcl_Obj *objPtr)
5518 {
5519 Tcl_Obj *arrayPtr = objPtr->internalRep.twoPtrValue.ptr1;
5520 char *elem = objPtr->internalRep.twoPtrValue.ptr2;
5521
5522 if (arrayPtr != NULL) {
5523 TclDecrRefCount(arrayPtr);
5524 ckfree(elem);
5525 }
5526 objPtr->typePtr = NULL;
5527 }
5528
5529 static void
5530 DupParsedVarName(
5531 Tcl_Obj *srcPtr,
5532 Tcl_Obj *dupPtr)
5533 {
5534 Tcl_Obj *arrayPtr = srcPtr->internalRep.twoPtrValue.ptr1;
5535 char *elem = srcPtr->internalRep.twoPtrValue.ptr2;
5536 char *elemCopy;
5537 unsigned elemLen;
5538
5539 if (arrayPtr != NULL) {
5540 Tcl_IncrRefCount(arrayPtr);
5541 elemLen = strlen(elem);
5542 elemCopy = (char *)ckalloc(elemLen + 1);
5543 memcpy(elemCopy, elem, elemLen);
5544 *(elemCopy + elemLen) = '\0';
5545 elem = elemCopy;
5546 }
5547
5548 dupPtr->internalRep.twoPtrValue.ptr1 = arrayPtr;
5549 dupPtr->internalRep.twoPtrValue.ptr2 = elem;
5550 dupPtr->typePtr = &tclParsedVarNameType;
5551 }
5552
5553 static void
5554 UpdateParsedVarName(
5555 Tcl_Obj *objPtr)
5556 {
5557 Tcl_Obj *arrayPtr = objPtr->internalRep.twoPtrValue.ptr1;
5558 char *part2 = objPtr->internalRep.twoPtrValue.ptr2;
5559 const char *part1;
5560 char *p;
5561 int len1, len2, totalLen;
5562
5563 if (arrayPtr == NULL) {
5564 /*
5565 * This is a parsed scalar name: what is it doing here?
5566 */
5567
5568 Tcl_Panic("scalar parsedVarName without a string rep");
5569 }
5570
5571 part1 = TclGetStringFromObj(arrayPtr, &len1);
5572 len2 = strlen(part2);
5573
5574 totalLen = len1 + len2 + 2;
5575 p = ckalloc(totalLen + 1);
5576 objPtr->bytes = p;
5577 objPtr->length = totalLen;
5578
5579 memcpy(p, part1, len1);
5580 p += len1;
5581 *p++ = '(';
5582 memcpy(p, part2, len2);
5583 p += len2;
5584 *p++ = ')';
5585 *p = '\0';
5586 }
5587
5588 /*
5589 *----------------------------------------------------------------------
5590 *
5591 * Tcl_FindNamespaceVar -- MOVED OVER from tclNamesp.c
5592 *
5593 * Searches for a namespace variable, a variable not local to a
5594 * procedure. The variable can be either a scalar or an array, but may
5595 * not be an element of an array.
5596 *
5597 * Results:
5598 * Returns a token for the variable if it is found. Otherwise, if it
5599 * can't be found or there is an error, returns NULL and leaves an error
5600 * message in the interpreter's result object if "flags" contains
5601 * TCL_LEAVE_ERR_MSG.
5602 *
5603 * Side effects:
5604 * None.
5605 *
5606 *----------------------------------------------------------------------
5607 */
5608
5609 Tcl_Var
5610 Tcl_FindNamespaceVar(
5611 Tcl_Interp *interp, /* The interpreter in which to find the
5612 * variable. */
5613 const char *name, /* Variable's name. If it starts with "::",
5614 * will be looked up in global namespace.
5615 * Else, looked up first in contextNsPtr
5616 * (current namespace if contextNsPtr is
5617 * NULL), then in global namespace. */
5618 Tcl_Namespace *contextNsPtr,/* Ignored if TCL_GLOBAL_ONLY flag set.
5619 * Otherwise, points to namespace in which to
5620 * resolve name. If NULL, look up name in the
5621 * current namespace. */
5622 int flags) /* An OR'd combination of:
5623 * TCL_AVOID_RESOLVERS, TCL_GLOBAL_ONLY (look
5624 * up name only in global namespace),
5625 * TCL_NAMESPACE_ONLY (look up only in
5626 * contextNsPtr, or the current namespace if
5627 * contextNsPtr is NULL), and
5628 * TCL_LEAVE_ERR_MSG. If both TCL_GLOBAL_ONLY
5629 * and TCL_NAMESPACE_ONLY are given,
5630 * TCL_GLOBAL_ONLY is ignored. */
5631 {
5632 Tcl_Obj *namePtr = Tcl_NewStringObj(name, -1);
5633 Tcl_Var var;
5634
5635 var = ObjFindNamespaceVar(interp, namePtr, contextNsPtr, flags);
5636 Tcl_DecrRefCount(namePtr);
5637 return var;
5638 }
5639
5640 static Tcl_Var
5641 ObjFindNamespaceVar(
5642 Tcl_Interp *interp, /* The interpreter in which to find the
5643 * variable. */
5644 Tcl_Obj *namePtr, /* Variable's name. If it starts with "::",
5645 * will be looked up in global namespace.
5646 * Else, looked up first in contextNsPtr
5647 * (current namespace if contextNsPtr is
5648 * NULL), then in global namespace. */
5649 Tcl_Namespace *contextNsPtr,/* Ignored if TCL_GLOBAL_ONLY flag set.
5650 * Otherwise, points to namespace in which to
5651 * resolve name. If NULL, look up name in the
5652 * current namespace. */
5653 int flags) /* An OR'd combination of:
5654 * TCL_AVOID_RESOLVERS, TCL_GLOBAL_ONLY (look
5655 * up name only in global namespace),
5656 * TCL_NAMESPACE_ONLY (look up only in
5657 * contextNsPtr, or the current namespace if
5658 * contextNsPtr is NULL), and
5659 * TCL_LEAVE_ERR_MSG. If both TCL_GLOBAL_ONLY
5660 * and TCL_NAMESPACE_ONLY are given,
5661 * TCL_GLOBAL_ONLY is ignored. */
5662 {
5663 Interp *iPtr = (Interp *) interp;
5664 ResolverScheme *resPtr;
5665 Namespace *nsPtr[2], *cxtNsPtr;
5666 const char *simpleName;
5667 Var *varPtr;
5668 int search;
5669 int result;
5670 Tcl_Var var;
5671 Tcl_Obj *simpleNamePtr;
5672 const char *name = TclGetString(namePtr);
5673
5674 /*
5675 * If this namespace has a variable resolver, then give it first crack at
5676 * the variable resolution. It may return a Tcl_Var value, it may signal
5677 * to continue onward, or it may signal an error.
5678 */
5679
5680 if ((flags & TCL_GLOBAL_ONLY) != 0) {
5681 cxtNsPtr = (Namespace *) TclGetGlobalNamespace(interp);
5682 } else if (contextNsPtr != NULL) {
5683 cxtNsPtr = (Namespace *) contextNsPtr;
5684 } else {
5685 cxtNsPtr = (Namespace *) TclGetCurrentNamespace(interp);
5686 }
5687
5688 if (!(flags & TCL_AVOID_RESOLVERS) &&
5689 (cxtNsPtr->varResProc != NULL || iPtr->resolverPtr != NULL)) {
5690 resPtr = iPtr->resolverPtr;
5691
5692 if (cxtNsPtr->varResProc) {
5693 result = cxtNsPtr->varResProc(interp, name,
5694 (Tcl_Namespace *) cxtNsPtr, flags, &var);
5695 } else {
5696 result = TCL_CONTINUE;
5697 }
5698
5699 while (result == TCL_CONTINUE && resPtr) {
5700 if (resPtr->varResProc) {
5701 result = resPtr->varResProc(interp, name,
5702 (Tcl_Namespace *) cxtNsPtr, flags, &var);
5703 }
5704 resPtr = resPtr->nextPtr;
5705 }
5706
5707 if (result == TCL_OK) {
5708 return var;
5709 } else if (result != TCL_CONTINUE) {
5710 return NULL;
5711 }
5712 }
5713
5714 /*
5715 * Find the namespace(s) that contain the variable.
5716 */
5717
5718 TclGetNamespaceForQualName(interp, name, (Namespace *) contextNsPtr,
5719 flags, &nsPtr[0], &nsPtr[1], &cxtNsPtr, &simpleName);
5720
5721 /*
5722 * Look for the variable in the variable table of its namespace. Be sure
5723 * to check both possible search paths: from the specified namespace
5724 * context and from the global namespace.
5725 */
5726
5727 varPtr = NULL;
5728 if (simpleName != name) {
5729 simpleNamePtr = Tcl_NewStringObj(simpleName, -1);
5730 } else {
5731 simpleNamePtr = namePtr;
5732 }
5733
5734 for (search = 0; (search < 2) && (varPtr == NULL); search++) {
5735 if ((nsPtr[search] != NULL) && (simpleName != NULL)) {
5736 varPtr = VarHashFindVar(&nsPtr[search]->varTable, simpleNamePtr);
5737 }
5738 }
5739 if (simpleName != name) {
5740 Tcl_DecrRefCount(simpleNamePtr);
5741 }
5742 if ((varPtr == NULL) && (flags & TCL_LEAVE_ERR_MSG)) {
5743 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
5744 "unknown variable \"%s\"", name));
5745 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARIABLE", name, (char *)NULL);
5746 }
5747 return (Tcl_Var) varPtr;
5748 }
5749
5750 /*
5751 *----------------------------------------------------------------------
5752 *
5753 * InfoVarsCmd -- (moved over from tclCmdIL.c)
5754 *
5755 * Called to implement the "info vars" command that returns the list of
5756 * variables in the interpreter that match an optional pattern. The
5757 * pattern, if any, consists of an optional sequence of namespace names
5758 * separated by "::" qualifiers, which is followed by a glob-style
5759 * pattern that restricts which variables are returned. Handles the
5760 * following syntax:
5761 *
5762 * info vars ?pattern?
5763 *
5764 * Results:
5765 * Returns TCL_OK if successful and TCL_ERROR if there is an error.
5766 *
5767 * Side effects:
5768 * Returns a result in the interpreter's result object. If there is an
5769 * error, the result is an error message.
5770 *
5771 *----------------------------------------------------------------------
5772 */
5773
5774 int
5775 TclInfoVarsCmd(
5776 ClientData dummy, /* Not used. */
5777 Tcl_Interp *interp, /* Current interpreter. */
5778 int objc, /* Number of arguments. */
5779 Tcl_Obj *const objv[]) /* Argument objects. */
5780 {
5781 Interp *iPtr = (Interp *) interp;
5782 const char *varName, *pattern, *simplePattern;
5783 Tcl_HashSearch search;
5784 Var *varPtr;
5785 Namespace *nsPtr;
5786 Namespace *globalNsPtr = (Namespace *) Tcl_GetGlobalNamespace(interp);
5787 Namespace *currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
5788 Tcl_Obj *listPtr, *elemObjPtr, *varNamePtr;
5789 int specificNsInPattern = 0;/* Init. to avoid compiler warning. */
5790 Tcl_Obj *simplePatternPtr = NULL;
5791
5792 /*
5793 * Get the pattern and find the "effective namespace" in which to list
5794 * variables. We only use this effective namespace if there's no active
5795 * Tcl procedure frame.
5796 */
5797
5798 if (objc == 1) {
5799 simplePattern = NULL;
5800 nsPtr = currNsPtr;
5801 specificNsInPattern = 0;
5802 } else if (objc == 2) {
5803 /*
5804 * From the pattern, get the effective namespace and the simple
5805 * pattern (no namespace qualifiers or ::'s) at the end. If an error
5806 * was found while parsing the pattern, return it. Otherwise, if the
5807 * namespace wasn't found, just leave nsPtr NULL: we will return an
5808 * empty list since no variables there can be found.
5809 */
5810
5811 Namespace *dummy1NsPtr, *dummy2NsPtr;
5812
5813 pattern = TclGetString(objv[1]);
5814 TclGetNamespaceForQualName(interp, pattern, NULL, /*flags*/ 0,
5815 &nsPtr, &dummy1NsPtr, &dummy2NsPtr, &simplePattern);
5816
5817 if (nsPtr != NULL) { /* We successfully found the pattern's ns. */
5818 specificNsInPattern = (strcmp(simplePattern, pattern) != 0);
5819 if (simplePattern == pattern) {
5820 simplePatternPtr = objv[1];
5821 } else {
5822 simplePatternPtr = Tcl_NewStringObj(simplePattern, -1);
5823 }
5824 Tcl_IncrRefCount(simplePatternPtr);
5825 }
5826 } else {
5827 Tcl_WrongNumArgs(interp, 1, objv, "?pattern?");
5828 return TCL_ERROR;
5829 }
5830
5831 /*
5832 * If the namespace specified in the pattern wasn't found, just return.
5833 */
5834
5835 if (nsPtr == NULL) {
5836 return TCL_OK;
5837 }
5838
5839 listPtr = Tcl_NewListObj(0, NULL);
5840
5841 if (!HasLocalVars(iPtr->varFramePtr) || specificNsInPattern) {
5842 /*
5843 * There is no frame pointer, the frame pointer was pushed only to
5844 * activate a namespace, or we are in a procedure call frame but a
5845 * specific namespace was specified. Create a list containing only the
5846 * variables in the effective namespace's variable table.
5847 */
5848
5849 if (simplePattern && TclMatchIsTrivial(simplePattern)) {
5850 /*
5851 * If we can just do hash lookups, that simplifies things a lot.
5852 */
5853
5854 varPtr = VarHashFindVar(&nsPtr->varTable, simplePatternPtr);
5855 if (varPtr) {
5856 if (!TclIsVarUndefined(varPtr)
5857 || TclIsVarNamespaceVar(varPtr)) {
5858 if (specificNsInPattern) {
5859 TclNewObj(elemObjPtr);
5860 Tcl_GetVariableFullName(interp, (Tcl_Var) varPtr,
5861 elemObjPtr);
5862 } else {
5863 elemObjPtr = VarHashGetKey(varPtr);
5864 }
5865 Tcl_ListObjAppendElement(interp, listPtr, elemObjPtr);
5866 }
5867 } else if ((nsPtr != globalNsPtr) && !specificNsInPattern) {
5868 varPtr = VarHashFindVar(&globalNsPtr->varTable,
5869 simplePatternPtr);
5870 if (varPtr) {
5871 if (!TclIsVarUndefined(varPtr)
5872 || TclIsVarNamespaceVar(varPtr)) {
5873 Tcl_ListObjAppendElement(interp, listPtr,
5874 VarHashGetKey(varPtr));
5875 }
5876 }
5877 }
5878 } else {
5879 /*
5880 * Have to scan the tables of variables.
5881 */
5882
5883 varPtr = VarHashFirstVar(&nsPtr->varTable, &search);
5884 while (varPtr) {
5885 if (!TclIsVarUndefined(varPtr)
5886 || TclIsVarNamespaceVar(varPtr)) {
5887 varNamePtr = VarHashGetKey(varPtr);
5888 varName = TclGetString(varNamePtr);
5889 if ((simplePattern == NULL)
5890 || Tcl_StringMatch(varName, simplePattern)) {
5891 if (specificNsInPattern) {
5892 TclNewObj(elemObjPtr);
5893 Tcl_GetVariableFullName(interp, (Tcl_Var) varPtr,
5894 elemObjPtr);
5895 } else {
5896 elemObjPtr = varNamePtr;
5897 }
5898 Tcl_ListObjAppendElement(interp, listPtr, elemObjPtr);
5899 }
5900 }
5901 varPtr = VarHashNextVar(&search);
5902 }
5903
5904 /*
5905 * If the effective namespace isn't the global :: namespace, and a
5906 * specific namespace wasn't requested in the pattern (i.e., the
5907 * pattern only specifies variable names), then add in all global
5908 * :: variables that match the simple pattern. Of course, add in
5909 * only those variables that aren't hidden by a variable in the
5910 * effective namespace.
5911 */
5912
5913 if ((nsPtr != globalNsPtr) && !specificNsInPattern) {
5914 varPtr = VarHashFirstVar(&globalNsPtr->varTable, &search);
5915 while (varPtr) {
5916 if (!TclIsVarUndefined(varPtr)
5917 || TclIsVarNamespaceVar(varPtr)) {
5918 varNamePtr = VarHashGetKey(varPtr);
5919 varName = TclGetString(varNamePtr);
5920 if ((simplePattern == NULL)
5921 || Tcl_StringMatch(varName, simplePattern)) {
5922 if (VarHashFindVar(&nsPtr->varTable,
5923 varNamePtr) == NULL) {
5924 Tcl_ListObjAppendElement(interp, listPtr,
5925 varNamePtr);
5926 }
5927 }
5928 }
5929 varPtr = VarHashNextVar(&search);
5930 }
5931 }
5932 }
5933 } else if (iPtr->varFramePtr->procPtr != NULL) {
5934 AppendLocals(interp, listPtr, simplePatternPtr, 1);
5935 }
5936
5937 if (simplePatternPtr) {
5938 Tcl_DecrRefCount(simplePatternPtr);
5939 }
5940 Tcl_SetObjResult(interp, listPtr);
5941 return TCL_OK;
5942 }
5943
5944 /*
5945 *----------------------------------------------------------------------
5946 *
5947 * InfoGlobalsCmd -- (moved over from tclCmdIL.c)
5948 *
5949 * Called to implement the "info globals" command that returns the list
5950 * of global variables matching an optional pattern. Handles the
5951 * following syntax:
5952 *
5953 * info globals ?pattern?
5954 *
5955 * Results:
5956 * Returns TCL_OK if successful and TCL_ERROR if there is an error.
5957 *
5958 * Side effects:
5959 * Returns a result in the interpreter's result object. If there is an
5960 * error, the result is an error message.
5961 *
5962 *----------------------------------------------------------------------
5963 */
5964
5965 int
5966 TclInfoGlobalsCmd(
5967 ClientData dummy, /* Not used. */
5968 Tcl_Interp *interp, /* Current interpreter. */
5969 int objc, /* Number of arguments. */
5970 Tcl_Obj *const objv[]) /* Argument objects. */
5971 {
5972 const char *varName, *pattern;
5973 Namespace *globalNsPtr = (Namespace *) Tcl_GetGlobalNamespace(interp);
5974 Tcl_HashSearch search;
5975 Var *varPtr;
5976 Tcl_Obj *listPtr, *varNamePtr, *patternPtr;
5977
5978 if (objc == 1) {
5979 pattern = NULL;
5980 } else if (objc == 2) {
5981 pattern = TclGetString(objv[1]);
5982
5983 /*
5984 * Strip leading global-namespace qualifiers. [Bug 1057461]
5985 */
5986
5987 if (pattern[0] == ':' && pattern[1] == ':') {
5988 while (*pattern == ':') {
5989 pattern++;
5990 }
5991 }
5992 } else {
5993 Tcl_WrongNumArgs(interp, 1, objv, "?pattern?");
5994 return TCL_ERROR;
5995 }
5996
5997 /*
5998 * Scan through the global :: namespace's variable table and create a list
5999 * of all global variables that match the pattern.
6000 */
6001
6002 listPtr = Tcl_NewListObj(0, NULL);
6003 if (pattern != NULL && TclMatchIsTrivial(pattern)) {
6004 if (pattern == TclGetString(objv[1])) {
6005 patternPtr = objv[1];
6006 } else {
6007 patternPtr = Tcl_NewStringObj(pattern, -1);
6008 }
6009 Tcl_IncrRefCount(patternPtr);
6010
6011 varPtr = VarHashFindVar(&globalNsPtr->varTable, patternPtr);
6012 if (varPtr) {
6013 if (!TclIsVarUndefined(varPtr)) {
6014 Tcl_ListObjAppendElement(interp, listPtr,
6015 VarHashGetKey(varPtr));
6016 }
6017 }
6018 Tcl_DecrRefCount(patternPtr);
6019 } else {
6020 for (varPtr = VarHashFirstVar(&globalNsPtr->varTable, &search);
6021 varPtr != NULL;
6022 varPtr = VarHashNextVar(&search)) {
6023 if (TclIsVarUndefined(varPtr)) {
6024 continue;
6025 }
6026 varNamePtr = VarHashGetKey(varPtr);
6027 varName = TclGetString(varNamePtr);
6028 if ((pattern == NULL) || Tcl_StringMatch(varName, pattern)) {
6029 Tcl_ListObjAppendElement(interp, listPtr, varNamePtr);
6030 }
6031 }
6032 }
6033 Tcl_SetObjResult(interp, listPtr);
6034 return TCL_OK;
6035 }
6036
6037 /*
6038 *----------------------------------------------------------------------
6039 *
6040 * TclInfoLocalsCmd -- (moved over from tclCmdIl.c)
6041 *
6042 * Called to implement the "info locals" command to return a list of
6043 * local variables that match an optional pattern. Handles the following
6044 * syntax:
6045 *
6046 * info locals ?pattern?
6047 *
6048 * Results:
6049 * Returns TCL_OK if successful and TCL_ERROR if there is an error.
6050 *
6051 * Side effects:
6052 * Returns a result in the interpreter's result object. If there is an
6053 * error, the result is an error message.
6054 *
6055 *----------------------------------------------------------------------
6056 */
6057
6058 int
6059 TclInfoLocalsCmd(
6060 ClientData dummy, /* Not used. */
6061 Tcl_Interp *interp, /* Current interpreter. */
6062 int objc, /* Number of arguments. */
6063 Tcl_Obj *const objv[]) /* Argument objects. */
6064 {
6065 Interp *iPtr = (Interp *) interp;
6066 Tcl_Obj *patternPtr, *listPtr;
6067
6068 if (objc == 1) {
6069 patternPtr = NULL;
6070 } else if (objc == 2) {
6071 patternPtr = objv[1];
6072 } else {
6073 Tcl_WrongNumArgs(interp, 1, objv, "?pattern?");
6074 return TCL_ERROR;
6075 }
6076
6077 if (!HasLocalVars(iPtr->varFramePtr)) {
6078 return TCL_OK;
6079 }
6080
6081 /*
6082 * Return a list containing names of first the compiled locals (i.e. the
6083 * ones stored in the call frame), then the variables in the local hash
6084 * table (if one exists).
6085 */
6086
6087 listPtr = Tcl_NewListObj(0, NULL);
6088 AppendLocals(interp, listPtr, patternPtr, 0);
6089 Tcl_SetObjResult(interp, listPtr);
6090 return TCL_OK;
6091 }
6092
6093 /*
6094 *----------------------------------------------------------------------
6095 *
6096 * AppendLocals --
6097 *
6098 * Append the local variables for the current frame to the specified list
6099 * object.
6100 *
6101 * Results:
6102 * None.
6103 *
6104 * Side effects:
6105 * None.
6106 *
6107 *----------------------------------------------------------------------
6108 */
6109
6110 static void
6111 AppendLocals(
6112 Tcl_Interp *interp, /* Current interpreter. */
6113 Tcl_Obj *listPtr, /* List object to append names to. */
6114 Tcl_Obj *patternPtr, /* Pattern to match against. */
6115 int includeLinks) /* 1 if upvars should be included, else 0. */
6116 {
6117 Interp *iPtr = (Interp *) interp;
6118 Var *varPtr;
6119 int i, localVarCt, added;
6120 Tcl_Obj *objNamePtr;
6121 const char *varName;
6122 TclVarHashTable *localVarTablePtr;
6123 Tcl_HashSearch search;
6124 Tcl_HashTable addedTable;
6125 const char *pattern = patternPtr? TclGetString(patternPtr) : NULL;
6126
6127 localVarCt = iPtr->varFramePtr->numCompiledLocals;
6128 varPtr = iPtr->varFramePtr->compiledLocals;
6129 localVarTablePtr = iPtr->varFramePtr->varTablePtr;
6130 if (includeLinks) {
6131 Tcl_InitObjHashTable(&addedTable);
6132 }
6133
6134 if (localVarCt > 0) {
6135 Tcl_Obj **varNamePtr = &iPtr->varFramePtr->localCachePtr->varName0;
6136
6137 for (i = 0; i < localVarCt; i++, varNamePtr++) {
6138 /*
6139 * Skip nameless (temporary) variables and undefined variables.
6140 */
6141
6142 if (*varNamePtr && !TclIsVarUndefined(varPtr)
6143 && (includeLinks || !TclIsVarLink(varPtr))) {
6144 varName = TclGetString(*varNamePtr);
6145 if ((pattern == NULL) || Tcl_StringMatch(varName, pattern)) {
6146 Tcl_ListObjAppendElement(interp, listPtr, *varNamePtr);
6147 if (includeLinks) {
6148 Tcl_CreateHashEntry(&addedTable, *varNamePtr, &added);
6149 }
6150 }
6151 }
6152 varPtr++;
6153 }
6154 }
6155
6156 /*
6157 * Do nothing if no local variables.
6158 */
6159
6160 if (localVarTablePtr == NULL) {
6161 goto objectVars;
6162 }
6163
6164 /*
6165 * Check for the simple and fast case.
6166 */
6167
6168 if ((pattern != NULL) && TclMatchIsTrivial(pattern)) {
6169 varPtr = VarHashFindVar(localVarTablePtr, patternPtr);
6170 if (varPtr != NULL) {
6171 if (!TclIsVarUndefined(varPtr)
6172 && (includeLinks || !TclIsVarLink(varPtr))) {
6173 Tcl_ListObjAppendElement(interp, listPtr,
6174 VarHashGetKey(varPtr));
6175 if (includeLinks) {
6176 Tcl_CreateHashEntry(&addedTable, VarHashGetKey(varPtr),
6177 &added);
6178 }
6179 }
6180 }
6181 goto objectVars;
6182 }
6183
6184 /*
6185 * Scan over and process all local variables.
6186 */
6187
6188 for (varPtr = VarHashFirstVar(localVarTablePtr, &search);
6189 varPtr != NULL;
6190 varPtr = VarHashNextVar(&search)) {
6191 if (!TclIsVarUndefined(varPtr)
6192 && (includeLinks || !TclIsVarLink(varPtr))) {
6193 objNamePtr = VarHashGetKey(varPtr);
6194 varName = TclGetString(objNamePtr);
6195 if ((pattern == NULL) || Tcl_StringMatch(varName, pattern)) {
6196 Tcl_ListObjAppendElement(interp, listPtr, objNamePtr);
6197 if (includeLinks) {
6198 Tcl_CreateHashEntry(&addedTable, objNamePtr, &added);
6199 }
6200 }
6201 }
6202 }
6203
6204 objectVars:
6205 if (!includeLinks) {
6206 return;
6207 }
6208
6209 if (iPtr->varFramePtr->isProcCallFrame & FRAME_IS_METHOD) {
6210 CallContext *contextPtr = iPtr->varFramePtr->clientData;
6211 Method *mPtr = contextPtr->callPtr->chain[contextPtr->index].mPtr;
6212
6213 if (mPtr->declaringObjectPtr) {
6214 FOREACH(objNamePtr, mPtr->declaringObjectPtr->variables) {
6215 Tcl_CreateHashEntry(&addedTable, objNamePtr, &added);
6216 if (added && (!pattern ||
6217 Tcl_StringMatch(TclGetString(objNamePtr), pattern))) {
6218 Tcl_ListObjAppendElement(interp, listPtr, objNamePtr);
6219 }
6220 }
6221 } else {
6222 FOREACH(objNamePtr, mPtr->declaringClassPtr->variables) {
6223 Tcl_CreateHashEntry(&addedTable, objNamePtr, &added);
6224 if (added && (!pattern ||
6225 Tcl_StringMatch(TclGetString(objNamePtr), pattern))) {
6226 Tcl_ListObjAppendElement(interp, listPtr, objNamePtr);
6227 }
6228 }
6229 }
6230 }
6231 Tcl_DeleteHashTable(&addedTable);
6232 }
6233
6234 /*
6235 * Hash table implementation - first, just copy and adapt the obj key stuff
6236 */
6237
6238 void
6239 TclInitVarHashTable(
6240 TclVarHashTable *tablePtr,
6241 Namespace *nsPtr)
6242 {
6243 Tcl_InitCustomHashTable(&tablePtr->table,
6244 TCL_CUSTOM_TYPE_KEYS, &tclVarHashKeyType);
6245 tablePtr->nsPtr = nsPtr;
6246 }
6247
6248 static Tcl_HashEntry *
6249 AllocVarEntry(
6250 Tcl_HashTable *tablePtr, /* Hash table. */
6251 void *keyPtr) /* Key to store in the hash table entry. */
6252 {
6253 Tcl_Obj *objPtr = (Tcl_Obj *)keyPtr;
6254 Tcl_HashEntry *hPtr;
6255 Var *varPtr;
6256
6257 varPtr = (Var *)ckalloc(sizeof(VarInHash));
6258 varPtr->flags = VAR_IN_HASHTABLE;
6259 varPtr->value.objPtr = NULL;
6260 VarHashRefCount(varPtr) = 1;
6261
6262 hPtr = &(((VarInHash *) varPtr)->entry);
6263 Tcl_SetHashValue(hPtr, varPtr);
6264 hPtr->key.objPtr = objPtr;
6265 Tcl_IncrRefCount(objPtr);
6266
6267 return hPtr;
6268 }
6269
6270 static void
6271 FreeVarEntry(
6272 Tcl_HashEntry *hPtr)
6273 {
6274 Var *varPtr = VarHashGetValue(hPtr);
6275 Tcl_Obj *objPtr = hPtr->key.objPtr;
6276
6277 if (TclIsVarUndefined(varPtr) && !TclIsVarTraced(varPtr)
6278 && (VarHashRefCount(varPtr) == 1)) {
6279 ckfree(varPtr);
6280 } else {
6281 VarHashInvalidateEntry(varPtr);
6282 TclSetVarUndefined(varPtr);
6283 VarHashRefCount(varPtr)--;
6284 }
6285 Tcl_DecrRefCount(objPtr);
6286 }
6287
6288 static int
6289 CompareVarKeys(
6290 void *keyPtr, /* New key to compare. */
6291 Tcl_HashEntry *hPtr) /* Existing key to compare. */
6292 {
6293 Tcl_Obj *objPtr1 = (Tcl_Obj *)keyPtr;
6294 Tcl_Obj *objPtr2 = hPtr->key.objPtr;
6295 const char *p1, *p2;
6296 int l1, l2;
6297
6298 /*
6299 * If the object pointers are the same then they match.
6300 * OPT: this comparison was moved to the caller
6301 *
6302 * if (objPtr1 == objPtr2) return 1;
6303 */
6304
6305 /*
6306 * Don't use Tcl_GetStringFromObj as it would prevent l1 and l2 being in a
6307 * register.
6308 */
6309
6310 p1 = TclGetString(objPtr1);
6311 l1 = objPtr1->length;
6312 p2 = TclGetString(objPtr2);
6313 l2 = objPtr2->length;
6314
6315 /*
6316 * Only compare string representations of the same length.
6317 */
6318
6319 return ((l1 == l2) && !memcmp(p1, p2, l1));
6320 }
6321
6322 /*
6323 * Local Variables:
6324 * mode: c
6325 * c-basic-offset: 4
6326 * fill-column: 78
6327 * End:
6328 */