Debian Codegraph @

generic/tclDictObj.c

raw
1 /*
2 * tclDictObj.c --
3 *
4 * This file contains functions that implement the Tcl dict object type
5 * and its accessor command.
6 *
7 * Copyright (c) 2002-2010 by Donal K. Fellows.
8 *
9 * See the file "license.terms" for information on usage and redistribution of
10 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 */
12
13 #include "tclInt.h"
14 #include "tommath.h"
15
16 /*
17 * Forward declaration.
18 */
19 struct Dict;
20
21 /*
22 * Prototypes for functions defined later in this file:
23 */
24
25 static void DeleteDict(struct Dict *dict);
26 static int DictAppendCmd(ClientData dummy, Tcl_Interp *interp,
27 int objc, Tcl_Obj *const *objv);
28 static int DictCreateCmd(ClientData dummy, Tcl_Interp *interp,
29 int objc, Tcl_Obj *const *objv);
30 static int DictExistsCmd(ClientData dummy, Tcl_Interp *interp,
31 int objc, Tcl_Obj *const *objv);
32 static int DictFilterCmd(ClientData dummy, Tcl_Interp *interp,
33 int objc, Tcl_Obj *const *objv);
34 static int DictGetCmd(ClientData dummy, Tcl_Interp *interp,
35 int objc, Tcl_Obj *const *objv);
36 static int DictIncrCmd(ClientData dummy, Tcl_Interp *interp,
37 int objc, Tcl_Obj *const *objv);
38 static int DictInfoCmd(ClientData dummy, Tcl_Interp *interp,
39 int objc, Tcl_Obj *const *objv);
40 static int DictKeysCmd(ClientData dummy, Tcl_Interp *interp,
41 int objc, Tcl_Obj *const *objv);
42 static int DictLappendCmd(ClientData dummy, Tcl_Interp *interp,
43 int objc, Tcl_Obj *const *objv);
44 static int DictMergeCmd(ClientData dummy, Tcl_Interp *interp,
45 int objc, Tcl_Obj *const *objv);
46 static int DictRemoveCmd(ClientData dummy, Tcl_Interp *interp,
47 int objc, Tcl_Obj *const *objv);
48 static int DictReplaceCmd(ClientData dummy, Tcl_Interp *interp,
49 int objc, Tcl_Obj *const *objv);
50 static int DictSetCmd(ClientData dummy, Tcl_Interp *interp,
51 int objc, Tcl_Obj *const *objv);
52 static int DictSizeCmd(ClientData dummy, Tcl_Interp *interp,
53 int objc, Tcl_Obj *const *objv);
54 static int DictUnsetCmd(ClientData dummy, Tcl_Interp *interp,
55 int objc, Tcl_Obj *const *objv);
56 static int DictUpdateCmd(ClientData dummy, Tcl_Interp *interp,
57 int objc, Tcl_Obj *const *objv);
58 static int DictValuesCmd(ClientData dummy, Tcl_Interp *interp,
59 int objc, Tcl_Obj *const *objv);
60 static int DictWithCmd(ClientData dummy, Tcl_Interp *interp,
61 int objc, Tcl_Obj *const *objv);
62 static void DupDictInternalRep(Tcl_Obj *srcPtr, Tcl_Obj *copyPtr);
63 static void FreeDictInternalRep(Tcl_Obj *dictPtr);
64 static void InvalidateDictChain(Tcl_Obj *dictObj);
65 static int SetDictFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr);
66 static void UpdateStringOfDict(Tcl_Obj *dictPtr);
67 static Tcl_HashEntry * AllocChainEntry(Tcl_HashTable *tablePtr,void *keyPtr);
68 static inline void InitChainTable(struct Dict *dict);
69 static inline void DeleteChainTable(struct Dict *dict);
70 static inline Tcl_HashEntry *CreateChainEntry(struct Dict *dict,
71 Tcl_Obj *keyPtr, int *newPtr);
72 static inline int DeleteChainEntry(struct Dict *dict, Tcl_Obj *keyPtr);
73 static Tcl_NRPostProc FinalizeDictUpdate;
74 static Tcl_NRPostProc FinalizeDictWith;
75 static Tcl_ObjCmdProc DictForNRCmd;
76 static Tcl_ObjCmdProc DictMapNRCmd;
77 static Tcl_NRPostProc DictForLoopCallback;
78 static Tcl_NRPostProc DictMapLoopCallback;
79
80 /*
81 * Table of dict subcommand names and implementations.
82 */
83
84 static const EnsembleImplMap implementationMap[] = {
85 {"append", DictAppendCmd, TclCompileDictAppendCmd, NULL, NULL, 0 },
86 {"create", DictCreateCmd, TclCompileDictCreateCmd, NULL, NULL, 0 },
87 {"exists", DictExistsCmd, TclCompileDictExistsCmd, NULL, NULL, 0 },
88 {"filter", DictFilterCmd, NULL, NULL, NULL, 0 },
89 {"for", NULL, TclCompileDictForCmd, DictForNRCmd, NULL, 0 },
90 {"get", DictGetCmd, TclCompileDictGetCmd, NULL, NULL, 0 },
91 {"incr", DictIncrCmd, TclCompileDictIncrCmd, NULL, NULL, 0 },
92 {"info", DictInfoCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0 },
93 {"keys", DictKeysCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0 },
94 {"lappend", DictLappendCmd, TclCompileDictLappendCmd, NULL, NULL, 0 },
95 {"map", NULL, TclCompileDictMapCmd, DictMapNRCmd, NULL, 0 },
96 {"merge", DictMergeCmd, TclCompileDictMergeCmd, NULL, NULL, 0 },
97 {"remove", DictRemoveCmd, TclCompileBasicMin1ArgCmd, NULL, NULL, 0 },
98 {"replace", DictReplaceCmd, NULL, NULL, NULL, 0 },
99 {"set", DictSetCmd, TclCompileDictSetCmd, NULL, NULL, 0 },
100 {"size", DictSizeCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0 },
101 {"unset", DictUnsetCmd, TclCompileDictUnsetCmd, NULL, NULL, 0 },
102 {"update", DictUpdateCmd, TclCompileDictUpdateCmd, NULL, NULL, 0 },
103 {"values", DictValuesCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0 },
104 {"with", DictWithCmd, TclCompileDictWithCmd, NULL, NULL, 0 },
105 {NULL, NULL, NULL, NULL, NULL, 0}
106 };
107
108 /*
109 * Internal representation of the entries in the hash table that backs a
110 * dictionary.
111 */
112
113 typedef struct ChainEntry {
114 Tcl_HashEntry entry;
115 struct ChainEntry *prevPtr;
116 struct ChainEntry *nextPtr;
117 } ChainEntry;
118
119 /*
120 * Internal representation of a dictionary.
121 *
122 * The internal representation of a dictionary object is a hash table (with
123 * Tcl_Objs for both keys and values), a reference count and epoch number for
124 * detecting concurrent modifications of the dictionary, and a pointer to the
125 * parent object (used when invalidating string reps of pathed dictionary
126 * trees) which is NULL in normal use. The fact that hash tables know (with
127 * appropriate initialisation) already about objects makes key management /so/
128 * much easier!
129 *
130 * Reference counts are used to enable safe iteration across hashes while
131 * allowing the type of the containing object to be modified.
132 */
133
134 typedef struct Dict {
135 Tcl_HashTable table; /* Object hash table to store mapping in. */
136 ChainEntry *entryChainHead; /* Linked list of all entries in the
137 * dictionary. Used for doing traversal of the
138 * entries in the order that they are
139 * created. */
140 ChainEntry *entryChainTail; /* Other end of linked list of all entries in
141 * the dictionary. Used for doing traversal of
142 * the entries in the order that they are
143 * created. */
144 int epoch; /* Epoch counter */
145 size_t refCount; /* Reference counter (see above) */
146 Tcl_Obj *chain; /* Linked list used for invalidating the
147 * string representations of updated nested
148 * dictionaries. */
149 } Dict;
150
151 /*
152 * Accessor macro for converting between a Tcl_Obj* and a Dict. Note that this
153 * must be assignable as well as readable.
154 */
155
156 #define DICT(dictObj) ((dictObj)->internalRep.twoPtrValue.ptr1)
157
158 /*
159 * The structure below defines the dictionary object type by means of
160 * functions that can be invoked by generic object code.
161 */
162
163 const Tcl_ObjType tclDictType = {
164 "dict",
165 FreeDictInternalRep, /* freeIntRepProc */
166 DupDictInternalRep, /* dupIntRepProc */
167 UpdateStringOfDict, /* updateStringProc */
168 SetDictFromAny /* setFromAnyProc */
169 };
170
171 /*
172 * The type of the specially adapted version of the Tcl_Obj*-containing hash
173 * table defined in the tclObj.c code. This version differs in that it
174 * allocates a bit more space in each hash entry in order to hold the pointers
175 * used to keep the hash entries in a linked list.
176 *
177 * Note that this type of hash table is *only* suitable for direct use in
178 * *this* file. Everything else should use the dict iterator API.
179 */
180
181 static const Tcl_HashKeyType chainHashType = {
182 TCL_HASH_KEY_TYPE_VERSION,
183 TCL_HASH_KEY_DIRECT_COMPARE, /* allows compare keys by pointers */
184 TclHashObjKey,
185 TclCompareObjKeys,
186 AllocChainEntry,
187 TclFreeObjEntry
188 };
189
190 /*
191 * Structure used in implementation of 'dict map' to hold the state that gets
192 * passed between parts of the implementation.
193 */
194
195 typedef struct {
196 Tcl_Obj *keyVarObj; /* The name of the variable that will have
197 * keys assigned to it. */
198 Tcl_Obj *valueVarObj; /* The name of the variable that will have
199 * values assigned to it. */
200 Tcl_DictSearch search; /* The dictionary search structure. */
201 Tcl_Obj *scriptObj; /* The script to evaluate each time through
202 * the loop. */
203 Tcl_Obj *accumulatorObj; /* The dictionary used to accumulate the
204 * results. */
205 } DictMapStorage;
206
207 /***** START OF FUNCTIONS IMPLEMENTING DICT CORE API *****/
208
209 /*
210 *----------------------------------------------------------------------
211 *
212 * AllocChainEntry --
213 *
214 * Allocate space for a Tcl_HashEntry containing the Tcl_Obj * key, and
215 * which has a bit of extra space afterwards for storing pointers to the
216 * rest of the chain of entries (the extra pointers are left NULL).
217 *
218 * Results:
219 * The return value is a pointer to the created entry.
220 *
221 * Side effects:
222 * Increments the reference count on the object.
223 *
224 *----------------------------------------------------------------------
225 */
226
227 static Tcl_HashEntry *
228 AllocChainEntry(
229 Tcl_HashTable *tablePtr,
230 void *keyPtr)
231 {
232 Tcl_Obj *objPtr = (Tcl_Obj *)keyPtr;
233 ChainEntry *cPtr;
234
235 cPtr = (ChainEntry *)ckalloc(sizeof(ChainEntry));
236 cPtr->entry.key.objPtr = objPtr;
237 Tcl_IncrRefCount(objPtr);
238 cPtr->entry.clientData = NULL;
239 cPtr->prevPtr = cPtr->nextPtr = NULL;
240
241 return &cPtr->entry;
242 }
243
244 /*
245 * Helper functions that disguise most of the details relating to how the
246 * linked list of hash entries is managed. In particular, these manage the
247 * creation of the table and initializing of the chain, the deletion of the
248 * table and chain, the adding of an entry to the chain, and the removal of an
249 * entry from the chain.
250 */
251
252 static inline void
253 InitChainTable(
254 Dict *dict)
255 {
256 Tcl_InitCustomHashTable(&dict->table, TCL_CUSTOM_PTR_KEYS,
257 &chainHashType);
258 dict->entryChainHead = dict->entryChainTail = NULL;
259 }
260
261 static inline void
262 DeleteChainTable(
263 Dict *dict)
264 {
265 ChainEntry *cPtr;
266
267 for (cPtr=dict->entryChainHead ; cPtr!=NULL ; cPtr=cPtr->nextPtr) {
268 Tcl_Obj *valuePtr = (Tcl_Obj *)Tcl_GetHashValue(&cPtr->entry);
269
270 TclDecrRefCount(valuePtr);
271 }
272 Tcl_DeleteHashTable(&dict->table);
273 }
274
275 static inline Tcl_HashEntry *
276 CreateChainEntry(
277 Dict *dict,
278 Tcl_Obj *keyPtr,
279 int *newPtr)
280 {
281 ChainEntry *cPtr = (ChainEntry *)
282 Tcl_CreateHashEntry(&dict->table, keyPtr, newPtr);
283
284 /*
285 * If this is a new entry in the hash table, stitch it into the chain.
286 */
287
288 if (*newPtr) {
289 cPtr->nextPtr = NULL;
290 if (dict->entryChainHead == NULL) {
291 cPtr->prevPtr = NULL;
292 dict->entryChainHead = cPtr;
293 dict->entryChainTail = cPtr;
294 } else {
295 cPtr->prevPtr = dict->entryChainTail;
296 dict->entryChainTail->nextPtr = cPtr;
297 dict->entryChainTail = cPtr;
298 }
299 }
300
301 return &cPtr->entry;
302 }
303
304 static inline int
305 DeleteChainEntry(
306 Dict *dict,
307 Tcl_Obj *keyPtr)
308 {
309 ChainEntry *cPtr = (ChainEntry *)
310 Tcl_FindHashEntry(&dict->table, keyPtr);
311
312 if (cPtr == NULL) {
313 return 0;
314 } else {
315 Tcl_Obj *valuePtr = (Tcl_Obj *)Tcl_GetHashValue(&cPtr->entry);
316
317 TclDecrRefCount(valuePtr);
318 }
319
320 /*
321 * Unstitch from the chain.
322 */
323
324 if (cPtr->nextPtr) {
325 cPtr->nextPtr->prevPtr = cPtr->prevPtr;
326 } else {
327 dict->entryChainTail = cPtr->prevPtr;
328 }
329 if (cPtr->prevPtr) {
330 cPtr->prevPtr->nextPtr = cPtr->nextPtr;
331 } else {
332 dict->entryChainHead = cPtr->nextPtr;
333 }
334
335 Tcl_DeleteHashEntry(&cPtr->entry);
336 return 1;
337 }
338
339 /*
340 *----------------------------------------------------------------------
341 *
342 * DupDictInternalRep --
343 *
344 * Initialize the internal representation of a dictionary Tcl_Obj to a
345 * copy of the internal representation of an existing dictionary object.
346 *
347 * Results:
348 * None.
349 *
350 * Side effects:
351 * "srcPtr"s dictionary internal rep pointer should not be NULL and we
352 * assume it is not NULL. We set "copyPtr"s internal rep to a pointer to
353 * a newly allocated dictionary rep that, in turn, points to "srcPtr"s
354 * key and value objects. Those objects are not actually copied but are
355 * shared between "srcPtr" and "copyPtr". The ref count of each key and
356 * value object is incremented.
357 *
358 *----------------------------------------------------------------------
359 */
360
361 static void
362 DupDictInternalRep(
363 Tcl_Obj *srcPtr,
364 Tcl_Obj *copyPtr)
365 {
366 Dict *oldDict = (Dict *)DICT(srcPtr);
367 Dict *newDict = (Dict *)ckalloc(sizeof(Dict));
368 ChainEntry *cPtr;
369
370 /*
371 * Copy values across from the old hash table.
372 */
373
374 InitChainTable(newDict);
375 for (cPtr=oldDict->entryChainHead ; cPtr!=NULL ; cPtr=cPtr->nextPtr) {
376 Tcl_Obj *key = (Tcl_Obj *)Tcl_GetHashKey(&oldDict->table, &cPtr->entry);
377 Tcl_Obj *valuePtr = (Tcl_Obj *)Tcl_GetHashValue(&cPtr->entry);
378 int n;
379 Tcl_HashEntry *hPtr = CreateChainEntry(newDict, key, &n);
380
381 /*
382 * Fill in the contents.
383 */
384
385 Tcl_SetHashValue(hPtr, valuePtr);
386 Tcl_IncrRefCount(valuePtr);
387 }
388
389 /*
390 * Initialise other fields.
391 */
392
393 newDict->epoch = 0;
394 newDict->chain = NULL;
395 newDict->refCount = 1;
396
397 /*
398 * Store in the object.
399 */
400
401 DICT(copyPtr) = newDict;
402 copyPtr->internalRep.twoPtrValue.ptr2 = NULL;
403 copyPtr->typePtr = &tclDictType;
404 }
405
406 /*
407 *----------------------------------------------------------------------
408 *
409 * FreeDictInternalRep --
410 *
411 * Deallocate the storage associated with a dictionary object's internal
412 * representation.
413 *
414 * Results:
415 * None
416 *
417 * Side effects:
418 * Frees the memory holding the dictionary's internal hash table unless
419 * it is locked by an iteration going over it.
420 *
421 *----------------------------------------------------------------------
422 */
423
424 static void
425 FreeDictInternalRep(
426 Tcl_Obj *dictPtr)
427 {
428 Dict *dict = (Dict *)DICT(dictPtr);
429
430 if (dict->refCount-- <= 1) {
431 DeleteDict(dict);
432 }
433 dictPtr->typePtr = NULL;
434 }
435
436 /*
437 *----------------------------------------------------------------------
438 *
439 * DeleteDict --
440 *
441 * Delete the structure that is used to implement a dictionary's internal
442 * representation. Called when either the dictionary object loses its
443 * internal representation or when the last iteration over the dictionary
444 * completes.
445 *
446 * Results:
447 * None
448 *
449 * Side effects:
450 * Decrements the reference count of all key and value objects in the
451 * dictionary, which may free them.
452 *
453 *----------------------------------------------------------------------
454 */
455
456 static void
457 DeleteDict(
458 Dict *dict)
459 {
460 DeleteChainTable(dict);
461 ckfree(dict);
462 }
463
464 /*
465 *----------------------------------------------------------------------
466 *
467 * UpdateStringOfDict --
468 *
469 * Update the string representation for a dictionary object. Note: This
470 * function does not invalidate an existing old string rep so storage
471 * will be lost if this has not already been done. This code is based on
472 * UpdateStringOfList in tclListObj.c
473 *
474 * Results:
475 * None.
476 *
477 * Side effects:
478 * The object's string is set to a valid string that results from the
479 * dict-to-string conversion. This string will be empty if the dictionary
480 * has no key/value pairs. The dictionary internal representation should
481 * not be NULL and we assume it is not NULL.
482 *
483 *----------------------------------------------------------------------
484 */
485
486 static void
487 UpdateStringOfDict(
488 Tcl_Obj *dictPtr)
489 {
490 #define LOCAL_SIZE 64
491 char localFlags[LOCAL_SIZE], *flagPtr = NULL;
492 Dict *dict = (Dict *)DICT(dictPtr);
493 ChainEntry *cPtr;
494 Tcl_Obj *keyPtr, *valuePtr;
495 int i, length;
496 unsigned int bytesNeeded = 0;
497 const char *elem;
498 char *dst;
499
500 /*
501 * This field is the most useful one in the whole hash structure, and it
502 * is not exposed by any API function...
503 */
504
505 int numElems = dict->table.numEntries * 2;
506
507 /* Handle empty list case first, simplifies what follows */
508 if (numElems == 0) {
509 dictPtr->bytes = tclEmptyStringRep;
510 dictPtr->length = 0;
511 return;
512 }
513
514 /*
515 * Pass 1: estimate space, gather flags.
516 */
517
518 if (numElems <= LOCAL_SIZE) {
519 flagPtr = localFlags;
520 } else {
521 flagPtr = (char *)ckalloc(numElems);
522 }
523 for (i=0,cPtr=dict->entryChainHead; i<numElems; i+=2,cPtr=cPtr->nextPtr) {
524 /*
525 * Assume that cPtr is never NULL since we know the number of array
526 * elements already.
527 */
528
529 flagPtr[i] = ( i ? TCL_DONT_QUOTE_HASH : 0 );
530 keyPtr = (Tcl_Obj *)Tcl_GetHashKey(&dict->table, &cPtr->entry);
531 elem = TclGetStringFromObj(keyPtr, &length);
532 bytesNeeded += TclScanElement(elem, length, flagPtr+i);
533 if (bytesNeeded > INT_MAX) {
534 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
535 }
536
537 flagPtr[i+1] = TCL_DONT_QUOTE_HASH;
538 valuePtr = (Tcl_Obj *)Tcl_GetHashValue(&cPtr->entry);
539 elem = TclGetStringFromObj(valuePtr, &length);
540 bytesNeeded += TclScanElement(elem, length, flagPtr+i+1);
541 if (bytesNeeded > INT_MAX) {
542 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
543 }
544 }
545 if (bytesNeeded + numElems > INT_MAX + 1U) {
546 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
547 }
548 bytesNeeded += numElems;
549
550 /*
551 * Pass 2: copy into string rep buffer.
552 */
553
554 dictPtr->length = bytesNeeded - 1;
555 dictPtr->bytes = (char *)ckalloc(bytesNeeded);
556 dst = dictPtr->bytes;
557 for (i=0,cPtr=dict->entryChainHead; i<numElems; i+=2,cPtr=cPtr->nextPtr) {
558 flagPtr[i] |= ( i ? TCL_DONT_QUOTE_HASH : 0 );
559 keyPtr = (Tcl_Obj *)Tcl_GetHashKey(&dict->table, &cPtr->entry);
560 elem = TclGetStringFromObj(keyPtr, &length);
561 dst += TclConvertElement(elem, length, dst, flagPtr[i]);
562 *dst++ = ' ';
563
564 flagPtr[i+1] |= TCL_DONT_QUOTE_HASH;
565 valuePtr = (Tcl_Obj *)Tcl_GetHashValue(&cPtr->entry);
566 elem = TclGetStringFromObj(valuePtr, &length);
567 dst += TclConvertElement(elem, length, dst, flagPtr[i+1]);
568 *dst++ = ' ';
569 }
570 dictPtr->bytes[dictPtr->length] = '\0';
571
572 if (flagPtr != localFlags) {
573 ckfree(flagPtr);
574 }
575 }
576
577 /*
578 *----------------------------------------------------------------------
579 *
580 * SetDictFromAny --
581 *
582 * Convert a non-dictionary object into a dictionary object. This code is
583 * very closely related to SetListFromAny in tclListObj.c but does not
584 * actually guarantee that a dictionary object will have a string rep (as
585 * conversions from lists are handled with a special case.)
586 *
587 * Results:
588 * A standard Tcl result.
589 *
590 * Side effects:
591 * If the string can be converted, it loses any old internal
592 * representation that it had and gains a dictionary's internalRep.
593 *
594 *----------------------------------------------------------------------
595 */
596
597 static int
598 SetDictFromAny(
599 Tcl_Interp *interp,
600 Tcl_Obj *objPtr)
601 {
602 Tcl_HashEntry *hPtr;
603 int isNew;
604 Dict *dict = (Dict *)ckalloc(sizeof(Dict));
605
606 InitChainTable(dict);
607
608 /*
609 * Since lists and dictionaries have very closely-related string
610 * representations (i.e. the same parsing code) we can safely special-case
611 * the conversion from lists to dictionaries.
612 */
613
614 if (objPtr->typePtr == &tclListType) {
615 int objc, i;
616 Tcl_Obj **objv;
617
618 /* Cannot fail, we already know the Tcl_ObjType is "list". */
619 TclListObjGetElements(NULL, objPtr, &objc, &objv);
620 if (objc & 1) {
621 goto missingValue;
622 }
623
624 for (i=0 ; i<objc ; i+=2) {
625
626 /* Store key and value in the hash table we're building. */
627 hPtr = CreateChainEntry(dict, objv[i], &isNew);
628 if (!isNew) {
629 Tcl_Obj *discardedValue = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
630
631 /*
632 * Not really a well-formed dictionary as there are duplicate
633 * keys, so better get the string rep here so that we can
634 * convert back.
635 */
636
637 (void) Tcl_GetString(objPtr);
638
639 TclDecrRefCount(discardedValue);
640 }
641 Tcl_SetHashValue(hPtr, objv[i+1]);
642 Tcl_IncrRefCount(objv[i+1]); /* Since hash now holds ref to it */
643 }
644 } else {
645 int length;
646 const char *nextElem = TclGetStringFromObj(objPtr, &length);
647 const char *limit = (nextElem + length);
648
649 while (nextElem < limit) {
650 Tcl_Obj *keyPtr, *valuePtr;
651 const char *elemStart;
652 int elemSize, literal;
653
654 if (TclFindDictElement(interp, nextElem, (limit - nextElem),
655 &elemStart, &nextElem, &elemSize, &literal) != TCL_OK) {
656 goto errorInFindDictElement;
657 }
658 if (elemStart == limit) {
659 break;
660 }
661 if (nextElem == limit) {
662 goto missingValue;
663 }
664
665 if (literal) {
666 TclNewStringObj(keyPtr, elemStart, elemSize);
667 } else {
668 /* Avoid double copy */
669 TclNewObj(keyPtr);
670 keyPtr->bytes = (char *)ckalloc(elemSize + 1);
671 keyPtr->length = TclCopyAndCollapse(elemSize, elemStart,
672 keyPtr->bytes);
673 }
674
675 if (TclFindDictElement(interp, nextElem, (limit - nextElem),
676 &elemStart, &nextElem, &elemSize, &literal) != TCL_OK) {
677 TclDecrRefCount(keyPtr);
678 goto errorInFindDictElement;
679 }
680
681 if (literal) {
682 TclNewStringObj(valuePtr, elemStart, elemSize);
683 } else {
684 /* Avoid double copy */
685 TclNewObj(valuePtr);
686 valuePtr->bytes = (char *)ckalloc(elemSize + 1);
687 valuePtr->length = TclCopyAndCollapse(elemSize, elemStart,
688 valuePtr->bytes);
689 }
690
691 /* Store key and value in the hash table we're building. */
692 hPtr = CreateChainEntry(dict, keyPtr, &isNew);
693 if (!isNew) {
694 Tcl_Obj *discardedValue = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
695
696 TclDecrRefCount(keyPtr);
697 TclDecrRefCount(discardedValue);
698 }
699 Tcl_SetHashValue(hPtr, valuePtr);
700 Tcl_IncrRefCount(valuePtr); /* since hash now holds ref to it */
701 }
702 }
703
704 /*
705 * Free the old internalRep before setting the new one. We do this as late
706 * as possible to allow the conversion code, in particular
707 * Tcl_GetStringFromObj, to use that old internalRep.
708 */
709
710 TclFreeIntRep(objPtr);
711 dict->epoch = 0;
712 dict->chain = NULL;
713 dict->refCount = 1;
714 DICT(objPtr) = dict;
715 objPtr->internalRep.twoPtrValue.ptr2 = NULL;
716 objPtr->typePtr = &tclDictType;
717 return TCL_OK;
718
719 missingValue:
720 if (interp != NULL) {
721 Tcl_SetObjResult(interp, Tcl_NewStringObj(
722 "missing value to go with key", -1));
723 Tcl_SetErrorCode(interp, "TCL", "VALUE", "DICTIONARY", (char *)NULL);
724 }
725 errorInFindDictElement:
726 DeleteChainTable(dict);
727 ckfree(dict);
728 return TCL_ERROR;
729 }
730
731 /*
732 *----------------------------------------------------------------------
733 *
734 * TclTraceDictPath --
735 *
736 * Trace through a tree of dictionaries using the array of keys given. If
737 * the flags argument has the DICT_PATH_UPDATE flag is set, a
738 * backward-pointing chain of dictionaries is also built (in the Dict's
739 * chain field) and the chained dictionaries are made into unshared
740 * dictionaries (if they aren't already.)
741 *
742 * Results:
743 * The object at the end of the path, or NULL if there was an error. Note
744 * that this it is an error for an intermediate dictionary on the path to
745 * not exist. If the flags argument has the DICT_PATH_EXISTS set, a
746 * non-existent path gives a DICT_PATH_NON_EXISTENT result.
747 *
748 * Side effects:
749 * If the flags argument is zero or DICT_PATH_EXISTS, there are no side
750 * effects (other than potential conversion of objects to dictionaries.)
751 * If the flags argument is DICT_PATH_UPDATE, the following additional
752 * side effects occur. Shared dictionaries along the path are converted
753 * into unshared objects, and a backward-pointing chain is built using
754 * the chain fields of the dictionaries (for easy invalidation of string
755 * representations using InvalidateDictChain). If the flags argument has
756 * the DICT_PATH_CREATE bits set (and not the DICT_PATH_EXISTS bit),
757 * non-extant keys will be inserted with a value of an empty
758 * dictionary, resulting in the path being built.
759 *
760 *----------------------------------------------------------------------
761 */
762
763 Tcl_Obj *
764 TclTraceDictPath(
765 Tcl_Interp *interp,
766 Tcl_Obj *dictPtr,
767 int keyc,
768 Tcl_Obj *const keyv[],
769 int flags)
770 {
771 Dict *dict, *newDict;
772 int i;
773
774 if (dictPtr->typePtr != &tclDictType
775 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
776 return NULL;
777 }
778 dict = (Dict *)DICT(dictPtr);
779 if (flags & DICT_PATH_UPDATE) {
780 dict->chain = NULL;
781 }
782
783 for (i=0 ; i<keyc ; i++) {
784 Tcl_HashEntry *hPtr = Tcl_FindHashEntry(&dict->table, keyv[i]);
785 Tcl_Obj *tmpObj;
786
787 if (hPtr == NULL) {
788 int isNew; /* Dummy */
789
790 if (flags & DICT_PATH_EXISTS) {
791 return DICT_PATH_NON_EXISTENT;
792 }
793 if ((flags & DICT_PATH_CREATE) != DICT_PATH_CREATE) {
794 if (interp != NULL) {
795 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
796 "key \"%s\" not known in dictionary",
797 TclGetString(keyv[i])));
798 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "DICT",
799 TclGetString(keyv[i]), (char *)NULL);
800 }
801 return NULL;
802 }
803
804 /*
805 * The next line should always set isNew to 1.
806 */
807
808 hPtr = CreateChainEntry(dict, keyv[i], &isNew);
809 tmpObj = Tcl_NewDictObj();
810 Tcl_IncrRefCount(tmpObj);
811 Tcl_SetHashValue(hPtr, tmpObj);
812 } else {
813 tmpObj = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
814 if (tmpObj->typePtr != &tclDictType
815 && SetDictFromAny(interp, tmpObj) != TCL_OK) {
816 return NULL;
817 }
818 }
819
820 newDict = (Dict *)DICT(tmpObj);
821 if (flags & DICT_PATH_UPDATE) {
822 if (Tcl_IsShared(tmpObj)) {
823 TclDecrRefCount(tmpObj);
824 tmpObj = Tcl_DuplicateObj(tmpObj);
825 Tcl_IncrRefCount(tmpObj);
826 Tcl_SetHashValue(hPtr, tmpObj);
827 dict->epoch++;
828 newDict = (Dict *)DICT(tmpObj);
829 }
830
831 newDict->chain = dictPtr;
832 }
833 dict = newDict;
834 dictPtr = tmpObj;
835 }
836 return dictPtr;
837 }
838
839 /*
840 *----------------------------------------------------------------------
841 *
842 * InvalidateDictChain --
843 *
844 * Go through a dictionary chain (built by an updating invocation of
845 * TclTraceDictPath) and invalidate the string representations of all the
846 * dictionaries on the chain.
847 *
848 * Results:
849 * None
850 *
851 * Side effects:
852 * String reps are invalidated and epoch counters (for detecting illegal
853 * concurrent modifications) are updated through the chain of updated
854 * dictionaries.
855 *
856 *----------------------------------------------------------------------
857 */
858
859 static void
860 InvalidateDictChain(
861 Tcl_Obj *dictObj)
862 {
863 Dict *dict = (Dict *)DICT(dictObj);
864
865 do {
866 TclInvalidateStringRep(dictObj);
867 dict->epoch++;
868 dictObj = dict->chain;
869 if (dictObj == NULL) {
870 break;
871 }
872 dict->chain = NULL;
873 dict = (Dict *)DICT(dictObj);
874 } while (dict != NULL);
875 }
876
877 /*
878 *----------------------------------------------------------------------
879 *
880 * Tcl_DictObjPut --
881 *
882 * Add a key,value pair to a dictionary, or update the value for a key if
883 * that key already has a mapping in the dictionary.
884 *
885 * Results:
886 * A standard Tcl result.
887 *
888 * Side effects:
889 * The object pointed to by dictPtr is converted to a dictionary if it is
890 * not already one, and any string representation that it has is
891 * invalidated.
892 *
893 *----------------------------------------------------------------------
894 */
895
896 int
897 Tcl_DictObjPut(
898 Tcl_Interp *interp,
899 Tcl_Obj *dictPtr,
900 Tcl_Obj *keyPtr,
901 Tcl_Obj *valuePtr)
902 {
903 Dict *dict;
904 Tcl_HashEntry *hPtr;
905 int isNew;
906
907 if (Tcl_IsShared(dictPtr)) {
908 Tcl_Panic("%s called with shared object", "Tcl_DictObjPut");
909 }
910
911 if (dictPtr->typePtr != &tclDictType
912 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
913 return TCL_ERROR;
914 }
915
916 if (dictPtr->bytes != NULL) {
917 TclInvalidateStringRep(dictPtr);
918 }
919 dict = (Dict *)DICT(dictPtr);
920 hPtr = CreateChainEntry(dict, keyPtr, &isNew);
921 Tcl_IncrRefCount(valuePtr);
922 if (!isNew) {
923 Tcl_Obj *oldValuePtr = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
924
925 TclDecrRefCount(oldValuePtr);
926 }
927 Tcl_SetHashValue(hPtr, valuePtr);
928 dict->epoch++;
929 return TCL_OK;
930 }
931
932 /*
933 *----------------------------------------------------------------------
934 *
935 * Tcl_DictObjGet --
936 *
937 * Given a key, get its value from the dictionary (or NULL if key is not
938 * found in dictionary.)
939 *
940 * Results:
941 * A standard Tcl result. The variable pointed to by valuePtrPtr is
942 * updated with the value for the key. Note that it is not an error for
943 * the key to have no mapping in the dictionary.
944 *
945 * Side effects:
946 * The object pointed to by dictPtr is converted to a dictionary if it is
947 * not already one.
948 *
949 *----------------------------------------------------------------------
950 */
951
952 int
953 Tcl_DictObjGet(
954 Tcl_Interp *interp,
955 Tcl_Obj *dictPtr,
956 Tcl_Obj *keyPtr,
957 Tcl_Obj **valuePtrPtr)
958 {
959 Dict *dict;
960 Tcl_HashEntry *hPtr;
961
962 if (dictPtr->typePtr != &tclDictType
963 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
964 *valuePtrPtr = NULL;
965 return TCL_ERROR;
966 }
967
968 dict = (Dict *)DICT(dictPtr);
969 hPtr = Tcl_FindHashEntry(&dict->table, keyPtr);
970 if (hPtr == NULL) {
971 *valuePtrPtr = NULL;
972 } else {
973 *valuePtrPtr = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
974 }
975 return TCL_OK;
976 }
977
978 /*
979 *----------------------------------------------------------------------
980 *
981 * Tcl_DictObjRemove --
982 *
983 * Remove the key,value pair with the given key from the dictionary; the
984 * key does not need to be present in the dictionary.
985 *
986 * Results:
987 * A standard Tcl result.
988 *
989 * Side effects:
990 * The object pointed to by dictPtr is converted to a dictionary if it is
991 * not already one, and any string representation that it has is
992 * invalidated.
993 *
994 *----------------------------------------------------------------------
995 */
996
997 int
998 Tcl_DictObjRemove(
999 Tcl_Interp *interp,
1000 Tcl_Obj *dictPtr,
1001 Tcl_Obj *keyPtr)
1002 {
1003 Dict *dict;
1004
1005 if (Tcl_IsShared(dictPtr)) {
1006 Tcl_Panic("%s called with shared object", "Tcl_DictObjRemove");
1007 }
1008
1009 if (dictPtr->typePtr != &tclDictType
1010 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
1011 return TCL_ERROR;
1012 }
1013
1014 dict = (Dict *)DICT(dictPtr);
1015 if (DeleteChainEntry(dict, keyPtr)) {
1016 if (dictPtr->bytes != NULL) {
1017 TclInvalidateStringRep(dictPtr);
1018 }
1019 dict->epoch++;
1020 }
1021 return TCL_OK;
1022 }
1023
1024 /*
1025 *----------------------------------------------------------------------
1026 *
1027 * Tcl_DictObjSize --
1028 *
1029 * How many key,value pairs are there in the dictionary?
1030 *
1031 * Results:
1032 * A standard Tcl result. Updates the variable pointed to by sizePtr with
1033 * the number of key,value pairs in the dictionary.
1034 *
1035 * Side effects:
1036 * The dictPtr object is converted to a dictionary type if it is not a
1037 * dictionary already.
1038 *
1039 *----------------------------------------------------------------------
1040 */
1041
1042 int
1043 Tcl_DictObjSize(
1044 Tcl_Interp *interp,
1045 Tcl_Obj *dictPtr,
1046 int *sizePtr)
1047 {
1048 Dict *dict;
1049
1050 if (dictPtr->typePtr != &tclDictType
1051 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
1052 return TCL_ERROR;
1053 }
1054
1055 dict = (Dict *)DICT(dictPtr);
1056 *sizePtr = dict->table.numEntries;
1057 return TCL_OK;
1058 }
1059
1060 /*
1061 *----------------------------------------------------------------------
1062 *
1063 * Tcl_DictObjFirst --
1064 *
1065 * Start a traversal of the dictionary. Caller must supply the search
1066 * context, pointers for returning key and value, and a pointer to allow
1067 * indication of whether the dictionary has been traversed (i.e. the
1068 * dictionary is empty). The order of traversal is undefined.
1069 *
1070 * Results:
1071 * A standard Tcl result. Updates the variables pointed to by keyPtrPtr,
1072 * valuePtrPtr and donePtr. Either of keyPtrPtr and valuePtrPtr may be
1073 * NULL, in which case the key/value is not made available to the caller.
1074 *
1075 * Side effects:
1076 * The dictPtr object is converted to a dictionary type if it is not a
1077 * dictionary already. The search context is initialised if the search
1078 * has not finished. The dictionary's internal rep is Tcl_Preserve()d if
1079 * the dictionary has at least one element.
1080 *
1081 *----------------------------------------------------------------------
1082 */
1083
1084 int
1085 Tcl_DictObjFirst(
1086 Tcl_Interp *interp, /* For error messages, or NULL if no error
1087 * messages desired. */
1088 Tcl_Obj *dictPtr, /* Dictionary to traverse. */
1089 Tcl_DictSearch *searchPtr, /* Pointer to a dict search context. */
1090 Tcl_Obj **keyPtrPtr, /* Pointer to a variable to have the first key
1091 * written into, or NULL. */
1092 Tcl_Obj **valuePtrPtr, /* Pointer to a variable to have the first
1093 * value written into, or NULL.*/
1094 int *donePtr) /* Pointer to a variable which will have a 1
1095 * written into when there are no further
1096 * values in the dictionary, or a 0
1097 * otherwise. */
1098 {
1099 Dict *dict;
1100 ChainEntry *cPtr;
1101
1102 if (dictPtr->typePtr != &tclDictType
1103 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
1104 return TCL_ERROR;
1105 }
1106
1107 dict = (Dict *)DICT(dictPtr);
1108 cPtr = dict->entryChainHead;
1109 if (cPtr == NULL) {
1110 searchPtr->epoch = -1;
1111 *donePtr = 1;
1112 } else {
1113 *donePtr = 0;
1114 searchPtr->dictionaryPtr = (Tcl_Dict) dict;
1115 searchPtr->epoch = dict->epoch;
1116 searchPtr->next = cPtr->nextPtr;
1117 dict->refCount++;
1118 if (keyPtrPtr != NULL) {
1119 *keyPtrPtr = (Tcl_Obj *)Tcl_GetHashKey(&dict->table, &cPtr->entry);
1120 }
1121 if (valuePtrPtr != NULL) {
1122 *valuePtrPtr = (Tcl_Obj *)Tcl_GetHashValue(&cPtr->entry);
1123 }
1124 }
1125 return TCL_OK;
1126 }
1127
1128 /*
1129 *----------------------------------------------------------------------
1130 *
1131 * Tcl_DictObjNext --
1132 *
1133 * Continue a traversal of a dictionary previously started with
1134 * Tcl_DictObjFirst. This function is safe against concurrent
1135 * modification of the underlying object (including type shimmering),
1136 * treating such situations as if the search has terminated, though it is
1137 * up to the caller to ensure that the object itself is not disposed
1138 * until the search has finished. It is _not_ safe against modifications
1139 * from other threads.
1140 *
1141 * Results:
1142 * Updates the variables pointed to by keyPtrPtr, valuePtrPtr and
1143 * donePtr. Either of keyPtrPtr and valuePtrPtr may be NULL, in which
1144 * case the key/value is not made available to the caller.
1145 *
1146 * Side effects:
1147 * Removes a reference to the dictionary's internal rep if the search
1148 * terminates.
1149 *
1150 *----------------------------------------------------------------------
1151 */
1152
1153 void
1154 Tcl_DictObjNext(
1155 Tcl_DictSearch *searchPtr, /* Pointer to a hash search context. */
1156 Tcl_Obj **keyPtrPtr, /* Pointer to a variable to have the first key
1157 * written into, or NULL. */
1158 Tcl_Obj **valuePtrPtr, /* Pointer to a variable to have the first
1159 * value written into, or NULL.*/
1160 int *donePtr) /* Pointer to a variable which will have a 1
1161 * written into when there are no further
1162 * values in the dictionary, or a 0
1163 * otherwise. */
1164 {
1165 ChainEntry *cPtr;
1166
1167 /*
1168 * If the search is done; we do no work.
1169 */
1170
1171 if (searchPtr->epoch == -1) {
1172 *donePtr = 1;
1173 return;
1174 }
1175
1176 /*
1177 * Bail out if the dictionary has had any elements added, modified or
1178 * removed. This *shouldn't* happen, but...
1179 */
1180
1181 if (((Dict *)searchPtr->dictionaryPtr)->epoch != searchPtr->epoch) {
1182 Tcl_Panic("concurrent dictionary modification and search");
1183 }
1184
1185 cPtr = (ChainEntry *)searchPtr->next;
1186 if (cPtr == NULL) {
1187 Tcl_DictObjDone(searchPtr);
1188 *donePtr = 1;
1189 return;
1190 }
1191
1192 searchPtr->next = cPtr->nextPtr;
1193 *donePtr = 0;
1194 if (keyPtrPtr != NULL) {
1195 *keyPtrPtr = (Tcl_Obj *)Tcl_GetHashKey(
1196 &((Dict *)searchPtr->dictionaryPtr)->table, &cPtr->entry);
1197 }
1198 if (valuePtrPtr != NULL) {
1199 *valuePtrPtr = (Tcl_Obj *)Tcl_GetHashValue(&cPtr->entry);
1200 }
1201 }
1202
1203 /*
1204 *----------------------------------------------------------------------
1205 *
1206 * Tcl_DictObjDone --
1207 *
1208 * Call this if you want to stop a search before you reach the end of the
1209 * dictionary (e.g. because of abnormal termination of the search). It
1210 * need not be used if the search reaches its natural end (i.e. if either
1211 * Tcl_DictObjFirst or Tcl_DictObjNext sets its donePtr variable to 1).
1212 *
1213 * Results:
1214 * None.
1215 *
1216 * Side effects:
1217 * Removes a reference to the dictionary's internal rep.
1218 *
1219 *----------------------------------------------------------------------
1220 */
1221
1222 void
1223 Tcl_DictObjDone(
1224 Tcl_DictSearch *searchPtr) /* Pointer to a hash search context. */
1225 {
1226 Dict *dict;
1227
1228 if (searchPtr->epoch != -1) {
1229 searchPtr->epoch = -1;
1230 dict = (Dict *) searchPtr->dictionaryPtr;
1231 if (dict->refCount-- <= 1) {
1232 DeleteDict(dict);
1233 }
1234 }
1235 }
1236
1237 /*
1238 *----------------------------------------------------------------------
1239 *
1240 * Tcl_DictObjPutKeyList --
1241 *
1242 * Add a key...key,value pair to a dictionary tree. The main dictionary
1243 * value must not be shared, though sub-dictionaries may be. All
1244 * intermediate dictionaries on the path must exist.
1245 *
1246 * Results:
1247 * A standard Tcl result. Note that in the error case, a message is left
1248 * in interp unless that is NULL.
1249 *
1250 * Side effects:
1251 * If the dictionary and any of its sub-dictionaries on the path have
1252 * string representations, these are invalidated.
1253 *
1254 *----------------------------------------------------------------------
1255 */
1256
1257 int
1258 Tcl_DictObjPutKeyList(
1259 Tcl_Interp *interp,
1260 Tcl_Obj *dictPtr,
1261 int keyc,
1262 Tcl_Obj *const keyv[],
1263 Tcl_Obj *valuePtr)
1264 {
1265 Dict *dict;
1266 Tcl_HashEntry *hPtr;
1267 int isNew;
1268
1269 if (Tcl_IsShared(dictPtr)) {
1270 Tcl_Panic("%s called with shared object", "Tcl_DictObjPutKeyList");
1271 }
1272 if (keyc < 1) {
1273 Tcl_Panic("%s called with empty key list", "Tcl_DictObjPutKeyList");
1274 }
1275
1276 dictPtr = TclTraceDictPath(interp, dictPtr, keyc-1,keyv, DICT_PATH_CREATE);
1277 if (dictPtr == NULL) {
1278 return TCL_ERROR;
1279 }
1280
1281 dict = (Dict *)DICT(dictPtr);
1282 hPtr = CreateChainEntry(dict, keyv[keyc-1], &isNew);
1283 Tcl_IncrRefCount(valuePtr);
1284 if (!isNew) {
1285 Tcl_Obj *oldValuePtr = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
1286
1287 TclDecrRefCount(oldValuePtr);
1288 }
1289 Tcl_SetHashValue(hPtr, valuePtr);
1290 InvalidateDictChain(dictPtr);
1291
1292 return TCL_OK;
1293 }
1294
1295 /*
1296 *----------------------------------------------------------------------
1297 *
1298 * Tcl_DictObjRemoveKeyList --
1299 *
1300 * Remove a key...key,value pair from a dictionary tree (the value
1301 * removed is implicit in the key path). The main dictionary value must
1302 * not be shared, though sub-dictionaries may be. It is not an error if
1303 * there is no value associated with the given key list, but all
1304 * intermediate dictionaries on the key path must exist.
1305 *
1306 * Results:
1307 * A standard Tcl result. Note that in the error case, a message is left
1308 * in interp unless that is NULL.
1309 *
1310 * Side effects:
1311 * If the dictionary and any of its sub-dictionaries on the key path have
1312 * string representations, these are invalidated.
1313 *
1314 *----------------------------------------------------------------------
1315 */
1316
1317 int
1318 Tcl_DictObjRemoveKeyList(
1319 Tcl_Interp *interp,
1320 Tcl_Obj *dictPtr,
1321 int keyc,
1322 Tcl_Obj *const keyv[])
1323 {
1324 Dict *dict;
1325
1326 if (Tcl_IsShared(dictPtr)) {
1327 Tcl_Panic("%s called with shared object", "Tcl_DictObjRemoveKeyList");
1328 }
1329 if (keyc < 1) {
1330 Tcl_Panic("%s called with empty key list", "Tcl_DictObjRemoveKeyList");
1331 }
1332
1333 dictPtr = TclTraceDictPath(interp, dictPtr, keyc-1,keyv, DICT_PATH_UPDATE);
1334 if (dictPtr == NULL) {
1335 return TCL_ERROR;
1336 }
1337
1338 dict = (Dict *)DICT(dictPtr);
1339 DeleteChainEntry(dict, keyv[keyc-1]);
1340 InvalidateDictChain(dictPtr);
1341 return TCL_OK;
1342 }
1343
1344 /*
1345 *----------------------------------------------------------------------
1346 *
1347 * Tcl_NewDictObj --
1348 *
1349 * This function is normally called when not debugging: i.e., when
1350 * TCL_MEM_DEBUG is not defined. It creates a new dict object without any
1351 * content.
1352 *
1353 * When TCL_MEM_DEBUG is defined, this function just returns the result
1354 * of calling the debugging version Tcl_DbNewDictObj.
1355 *
1356 * Results:
1357 * A new dict object is returned; it has no keys defined in it. The new
1358 * object's string representation is left NULL, and the ref count of the
1359 * object is 0.
1360 *
1361 * Side Effects:
1362 * None.
1363 *
1364 *----------------------------------------------------------------------
1365 */
1366
1367 Tcl_Obj *
1368 Tcl_NewDictObj(void)
1369 {
1370 #ifdef TCL_MEM_DEBUG
1371 return Tcl_DbNewDictObj("unknown", 0);
1372 #else /* !TCL_MEM_DEBUG */
1373
1374 Tcl_Obj *dictPtr;
1375 Dict *dict;
1376
1377 TclNewObj(dictPtr);
1378 TclInvalidateStringRep(dictPtr);
1379 dict = (Dict *)ckalloc(sizeof(Dict));
1380 InitChainTable(dict);
1381 dict->epoch = 0;
1382 dict->chain = NULL;
1383 dict->refCount = 1;
1384 DICT(dictPtr) = dict;
1385 dictPtr->internalRep.twoPtrValue.ptr2 = NULL;
1386 dictPtr->typePtr = &tclDictType;
1387 return dictPtr;
1388 #endif
1389 }
1390
1391 /*
1392 *----------------------------------------------------------------------
1393 *
1394 * Tcl_DbNewDictObj --
1395 *
1396 * This function is normally called when debugging: i.e., when
1397 * TCL_MEM_DEBUG is defined. It creates new dict objects. It is the same
1398 * as the Tcl_NewDictObj function above except that it calls
1399 * Tcl_DbCkalloc directly with the file name and line number from its
1400 * caller. This simplifies debugging since then the [memory active]
1401 * command will report the correct file name and line number when
1402 * reporting objects that haven't been freed.
1403 *
1404 * When TCL_MEM_DEBUG is not defined, this function just returns the
1405 * result of calling Tcl_NewDictObj.
1406 *
1407 * Results:
1408 * A new dict object is returned; it has no keys defined in it. The new
1409 * object's string representation is left NULL, and the ref count of the
1410 * object is 0.
1411 *
1412 * Side Effects:
1413 * None.
1414 *
1415 *----------------------------------------------------------------------
1416 */
1417
1418 Tcl_Obj *
1419 Tcl_DbNewDictObj(
1420 const char *file,
1421 int line)
1422 {
1423 #ifdef TCL_MEM_DEBUG
1424 Tcl_Obj *dictPtr;
1425 Dict *dict;
1426
1427 TclDbNewObj(dictPtr, file, line);
1428 TclInvalidateStringRep(dictPtr);
1429 dict = (Dict *)ckalloc(sizeof(Dict));
1430 InitChainTable(dict);
1431 dict->epoch = 0;
1432 dict->chain = NULL;
1433 dict->refCount = 1;
1434 DICT(dictPtr) = dict;
1435 dictPtr->internalRep.twoPtrValue.ptr2 = NULL;
1436 dictPtr->typePtr = &tclDictType;
1437 return dictPtr;
1438 #else /* !TCL_MEM_DEBUG */
1439 return Tcl_NewDictObj();
1440 #endif
1441 }
1442
1443 /***** START OF FUNCTIONS ACTING AS HELPERS *****/
1444
1445 /*
1446 *----------------------------------------------------------------------
1447 *
1448 * TclDictGet --
1449 *
1450 * Given a key, get its value from the dictionary (or NULL if key is not
1451 * found in dictionary.)
1452 *
1453 * Results:
1454 * A standard Tcl result. The variable pointed to by valuePtrPtr is
1455 * updated with the value for the key. Note that it is not an error for
1456 * the key to have no mapping in the dictionary.
1457 *
1458 * Side effects:
1459 * The object pointed to by dictPtr is converted to a dictionary if it is
1460 * not already one.
1461 *
1462 *----------------------------------------------------------------------
1463 */
1464 int
1465 TclDictGet(
1466 Tcl_Interp *interp,
1467 Tcl_Obj *dictPtr,
1468 const char *key, /* The key in a C string. */
1469 Tcl_Obj **valuePtrPtr) /* Where to write the value. */
1470 {
1471 Tcl_Obj *keyPtr = Tcl_NewStringObj(key, -1);
1472 int code;
1473
1474 Tcl_IncrRefCount(keyPtr);
1475 code = Tcl_DictObjGet(interp, dictPtr, keyPtr, valuePtrPtr);
1476 Tcl_DecrRefCount(keyPtr);
1477 return code;
1478 }
1479
1480 /*
1481 *----------------------------------------------------------------------
1482 *
1483 * TclDictPut --
1484 *
1485 * Add a key,value pair to a dictionary, or update the value for a key if
1486 * that key already has a mapping in the dictionary.
1487 *
1488 * If valuePtr is a zero-count object and is not written into the
1489 * dictionary because of an error, it is freed by this routine. The caller
1490 * does NOT need to do reference count management.
1491 *
1492 * Results:
1493 * A standard Tcl result.
1494 *
1495 * Side effects:
1496 * The object pointed to by dictPtr is converted to a dictionary if it is
1497 * not already one, and any string representation that it has is
1498 * invalidated.
1499 *
1500 *----------------------------------------------------------------------
1501 */
1502 int
1503 TclDictPut(
1504 Tcl_Interp *interp,
1505 Tcl_Obj *dictPtr,
1506 const char *key, /* The key in a C string. */
1507 Tcl_Obj *valuePtr) /* The value to write in. */
1508 {
1509 Tcl_Obj *keyPtr = Tcl_NewStringObj(key, -1);
1510 int code;
1511
1512 Tcl_IncrRefCount(keyPtr);
1513 Tcl_IncrRefCount(valuePtr);
1514 code = Tcl_DictObjPut(interp, dictPtr, keyPtr, valuePtr);
1515 Tcl_DecrRefCount(keyPtr);
1516 Tcl_DecrRefCount(valuePtr);
1517 return code;
1518 }
1519
1520 /*
1521 *----------------------------------------------------------------------
1522 *
1523 * TclDictPutString --
1524 *
1525 * Add a key,value pair to a dictionary, or update the value for a key if
1526 * that key already has a mapping in the dictionary.
1527 *
1528 * Results:
1529 * A standard Tcl result.
1530 *
1531 * Side effects:
1532 * The object pointed to by dictPtr is converted to a dictionary if it is
1533 * not already one, and any string representation that it has is
1534 * invalidated.
1535 *
1536 *----------------------------------------------------------------------
1537 */
1538 int
1539 TclDictPutString(
1540 Tcl_Interp *interp,
1541 Tcl_Obj *dictPtr,
1542 const char *key, /* The key in a C string. */
1543 const char *value) /* The value in a C string. */
1544 {
1545 Tcl_Obj *keyPtr = Tcl_NewStringObj(key, -1);
1546 Tcl_Obj *valuePtr = Tcl_NewStringObj(value, -1);
1547 int code;
1548
1549 Tcl_IncrRefCount(keyPtr);
1550 Tcl_IncrRefCount(valuePtr);
1551 code = Tcl_DictObjPut(interp, dictPtr, keyPtr, valuePtr);
1552 Tcl_DecrRefCount(keyPtr);
1553 Tcl_DecrRefCount(valuePtr);
1554 return code;
1555 }
1556
1557 /*
1558 *----------------------------------------------------------------------
1559 *
1560 * TclDictRemove --
1561 *
1562 * Remove the key,value pair with the given key from the dictionary; the
1563 * key does not need to be present in the dictionary.
1564 *
1565 * Results:
1566 * A standard Tcl result.
1567 *
1568 * Side effects:
1569 * The object pointed to by dictPtr is converted to a dictionary if it is
1570 * not already one, and any string representation that it has is
1571 * invalidated.
1572 *
1573 *----------------------------------------------------------------------
1574 */
1575 int
1576 TclDictRemove(
1577 Tcl_Interp *interp,
1578 Tcl_Obj *dictPtr,
1579 const char *key) /* The key in a C string. */
1580 {
1581 Tcl_Obj *keyPtr = Tcl_NewStringObj(key, -1);
1582 int code;
1583
1584 Tcl_IncrRefCount(keyPtr);
1585 code = Tcl_DictObjRemove(interp, dictPtr, keyPtr);
1586 Tcl_DecrRefCount(keyPtr);
1587 return code;
1588 }
1589
1590 /***** START OF FUNCTIONS IMPLEMENTING TCL COMMANDS *****/
1591
1592 /*
1593 *----------------------------------------------------------------------
1594 *
1595 * DictCreateCmd --
1596 *
1597 * This function implements the "dict create" Tcl command. See the user
1598 * documentation for details on what it does, and TIP#111 for the formal
1599 * specification.
1600 *
1601 * Results:
1602 * A standard Tcl result.
1603 *
1604 * Side effects:
1605 * See the user documentation.
1606 *
1607 *----------------------------------------------------------------------
1608 */
1609
1610 static int
1611 DictCreateCmd(
1612 ClientData dummy,
1613 Tcl_Interp *interp,
1614 int objc,
1615 Tcl_Obj *const *objv)
1616 {
1617 Tcl_Obj *dictObj;
1618 int i;
1619
1620 /*
1621 * Must have an even number of arguments; note that number of preceding
1622 * arguments (i.e. "dict create" is also even, which makes this much
1623 * easier.)
1624 */
1625
1626 if ((objc & 1) == 0) {
1627 Tcl_WrongNumArgs(interp, 1, objv, "?key value ...?");
1628 return TCL_ERROR;
1629 }
1630
1631 dictObj = Tcl_NewDictObj();
1632 for (i=1 ; i<objc ; i+=2) {
1633 /*
1634 * The next command is assumed to never fail...
1635 */
1636 Tcl_DictObjPut(NULL, dictObj, objv[i], objv[i+1]);
1637 }
1638 Tcl_SetObjResult(interp, dictObj);
1639 return TCL_OK;
1640 }
1641
1642 /*
1643 *----------------------------------------------------------------------
1644 *
1645 * DictGetCmd --
1646 *
1647 * This function implements the "dict get" Tcl command. See the user
1648 * documentation for details on what it does, and TIP#111 for the formal
1649 * specification.
1650 *
1651 * Results:
1652 * A standard Tcl result.
1653 *
1654 * Side effects:
1655 * See the user documentation.
1656 *
1657 *----------------------------------------------------------------------
1658 */
1659
1660 static int
1661 DictGetCmd(
1662 ClientData dummy,
1663 Tcl_Interp *interp,
1664 int objc,
1665 Tcl_Obj *const *objv)
1666 {
1667 Tcl_Obj *dictPtr, *valuePtr = NULL;
1668 int result;
1669
1670 if (objc < 2) {
1671 Tcl_WrongNumArgs(interp, 1, objv, "dictionary ?key ...?");
1672 return TCL_ERROR;
1673 }
1674
1675 /*
1676 * Test for the special case of no keys, which returns a *list* of all
1677 * key,value pairs. We produce a copy here because that makes subsequent
1678 * list handling more efficient.
1679 */
1680
1681 if (objc == 2) {
1682 Tcl_Obj *keyPtr = NULL, *listPtr;
1683 Tcl_DictSearch search;
1684 int done;
1685
1686 result = Tcl_DictObjFirst(interp, objv[1], &search,
1687 &keyPtr, &valuePtr, &done);
1688 if (result != TCL_OK) {
1689 return result;
1690 }
1691 listPtr = Tcl_NewListObj(0, NULL);
1692 while (!done) {
1693 /*
1694 * Assume these won't fail as we have complete control over the
1695 * types of things here.
1696 */
1697
1698 Tcl_ListObjAppendElement(interp, listPtr, keyPtr);
1699 Tcl_ListObjAppendElement(interp, listPtr, valuePtr);
1700
1701 Tcl_DictObjNext(&search, &keyPtr, &valuePtr, &done);
1702 }
1703 Tcl_SetObjResult(interp, listPtr);
1704 return TCL_OK;
1705 }
1706
1707 /*
1708 * Loop through the list of keys, looking up the key at the current index
1709 * in the current dictionary each time. Once we've done the lookup, we set
1710 * the current dictionary to be the value we looked up (in case the value
1711 * was not the last one and we are going through a chain of searches.)
1712 * Note that this loop always executes at least once.
1713 */
1714
1715 dictPtr = TclTraceDictPath(interp, objv[1], objc-3,objv+2, DICT_PATH_READ);
1716 if (dictPtr == NULL) {
1717 return TCL_ERROR;
1718 }
1719 result = Tcl_DictObjGet(interp, dictPtr, objv[objc-1], &valuePtr);
1720 if (result != TCL_OK) {
1721 return result;
1722 }
1723 if (valuePtr == NULL) {
1724 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1725 "key \"%s\" not known in dictionary",
1726 TclGetString(objv[objc-1])));
1727 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "DICT",
1728 TclGetString(objv[objc-1]), (char *)NULL);
1729 return TCL_ERROR;
1730 }
1731 Tcl_SetObjResult(interp, valuePtr);
1732 return TCL_OK;
1733 }
1734
1735 /*
1736 *----------------------------------------------------------------------
1737 *
1738 * DictReplaceCmd --
1739 *
1740 * This function implements the "dict replace" Tcl command. See the user
1741 * documentation for details on what it does, and TIP#111 for the formal
1742 * specification.
1743 *
1744 * Results:
1745 * A standard Tcl result.
1746 *
1747 * Side effects:
1748 * See the user documentation.
1749 *
1750 *----------------------------------------------------------------------
1751 */
1752
1753 static int
1754 DictReplaceCmd(
1755 ClientData dummy,
1756 Tcl_Interp *interp,
1757 int objc,
1758 Tcl_Obj *const *objv)
1759 {
1760 Tcl_Obj *dictPtr;
1761 int i;
1762
1763 if ((objc < 2) || (objc & 1)) {
1764 Tcl_WrongNumArgs(interp, 1, objv, "dictionary ?key value ...?");
1765 return TCL_ERROR;
1766 }
1767
1768 dictPtr = objv[1];
1769 if (dictPtr->typePtr != &tclDictType
1770 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
1771 return TCL_ERROR;
1772 }
1773 if (Tcl_IsShared(dictPtr)) {
1774 dictPtr = Tcl_DuplicateObj(dictPtr);
1775 }
1776 if (dictPtr->bytes != NULL) {
1777 TclInvalidateStringRep(dictPtr);
1778 }
1779 for (i=2 ; i<objc ; i+=2) {
1780 Tcl_DictObjPut(NULL, dictPtr, objv[i], objv[i+1]);
1781 }
1782 Tcl_SetObjResult(interp, dictPtr);
1783 return TCL_OK;
1784 }
1785
1786 /*
1787 *----------------------------------------------------------------------
1788 *
1789 * DictRemoveCmd --
1790 *
1791 * This function implements the "dict remove" Tcl command. See the user
1792 * documentation for details on what it does, and TIP#111 for the formal
1793 * specification.
1794 *
1795 * Results:
1796 * A standard Tcl result.
1797 *
1798 * Side effects:
1799 * See the user documentation.
1800 *
1801 *----------------------------------------------------------------------
1802 */
1803
1804 static int
1805 DictRemoveCmd(
1806 ClientData dummy,
1807 Tcl_Interp *interp,
1808 int objc,
1809 Tcl_Obj *const *objv)
1810 {
1811 Tcl_Obj *dictPtr;
1812 int i;
1813
1814 if (objc < 2) {
1815 Tcl_WrongNumArgs(interp, 1, objv, "dictionary ?key ...?");
1816 return TCL_ERROR;
1817 }
1818
1819 dictPtr = objv[1];
1820 if (dictPtr->typePtr != &tclDictType
1821 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
1822 return TCL_ERROR;
1823 }
1824 if (Tcl_IsShared(dictPtr)) {
1825 dictPtr = Tcl_DuplicateObj(dictPtr);
1826 }
1827 if (dictPtr->bytes != NULL) {
1828 TclInvalidateStringRep(dictPtr);
1829 }
1830 for (i=2 ; i<objc ; i++) {
1831 Tcl_DictObjRemove(NULL, dictPtr, objv[i]);
1832 }
1833 Tcl_SetObjResult(interp, dictPtr);
1834 return TCL_OK;
1835 }
1836
1837 /*
1838 *----------------------------------------------------------------------
1839 *
1840 * DictMergeCmd --
1841 *
1842 * This function implements the "dict merge" Tcl command. See the user
1843 * documentation for details on what it does, and TIP#163 for the formal
1844 * specification.
1845 *
1846 * Results:
1847 * A standard Tcl result.
1848 *
1849 * Side effects:
1850 * See the user documentation.
1851 *
1852 *----------------------------------------------------------------------
1853 */
1854
1855 static int
1856 DictMergeCmd(
1857 ClientData dummy,
1858 Tcl_Interp *interp,
1859 int objc,
1860 Tcl_Obj *const *objv)
1861 {
1862 Tcl_Obj *targetObj, *keyObj = NULL, *valueObj = NULL;
1863 int allocatedDict = 0;
1864 int i, done;
1865 Tcl_DictSearch search;
1866
1867 if (objc == 1) {
1868 /*
1869 * No dictionary arguments; return default (empty value).
1870 */
1871
1872 return TCL_OK;
1873 }
1874
1875 /*
1876 * Make sure first argument is a dictionary.
1877 */
1878
1879 targetObj = objv[1];
1880 if (targetObj->typePtr != &tclDictType
1881 && SetDictFromAny(interp, targetObj) != TCL_OK) {
1882 return TCL_ERROR;
1883 }
1884
1885 if (objc == 2) {
1886 /*
1887 * Single argument, return it.
1888 */
1889
1890 Tcl_SetObjResult(interp, objv[1]);
1891 return TCL_OK;
1892 }
1893
1894 /*
1895 * Normal behaviour: combining two (or more) dictionaries.
1896 */
1897
1898 if (Tcl_IsShared(targetObj)) {
1899 targetObj = Tcl_DuplicateObj(targetObj);
1900 allocatedDict = 1;
1901 }
1902 for (i=2 ; i<objc ; i++) {
1903 if (Tcl_DictObjFirst(interp, objv[i], &search, &keyObj, &valueObj,
1904 &done) != TCL_OK) {
1905 if (allocatedDict) {
1906 TclDecrRefCount(targetObj);
1907 }
1908 return TCL_ERROR;
1909 }
1910 while (!done) {
1911 /*
1912 * Next line can't fail; already know we have a dictionary in
1913 * targetObj.
1914 */
1915
1916 Tcl_DictObjPut(NULL, targetObj, keyObj, valueObj);
1917 Tcl_DictObjNext(&search, &keyObj, &valueObj, &done);
1918 }
1919 Tcl_DictObjDone(&search);
1920 }
1921 Tcl_SetObjResult(interp, targetObj);
1922 return TCL_OK;
1923 }
1924
1925 /*
1926 *----------------------------------------------------------------------
1927 *
1928 * DictKeysCmd --
1929 *
1930 * This function implements the "dict keys" Tcl command. See the user
1931 * documentation for details on what it does, and TIP#111 for the formal
1932 * specification.
1933 *
1934 * Results:
1935 * A standard Tcl result.
1936 *
1937 * Side effects:
1938 * See the user documentation.
1939 *
1940 *----------------------------------------------------------------------
1941 */
1942
1943 static int
1944 DictKeysCmd(
1945 ClientData dummy,
1946 Tcl_Interp *interp,
1947 int objc,
1948 Tcl_Obj *const *objv)
1949 {
1950 Tcl_Obj *listPtr;
1951 const char *pattern = NULL;
1952
1953 if (objc!=2 && objc!=3) {
1954 Tcl_WrongNumArgs(interp, 1, objv, "dictionary ?pattern?");
1955 return TCL_ERROR;
1956 }
1957
1958 /*
1959 * A direct check that we have a dictionary. We don't start the iteration
1960 * yet because that might allocate memory or set locks that we do not
1961 * need. [Bug 1705778, leak K04]
1962 */
1963
1964 if (objv[1]->typePtr != &tclDictType
1965 && SetDictFromAny(interp, objv[1]) != TCL_OK) {
1966 return TCL_ERROR;
1967 }
1968
1969 if (objc == 3) {
1970 pattern = TclGetString(objv[2]);
1971 }
1972 listPtr = Tcl_NewListObj(0, NULL);
1973 if ((pattern != NULL) && TclMatchIsTrivial(pattern)) {
1974 Tcl_Obj *valuePtr = NULL;
1975
1976 Tcl_DictObjGet(interp, objv[1], objv[2], &valuePtr);
1977 if (valuePtr != NULL) {
1978 Tcl_ListObjAppendElement(NULL, listPtr, objv[2]);
1979 }
1980 } else {
1981 Tcl_DictSearch search;
1982 Tcl_Obj *keyPtr = NULL;
1983 int done = 0;
1984
1985 /*
1986 * At this point, we know we have a dictionary (or at least something
1987 * that can be represented; it could theoretically have shimmered away
1988 * when the pattern was fetched, but that shouldn't be damaging) so we
1989 * can start the iteration process without checking for failures.
1990 */
1991
1992 Tcl_DictObjFirst(NULL, objv[1], &search, &keyPtr, NULL, &done);
1993 for (; !done ; Tcl_DictObjNext(&search, &keyPtr, NULL, &done)) {
1994 if (!pattern || Tcl_StringMatch(TclGetString(keyPtr), pattern)) {
1995 Tcl_ListObjAppendElement(NULL, listPtr, keyPtr);
1996 }
1997 }
1998 Tcl_DictObjDone(&search);
1999 }
2000
2001 Tcl_SetObjResult(interp, listPtr);
2002 return TCL_OK;
2003 }
2004
2005 /*
2006 *----------------------------------------------------------------------
2007 *
2008 * DictValuesCmd --
2009 *
2010 * This function implements the "dict values" Tcl command. See the user
2011 * documentation for details on what it does, and TIP#111 for the formal
2012 * specification.
2013 *
2014 * Results:
2015 * A standard Tcl result.
2016 *
2017 * Side effects:
2018 * See the user documentation.
2019 *
2020 *----------------------------------------------------------------------
2021 */
2022
2023 static int
2024 DictValuesCmd(
2025 ClientData dummy,
2026 Tcl_Interp *interp,
2027 int objc,
2028 Tcl_Obj *const *objv)
2029 {
2030 Tcl_Obj *valuePtr = NULL, *listPtr;
2031 Tcl_DictSearch search;
2032 int done;
2033 const char *pattern;
2034
2035 if (objc!=2 && objc!=3) {
2036 Tcl_WrongNumArgs(interp, 1, objv, "dictionary ?pattern?");
2037 return TCL_ERROR;
2038 }
2039
2040 if (Tcl_DictObjFirst(interp, objv[1], &search, NULL, &valuePtr,
2041 &done) != TCL_OK) {
2042 return TCL_ERROR;
2043 }
2044 if (objc == 3) {
2045 pattern = TclGetString(objv[2]);
2046 } else {
2047 pattern = NULL;
2048 }
2049 listPtr = Tcl_NewListObj(0, NULL);
2050 for (; !done ; Tcl_DictObjNext(&search, NULL, &valuePtr, &done)) {
2051 if (pattern==NULL || Tcl_StringMatch(TclGetString(valuePtr),pattern)) {
2052 /*
2053 * Assume this operation always succeeds.
2054 */
2055
2056 Tcl_ListObjAppendElement(interp, listPtr, valuePtr);
2057 }
2058 }
2059 Tcl_DictObjDone(&search);
2060
2061 Tcl_SetObjResult(interp, listPtr);
2062 return TCL_OK;
2063 }
2064
2065 /*
2066 *----------------------------------------------------------------------
2067 *
2068 * DictSizeCmd --
2069 *
2070 * This function implements the "dict size" Tcl command. See the user
2071 * documentation for details on what it does, and TIP#111 for the formal
2072 * specification.
2073 *
2074 * Results:
2075 * A standard Tcl result.
2076 *
2077 * Side effects:
2078 * See the user documentation.
2079 *
2080 *----------------------------------------------------------------------
2081 */
2082
2083 static int
2084 DictSizeCmd(
2085 ClientData dummy,
2086 Tcl_Interp *interp,
2087 int objc,
2088 Tcl_Obj *const *objv)
2089 {
2090 int result, size;
2091
2092 if (objc != 2) {
2093 Tcl_WrongNumArgs(interp, 1, objv, "dictionary");
2094 return TCL_ERROR;
2095 }
2096 result = Tcl_DictObjSize(interp, objv[1], &size);
2097 if (result == TCL_OK) {
2098 Tcl_SetObjResult(interp, Tcl_NewIntObj(size));
2099 }
2100 return result;
2101 }
2102
2103 /*
2104 *----------------------------------------------------------------------
2105 *
2106 * DictExistsCmd --
2107 *
2108 * This function implements the "dict exists" Tcl command. See the user
2109 * documentation for details on what it does, and TIP#111 for the formal
2110 * specification.
2111 *
2112 * Results:
2113 * A standard Tcl result.
2114 *
2115 * Side effects:
2116 * See the user documentation.
2117 *
2118 *----------------------------------------------------------------------
2119 */
2120
2121 static int
2122 DictExistsCmd(
2123 ClientData dummy,
2124 Tcl_Interp *interp,
2125 int objc,
2126 Tcl_Obj *const *objv)
2127 {
2128 Tcl_Obj *dictPtr, *valuePtr;
2129
2130 if (objc < 3) {
2131 Tcl_WrongNumArgs(interp, 1, objv, "dictionary key ?key ...?");
2132 return TCL_ERROR;
2133 }
2134
2135 dictPtr = TclTraceDictPath(interp, objv[1], objc-3, objv+2,
2136 DICT_PATH_EXISTS);
2137 if (dictPtr == NULL || dictPtr == DICT_PATH_NON_EXISTENT
2138 || Tcl_DictObjGet(interp, dictPtr, objv[objc-1],
2139 &valuePtr) != TCL_OK) {
2140 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(0));
2141 } else {
2142 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(valuePtr != NULL));
2143 }
2144 return TCL_OK;
2145 }
2146
2147 /*
2148 *----------------------------------------------------------------------
2149 *
2150 * DictInfoCmd --
2151 *
2152 * This function implements the "dict info" Tcl command. See the user
2153 * documentation for details on what it does, and TIP#111 for the formal
2154 * specification.
2155 *
2156 * Results:
2157 * A standard Tcl result.
2158 *
2159 * Side effects:
2160 * See the user documentation.
2161 *
2162 *----------------------------------------------------------------------
2163 */
2164
2165 static int
2166 DictInfoCmd(
2167 ClientData dummy,
2168 Tcl_Interp *interp,
2169 int objc,
2170 Tcl_Obj *const *objv)
2171 {
2172 Tcl_Obj *dictPtr;
2173 Dict *dict;
2174 char *statsStr;
2175
2176 if (objc != 2) {
2177 Tcl_WrongNumArgs(interp, 1, objv, "dictionary");
2178 return TCL_ERROR;
2179 }
2180
2181 dictPtr = objv[1];
2182 if (dictPtr->typePtr != &tclDictType
2183 && SetDictFromAny(interp, dictPtr) != TCL_OK) {
2184 return TCL_ERROR;
2185 }
2186 dict = (Dict *)DICT(dictPtr);
2187
2188 statsStr = Tcl_HashStats(&dict->table);
2189 Tcl_SetObjResult(interp, Tcl_NewStringObj(statsStr, -1));
2190 ckfree(statsStr);
2191 return TCL_OK;
2192 }
2193
2194 /*
2195 *----------------------------------------------------------------------
2196 *
2197 * DictIncrCmd --
2198 *
2199 * This function implements the "dict incr" Tcl command. See the user
2200 * documentation for details on what it does, and TIP#111 for the formal
2201 * specification.
2202 *
2203 * Results:
2204 * A standard Tcl result.
2205 *
2206 * Side effects:
2207 * See the user documentation.
2208 *
2209 *----------------------------------------------------------------------
2210 */
2211
2212 static int
2213 DictIncrCmd(
2214 ClientData dummy,
2215 Tcl_Interp *interp,
2216 int objc,
2217 Tcl_Obj *const *objv)
2218 {
2219 int code = TCL_OK;
2220 Tcl_Obj *dictPtr, *valuePtr = NULL;
2221
2222 if (objc < 3 || objc > 4) {
2223 Tcl_WrongNumArgs(interp, 1, objv, "dictVarName key ?increment?");
2224 return TCL_ERROR;
2225 }
2226
2227 dictPtr = Tcl_ObjGetVar2(interp, objv[1], NULL, 0);
2228 if (dictPtr == NULL) {
2229 /*
2230 * Variable didn't yet exist. Create new dictionary value.
2231 */
2232
2233 dictPtr = Tcl_NewDictObj();
2234 } else if (Tcl_DictObjGet(interp, dictPtr, objv[2], &valuePtr) != TCL_OK) {
2235 /*
2236 * Variable contents are not a dict, report error.
2237 */
2238
2239 return TCL_ERROR;
2240 }
2241 if (Tcl_IsShared(dictPtr)) {
2242 /*
2243 * A little internals surgery to avoid copying a string rep that will
2244 * soon be no good.
2245 */
2246
2247 char *saved = dictPtr->bytes;
2248 Tcl_Obj *oldPtr = dictPtr;
2249
2250 dictPtr->bytes = NULL;
2251 dictPtr = Tcl_DuplicateObj(dictPtr);
2252 oldPtr->bytes = saved;
2253 }
2254 if (valuePtr == NULL) {
2255 /*
2256 * Key not in dictionary. Create new key with increment as value.
2257 */
2258
2259 if (objc == 4) {
2260 /*
2261 * Verify increment is an integer.
2262 */
2263
2264 mp_int increment;
2265
2266 code = Tcl_GetBignumFromObj(interp, objv[3], &increment);
2267 if (code != TCL_OK) {
2268 Tcl_AddErrorInfo(interp, "\n (reading increment)");
2269 } else {
2270 /*
2271 * Remember to dispose with the bignum as we're not actually
2272 * using it directly. [Bug 2874678]
2273 */
2274
2275 mp_clear(&increment);
2276 Tcl_DictObjPut(NULL, dictPtr, objv[2], objv[3]);
2277 }
2278 } else {
2279 Tcl_DictObjPut(NULL, dictPtr, objv[2], Tcl_NewIntObj(1));
2280 }
2281 } else {
2282 /*
2283 * Key in dictionary. Increment its value with minimum dup.
2284 */
2285
2286 if (Tcl_IsShared(valuePtr)) {
2287 valuePtr = Tcl_DuplicateObj(valuePtr);
2288 Tcl_DictObjPut(NULL, dictPtr, objv[2], valuePtr);
2289 }
2290 if (objc == 4) {
2291 code = TclIncrObj(interp, valuePtr, objv[3]);
2292 } else {
2293 Tcl_Obj *incrPtr;
2294
2295 TclNewIntObj(incrPtr, 1);
2296 Tcl_IncrRefCount(incrPtr);
2297 code = TclIncrObj(interp, valuePtr, incrPtr);
2298 TclDecrRefCount(incrPtr);
2299 }
2300 }
2301 if (code == TCL_OK) {
2302 TclInvalidateStringRep(dictPtr);
2303 valuePtr = Tcl_ObjSetVar2(interp, objv[1], NULL,
2304 dictPtr, TCL_LEAVE_ERR_MSG);
2305 if (valuePtr == NULL) {
2306 code = TCL_ERROR;
2307 } else {
2308 Tcl_SetObjResult(interp, valuePtr);
2309 }
2310 } else if (dictPtr->refCount == 0) {
2311 TclDecrRefCount(dictPtr);
2312 }
2313 return code;
2314 }
2315
2316 /*
2317 *----------------------------------------------------------------------
2318 *
2319 * DictLappendCmd --
2320 *
2321 * This function implements the "dict lappend" Tcl command. See the user
2322 * documentation for details on what it does, and TIP#111 for the formal
2323 * specification.
2324 *
2325 * Results:
2326 * A standard Tcl result.
2327 *
2328 * Side effects:
2329 * See the user documentation.
2330 *
2331 *----------------------------------------------------------------------
2332 */
2333
2334 static int
2335 DictLappendCmd(
2336 ClientData dummy,
2337 Tcl_Interp *interp,
2338 int objc,
2339 Tcl_Obj *const *objv)
2340 {
2341 Tcl_Obj *dictPtr, *valuePtr, *resultPtr;
2342 int i, allocatedDict = 0, allocatedValue = 0;
2343
2344 if (objc < 3) {
2345 Tcl_WrongNumArgs(interp, 1, objv, "dictVarName key ?value ...?");
2346 return TCL_ERROR;
2347 }
2348
2349 dictPtr = Tcl_ObjGetVar2(interp, objv[1], NULL, 0);
2350 if (dictPtr == NULL) {
2351 allocatedDict = 1;
2352 dictPtr = Tcl_NewDictObj();
2353 } else if (Tcl_IsShared(dictPtr)) {
2354 allocatedDict = 1;
2355 dictPtr = Tcl_DuplicateObj(dictPtr);
2356 }
2357
2358 if (Tcl_DictObjGet(interp, dictPtr, objv[2], &valuePtr) != TCL_OK) {
2359 if (allocatedDict) {
2360 TclDecrRefCount(dictPtr);
2361 }
2362 return TCL_ERROR;
2363 }
2364
2365 if (valuePtr == NULL) {
2366 valuePtr = Tcl_NewListObj(objc-3, objv+3);
2367 allocatedValue = 1;
2368 } else {
2369 if (Tcl_IsShared(valuePtr)) {
2370 allocatedValue = 1;
2371 valuePtr = Tcl_DuplicateObj(valuePtr);
2372 }
2373
2374 for (i=3 ; i<objc ; i++) {
2375 if (Tcl_ListObjAppendElement(interp, valuePtr,
2376 objv[i]) != TCL_OK) {
2377 if (allocatedValue) {
2378 TclDecrRefCount(valuePtr);
2379 }
2380 if (allocatedDict) {
2381 TclDecrRefCount(dictPtr);
2382 }
2383 return TCL_ERROR;
2384 }
2385 }
2386 }
2387
2388 if (allocatedValue) {
2389 Tcl_DictObjPut(NULL, dictPtr, objv[2], valuePtr);
2390 } else if (dictPtr->bytes != NULL) {
2391 TclInvalidateStringRep(dictPtr);
2392 }
2393
2394 resultPtr = Tcl_ObjSetVar2(interp, objv[1], NULL, dictPtr,
2395 TCL_LEAVE_ERR_MSG);
2396 if (resultPtr == NULL) {
2397 return TCL_ERROR;
2398 }
2399 Tcl_SetObjResult(interp, resultPtr);
2400 return TCL_OK;
2401 }
2402
2403 /*
2404 *----------------------------------------------------------------------
2405 *
2406 * DictAppendCmd --
2407 *
2408 * This function implements the "dict append" Tcl command. See the user
2409 * documentation for details on what it does, and TIP#111 for the formal
2410 * specification.
2411 *
2412 * Results:
2413 * A standard Tcl result.
2414 *
2415 * Side effects:
2416 * See the user documentation.
2417 *
2418 *----------------------------------------------------------------------
2419 */
2420
2421 static int
2422 DictAppendCmd(
2423 ClientData dummy,
2424 Tcl_Interp *interp,
2425 int objc,
2426 Tcl_Obj *const *objv)
2427 {
2428 Tcl_Obj *dictPtr, *valuePtr, *resultPtr;
2429 int i, allocatedDict = 0;
2430
2431 if (objc < 3) {
2432 Tcl_WrongNumArgs(interp, 1, objv, "dictVarName key ?value ...?");
2433 return TCL_ERROR;
2434 }
2435
2436 dictPtr = Tcl_ObjGetVar2(interp, objv[1], NULL, 0);
2437 if (dictPtr == NULL) {
2438 allocatedDict = 1;
2439 dictPtr = Tcl_NewDictObj();
2440 } else if (Tcl_IsShared(dictPtr)) {
2441 allocatedDict = 1;
2442 dictPtr = Tcl_DuplicateObj(dictPtr);
2443 }
2444
2445 if (Tcl_DictObjGet(interp, dictPtr, objv[2], &valuePtr) != TCL_OK) {
2446 if (allocatedDict) {
2447 TclDecrRefCount(dictPtr);
2448 }
2449 return TCL_ERROR;
2450 }
2451
2452 if (valuePtr == NULL) {
2453 TclNewObj(valuePtr);
2454 } else if (Tcl_IsShared(valuePtr)) {
2455 valuePtr = Tcl_DuplicateObj(valuePtr);
2456 }
2457
2458 for (i=3 ; i<objc ; i++) {
2459 Tcl_AppendObjToObj(valuePtr, objv[i]);
2460 }
2461
2462 Tcl_DictObjPut(NULL, dictPtr, objv[2], valuePtr);
2463
2464 resultPtr = Tcl_ObjSetVar2(interp, objv[1], NULL, dictPtr,
2465 TCL_LEAVE_ERR_MSG);
2466 if (resultPtr == NULL) {
2467 return TCL_ERROR;
2468 }
2469 Tcl_SetObjResult(interp, resultPtr);
2470 return TCL_OK;
2471 }
2472
2473 /*
2474 *----------------------------------------------------------------------
2475 *
2476 * DictForNRCmd --
2477 *
2478 * These functions implement the "dict for" Tcl command. See the user
2479 * documentation for details on what it does, and TIP#111 for the formal
2480 * specification.
2481 *
2482 * Results:
2483 * A standard Tcl result.
2484 *
2485 * Side effects:
2486 * See the user documentation.
2487 *
2488 *----------------------------------------------------------------------
2489 */
2490
2491 static int
2492 DictForNRCmd(
2493 ClientData dummy,
2494 Tcl_Interp *interp,
2495 int objc,
2496 Tcl_Obj *const *objv)
2497 {
2498 Interp *iPtr = (Interp *) interp;
2499 Tcl_Obj *scriptObj, *keyVarObj, *valueVarObj;
2500 Tcl_Obj **varv, *keyObj, *valueObj;
2501 Tcl_DictSearch *searchPtr;
2502 int varc, done;
2503
2504 if (objc != 4) {
2505 Tcl_WrongNumArgs(interp, 1, objv,
2506 "{keyVarName valueVarName} dictionary script");
2507 return TCL_ERROR;
2508 }
2509
2510 /*
2511 * Parse arguments.
2512 */
2513
2514 if (TclListObjGetElements(interp, objv[1], &varc, &varv) != TCL_OK) {
2515 return TCL_ERROR;
2516 }
2517 if (varc != 2) {
2518 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2519 "must have exactly two variable names", -1));
2520 Tcl_SetErrorCode(interp, "TCL", "SYNTAX", "dict", "for", (char *)NULL);
2521 return TCL_ERROR;
2522 }
2523 searchPtr = (Tcl_DictSearch *)TclStackAlloc(interp, sizeof(Tcl_DictSearch));
2524 if (Tcl_DictObjFirst(interp, objv[2], searchPtr, &keyObj, &valueObj,
2525 &done) != TCL_OK) {
2526 TclStackFree(interp, searchPtr);
2527 return TCL_ERROR;
2528 }
2529 if (done) {
2530 TclStackFree(interp, searchPtr);
2531 return TCL_OK;
2532 }
2533 TclListObjGetElements(NULL, objv[1], &varc, &varv);
2534 keyVarObj = varv[0];
2535 valueVarObj = varv[1];
2536 scriptObj = objv[3];
2537
2538 /*
2539 * Make sure that these objects (which we need throughout the body of the
2540 * loop) don't vanish. Note that the dictionary internal rep is locked
2541 * internally so that updates, shimmering, etc are not a problem.
2542 */
2543
2544 Tcl_IncrRefCount(keyVarObj);
2545 Tcl_IncrRefCount(valueVarObj);
2546 Tcl_IncrRefCount(scriptObj);
2547
2548 /*
2549 * Stop the value from getting hit in any way by any traces on the key
2550 * variable.
2551 */
2552
2553 Tcl_IncrRefCount(valueObj);
2554 if (Tcl_ObjSetVar2(interp, keyVarObj, NULL, keyObj,
2555 TCL_LEAVE_ERR_MSG) == NULL) {
2556 TclDecrRefCount(valueObj);
2557 goto error;
2558 }
2559 TclDecrRefCount(valueObj);
2560 if (Tcl_ObjSetVar2(interp, valueVarObj, NULL, valueObj,
2561 TCL_LEAVE_ERR_MSG) == NULL) {
2562 goto error;
2563 }
2564
2565 /*
2566 * Run the script.
2567 */
2568
2569 TclNRAddCallback(interp, DictForLoopCallback, searchPtr, keyVarObj,
2570 valueVarObj, scriptObj);
2571 return TclNREvalObjEx(interp, scriptObj, 0, iPtr->cmdFramePtr, 3);
2572
2573 /*
2574 * For unwinding everything on error.
2575 */
2576
2577 error:
2578 TclDecrRefCount(keyVarObj);
2579 TclDecrRefCount(valueVarObj);
2580 TclDecrRefCount(scriptObj);
2581 Tcl_DictObjDone(searchPtr);
2582 TclStackFree(interp, searchPtr);
2583 return TCL_ERROR;
2584 }
2585
2586 static int
2587 DictForLoopCallback(
2588 ClientData data[],
2589 Tcl_Interp *interp,
2590 int result)
2591 {
2592 Interp *iPtr = (Interp *) interp;
2593 Tcl_DictSearch *searchPtr = (Tcl_DictSearch *)data[0];
2594 Tcl_Obj *keyVarObj = (Tcl_Obj *)data[1];
2595 Tcl_Obj *valueVarObj = (Tcl_Obj *)data[2];
2596 Tcl_Obj *scriptObj = (Tcl_Obj *)data[3];
2597 Tcl_Obj *keyObj, *valueObj;
2598 int done;
2599
2600 /*
2601 * Process the result from the previous execution of the script body.
2602 */
2603
2604 if (result == TCL_CONTINUE) {
2605 result = TCL_OK;
2606 } else if (result != TCL_OK) {
2607 if (result == TCL_BREAK) {
2608 Tcl_ResetResult(interp);
2609 result = TCL_OK;
2610 } else if (result == TCL_ERROR) {
2611 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
2612 "\n (\"dict for\" body line %d)",
2613 Tcl_GetErrorLine(interp)));
2614 }
2615 goto done;
2616 }
2617
2618 /*
2619 * Get the next mapping from the dictionary.
2620 */
2621
2622 Tcl_DictObjNext(searchPtr, &keyObj, &valueObj, &done);
2623 if (done) {
2624 Tcl_ResetResult(interp);
2625 goto done;
2626 }
2627
2628 /*
2629 * Stop the value from getting hit in any way by any traces on the key
2630 * variable.
2631 */
2632
2633 Tcl_IncrRefCount(valueObj);
2634 if (Tcl_ObjSetVar2(interp, keyVarObj, NULL, keyObj,
2635 TCL_LEAVE_ERR_MSG) == NULL) {
2636 TclDecrRefCount(valueObj);
2637 result = TCL_ERROR;
2638 goto done;
2639 }
2640 TclDecrRefCount(valueObj);
2641 if (Tcl_ObjSetVar2(interp, valueVarObj, NULL, valueObj,
2642 TCL_LEAVE_ERR_MSG) == NULL) {
2643 result = TCL_ERROR;
2644 goto done;
2645 }
2646
2647 /*
2648 * Run the script.
2649 */
2650
2651 TclNRAddCallback(interp, DictForLoopCallback, searchPtr, keyVarObj,
2652 valueVarObj, scriptObj);
2653 return TclNREvalObjEx(interp, scriptObj, 0, iPtr->cmdFramePtr, 3);
2654
2655 /*
2656 * For unwinding everything once the iterating is done.
2657 */
2658
2659 done:
2660 TclDecrRefCount(keyVarObj);
2661 TclDecrRefCount(valueVarObj);
2662 TclDecrRefCount(scriptObj);
2663 Tcl_DictObjDone(searchPtr);
2664 TclStackFree(interp, searchPtr);
2665 return result;
2666 }
2667
2668 /*
2669 *----------------------------------------------------------------------
2670 *
2671 * DictMapNRCmd --
2672 *
2673 * These functions implement the "dict map" Tcl command. See the user
2674 * documentation for details on what it does, and TIP#405 for the formal
2675 * specification.
2676 *
2677 * Results:
2678 * A standard Tcl result.
2679 *
2680 * Side effects:
2681 * See the user documentation.
2682 *
2683 *----------------------------------------------------------------------
2684 */
2685
2686 static int
2687 DictMapNRCmd(
2688 ClientData dummy,
2689 Tcl_Interp *interp,
2690 int objc,
2691 Tcl_Obj *const *objv)
2692 {
2693 Interp *iPtr = (Interp *) interp;
2694 Tcl_Obj **varv, *keyObj, *valueObj;
2695 DictMapStorage *storagePtr;
2696 int varc;
2697 int done;
2698
2699 if (objc != 4) {
2700 Tcl_WrongNumArgs(interp, 1, objv,
2701 "{keyVarName valueVarName} dictionary script");
2702 return TCL_ERROR;
2703 }
2704
2705 /*
2706 * Parse arguments.
2707 */
2708
2709 if (TclListObjGetElements(interp, objv[1], &varc, &varv) != TCL_OK) {
2710 return TCL_ERROR;
2711 }
2712 if (varc != 2) {
2713 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2714 "must have exactly two variable names", -1));
2715 Tcl_SetErrorCode(interp, "TCL", "SYNTAX", "dict", "map", (char *)NULL);
2716 return TCL_ERROR;
2717 }
2718 storagePtr = (DictMapStorage *)TclStackAlloc(interp, sizeof(DictMapStorage));
2719 if (Tcl_DictObjFirst(interp, objv[2], &storagePtr->search, &keyObj,
2720 &valueObj, &done) != TCL_OK) {
2721 TclStackFree(interp, storagePtr);
2722 return TCL_ERROR;
2723 }
2724 if (done) {
2725 /*
2726 * Note that this exit leaves an empty value in the result (due to
2727 * command calling conventions) but that is OK since an empty value is
2728 * an empty dictionary.
2729 */
2730
2731 TclStackFree(interp, storagePtr);
2732 return TCL_OK;
2733 }
2734 TclNewObj(storagePtr->accumulatorObj);
2735 TclListObjGetElements(NULL, objv[1], &varc, &varv);
2736 storagePtr->keyVarObj = varv[0];
2737 storagePtr->valueVarObj = varv[1];
2738 storagePtr->scriptObj = objv[3];
2739
2740 /*
2741 * Make sure that these objects (which we need throughout the body of the
2742 * loop) don't vanish. Note that the dictionary internal rep is locked
2743 * internally so that updates, shimmering, etc are not a problem.
2744 */
2745
2746 Tcl_IncrRefCount(storagePtr->accumulatorObj);
2747 Tcl_IncrRefCount(storagePtr->keyVarObj);
2748 Tcl_IncrRefCount(storagePtr->valueVarObj);
2749 Tcl_IncrRefCount(storagePtr->scriptObj);
2750
2751 /*
2752 * Stop the value from getting hit in any way by any traces on the key
2753 * variable.
2754 */
2755
2756 Tcl_IncrRefCount(valueObj);
2757 if (Tcl_ObjSetVar2(interp, storagePtr->keyVarObj, NULL, keyObj,
2758 TCL_LEAVE_ERR_MSG) == NULL) {
2759 TclDecrRefCount(valueObj);
2760 goto error;
2761 }
2762 if (Tcl_ObjSetVar2(interp, storagePtr->valueVarObj, NULL, valueObj,
2763 TCL_LEAVE_ERR_MSG) == NULL) {
2764 TclDecrRefCount(valueObj);
2765 goto error;
2766 }
2767 TclDecrRefCount(valueObj);
2768
2769 /*
2770 * Run the script.
2771 */
2772
2773 TclNRAddCallback(interp, DictMapLoopCallback, storagePtr, NULL,NULL,NULL);
2774 return TclNREvalObjEx(interp, storagePtr->scriptObj, 0,
2775 iPtr->cmdFramePtr, 3);
2776
2777 /*
2778 * For unwinding everything on error.
2779 */
2780
2781 error:
2782 TclDecrRefCount(storagePtr->keyVarObj);
2783 TclDecrRefCount(storagePtr->valueVarObj);
2784 TclDecrRefCount(storagePtr->scriptObj);
2785 TclDecrRefCount(storagePtr->accumulatorObj);
2786 Tcl_DictObjDone(&storagePtr->search);
2787 TclStackFree(interp, storagePtr);
2788 return TCL_ERROR;
2789 }
2790
2791 static int
2792 DictMapLoopCallback(
2793 ClientData data[],
2794 Tcl_Interp *interp,
2795 int result)
2796 {
2797 Interp *iPtr = (Interp *) interp;
2798 DictMapStorage *storagePtr = (DictMapStorage *)data[0];
2799 Tcl_Obj *keyObj, *valueObj;
2800 int done;
2801
2802 /*
2803 * Process the result from the previous execution of the script body.
2804 */
2805
2806 if (result == TCL_CONTINUE) {
2807 result = TCL_OK;
2808 } else if (result != TCL_OK) {
2809 if (result == TCL_BREAK) {
2810 Tcl_ResetResult(interp);
2811 result = TCL_OK;
2812 } else if (result == TCL_ERROR) {
2813 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
2814 "\n (\"dict map\" body line %d)",
2815 Tcl_GetErrorLine(interp)));
2816 }
2817 goto done;
2818 } else {
2819 keyObj = Tcl_ObjGetVar2(interp, storagePtr->keyVarObj, NULL,
2820 TCL_LEAVE_ERR_MSG);
2821 if (keyObj == NULL) {
2822 result = TCL_ERROR;
2823 goto done;
2824 }
2825 Tcl_DictObjPut(NULL, storagePtr->accumulatorObj, keyObj,
2826 Tcl_GetObjResult(interp));
2827 }
2828
2829 /*
2830 * Get the next mapping from the dictionary.
2831 */
2832
2833 Tcl_DictObjNext(&storagePtr->search, &keyObj, &valueObj, &done);
2834 if (done) {
2835 Tcl_SetObjResult(interp, storagePtr->accumulatorObj);
2836 goto done;
2837 }
2838
2839 /*
2840 * Stop the value from getting hit in any way by any traces on the key
2841 * variable.
2842 */
2843
2844 Tcl_IncrRefCount(valueObj);
2845 if (Tcl_ObjSetVar2(interp, storagePtr->keyVarObj, NULL, keyObj,
2846 TCL_LEAVE_ERR_MSG) == NULL) {
2847 TclDecrRefCount(valueObj);
2848 result = TCL_ERROR;
2849 goto done;
2850 }
2851 if (Tcl_ObjSetVar2(interp, storagePtr->valueVarObj, NULL, valueObj,
2852 TCL_LEAVE_ERR_MSG) == NULL) {
2853 TclDecrRefCount(valueObj);
2854 result = TCL_ERROR;
2855 goto done;
2856 }
2857 TclDecrRefCount(valueObj);
2858
2859 /*
2860 * Run the script.
2861 */
2862
2863 TclNRAddCallback(interp, DictMapLoopCallback, storagePtr, NULL,NULL,NULL);
2864 return TclNREvalObjEx(interp, storagePtr->scriptObj, 0,
2865 iPtr->cmdFramePtr, 3);
2866
2867 /*
2868 * For unwinding everything once the iterating is done.
2869 */
2870
2871 done:
2872 TclDecrRefCount(storagePtr->keyVarObj);
2873 TclDecrRefCount(storagePtr->valueVarObj);
2874 TclDecrRefCount(storagePtr->scriptObj);
2875 TclDecrRefCount(storagePtr->accumulatorObj);
2876 Tcl_DictObjDone(&storagePtr->search);
2877 TclStackFree(interp, storagePtr);
2878 return result;
2879 }
2880
2881 /*
2882 *----------------------------------------------------------------------
2883 *
2884 * DictSetCmd --
2885 *
2886 * This function implements the "dict set" Tcl command. See the user
2887 * documentation for details on what it does, and TIP#111 for the formal
2888 * specification.
2889 *
2890 * Results:
2891 * A standard Tcl result.
2892 *
2893 * Side effects:
2894 * See the user documentation.
2895 *
2896 *----------------------------------------------------------------------
2897 */
2898
2899 static int
2900 DictSetCmd(
2901 ClientData dummy,
2902 Tcl_Interp *interp,
2903 int objc,
2904 Tcl_Obj *const *objv)
2905 {
2906 Tcl_Obj *dictPtr, *resultPtr;
2907 int result, allocatedDict = 0;
2908
2909 if (objc < 4) {
2910 Tcl_WrongNumArgs(interp, 1, objv, "dictVarName key ?key ...? value");
2911 return TCL_ERROR;
2912 }
2913
2914 dictPtr = Tcl_ObjGetVar2(interp, objv[1], NULL, 0);
2915 if (dictPtr == NULL) {
2916 allocatedDict = 1;
2917 dictPtr = Tcl_NewDictObj();
2918 } else if (Tcl_IsShared(dictPtr)) {
2919 allocatedDict = 1;
2920 dictPtr = Tcl_DuplicateObj(dictPtr);
2921 }
2922
2923 result = Tcl_DictObjPutKeyList(interp, dictPtr, objc-3, objv+2,
2924 objv[objc-1]);
2925 if (result != TCL_OK) {
2926 if (allocatedDict) {
2927 TclDecrRefCount(dictPtr);
2928 }
2929 return TCL_ERROR;
2930 }
2931
2932 resultPtr = Tcl_ObjSetVar2(interp, objv[1], NULL, dictPtr,
2933 TCL_LEAVE_ERR_MSG);
2934 if (resultPtr == NULL) {
2935 return TCL_ERROR;
2936 }
2937 Tcl_SetObjResult(interp, resultPtr);
2938 return TCL_OK;
2939 }
2940
2941 /*
2942 *----------------------------------------------------------------------
2943 *
2944 * DictUnsetCmd --
2945 *
2946 * This function implements the "dict unset" Tcl command. See the user
2947 * documentation for details on what it does, and TIP#111 for the formal
2948 * specification.
2949 *
2950 * Results:
2951 * A standard Tcl result.
2952 *
2953 * Side effects:
2954 * See the user documentation.
2955 *
2956 *----------------------------------------------------------------------
2957 */
2958
2959 static int
2960 DictUnsetCmd(
2961 ClientData dummy,
2962 Tcl_Interp *interp,
2963 int objc,
2964 Tcl_Obj *const *objv)
2965 {
2966 Tcl_Obj *dictPtr, *resultPtr;
2967 int result, allocatedDict = 0;
2968
2969 if (objc < 3) {
2970 Tcl_WrongNumArgs(interp, 1, objv, "dictVarName key ?key ...?");
2971 return TCL_ERROR;
2972 }
2973
2974 dictPtr = Tcl_ObjGetVar2(interp, objv[1], NULL, 0);
2975 if (dictPtr == NULL) {
2976 allocatedDict = 1;
2977 dictPtr = Tcl_NewDictObj();
2978 } else if (Tcl_IsShared(dictPtr)) {
2979 allocatedDict = 1;
2980 dictPtr = Tcl_DuplicateObj(dictPtr);
2981 }
2982
2983 result = Tcl_DictObjRemoveKeyList(interp, dictPtr, objc-2, objv+2);
2984 if (result != TCL_OK) {
2985 if (allocatedDict) {
2986 TclDecrRefCount(dictPtr);
2987 }
2988 return TCL_ERROR;
2989 }
2990
2991 resultPtr = Tcl_ObjSetVar2(interp, objv[1], NULL, dictPtr,
2992 TCL_LEAVE_ERR_MSG);
2993 if (resultPtr == NULL) {
2994 return TCL_ERROR;
2995 }
2996 Tcl_SetObjResult(interp, resultPtr);
2997 return TCL_OK;
2998 }
2999
3000 /*
3001 *----------------------------------------------------------------------
3002 *
3003 * DictFilterCmd --
3004 *
3005 * This function implements the "dict filter" Tcl command. See the user
3006 * documentation for details on what it does, and TIP#111 for the formal
3007 * specification.
3008 *
3009 * Results:
3010 * A standard Tcl result.
3011 *
3012 * Side effects:
3013 * See the user documentation.
3014 *
3015 *----------------------------------------------------------------------
3016 */
3017
3018 static int
3019 DictFilterCmd(
3020 ClientData dummy,
3021 Tcl_Interp *interp,
3022 int objc,
3023 Tcl_Obj *const *objv)
3024 {
3025 Interp *iPtr = (Interp *) interp;
3026 static const char *const filters[] = {
3027 "key", "script", "value", NULL
3028 };
3029 enum FilterTypes {
3030 FILTER_KEYS, FILTER_SCRIPT, FILTER_VALUES
3031 };
3032 Tcl_Obj *scriptObj, *keyVarObj, *valueVarObj;
3033 Tcl_Obj **varv, *keyObj = NULL, *valueObj = NULL, *resultObj, *boolObj;
3034 Tcl_DictSearch search;
3035 int index, varc, done, result, satisfied;
3036 const char *pattern;
3037
3038 if (objc < 3) {
3039 Tcl_WrongNumArgs(interp, 1, objv, "dictionary filterType ?arg ...?");
3040 return TCL_ERROR;
3041 }
3042 if (Tcl_GetIndexFromObj(interp, objv[2], filters, "filterType",
3043 0, &index) != TCL_OK) {
3044 return TCL_ERROR;
3045 }
3046
3047 switch ((enum FilterTypes) index) {
3048 case FILTER_KEYS:
3049 /*
3050 * Create a dictionary whose keys all match a certain pattern.
3051 */
3052
3053 if (Tcl_DictObjFirst(interp, objv[1], &search,
3054 &keyObj, &valueObj, &done) != TCL_OK) {
3055 return TCL_ERROR;
3056 }
3057 if (objc == 3) {
3058 /*
3059 * Nothing to match, so return nothing (== empty dictionary).
3060 */
3061
3062 Tcl_DictObjDone(&search);
3063 return TCL_OK;
3064 } else if (objc == 4) {
3065 pattern = TclGetString(objv[3]);
3066 resultObj = Tcl_NewDictObj();
3067 if (TclMatchIsTrivial(pattern)) {
3068 /*
3069 * Must release the search lock here to prevent a memory leak
3070 * since we are not exhausing the search. [Bug 1705778, leak
3071 * K05]
3072 */
3073
3074 Tcl_DictObjDone(&search);
3075 Tcl_DictObjGet(interp, objv[1], objv[3], &valueObj);
3076 if (valueObj != NULL) {
3077 Tcl_DictObjPut(NULL, resultObj, objv[3], valueObj);
3078 }
3079 } else {
3080 while (!done) {
3081 if (Tcl_StringMatch(TclGetString(keyObj), pattern)) {
3082 Tcl_DictObjPut(NULL, resultObj, keyObj, valueObj);
3083 }
3084 Tcl_DictObjNext(&search, &keyObj, &valueObj, &done);
3085 }
3086 }
3087 } else {
3088 /*
3089 * Can't optimize this match for trivial globbing: would disturb
3090 * order.
3091 */
3092
3093 resultObj = Tcl_NewDictObj();
3094 while (!done) {
3095 int i;
3096
3097 for (i=3 ; i<objc ; i++) {
3098 pattern = TclGetString(objv[i]);
3099 if (Tcl_StringMatch(TclGetString(keyObj), pattern)) {
3100 Tcl_DictObjPut(NULL, resultObj, keyObj, valueObj);
3101 break; /* stop inner loop */
3102 }
3103 }
3104 Tcl_DictObjNext(&search, &keyObj, &valueObj, &done);
3105 }
3106 }
3107 Tcl_SetObjResult(interp, resultObj);
3108 return TCL_OK;
3109
3110 case FILTER_VALUES:
3111 /*
3112 * Create a dictionary whose values all match a certain pattern.
3113 */
3114
3115 if (Tcl_DictObjFirst(interp, objv[1], &search,
3116 &keyObj, &valueObj, &done) != TCL_OK) {
3117 return TCL_ERROR;
3118 }
3119 resultObj = Tcl_NewDictObj();
3120 while (!done) {
3121 int i;
3122
3123 for (i=3 ; i<objc ; i++) {
3124 pattern = TclGetString(objv[i]);
3125 if (Tcl_StringMatch(TclGetString(valueObj), pattern)) {
3126 Tcl_DictObjPut(NULL, resultObj, keyObj, valueObj);
3127 break; /* stop inner loop */
3128 }
3129 }
3130 Tcl_DictObjNext(&search, &keyObj, &valueObj, &done);
3131 }
3132 Tcl_SetObjResult(interp, resultObj);
3133 return TCL_OK;
3134
3135 case FILTER_SCRIPT:
3136 if (objc != 5) {
3137 Tcl_WrongNumArgs(interp, 1, objv,
3138 "dictionary script {keyVarName valueVarName} filterScript");
3139 return TCL_ERROR;
3140 }
3141
3142 /*
3143 * Create a dictionary whose key,value pairs all satisfy a script
3144 * (i.e. get a true boolean result from its evaluation). Massive
3145 * copying from the "dict for" implementation has occurred!
3146 */
3147
3148 if (TclListObjGetElements(interp, objv[3], &varc, &varv) != TCL_OK) {
3149 return TCL_ERROR;
3150 }
3151 if (varc != 2) {
3152 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3153 "must have exactly two variable names", -1));
3154 Tcl_SetErrorCode(interp, "TCL", "SYNTAX", "dict", "filter", (char *)NULL);
3155 return TCL_ERROR;
3156 }
3157 keyVarObj = varv[0];
3158 valueVarObj = varv[1];
3159 scriptObj = objv[4];
3160
3161 /*
3162 * Make sure that these objects (which we need throughout the body of
3163 * the loop) don't vanish. Note that the dictionary internal rep is
3164 * locked internally so that updates, shimmering, etc are not a
3165 * problem.
3166 */
3167
3168 Tcl_IncrRefCount(keyVarObj);
3169 Tcl_IncrRefCount(valueVarObj);
3170 Tcl_IncrRefCount(scriptObj);
3171
3172 result = Tcl_DictObjFirst(interp, objv[1],
3173 &search, &keyObj, &valueObj, &done);
3174 if (result != TCL_OK) {
3175 TclDecrRefCount(keyVarObj);
3176 TclDecrRefCount(valueVarObj);
3177 TclDecrRefCount(scriptObj);
3178 return TCL_ERROR;
3179 }
3180
3181 resultObj = Tcl_NewDictObj();
3182
3183 while (!done) {
3184 /*
3185 * Stop the value from getting hit in any way by any traces on the
3186 * key variable.
3187 */
3188
3189 Tcl_IncrRefCount(keyObj);
3190 Tcl_IncrRefCount(valueObj);
3191 if (Tcl_ObjSetVar2(interp, keyVarObj, NULL, keyObj,
3192 TCL_LEAVE_ERR_MSG) == NULL) {
3193 Tcl_AddErrorInfo(interp,
3194 "\n (\"dict filter\" filter script key variable)");
3195 result = TCL_ERROR;
3196 goto abnormalResult;
3197 }
3198 if (Tcl_ObjSetVar2(interp, valueVarObj, NULL, valueObj,
3199 TCL_LEAVE_ERR_MSG) == NULL) {
3200 Tcl_AddErrorInfo(interp,
3201 "\n (\"dict filter\" filter script value variable)");
3202 result = TCL_ERROR;
3203 goto abnormalResult;
3204 }
3205
3206 /*
3207 * TIP #280. Make invoking context available to loop body.
3208 */
3209
3210 result = TclEvalObjEx(interp, scriptObj, 0, iPtr->cmdFramePtr, 4);
3211 switch (result) {
3212 case TCL_OK:
3213 boolObj = Tcl_GetObjResult(interp);
3214 Tcl_IncrRefCount(boolObj);
3215 Tcl_ResetResult(interp);
3216 if (Tcl_GetBooleanFromObj(interp, boolObj,
3217 &satisfied) != TCL_OK) {
3218 TclDecrRefCount(boolObj);
3219 result = TCL_ERROR;
3220 goto abnormalResult;
3221 }
3222 TclDecrRefCount(boolObj);
3223 if (satisfied) {
3224 Tcl_DictObjPut(NULL, resultObj, keyObj, valueObj);
3225 }
3226 break;
3227 case TCL_BREAK:
3228 /*
3229 * Force loop termination by calling Tcl_DictObjDone; this
3230 * makes the next Tcl_DictObjNext say there is nothing more to
3231 * do.
3232 */
3233
3234 Tcl_ResetResult(interp);
3235 Tcl_DictObjDone(&search);
3236 /* FALLTHRU */
3237 case TCL_CONTINUE:
3238 result = TCL_OK;
3239 break;
3240 case TCL_ERROR:
3241 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
3242 "\n (\"dict filter\" script line %d)",
3243 Tcl_GetErrorLine(interp)));
3244 default:
3245 goto abnormalResult;
3246 }
3247
3248 TclDecrRefCount(keyObj);
3249 TclDecrRefCount(valueObj);
3250
3251 Tcl_DictObjNext(&search, &keyObj, &valueObj, &done);
3252 }
3253
3254 /*
3255 * Stop holding a reference to these objects.
3256 */
3257
3258 TclDecrRefCount(keyVarObj);
3259 TclDecrRefCount(valueVarObj);
3260 TclDecrRefCount(scriptObj);
3261 Tcl_DictObjDone(&search);
3262
3263 if (result == TCL_OK) {
3264 Tcl_SetObjResult(interp, resultObj);
3265 } else {
3266 TclDecrRefCount(resultObj);
3267 }
3268 return result;
3269
3270 abnormalResult:
3271 Tcl_DictObjDone(&search);
3272 TclDecrRefCount(keyObj);
3273 TclDecrRefCount(valueObj);
3274 TclDecrRefCount(keyVarObj);
3275 TclDecrRefCount(valueVarObj);
3276 TclDecrRefCount(scriptObj);
3277 TclDecrRefCount(resultObj);
3278 return result;
3279 }
3280 Tcl_Panic("unexpected fallthrough");
3281 /* Control never reaches this point. */
3282 return TCL_ERROR;
3283 }
3284
3285 /*
3286 *----------------------------------------------------------------------
3287 *
3288 * DictUpdateCmd --
3289 *
3290 * This function implements the "dict update" Tcl command. See the user
3291 * documentation for details on what it does, and TIP#212 for the formal
3292 * specification.
3293 *
3294 * Results:
3295 * A standard Tcl result.
3296 *
3297 * Side effects:
3298 * See the user documentation.
3299 *
3300 *----------------------------------------------------------------------
3301 */
3302
3303 static int
3304 DictUpdateCmd(
3305 ClientData clientData,
3306 Tcl_Interp *interp,
3307 int objc,
3308 Tcl_Obj *const *objv)
3309 {
3310 Interp *iPtr = (Interp *) interp;
3311 Tcl_Obj *dictPtr, *objPtr;
3312 int i, dummy;
3313
3314 if (objc < 5 || !(objc & 1)) {
3315 Tcl_WrongNumArgs(interp, 1, objv,
3316 "dictVarName key varName ?key varName ...? script");
3317 return TCL_ERROR;
3318 }
3319
3320 dictPtr = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG);
3321 if (dictPtr == NULL) {
3322 return TCL_ERROR;
3323 }
3324 if (Tcl_DictObjSize(interp, dictPtr, &dummy) != TCL_OK) {
3325 return TCL_ERROR;
3326 }
3327 Tcl_IncrRefCount(dictPtr);
3328 for (i=2 ; i+2<objc ; i+=2) {
3329 if (Tcl_DictObjGet(interp, dictPtr, objv[i], &objPtr) != TCL_OK) {
3330 TclDecrRefCount(dictPtr);
3331 return TCL_ERROR;
3332 }
3333 if (objPtr == NULL) {
3334 /* ??? */
3335 Tcl_UnsetVar(interp, Tcl_GetString(objv[i+1]), 0);
3336 } else if (Tcl_ObjSetVar2(interp, objv[i+1], NULL, objPtr,
3337 TCL_LEAVE_ERR_MSG) == NULL) {
3338 TclDecrRefCount(dictPtr);
3339 return TCL_ERROR;
3340 }
3341 }
3342 TclDecrRefCount(dictPtr);
3343
3344 /*
3345 * Execute the body after setting up the NRE handler to process the
3346 * results.
3347 */
3348
3349 objPtr = Tcl_NewListObj(objc-3, objv+2);
3350 Tcl_IncrRefCount(objPtr);
3351 Tcl_IncrRefCount(objv[1]);
3352 TclNRAddCallback(interp, FinalizeDictUpdate, objv[1], objPtr, NULL,NULL);
3353
3354 return TclNREvalObjEx(interp, objv[objc-1], 0, iPtr->cmdFramePtr, objc-1);
3355 }
3356
3357 static int
3358 FinalizeDictUpdate(
3359 ClientData data[],
3360 Tcl_Interp *interp,
3361 int result)
3362 {
3363 Tcl_Obj *dictPtr, *objPtr, **objv;
3364 Tcl_InterpState state;
3365 int i, objc;
3366 Tcl_Obj *varName = (Tcl_Obj *)data[0];
3367 Tcl_Obj *argsObj = (Tcl_Obj *)data[1];
3368
3369 /*
3370 * ErrorInfo handling.
3371 */
3372
3373 if (result == TCL_ERROR) {
3374 Tcl_AddErrorInfo(interp, "\n (body of \"dict update\")");
3375 }
3376
3377 /*
3378 * If the dictionary variable doesn't exist, drop everything silently.
3379 */
3380
3381 dictPtr = Tcl_ObjGetVar2(interp, varName, NULL, 0);
3382 if (dictPtr == NULL) {
3383 TclDecrRefCount(varName);
3384 TclDecrRefCount(argsObj);
3385 return result;
3386 }
3387
3388 /*
3389 * Double-check that it is still a dictionary.
3390 */
3391
3392 state = Tcl_SaveInterpState(interp, result);
3393 if (Tcl_DictObjSize(interp, dictPtr, &objc) != TCL_OK) {
3394 Tcl_DiscardInterpState(state);
3395 TclDecrRefCount(varName);
3396 TclDecrRefCount(argsObj);
3397 return TCL_ERROR;
3398 }
3399
3400 if (Tcl_IsShared(dictPtr)) {
3401 dictPtr = Tcl_DuplicateObj(dictPtr);
3402 }
3403
3404 /*
3405 * Write back the values from the variables, treating failure to read as
3406 * an instruction to remove the key.
3407 */
3408
3409 TclListObjGetElements(NULL, argsObj, &objc, &objv);
3410 for (i=0 ; i<objc ; i+=2) {
3411 objPtr = Tcl_ObjGetVar2(interp, objv[i+1], NULL, 0);
3412 if (objPtr == NULL) {
3413 Tcl_DictObjRemove(NULL, dictPtr, objv[i]);
3414 } else if (objPtr == dictPtr) {
3415 /*
3416 * Someone is messing us around, trying to build a recursive
3417 * structure. [Bug 1786481]
3418 */
3419
3420 Tcl_DictObjPut(NULL, dictPtr, objv[i], Tcl_DuplicateObj(objPtr));
3421 } else {
3422 /* Shouldn't fail */
3423 Tcl_DictObjPut(NULL, dictPtr, objv[i], objPtr);
3424 }
3425 }
3426 TclDecrRefCount(argsObj);
3427
3428 /*
3429 * Write the dictionary back to its variable.
3430 */
3431
3432 if (Tcl_ObjSetVar2(interp, varName, NULL, dictPtr,
3433 TCL_LEAVE_ERR_MSG) == NULL) {
3434 Tcl_DiscardInterpState(state);
3435 TclDecrRefCount(varName);
3436 return TCL_ERROR;
3437 }
3438
3439 TclDecrRefCount(varName);
3440 return Tcl_RestoreInterpState(interp, state);
3441 }
3442
3443 /*
3444 *----------------------------------------------------------------------
3445 *
3446 * DictWithCmd --
3447 *
3448 * This function implements the "dict with" Tcl command. See the user
3449 * documentation for details on what it does, and TIP#212 for the formal
3450 * specification.
3451 *
3452 * Results:
3453 * A standard Tcl result.
3454 *
3455 * Side effects:
3456 * See the user documentation.
3457 *
3458 *----------------------------------------------------------------------
3459 */
3460
3461 static int
3462 DictWithCmd(
3463 ClientData dummy,
3464 Tcl_Interp *interp,
3465 int objc,
3466 Tcl_Obj *const *objv)
3467 {
3468 Interp *iPtr = (Interp *) interp;
3469 Tcl_Obj *dictPtr, *keysPtr, *pathPtr;
3470
3471 if (objc < 3) {
3472 Tcl_WrongNumArgs(interp, 1, objv, "dictVarName ?key ...? script");
3473 return TCL_ERROR;
3474 }
3475
3476 /*
3477 * Get the dictionary to open out.
3478 */
3479
3480 dictPtr = Tcl_ObjGetVar2(interp, objv[1], NULL, TCL_LEAVE_ERR_MSG);
3481 if (dictPtr == NULL) {
3482 return TCL_ERROR;
3483 }
3484
3485 keysPtr = TclDictWithInit(interp, dictPtr, objc-3, objv+2);
3486 if (keysPtr == NULL) {
3487 return TCL_ERROR;
3488 }
3489 Tcl_IncrRefCount(keysPtr);
3490
3491 /*
3492 * Execute the body, while making the invoking context available to the
3493 * loop body (TIP#280) and postponing the cleanup until later (NRE).
3494 */
3495
3496 pathPtr = NULL;
3497 if (objc > 3) {
3498 pathPtr = Tcl_NewListObj(objc-3, objv+2);
3499 Tcl_IncrRefCount(pathPtr);
3500 }
3501 Tcl_IncrRefCount(objv[1]);
3502 TclNRAddCallback(interp, FinalizeDictWith, objv[1], keysPtr, pathPtr,
3503 NULL);
3504
3505 return TclNREvalObjEx(interp, objv[objc-1], 0, iPtr->cmdFramePtr, objc-1);
3506 }
3507
3508 static int
3509 FinalizeDictWith(
3510 ClientData data[],
3511 Tcl_Interp *interp,
3512 int result)
3513 {
3514 Tcl_Obj **pathv;
3515 int pathc;
3516 Tcl_InterpState state;
3517 Tcl_Obj *varName = (Tcl_Obj *)data[0];
3518 Tcl_Obj *keysPtr = (Tcl_Obj *)data[1];
3519 Tcl_Obj *pathPtr = (Tcl_Obj *)data[2];
3520 Var *varPtr, *arrayPtr;
3521
3522 if (result == TCL_ERROR) {
3523 Tcl_AddErrorInfo(interp, "\n (body of \"dict with\")");
3524 }
3525
3526 /*
3527 * Save the result state; TDWF doesn't guarantee to not modify that on
3528 * TCL_OK result.
3529 */
3530
3531 state = Tcl_SaveInterpState(interp, result);
3532 if (pathPtr != NULL) {
3533 TclListObjGetElements(NULL, pathPtr, &pathc, &pathv);
3534 } else {
3535 pathc = 0;
3536 pathv = NULL;
3537 }
3538
3539 /*
3540 * Pack from local variables back into the dictionary.
3541 */
3542
3543 varPtr = TclObjLookupVarEx(interp, varName, NULL, TCL_LEAVE_ERR_MSG, "set",
3544 /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr);
3545 if (varPtr == NULL) {
3546 result = TCL_ERROR;
3547 } else {
3548 result = TclDictWithFinish(interp, varPtr, arrayPtr, varName, NULL, -1,
3549 pathc, pathv, keysPtr);
3550 }
3551
3552 /*
3553 * Tidy up and return the real result (unless we had an error).
3554 */
3555
3556 TclDecrRefCount(varName);
3557 TclDecrRefCount(keysPtr);
3558 if (pathPtr != NULL) {
3559 TclDecrRefCount(pathPtr);
3560 }
3561 if (result != TCL_OK) {
3562 Tcl_DiscardInterpState(state);
3563 return TCL_ERROR;
3564 }
3565 return Tcl_RestoreInterpState(interp, state);
3566 }
3567
3568 /*
3569 *----------------------------------------------------------------------
3570 *
3571 * TclDictWithInit --
3572 *
3573 * Part of the core of [dict with]. Pokes into a dictionary and converts
3574 * the mappings there into assignments to (presumably) local variables.
3575 * Returns a list of all the names that were mapped so that removal of
3576 * either the variable or the dictionary entry won't surprise us when we
3577 * come to stuffing everything back.
3578 *
3579 * Result:
3580 * List of mapped names, or NULL if there was an error.
3581 *
3582 * Side effects:
3583 * Assigns to variables, so potentially legion due to traces.
3584 *
3585 *----------------------------------------------------------------------
3586 */
3587
3588 Tcl_Obj *
3589 TclDictWithInit(
3590 Tcl_Interp *interp,
3591 Tcl_Obj *dictPtr,
3592 int pathc,
3593 Tcl_Obj *const pathv[])
3594 {
3595 Tcl_DictSearch s;
3596 Tcl_Obj *keyPtr, *valPtr, *keysPtr;
3597 int done;
3598
3599 if (pathc > 0) {
3600 dictPtr = TclTraceDictPath(interp, dictPtr, pathc, pathv,
3601 DICT_PATH_READ);
3602 if (dictPtr == NULL) {
3603 return NULL;
3604 }
3605 }
3606
3607 /*
3608 * Go over the list of keys and write each corresponding value to a
3609 * variable in the current context with the same name. Also keep a copy of
3610 * the keys so we can write back properly later on even if the dictionary
3611 * has been structurally modified.
3612 */
3613
3614 if (Tcl_DictObjFirst(interp, dictPtr, &s, &keyPtr, &valPtr,
3615 &done) != TCL_OK) {
3616 return NULL;
3617 }
3618
3619 TclNewObj(keysPtr);
3620
3621 for (; !done ; Tcl_DictObjNext(&s, &keyPtr, &valPtr, &done)) {
3622 Tcl_ListObjAppendElement(NULL, keysPtr, keyPtr);
3623 if (Tcl_ObjSetVar2(interp, keyPtr, NULL, valPtr,
3624 TCL_LEAVE_ERR_MSG) == NULL) {
3625 TclDecrRefCount(keysPtr);
3626 Tcl_DictObjDone(&s);
3627 return NULL;
3628 }
3629 }
3630
3631 return keysPtr;
3632 }
3633
3634 /*
3635 *----------------------------------------------------------------------
3636 *
3637 * TclDictWithFinish --
3638 *
3639 * Part of the core of [dict with]. Reassembles the piece of the dict (in
3640 * varName, location given by pathc/pathv) from the variables named in
3641 * the keysPtr argument. NB, does not try to preserve errors or manage
3642 * argument lifetimes.
3643 *
3644 * Result:
3645 * TCL_OK if we succeeded, or TCL_ERROR if we failed.
3646 *
3647 * Side effects:
3648 * Assigns to a variable, so potentially legion due to traces. Updates
3649 * the dictionary in the named variable.
3650 *
3651 *----------------------------------------------------------------------
3652 */
3653
3654 int
3655 TclDictWithFinish(
3656 Tcl_Interp *interp, /* Command interpreter in which variable
3657 * exists. Used for state management, traces
3658 * and error reporting. */
3659 Var *varPtr, /* Reference to the variable holding the
3660 * dictionary. */
3661 Var *arrayPtr, /* Reference to the array containing the
3662 * variable, or NULL if the variable is a
3663 * scalar. */
3664 Tcl_Obj *part1Ptr, /* Name of an array (if part2 is non-NULL) or
3665 * the name of a variable. NULL if the 'index'
3666 * parameter is >= 0 */
3667 Tcl_Obj *part2Ptr, /* If non-NULL, gives the name of an element
3668 * in the array part1. */
3669 int index, /* Index into the local variable table of the
3670 * variable, or -1. Only used when part1Ptr is
3671 * NULL. */
3672 int pathc, /* The number of elements in the path into the
3673 * dictionary. */
3674 Tcl_Obj *const pathv[], /* The elements of the path to the subdict. */
3675 Tcl_Obj *keysPtr) /* List of keys to be synchronized. This is
3676 * the result value from TclDictWithInit. */
3677 {
3678 Tcl_Obj *dictPtr, *leafPtr, *valPtr;
3679 int i, allocdict, keyc;
3680 Tcl_Obj **keyv;
3681
3682 /*
3683 * If the dictionary variable doesn't exist, drop everything silently.
3684 */
3685
3686 dictPtr = TclPtrGetVarIdx(interp, varPtr, arrayPtr, part1Ptr, part2Ptr,
3687 TCL_LEAVE_ERR_MSG, index);
3688 if (dictPtr == NULL) {
3689 return TCL_OK;
3690 }
3691
3692 /*
3693 * Double-check that it is still a dictionary.
3694 */
3695
3696 if (Tcl_DictObjSize(interp, dictPtr, &i) != TCL_OK) {
3697 return TCL_ERROR;
3698 }
3699
3700 if (Tcl_IsShared(dictPtr)) {
3701 dictPtr = Tcl_DuplicateObj(dictPtr);
3702 allocdict = 1;
3703 } else {
3704 allocdict = 0;
3705 }
3706
3707 if (pathc > 0) {
3708 /*
3709 * Want to get to the dictionary which we will update; need to do
3710 * prepare-for-update unsharing along the path *but* avoid generating
3711 * an error on a non-extant path (we'll treat that the same as a
3712 * non-extant variable. Luckily, the unsharing operation isn't
3713 * deeply damaging if we don't go on to update; it's just less than
3714 * perfectly efficient (but no memory should be leaked).
3715 */
3716
3717 leafPtr = TclTraceDictPath(interp, dictPtr, pathc, pathv,
3718 DICT_PATH_EXISTS | DICT_PATH_UPDATE);
3719 if (leafPtr == NULL) {
3720 if (allocdict) {
3721 TclDecrRefCount(dictPtr);
3722 }
3723 return TCL_ERROR;
3724 }
3725 if (leafPtr == DICT_PATH_NON_EXISTENT) {
3726 if (allocdict) {
3727 TclDecrRefCount(dictPtr);
3728 }
3729 return TCL_OK;
3730 }
3731 } else {
3732 leafPtr = dictPtr;
3733 }
3734
3735 /*
3736 * Now process our updates on the leaf dictionary.
3737 */
3738
3739 TclListObjGetElements(NULL, keysPtr, &keyc, &keyv);
3740 for (i=0 ; i<keyc ; i++) {
3741 valPtr = Tcl_ObjGetVar2(interp, keyv[i], NULL, 0);
3742 if (valPtr == NULL) {
3743 Tcl_DictObjRemove(NULL, leafPtr, keyv[i]);
3744 } else if (leafPtr == valPtr) {
3745 /*
3746 * Someone is messing us around, trying to build a recursive
3747 * structure. [Bug 1786481]
3748 */
3749
3750 Tcl_DictObjPut(NULL, leafPtr, keyv[i], Tcl_DuplicateObj(valPtr));
3751 } else {
3752 Tcl_DictObjPut(NULL, leafPtr, keyv[i], valPtr);
3753 }
3754 }
3755
3756 /*
3757 * Ensure that none of the dictionaries in the chain still have a string
3758 * rep.
3759 */
3760
3761 if (pathc > 0) {
3762 InvalidateDictChain(leafPtr);
3763 }
3764
3765 /*
3766 * Write back the outermost dictionary to the variable.
3767 */
3768
3769 if (TclPtrSetVarIdx(interp, varPtr, arrayPtr, part1Ptr, part2Ptr,
3770 dictPtr, TCL_LEAVE_ERR_MSG, index) == NULL) {
3771 if (allocdict) {
3772 TclDecrRefCount(dictPtr);
3773 }
3774 return TCL_ERROR;
3775 }
3776 return TCL_OK;
3777 }
3778
3779 /*
3780 *----------------------------------------------------------------------
3781 *
3782 * TclInitDictCmd --
3783 *
3784 * This function is create the "dict" Tcl command. See the user
3785 * documentation for details on what it does, and TIP#111 for the formal
3786 * specification.
3787 *
3788 * Results:
3789 * A Tcl command handle.
3790 *
3791 * Side effects:
3792 * May advance compilation epoch.
3793 *
3794 *----------------------------------------------------------------------
3795 */
3796
3797 Tcl_Command
3798 TclInitDictCmd(
3799 Tcl_Interp *interp)
3800 {
3801 return TclMakeEnsemble(interp, "dict", implementationMap);
3802 }
3803
3804 /*
3805 * Local Variables:
3806 * mode: c
3807 * c-basic-offset: 4
3808 * fill-column: 78
3809 * End:
3810 */