Debian Codegraph @

generic/tclEnsemble.c

raw
1 /*
2 * tclEnsemble.c --
3 *
4 * Contains support for ensembles (see TIP#112), which provide simple
5 * mechanism for creating composite commands on top of namespaces.
6 *
7 * Copyright (c) 2005-2013 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 "tclCompile.h"
15
16 /*
17 * Declarations for functions local to this file:
18 */
19
20 static inline Tcl_Obj * NewNsObj(Tcl_Namespace *namespacePtr);
21 static inline int EnsembleUnknownCallback(Tcl_Interp *interp,
22 EnsembleConfig *ensemblePtr, int objc,
23 Tcl_Obj *const objv[], Tcl_Obj **prefixObjPtr);
24 static int NsEnsembleImplementationCmd(ClientData clientData,
25 Tcl_Interp *interp,int objc,Tcl_Obj *const objv[]);
26 static int NsEnsembleImplementationCmdNR(ClientData clientData,
27 Tcl_Interp *interp,int objc,Tcl_Obj *const objv[]);
28 static void BuildEnsembleConfig(EnsembleConfig *ensemblePtr);
29 static int NsEnsembleStringOrder(const void *strPtr1,
30 const void *strPtr2);
31 static void DeleteEnsembleConfig(ClientData clientData);
32 static void MakeCachedEnsembleCommand(Tcl_Obj *objPtr,
33 EnsembleConfig *ensemblePtr, Tcl_HashEntry *hPtr,
34 Tcl_Obj *fix);
35 static void FreeEnsembleCmdRep(Tcl_Obj *objPtr);
36 static void DupEnsembleCmdRep(Tcl_Obj *objPtr, Tcl_Obj *copyPtr);
37 static void CompileToInvokedCommand(Tcl_Interp *interp,
38 Tcl_Parse *parsePtr, Tcl_Obj *replacements,
39 Command *cmdPtr, CompileEnv *envPtr);
40 static int CompileBasicNArgCommand(Tcl_Interp *interp,
41 Tcl_Parse *parsePtr, Command *cmdPtr,
42 CompileEnv *envPtr);
43
44 static Tcl_NRPostProc FreeER;
45
46 /*
47 * The lists of subcommands and options for the [namespace ensemble] command.
48 */
49
50 static const char *const ensembleSubcommands[] = {
51 "configure", "create", "exists", NULL
52 };
53 enum EnsSubcmds {
54 ENS_CONFIG, ENS_CREATE, ENS_EXISTS
55 };
56
57 static const char *const ensembleCreateOptions[] = {
58 "-command", "-map", "-parameters", "-prefixes", "-subcommands",
59 "-unknown", NULL
60 };
61 enum EnsCreateOpts {
62 CRT_CMD, CRT_MAP, CRT_PARAM, CRT_PREFIX, CRT_SUBCMDS, CRT_UNKNOWN
63 };
64
65 static const char *const ensembleConfigOptions[] = {
66 "-map", "-namespace", "-parameters", "-prefixes", "-subcommands",
67 "-unknown", NULL
68 };
69 enum EnsConfigOpts {
70 CONF_MAP, CONF_NAMESPACE, CONF_PARAM, CONF_PREFIX, CONF_SUBCMDS,
71 CONF_UNKNOWN
72 };
73
74 /*
75 * ensembleCmdType is a Tcl object type that contains a reference to an
76 * ensemble subcommand, e.g. the "length" in [string length ab]. It is used
77 * to cache the mapping between the subcommand itself and the real command
78 * that implements it.
79 */
80
81 static const Tcl_ObjType ensembleCmdType = {
82 "ensembleCommand", /* the type's name */
83 FreeEnsembleCmdRep, /* freeIntRepProc */
84 DupEnsembleCmdRep, /* dupIntRepProc */
85 NULL, /* updateStringProc */
86 NULL /* setFromAnyProc */
87 };
88
89 /*
90 * The internal rep for caching ensemble subcommand lookups and spelling
91 * corrections.
92 */
93
94 typedef struct {
95 int epoch; /* Used to confirm when the data in this
96 * really structure matches up with the
97 * ensemble. */
98 Command *token; /* Reference to the command for which this
99 * structure is a cache of the resolution. */
100 Tcl_Obj *fix; /* Corrected spelling, if needed. */
101 Tcl_HashEntry *hPtr; /* Direct link to entry in the subcommand hash
102 * table. */
103 } EnsembleCmdRep;
104
105 static inline Tcl_Obj *
106 NewNsObj(
107 Tcl_Namespace *namespacePtr)
108 {
109 Namespace *nsPtr = (Namespace *) namespacePtr;
110
111 if (namespacePtr == TclGetGlobalNamespace(nsPtr->interp)) {
112 return Tcl_NewStringObj("::", 2);
113 }
114 return Tcl_NewStringObj(nsPtr->fullName, -1);
115 }
116
117 /*
118 *----------------------------------------------------------------------
119 *
120 * TclNamespaceEnsembleCmd --
121 *
122 * Invoked to implement the "namespace ensemble" command that creates and
123 * manipulates ensembles built on top of namespaces. Handles the
124 * following syntax:
125 *
126 * namespace ensemble name ?dictionary?
127 *
128 * Results:
129 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
130 *
131 * Side effects:
132 * Creates the ensemble for the namespace if one did not previously
133 * exist. Alternatively, alters the way that the ensemble's subcommand =>
134 * implementation prefix is configured.
135 *
136 *----------------------------------------------------------------------
137 */
138
139 int
140 TclNamespaceEnsembleCmd(
141 ClientData dummy,
142 Tcl_Interp *interp,
143 int objc,
144 Tcl_Obj *const objv[])
145 {
146 Tcl_Namespace *namespacePtr;
147 Namespace *nsPtr = (Namespace *) TclGetCurrentNamespace(interp), *cxtPtr,
148 *foundNsPtr, *altFoundNsPtr, *actualCxtPtr;
149 Tcl_Command token;
150 Tcl_DictSearch search;
151 Tcl_Obj *listObj;
152 const char *simpleName;
153 int index;
154 int done;
155
156 if (nsPtr == NULL || nsPtr->flags & NS_DYING) {
157 if (!Tcl_InterpDeleted(interp)) {
158 Tcl_SetObjResult(interp, Tcl_NewStringObj(
159 "tried to manipulate ensemble of deleted namespace",
160 -1));
161 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "DEAD", (char *)NULL);
162 }
163 return TCL_ERROR;
164 }
165
166 if (objc < 2) {
167 Tcl_WrongNumArgs(interp, 1, objv, "subcommand ?arg ...?");
168 return TCL_ERROR;
169 }
170 if (Tcl_GetIndexFromObj(interp, objv[1], ensembleSubcommands,
171 "subcommand", 0, &index) != TCL_OK) {
172 return TCL_ERROR;
173 }
174
175 switch ((enum EnsSubcmds) index) {
176 case ENS_CREATE: {
177 const char *name;
178 int len;
179 int allocatedMapFlag = 0;
180 /*
181 * Defaults
182 */
183 Tcl_Obj *subcmdObj = NULL;
184 Tcl_Obj *mapObj = NULL;
185 int permitPrefix = 1;
186 Tcl_Obj *unknownObj = NULL;
187 Tcl_Obj *paramObj = NULL;
188
189 /*
190 * Check that we've got option-value pairs... [Bug 1558654]
191 */
192
193 if (objc & 1) {
194 Tcl_WrongNumArgs(interp, 2, objv, "?option value ...?");
195 return TCL_ERROR;
196 }
197 objv += 2;
198 objc -= 2;
199
200 name = nsPtr->name;
201 cxtPtr = (Namespace *) nsPtr->parentPtr;
202
203 /*
204 * Parse the option list, applying type checks as we go. Note that we
205 * are not incrementing any reference counts in the objects at this
206 * stage, so the presence of an option multiple times won't cause any
207 * memory leaks.
208 */
209
210 for (; objc>1 ; objc-=2,objv+=2) {
211 if (Tcl_GetIndexFromObj(interp, objv[0], ensembleCreateOptions,
212 "option", 0, &index) != TCL_OK) {
213 if (allocatedMapFlag) {
214 Tcl_DecrRefCount(mapObj);
215 }
216 return TCL_ERROR;
217 }
218 switch ((enum EnsCreateOpts) index) {
219 case CRT_CMD:
220 name = TclGetString(objv[1]);
221 cxtPtr = nsPtr;
222 continue;
223 case CRT_SUBCMDS:
224 if (TclListObjLength(interp, objv[1], &len) != TCL_OK) {
225 if (allocatedMapFlag) {
226 Tcl_DecrRefCount(mapObj);
227 }
228 return TCL_ERROR;
229 }
230 subcmdObj = (len > 0 ? objv[1] : NULL);
231 continue;
232 case CRT_PARAM:
233 if (TclListObjLength(interp, objv[1], &len) != TCL_OK) {
234 if (allocatedMapFlag) {
235 Tcl_DecrRefCount(mapObj);
236 }
237 return TCL_ERROR;
238 }
239 paramObj = (len > 0 ? objv[1] : NULL);
240 continue;
241 case CRT_MAP: {
242 Tcl_Obj *patchedDict = NULL, *subcmdWordsObj;
243
244 /*
245 * Verify that the map is sensible.
246 */
247
248 if (Tcl_DictObjFirst(interp, objv[1], &search,
249 &subcmdWordsObj, &listObj, &done) != TCL_OK) {
250 if (allocatedMapFlag) {
251 Tcl_DecrRefCount(mapObj);
252 }
253 return TCL_ERROR;
254 }
255 if (done) {
256 mapObj = NULL;
257 continue;
258 }
259 do {
260 Tcl_Obj **listv;
261 const char *cmd;
262
263 if (TclListObjGetElements(interp, listObj, &len,
264 &listv) != TCL_OK) {
265 Tcl_DictObjDone(&search);
266 if (patchedDict) {
267 Tcl_DecrRefCount(patchedDict);
268 }
269 if (allocatedMapFlag) {
270 Tcl_DecrRefCount(mapObj);
271 }
272 return TCL_ERROR;
273 }
274 if (len < 1) {
275 Tcl_SetObjResult(interp, Tcl_NewStringObj(
276 "ensemble subcommand implementations "
277 "must be non-empty lists", -1));
278 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE",
279 "EMPTY_TARGET", (char *)NULL);
280 Tcl_DictObjDone(&search);
281 if (patchedDict) {
282 Tcl_DecrRefCount(patchedDict);
283 }
284 if (allocatedMapFlag) {
285 Tcl_DecrRefCount(mapObj);
286 }
287 return TCL_ERROR;
288 }
289 cmd = TclGetString(listv[0]);
290 if (!(cmd[0] == ':' && cmd[1] == ':')) {
291 Tcl_Obj *newList = Tcl_NewListObj(len, listv);
292 Tcl_Obj *newCmd = NewNsObj((Tcl_Namespace *) nsPtr);
293
294 if (nsPtr->parentPtr) {
295 Tcl_AppendStringsToObj(newCmd, "::", (char *)NULL);
296 }
297 Tcl_AppendObjToObj(newCmd, listv[0]);
298 Tcl_ListObjReplace(NULL, newList, 0, 1, 1, &newCmd);
299 if (patchedDict == NULL) {
300 patchedDict = Tcl_DuplicateObj(objv[1]);
301 }
302 Tcl_DictObjPut(NULL, patchedDict, subcmdWordsObj,
303 newList);
304 }
305 Tcl_DictObjNext(&search, &subcmdWordsObj, &listObj, &done);
306 } while (!done);
307
308 if (allocatedMapFlag) {
309 Tcl_DecrRefCount(mapObj);
310 }
311 mapObj = (patchedDict ? patchedDict : objv[1]);
312 if (patchedDict) {
313 allocatedMapFlag = 1;
314 }
315 continue;
316 }
317 case CRT_PREFIX: {
318 if (Tcl_GetBooleanFromObj(interp, objv[1],
319 &permitPrefix) != TCL_OK) {
320 if (allocatedMapFlag) {
321 Tcl_DecrRefCount(mapObj);
322 }
323 return TCL_ERROR;
324 }
325 continue;
326 }
327 case CRT_UNKNOWN:
328 if (TclListObjLength(interp, objv[1], &len) != TCL_OK) {
329 if (allocatedMapFlag) {
330 Tcl_DecrRefCount(mapObj);
331 }
332 return TCL_ERROR;
333 }
334 unknownObj = (len > 0 ? objv[1] : NULL);
335 continue;
336 }
337 }
338
339 TclGetNamespaceForQualName(interp, name, cxtPtr,
340 TCL_CREATE_NS_IF_UNKNOWN, &foundNsPtr, &altFoundNsPtr,
341 &actualCxtPtr, &simpleName);
342
343 /*
344 * Create the ensemble. Note that this might delete another ensemble
345 * linked to the same namespace, so we must be careful. However, we
346 * should be OK because we only link the namespace into the list once
347 * we've created it (and after any deletions have occurred.)
348 */
349
350 token = TclCreateEnsembleInNs(interp, simpleName,
351 (Tcl_Namespace *) foundNsPtr, (Tcl_Namespace *) nsPtr,
352 (permitPrefix ? TCL_ENSEMBLE_PREFIX : 0));
353 Tcl_SetEnsembleSubcommandList(interp, token, subcmdObj);
354 Tcl_SetEnsembleMappingDict(interp, token, mapObj);
355 Tcl_SetEnsembleUnknownHandler(interp, token, unknownObj);
356 Tcl_SetEnsembleParameterList(interp, token, paramObj);
357
358 /*
359 * Tricky! Must ensure that the result is not shared (command delete
360 * traces could have corrupted the pristine object that we started
361 * with). [Snit test rename-1.5]
362 */
363
364 Tcl_ResetResult(interp);
365 Tcl_GetCommandFullName(interp, token, Tcl_GetObjResult(interp));
366 return TCL_OK;
367 }
368
369 case ENS_EXISTS:
370 if (objc != 3) {
371 Tcl_WrongNumArgs(interp, 2, objv, "cmdname");
372 return TCL_ERROR;
373 }
374 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(
375 Tcl_FindEnsemble(interp, objv[2], 0) != NULL));
376 return TCL_OK;
377
378 case ENS_CONFIG:
379 if (objc < 3 || (objc != 4 && !(objc & 1))) {
380 Tcl_WrongNumArgs(interp, 2, objv,
381 "cmdname ?-option value ...? ?arg ...?");
382 return TCL_ERROR;
383 }
384 token = Tcl_FindEnsemble(interp, objv[2], TCL_LEAVE_ERR_MSG);
385 if (token == NULL) {
386 return TCL_ERROR;
387 }
388
389 if (objc == 4) {
390 Tcl_Obj *resultObj = NULL; /* silence gcc 4 warning */
391
392 if (Tcl_GetIndexFromObj(interp, objv[3], ensembleConfigOptions,
393 "option", 0, &index) != TCL_OK) {
394 return TCL_ERROR;
395 }
396 switch ((enum EnsConfigOpts) index) {
397 case CONF_SUBCMDS:
398 Tcl_GetEnsembleSubcommandList(NULL, token, &resultObj);
399 if (resultObj != NULL) {
400 Tcl_SetObjResult(interp, resultObj);
401 }
402 break;
403 case CONF_PARAM:
404 Tcl_GetEnsembleParameterList(NULL, token, &resultObj);
405 if (resultObj != NULL) {
406 Tcl_SetObjResult(interp, resultObj);
407 }
408 break;
409 case CONF_MAP:
410 Tcl_GetEnsembleMappingDict(NULL, token, &resultObj);
411 if (resultObj != NULL) {
412 Tcl_SetObjResult(interp, resultObj);
413 }
414 break;
415 case CONF_NAMESPACE:
416 namespacePtr = NULL; /* silence gcc 4 warning */
417 Tcl_GetEnsembleNamespace(NULL, token, &namespacePtr);
418 Tcl_SetObjResult(interp, NewNsObj(namespacePtr));
419 break;
420 case CONF_PREFIX: {
421 int flags = 0; /* silence gcc 4 warning */
422
423 Tcl_GetEnsembleFlags(NULL, token, &flags);
424 Tcl_SetObjResult(interp,
425 Tcl_NewBooleanObj(flags & TCL_ENSEMBLE_PREFIX));
426 break;
427 }
428 case CONF_UNKNOWN:
429 Tcl_GetEnsembleUnknownHandler(NULL, token, &resultObj);
430 if (resultObj != NULL) {
431 Tcl_SetObjResult(interp, resultObj);
432 }
433 break;
434 }
435 } else if (objc == 3) {
436 /*
437 * Produce list of all information.
438 */
439
440 Tcl_Obj *resultObj, *tmpObj = NULL; /* silence gcc 4 warning */
441 int flags = 0; /* silence gcc 4 warning */
442
443 TclNewObj(resultObj);
444
445 /* -map option */
446 Tcl_ListObjAppendElement(NULL, resultObj,
447 Tcl_NewStringObj(ensembleConfigOptions[CONF_MAP], -1));
448 Tcl_GetEnsembleMappingDict(NULL, token, &tmpObj);
449 Tcl_ListObjAppendElement(NULL, resultObj,
450 (tmpObj != NULL) ? tmpObj : Tcl_NewObj());
451
452 /* -namespace option */
453 Tcl_ListObjAppendElement(NULL, resultObj,
454 Tcl_NewStringObj(ensembleConfigOptions[CONF_NAMESPACE],
455 -1));
456 namespacePtr = NULL; /* silence gcc 4 warning */
457 Tcl_GetEnsembleNamespace(NULL, token, &namespacePtr);
458 Tcl_ListObjAppendElement(NULL, resultObj, NewNsObj(namespacePtr));
459
460 /* -parameters option */
461 Tcl_ListObjAppendElement(NULL, resultObj,
462 Tcl_NewStringObj(ensembleConfigOptions[CONF_PARAM], -1));
463 Tcl_GetEnsembleParameterList(NULL, token, &tmpObj);
464 Tcl_ListObjAppendElement(NULL, resultObj,
465 (tmpObj != NULL) ? tmpObj : Tcl_NewObj());
466
467 /* -prefix option */
468 Tcl_ListObjAppendElement(NULL, resultObj,
469 Tcl_NewStringObj(ensembleConfigOptions[CONF_PREFIX], -1));
470 Tcl_GetEnsembleFlags(NULL, token, &flags);
471 Tcl_ListObjAppendElement(NULL, resultObj,
472 Tcl_NewBooleanObj(flags & TCL_ENSEMBLE_PREFIX));
473
474 /* -subcommands option */
475 Tcl_ListObjAppendElement(NULL, resultObj,
476 Tcl_NewStringObj(ensembleConfigOptions[CONF_SUBCMDS],-1));
477 Tcl_GetEnsembleSubcommandList(NULL, token, &tmpObj);
478 Tcl_ListObjAppendElement(NULL, resultObj,
479 (tmpObj != NULL) ? tmpObj : Tcl_NewObj());
480
481 /* -unknown option */
482 Tcl_ListObjAppendElement(NULL, resultObj,
483 Tcl_NewStringObj(ensembleConfigOptions[CONF_UNKNOWN],-1));
484 Tcl_GetEnsembleUnknownHandler(NULL, token, &tmpObj);
485 Tcl_ListObjAppendElement(NULL, resultObj,
486 (tmpObj != NULL) ? tmpObj : Tcl_NewObj());
487
488 Tcl_SetObjResult(interp, resultObj);
489 } else {
490 int len;
491 int allocatedMapFlag = 0;
492 Tcl_Obj *subcmdObj = NULL, *mapObj = NULL, *paramObj = NULL,
493 *unknownObj = NULL; /* Defaults, silence gcc 4 warnings */
494 int permitPrefix, flags = 0; /* silence gcc 4 warning */
495
496 Tcl_GetEnsembleSubcommandList(NULL, token, &subcmdObj);
497 Tcl_GetEnsembleMappingDict(NULL, token, &mapObj);
498 Tcl_GetEnsembleParameterList(NULL, token, &paramObj);
499 Tcl_GetEnsembleUnknownHandler(NULL, token, &unknownObj);
500 Tcl_GetEnsembleFlags(NULL, token, &flags);
501 permitPrefix = (flags & TCL_ENSEMBLE_PREFIX) != 0;
502
503 objv += 3;
504 objc -= 3;
505
506 /*
507 * Parse the option list, applying type checks as we go. Note that
508 * we are not incrementing any reference counts in the objects at
509 * this stage, so the presence of an option multiple times won't
510 * cause any memory leaks.
511 */
512
513 for (; objc>0 ; objc-=2,objv+=2) {
514 if (Tcl_GetIndexFromObj(interp, objv[0],ensembleConfigOptions,
515 "option", 0, &index) != TCL_OK) {
516 freeMapAndError:
517 if (allocatedMapFlag) {
518 Tcl_DecrRefCount(mapObj);
519 }
520 return TCL_ERROR;
521 }
522 switch ((enum EnsConfigOpts) index) {
523 case CONF_SUBCMDS:
524 if (TclListObjLength(interp, objv[1], &len) != TCL_OK) {
525 goto freeMapAndError;
526 }
527 subcmdObj = (len > 0 ? objv[1] : NULL);
528 continue;
529 case CONF_PARAM:
530 if (TclListObjLength(interp, objv[1], &len) != TCL_OK) {
531 goto freeMapAndError;
532 }
533 paramObj = (len > 0 ? objv[1] : NULL);
534 continue;
535 case CONF_MAP: {
536 Tcl_Obj *patchedDict = NULL, *subcmdWordsObj, **listv;
537 const char *cmd;
538
539 /*
540 * Verify that the map is sensible.
541 */
542
543 if (Tcl_DictObjFirst(interp, objv[1], &search,
544 &subcmdWordsObj, &listObj, &done) != TCL_OK) {
545 goto freeMapAndError;
546 }
547 if (done) {
548 mapObj = NULL;
549 continue;
550 }
551 do {
552 if (TclListObjGetElements(interp, listObj, &len,
553 &listv) != TCL_OK) {
554 Tcl_DictObjDone(&search);
555 if (patchedDict) {
556 Tcl_DecrRefCount(patchedDict);
557 }
558 goto freeMapAndError;
559 }
560 if (len < 1) {
561 Tcl_SetObjResult(interp, Tcl_NewStringObj(
562 "ensemble subcommand implementations "
563 "must be non-empty lists", -1));
564 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE",
565 "EMPTY_TARGET", (char *)NULL);
566 Tcl_DictObjDone(&search);
567 if (patchedDict) {
568 Tcl_DecrRefCount(patchedDict);
569 }
570 goto freeMapAndError;
571 }
572 cmd = TclGetString(listv[0]);
573 if (!(cmd[0] == ':' && cmd[1] == ':')) {
574 Tcl_Obj *newList = Tcl_DuplicateObj(listObj);
575 Tcl_Obj *newCmd = NewNsObj((Tcl_Namespace*)nsPtr);
576
577 if (nsPtr->parentPtr) {
578 Tcl_AppendStringsToObj(newCmd, "::", (char *)NULL);
579 }
580 Tcl_AppendObjToObj(newCmd, listv[0]);
581 Tcl_ListObjReplace(NULL, newList, 0, 1, 1, &newCmd);
582 if (patchedDict == NULL) {
583 patchedDict = Tcl_DuplicateObj(objv[1]);
584 }
585 Tcl_DictObjPut(NULL, patchedDict, subcmdWordsObj,
586 newList);
587 }
588 Tcl_DictObjNext(&search, &subcmdWordsObj, &listObj,
589 &done);
590 } while (!done);
591 if (allocatedMapFlag) {
592 Tcl_DecrRefCount(mapObj);
593 }
594 mapObj = (patchedDict ? patchedDict : objv[1]);
595 if (patchedDict) {
596 allocatedMapFlag = 1;
597 }
598 continue;
599 }
600 case CONF_NAMESPACE:
601 Tcl_SetObjResult(interp, Tcl_NewStringObj(
602 "option -namespace is read-only", -1));
603 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "READ_ONLY",
604 (char *)NULL);
605 goto freeMapAndError;
606 case CONF_PREFIX:
607 if (Tcl_GetBooleanFromObj(interp, objv[1],
608 &permitPrefix) != TCL_OK) {
609 goto freeMapAndError;
610 }
611 continue;
612 case CONF_UNKNOWN:
613 if (TclListObjLength(interp, objv[1], &len) != TCL_OK) {
614 goto freeMapAndError;
615 }
616 unknownObj = (len > 0 ? objv[1] : NULL);
617 continue;
618 }
619 }
620
621 /*
622 * Update the namespace now that we've finished the parsing stage.
623 */
624
625 flags = (permitPrefix ? flags|TCL_ENSEMBLE_PREFIX
626 : flags&~TCL_ENSEMBLE_PREFIX);
627 Tcl_SetEnsembleSubcommandList(interp, token, subcmdObj);
628 Tcl_SetEnsembleMappingDict(interp, token, mapObj);
629 Tcl_SetEnsembleParameterList(interp, token, paramObj);
630 Tcl_SetEnsembleUnknownHandler(interp, token, unknownObj);
631 Tcl_SetEnsembleFlags(interp, token, flags);
632 }
633 return TCL_OK;
634
635 default:
636 Tcl_Panic("unexpected ensemble command");
637 }
638 return TCL_OK;
639 }
640
641 /*
642 *----------------------------------------------------------------------
643 *
644 * TclCreateEnsembleInNs --
645 *
646 * Like Tcl_CreateEnsemble, but additionally accepts as an argument the
647 * name of the namespace to create the command in.
648 *
649 *----------------------------------------------------------------------
650 */
651
652 Tcl_Command
653 TclCreateEnsembleInNs(
654 Tcl_Interp *interp,
655 const char *name, /* Simple name of command to create (no
656 * namespace components). */
657 Tcl_Namespace *nameNsPtr, /* Name of namespace to create the command
658 * in. */
659 Tcl_Namespace *ensembleNsPtr,
660 /* Name of the namespace for the ensemble. */
661 int flags)
662 {
663 Namespace *nsPtr = (Namespace *) ensembleNsPtr;
664 EnsembleConfig *ensemblePtr;
665 Tcl_Command token;
666
667 ensemblePtr = (EnsembleConfig *)ckalloc(sizeof(EnsembleConfig));
668 token = TclNRCreateCommandInNs(interp, name,
669 (Tcl_Namespace *) nameNsPtr, NsEnsembleImplementationCmd,
670 NsEnsembleImplementationCmdNR, ensemblePtr, DeleteEnsembleConfig);
671 if (token == NULL) {
672 ckfree(ensemblePtr);
673 return NULL;
674 }
675
676 ensemblePtr->nsPtr = nsPtr;
677 ensemblePtr->epoch = 0;
678 Tcl_InitHashTable(&ensemblePtr->subcommandTable, TCL_STRING_KEYS);
679 ensemblePtr->subcommandArrayPtr = NULL;
680 ensemblePtr->subcmdList = NULL;
681 ensemblePtr->subcommandDict = NULL;
682 ensemblePtr->flags = flags;
683 ensemblePtr->numParameters = 0;
684 ensemblePtr->parameterList = NULL;
685 ensemblePtr->unknownHandler = NULL;
686 ensemblePtr->token = token;
687 ensemblePtr->next = (EnsembleConfig *) nsPtr->ensembles;
688 nsPtr->ensembles = (Tcl_Ensemble *) ensemblePtr;
689
690 /*
691 * Trigger an eventual recomputation of the ensemble command set. Note
692 * that this is slightly tricky, as it means that we are not actually
693 * counting the number of namespace export actions, but it is the simplest
694 * way to go!
695 */
696
697 nsPtr->exportLookupEpoch++;
698
699 if (flags & ENSEMBLE_COMPILE) {
700 ((Command *) ensemblePtr->token)->compileProc = TclCompileEnsemble;
701 }
702
703 return ensemblePtr->token;
704 }
705
706 /*
707 *----------------------------------------------------------------------
708 *
709 * Tcl_CreateEnsemble
710 *
711 * Create a simple ensemble attached to the given namespace. Deprecated
712 * (internally) by TclCreateEnsembleInNs.
713 *
714 * Value
715 *
716 * The token for the command created.
717 *
718 * Effect
719 * The ensemble is created and marked for compilation.
720 *
721 *
722 *----------------------------------------------------------------------
723 */
724
725 Tcl_Command
726 Tcl_CreateEnsemble(
727 Tcl_Interp *interp,
728 const char *name,
729 Tcl_Namespace *namespacePtr,
730 int flags)
731 {
732 Namespace *nsPtr = (Namespace *)namespacePtr, *foundNsPtr, *altNsPtr,
733 *actualNsPtr;
734 const char * simpleName;
735
736 if (nsPtr == NULL) {
737 nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
738 }
739
740 TclGetNamespaceForQualName(interp, name, nsPtr, TCL_CREATE_NS_IF_UNKNOWN,
741 &foundNsPtr, &altNsPtr, &actualNsPtr, &simpleName);
742 return TclCreateEnsembleInNs(interp, simpleName,
743 (Tcl_Namespace *) foundNsPtr, (Tcl_Namespace *) nsPtr, flags);
744 }
745
746 /*
747 *----------------------------------------------------------------------
748 *
749 * Tcl_SetEnsembleSubcommandList --
750 *
751 * Set the subcommand list for a particular ensemble.
752 *
753 * Results:
754 * Tcl result code (error if command token does not indicate an ensemble
755 * or the subcommand list - if non-NULL - is not a list).
756 *
757 * Side effects:
758 * The ensemble is updated and marked for recompilation.
759 *
760 *----------------------------------------------------------------------
761 */
762
763 int
764 Tcl_SetEnsembleSubcommandList(
765 Tcl_Interp *interp,
766 Tcl_Command token,
767 Tcl_Obj *subcmdList)
768 {
769 Command *cmdPtr = (Command *) token;
770 EnsembleConfig *ensemblePtr;
771 Tcl_Obj *oldList;
772
773 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
774 Tcl_SetObjResult(interp, Tcl_NewStringObj(
775 "command is not an ensemble", -1));
776 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
777 return TCL_ERROR;
778 }
779 if (subcmdList != NULL) {
780 int length;
781
782 if (TclListObjLength(interp, subcmdList, &length) != TCL_OK) {
783 return TCL_ERROR;
784 }
785 if (length < 1) {
786 subcmdList = NULL;
787 }
788 }
789
790 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
791 oldList = ensemblePtr->subcmdList;
792 ensemblePtr->subcmdList = subcmdList;
793 if (subcmdList != NULL) {
794 Tcl_IncrRefCount(subcmdList);
795 }
796 if (oldList != NULL) {
797 TclDecrRefCount(oldList);
798 }
799
800 /*
801 * Trigger an eventual recomputation of the ensemble command set. Note
802 * that this is slightly tricky, as it means that we are not actually
803 * counting the number of namespace export actions, but it is the simplest
804 * way to go!
805 */
806
807 ensemblePtr->nsPtr->exportLookupEpoch++;
808
809 /*
810 * Special hack to make compiling of [info exists] work when the
811 * dictionary is modified.
812 */
813
814 if (cmdPtr->compileProc != NULL) {
815 ((Interp *) interp)->compileEpoch++;
816 }
817
818 return TCL_OK;
819 }
820
821 /*
822 *----------------------------------------------------------------------
823 *
824 * Tcl_SetEnsembleParameterList --
825 *
826 * Set the parameter list for a particular ensemble.
827 *
828 * Results:
829 * Tcl result code (error if command token does not indicate an ensemble
830 * or the parameter list - if non-NULL - is not a list).
831 *
832 * Side effects:
833 * The ensemble is updated and marked for recompilation.
834 *
835 *----------------------------------------------------------------------
836 */
837
838 int
839 Tcl_SetEnsembleParameterList(
840 Tcl_Interp *interp,
841 Tcl_Command token,
842 Tcl_Obj *paramList)
843 {
844 Command *cmdPtr = (Command *) token;
845 EnsembleConfig *ensemblePtr;
846 Tcl_Obj *oldList;
847 int length;
848
849 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
850 Tcl_SetObjResult(interp, Tcl_NewStringObj(
851 "command is not an ensemble", -1));
852 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
853 return TCL_ERROR;
854 }
855 if (paramList == NULL) {
856 length = 0;
857 } else {
858 if (TclListObjLength(interp, paramList, &length) != TCL_OK) {
859 return TCL_ERROR;
860 }
861 if (length < 1) {
862 paramList = NULL;
863 }
864 }
865
866 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
867 oldList = ensemblePtr->parameterList;
868 ensemblePtr->parameterList = paramList;
869 if (paramList != NULL) {
870 Tcl_IncrRefCount(paramList);
871 }
872 if (oldList != NULL) {
873 TclDecrRefCount(oldList);
874 }
875 ensemblePtr->numParameters = length;
876
877 /*
878 * Trigger an eventual recomputation of the ensemble command set. Note
879 * that this is slightly tricky, as it means that we are not actually
880 * counting the number of namespace export actions, but it is the simplest
881 * way to go!
882 */
883
884 ensemblePtr->nsPtr->exportLookupEpoch++;
885
886 /*
887 * Special hack to make compiling of [info exists] work when the
888 * dictionary is modified.
889 */
890
891 if (cmdPtr->compileProc != NULL) {
892 ((Interp *) interp)->compileEpoch++;
893 }
894
895 return TCL_OK;
896 }
897
898 /*
899 *----------------------------------------------------------------------
900 *
901 * Tcl_SetEnsembleMappingDict --
902 *
903 * Set the mapping dictionary for a particular ensemble.
904 *
905 * Results:
906 * Tcl result code (error if command token does not indicate an ensemble
907 * or the mapping - if non-NULL - is not a dict).
908 *
909 * Side effects:
910 * The ensemble is updated and marked for recompilation.
911 *
912 *----------------------------------------------------------------------
913 */
914
915 int
916 Tcl_SetEnsembleMappingDict(
917 Tcl_Interp *interp,
918 Tcl_Command token,
919 Tcl_Obj *mapDict)
920 {
921 Command *cmdPtr = (Command *) token;
922 EnsembleConfig *ensemblePtr;
923 Tcl_Obj *oldDict;
924
925 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
926 Tcl_SetObjResult(interp, Tcl_NewStringObj(
927 "command is not an ensemble", -1));
928 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
929 return TCL_ERROR;
930 }
931 if (mapDict != NULL) {
932 int size;
933 int done;
934 Tcl_DictSearch search;
935 Tcl_Obj *valuePtr;
936
937 if (Tcl_DictObjSize(interp, mapDict, &size) != TCL_OK) {
938 return TCL_ERROR;
939 }
940
941 for (Tcl_DictObjFirst(NULL, mapDict, &search, NULL, &valuePtr, &done);
942 !done; Tcl_DictObjNext(&search, NULL, &valuePtr, &done)) {
943 Tcl_Obj *cmdObjPtr;
944 const char *bytes;
945
946 if (Tcl_ListObjIndex(interp, valuePtr, 0, &cmdObjPtr) != TCL_OK) {
947 Tcl_DictObjDone(&search);
948 return TCL_ERROR;
949 }
950 bytes = TclGetString(cmdObjPtr);
951 if (bytes[0] != ':' || bytes[1] != ':') {
952 Tcl_SetObjResult(interp, Tcl_NewStringObj(
953 "ensemble target is not a fully-qualified command",
954 -1));
955 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE",
956 "UNQUALIFIED_TARGET", (char *)NULL);
957 Tcl_DictObjDone(&search);
958 return TCL_ERROR;
959 }
960 }
961
962 if (size < 1) {
963 mapDict = NULL;
964 }
965 }
966
967 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
968 oldDict = ensemblePtr->subcommandDict;
969 ensemblePtr->subcommandDict = mapDict;
970 if (mapDict != NULL) {
971 Tcl_IncrRefCount(mapDict);
972 }
973 if (oldDict != NULL) {
974 TclDecrRefCount(oldDict);
975 }
976
977 /*
978 * Trigger an eventual recomputation of the ensemble command set. Note
979 * that this is slightly tricky, as it means that we are not actually
980 * counting the number of namespace export actions, but it is the simplest
981 * way to go!
982 */
983
984 ensemblePtr->nsPtr->exportLookupEpoch++;
985
986 /*
987 * Special hack to make compiling of [info exists] work when the
988 * dictionary is modified.
989 */
990
991 if (cmdPtr->compileProc != NULL) {
992 ((Interp *) interp)->compileEpoch++;
993 }
994
995 return TCL_OK;
996 }
997
998 /*
999 *----------------------------------------------------------------------
1000 *
1001 * Tcl_SetEnsembleUnknownHandler --
1002 *
1003 * Set the unknown handler for a particular ensemble.
1004 *
1005 * Results:
1006 * Tcl result code (error if command token does not indicate an ensemble
1007 * or the unknown handler - if non-NULL - is not a list).
1008 *
1009 * Side effects:
1010 * The ensemble is updated and marked for recompilation.
1011 *
1012 *----------------------------------------------------------------------
1013 */
1014
1015 int
1016 Tcl_SetEnsembleUnknownHandler(
1017 Tcl_Interp *interp,
1018 Tcl_Command token,
1019 Tcl_Obj *unknownList)
1020 {
1021 Command *cmdPtr = (Command *) token;
1022 EnsembleConfig *ensemblePtr;
1023 Tcl_Obj *oldList;
1024
1025 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1026 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1027 "command is not an ensemble", -1));
1028 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
1029 return TCL_ERROR;
1030 }
1031 if (unknownList != NULL) {
1032 int length;
1033
1034 if (TclListObjLength(interp, unknownList, &length) != TCL_OK) {
1035 return TCL_ERROR;
1036 }
1037 if (length < 1) {
1038 unknownList = NULL;
1039 }
1040 }
1041
1042 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
1043 oldList = ensemblePtr->unknownHandler;
1044 ensemblePtr->unknownHandler = unknownList;
1045 if (unknownList != NULL) {
1046 Tcl_IncrRefCount(unknownList);
1047 }
1048 if (oldList != NULL) {
1049 TclDecrRefCount(oldList);
1050 }
1051
1052 /*
1053 * Trigger an eventual recomputation of the ensemble command set. Note
1054 * that this is slightly tricky, as it means that we are not actually
1055 * counting the number of namespace export actions, but it is the simplest
1056 * way to go!
1057 */
1058
1059 ensemblePtr->nsPtr->exportLookupEpoch++;
1060
1061 return TCL_OK;
1062 }
1063
1064 /*
1065 *----------------------------------------------------------------------
1066 *
1067 * Tcl_SetEnsembleFlags --
1068 *
1069 * Set the flags for a particular ensemble.
1070 *
1071 * Results:
1072 * Tcl result code (error if command token does not indicate an
1073 * ensemble).
1074 *
1075 * Side effects:
1076 * The ensemble is updated and marked for recompilation.
1077 *
1078 *----------------------------------------------------------------------
1079 */
1080
1081 int
1082 Tcl_SetEnsembleFlags(
1083 Tcl_Interp *interp,
1084 Tcl_Command token,
1085 int flags)
1086 {
1087 Command *cmdPtr = (Command *) token;
1088 EnsembleConfig *ensemblePtr;
1089 int wasCompiled;
1090
1091 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1092 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1093 "command is not an ensemble", -1));
1094 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
1095 return TCL_ERROR;
1096 }
1097
1098 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
1099 wasCompiled = ensemblePtr->flags & ENSEMBLE_COMPILE;
1100
1101 /*
1102 * This API refuses to set the ENSEMBLE_DEAD flag...
1103 */
1104
1105 ensemblePtr->flags &= ENSEMBLE_DEAD;
1106 ensemblePtr->flags |= flags & ~ENSEMBLE_DEAD;
1107
1108 /*
1109 * Trigger an eventual recomputation of the ensemble command set. Note
1110 * that this is slightly tricky, as it means that we are not actually
1111 * counting the number of namespace export actions, but it is the simplest
1112 * way to go!
1113 */
1114
1115 ensemblePtr->nsPtr->exportLookupEpoch++;
1116
1117 /*
1118 * If the ENSEMBLE_COMPILE flag status was changed, install or remove the
1119 * compiler function and bump the interpreter's compilation epoch so that
1120 * bytecode gets regenerated.
1121 */
1122
1123 if (flags & ENSEMBLE_COMPILE) {
1124 if (!wasCompiled) {
1125 ((Command*) ensemblePtr->token)->compileProc = TclCompileEnsemble;
1126 ((Interp *) interp)->compileEpoch++;
1127 }
1128 } else {
1129 if (wasCompiled) {
1130 ((Command *) ensemblePtr->token)->compileProc = NULL;
1131 ((Interp *) interp)->compileEpoch++;
1132 }
1133 }
1134
1135 return TCL_OK;
1136 }
1137
1138 /*
1139 *----------------------------------------------------------------------
1140 *
1141 * Tcl_GetEnsembleSubcommandList --
1142 *
1143 * Get the list of subcommands associated with a particular ensemble.
1144 *
1145 * Results:
1146 * Tcl result code (error if command token does not indicate an
1147 * ensemble). The list of subcommands is returned by updating the
1148 * variable pointed to by the last parameter (NULL if this is to be
1149 * derived from the mapping dictionary or the associated namespace's
1150 * exported commands).
1151 *
1152 * Side effects:
1153 * None
1154 *
1155 *----------------------------------------------------------------------
1156 */
1157
1158 int
1159 Tcl_GetEnsembleSubcommandList(
1160 Tcl_Interp *interp,
1161 Tcl_Command token,
1162 Tcl_Obj **subcmdListPtr)
1163 {
1164 Command *cmdPtr = (Command *) token;
1165 EnsembleConfig *ensemblePtr;
1166
1167 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1168 if (interp != NULL) {
1169 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1170 "command is not an ensemble", -1));
1171 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
1172 }
1173 return TCL_ERROR;
1174 }
1175
1176 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
1177 *subcmdListPtr = ensemblePtr->subcmdList;
1178 return TCL_OK;
1179 }
1180
1181 /*
1182 *----------------------------------------------------------------------
1183 *
1184 * Tcl_GetEnsembleParameterList --
1185 *
1186 * Get the list of parameters associated with a particular ensemble.
1187 *
1188 * Results:
1189 * Tcl result code (error if command token does not indicate an
1190 * ensemble). The list of parameters is returned by updating the
1191 * variable pointed to by the last parameter (NULL if there are
1192 * no parameters).
1193 *
1194 * Side effects:
1195 * None
1196 *
1197 *----------------------------------------------------------------------
1198 */
1199
1200 int
1201 Tcl_GetEnsembleParameterList(
1202 Tcl_Interp *interp,
1203 Tcl_Command token,
1204 Tcl_Obj **paramListPtr)
1205 {
1206 Command *cmdPtr = (Command *) token;
1207 EnsembleConfig *ensemblePtr;
1208
1209 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1210 if (interp != NULL) {
1211 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1212 "command is not an ensemble", -1));
1213 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
1214 }
1215 return TCL_ERROR;
1216 }
1217
1218 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
1219 *paramListPtr = ensemblePtr->parameterList;
1220 return TCL_OK;
1221 }
1222
1223 /*
1224 *----------------------------------------------------------------------
1225 *
1226 * Tcl_GetEnsembleMappingDict --
1227 *
1228 * Get the command mapping dictionary associated with a particular
1229 * ensemble.
1230 *
1231 * Results:
1232 * Tcl result code (error if command token does not indicate an
1233 * ensemble). The mapping dict is returned by updating the variable
1234 * pointed to by the last parameter (NULL if none is installed).
1235 *
1236 * Side effects:
1237 * None
1238 *
1239 *----------------------------------------------------------------------
1240 */
1241
1242 int
1243 Tcl_GetEnsembleMappingDict(
1244 Tcl_Interp *interp,
1245 Tcl_Command token,
1246 Tcl_Obj **mapDictPtr)
1247 {
1248 Command *cmdPtr = (Command *) token;
1249 EnsembleConfig *ensemblePtr;
1250
1251 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1252 if (interp != NULL) {
1253 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1254 "command is not an ensemble", -1));
1255 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
1256 }
1257 return TCL_ERROR;
1258 }
1259
1260 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
1261 *mapDictPtr = ensemblePtr->subcommandDict;
1262 return TCL_OK;
1263 }
1264
1265 /*
1266 *----------------------------------------------------------------------
1267 *
1268 * Tcl_GetEnsembleUnknownHandler --
1269 *
1270 * Get the unknown handler associated with a particular ensemble.
1271 *
1272 * Results:
1273 * Tcl result code (error if command token does not indicate an
1274 * ensemble). The unknown handler is returned by updating the variable
1275 * pointed to by the last parameter (NULL if no handler is installed).
1276 *
1277 * Side effects:
1278 * None
1279 *
1280 *----------------------------------------------------------------------
1281 */
1282
1283 int
1284 Tcl_GetEnsembleUnknownHandler(
1285 Tcl_Interp *interp,
1286 Tcl_Command token,
1287 Tcl_Obj **unknownListPtr)
1288 {
1289 Command *cmdPtr = (Command *) token;
1290 EnsembleConfig *ensemblePtr;
1291
1292 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1293 if (interp != NULL) {
1294 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1295 "command is not an ensemble", -1));
1296 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
1297 }
1298 return TCL_ERROR;
1299 }
1300
1301 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
1302 *unknownListPtr = ensemblePtr->unknownHandler;
1303 return TCL_OK;
1304 }
1305
1306 /*
1307 *----------------------------------------------------------------------
1308 *
1309 * Tcl_GetEnsembleFlags --
1310 *
1311 * Get the flags for a particular ensemble.
1312 *
1313 * Results:
1314 * Tcl result code (error if command token does not indicate an
1315 * ensemble). The flags are returned by updating the variable pointed to
1316 * by the last parameter.
1317 *
1318 * Side effects:
1319 * None
1320 *
1321 *----------------------------------------------------------------------
1322 */
1323
1324 int
1325 Tcl_GetEnsembleFlags(
1326 Tcl_Interp *interp,
1327 Tcl_Command token,
1328 int *flagsPtr)
1329 {
1330 Command *cmdPtr = (Command *) token;
1331 EnsembleConfig *ensemblePtr;
1332
1333 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1334 if (interp != NULL) {
1335 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1336 "command is not an ensemble", -1));
1337 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
1338 }
1339 return TCL_ERROR;
1340 }
1341
1342 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
1343 *flagsPtr = ensemblePtr->flags;
1344 return TCL_OK;
1345 }
1346
1347 /*
1348 *----------------------------------------------------------------------
1349 *
1350 * Tcl_GetEnsembleNamespace --
1351 *
1352 * Get the namespace associated with a particular ensemble.
1353 *
1354 * Results:
1355 * Tcl result code (error if command token does not indicate an
1356 * ensemble). Namespace is returned by updating the variable pointed to
1357 * by the last parameter.
1358 *
1359 * Side effects:
1360 * None
1361 *
1362 *----------------------------------------------------------------------
1363 */
1364
1365 int
1366 Tcl_GetEnsembleNamespace(
1367 Tcl_Interp *interp,
1368 Tcl_Command token,
1369 Tcl_Namespace **namespacePtrPtr)
1370 {
1371 Command *cmdPtr = (Command *) token;
1372 EnsembleConfig *ensemblePtr;
1373
1374 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1375 if (interp != NULL) {
1376 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1377 "command is not an ensemble", -1));
1378 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "NOT_ENSEMBLE", (char *)NULL);
1379 }
1380 return TCL_ERROR;
1381 }
1382
1383 ensemblePtr = (EnsembleConfig *)cmdPtr->objClientData;
1384 *namespacePtrPtr = (Tcl_Namespace *) ensemblePtr->nsPtr;
1385 return TCL_OK;
1386 }
1387
1388 /*
1389 *----------------------------------------------------------------------
1390 *
1391 * Tcl_FindEnsemble --
1392 *
1393 * Given a command name, get the ensemble token for it, allowing for
1394 * [namespace import]s. [Bug 1017022]
1395 *
1396 * Results:
1397 * The token for the ensemble command with the given name, or NULL if the
1398 * command either does not exist or is not an ensemble (when an error
1399 * message will be written into the interp if thats non-NULL).
1400 *
1401 * Side effects:
1402 * None
1403 *
1404 *----------------------------------------------------------------------
1405 */
1406
1407 Tcl_Command
1408 Tcl_FindEnsemble(
1409 Tcl_Interp *interp, /* Where to do the lookup, and where to write
1410 * the errors if TCL_LEAVE_ERR_MSG is set in
1411 * the flags. */
1412 Tcl_Obj *cmdNameObj, /* Name of command to look up. */
1413 int flags) /* Either 0 or TCL_LEAVE_ERR_MSG; other flags
1414 * are probably not useful. */
1415 {
1416 Command *cmdPtr;
1417
1418 cmdPtr = (Command *)
1419 Tcl_FindCommand(interp, TclGetString(cmdNameObj), NULL, flags);
1420 if (cmdPtr == NULL) {
1421 return NULL;
1422 }
1423
1424 if (cmdPtr->objProc != NsEnsembleImplementationCmd) {
1425 /*
1426 * Reuse existing infrastructure for following import link chains
1427 * rather than duplicating it.
1428 */
1429
1430 cmdPtr = (Command *) TclGetOriginalCommand((Tcl_Command) cmdPtr);
1431
1432 if (cmdPtr == NULL || cmdPtr->objProc != NsEnsembleImplementationCmd){
1433 if (flags & TCL_LEAVE_ERR_MSG) {
1434 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1435 "\"%s\" is not an ensemble command",
1436 TclGetString(cmdNameObj)));
1437 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "ENSEMBLE",
1438 TclGetString(cmdNameObj), (char *)NULL);
1439 }
1440 return NULL;
1441 }
1442 }
1443
1444 return (Tcl_Command) cmdPtr;
1445 }
1446
1447 /*
1448 *----------------------------------------------------------------------
1449 *
1450 * Tcl_IsEnsemble --
1451 *
1452 * Simple test for ensemble-hood that takes into account imported
1453 * ensemble commands as well.
1454 *
1455 * Results:
1456 * Boolean value
1457 *
1458 * Side effects:
1459 * None
1460 *
1461 *----------------------------------------------------------------------
1462 */
1463
1464 int
1465 Tcl_IsEnsemble(
1466 Tcl_Command token)
1467 {
1468 Command *cmdPtr = (Command *) token;
1469
1470 if (cmdPtr->objProc == NsEnsembleImplementationCmd) {
1471 return 1;
1472 }
1473 cmdPtr = (Command *) TclGetOriginalCommand((Tcl_Command) cmdPtr);
1474 if (cmdPtr == NULL || cmdPtr->objProc != NsEnsembleImplementationCmd) {
1475 return 0;
1476 }
1477 return 1;
1478 }
1479
1480 /*
1481 *----------------------------------------------------------------------
1482 *
1483 * TclMakeEnsemble --
1484 *
1485 * Create an ensemble from a table of implementation commands. The
1486 * ensemble will be subject to (limited) compilation if any of the
1487 * implementation commands are compilable.
1488 *
1489 * The 'name' parameter may be a single command name or a list if
1490 * creating an ensemble subcommand (see the binary implementation).
1491 *
1492 * Currently, the TCL_ENSEMBLE_PREFIX ensemble flag is only used on
1493 * top-level ensemble commands.
1494 *
1495 * Results:
1496 * Handle for the new ensemble, or NULL on failure.
1497 *
1498 * Side effects:
1499 * May advance the bytecode compilation epoch.
1500 *
1501 *----------------------------------------------------------------------
1502 */
1503
1504 Tcl_Command
1505 TclMakeEnsemble(
1506 Tcl_Interp *interp,
1507 const char *name, /* The ensemble name (as explained above) */
1508 const EnsembleImplMap map[]) /* The subcommands to create */
1509 {
1510 Tcl_Command ensemble;
1511 Tcl_Namespace *ns;
1512 Tcl_DString buf, hiddenBuf;
1513 const char **nameParts = NULL;
1514 const char *cmdName = NULL;
1515 int i, nameCount = 0;
1516 int ensembleFlags = 0, hiddenLen;
1517
1518 /*
1519 * Construct the path for the ensemble namespace and create it.
1520 */
1521
1522 Tcl_DStringInit(&buf);
1523 Tcl_DStringInit(&hiddenBuf);
1524 TclDStringAppendLiteral(&hiddenBuf, "tcl:");
1525 Tcl_DStringAppend(&hiddenBuf, name, -1);
1526 TclDStringAppendLiteral(&hiddenBuf, ":");
1527 hiddenLen = Tcl_DStringLength(&hiddenBuf);
1528 if (name[0] == ':' && name[1] == ':') {
1529 /*
1530 * An absolute name, so use it directly.
1531 */
1532
1533 cmdName = name;
1534 Tcl_DStringAppend(&buf, name, -1);
1535 ensembleFlags = TCL_ENSEMBLE_PREFIX;
1536 } else {
1537 /*
1538 * Not an absolute name, so do munging of it. Note that this treats a
1539 * multi-word list differently to a single word.
1540 */
1541
1542 TclDStringAppendLiteral(&buf, "::tcl");
1543
1544 if (Tcl_SplitList(NULL, name, &nameCount, &nameParts) != TCL_OK) {
1545 Tcl_Panic("invalid ensemble name '%s'", name);
1546 }
1547
1548 for (i = 0; i < nameCount; ++i) {
1549 TclDStringAppendLiteral(&buf, "::");
1550 Tcl_DStringAppend(&buf, nameParts[i], -1);
1551 }
1552 }
1553
1554 ns = Tcl_FindNamespace(interp, Tcl_DStringValue(&buf), NULL,
1555 TCL_CREATE_NS_IF_UNKNOWN);
1556 if (!ns) {
1557 Tcl_Panic("unable to find or create %s namespace!",
1558 Tcl_DStringValue(&buf));
1559 }
1560
1561 /*
1562 * Create the named ensemble in the correct namespace
1563 */
1564
1565 if (cmdName == NULL) {
1566 if (nameCount == 1) {
1567 ensembleFlags = TCL_ENSEMBLE_PREFIX;
1568 cmdName = Tcl_DStringValue(&buf) + 5;
1569 } else {
1570 ns = ns->parentPtr;
1571 cmdName = nameParts[nameCount - 1];
1572 }
1573 }
1574
1575 /*
1576 * Switch on compilation always for core ensembles now that we can do
1577 * nice bytecode things with them. Do it now. Waiting until later will
1578 * just cause pointless epoch bumps.
1579 */
1580
1581 ensembleFlags |= ENSEMBLE_COMPILE;
1582 ensemble = Tcl_CreateEnsemble(interp, cmdName, ns, ensembleFlags);
1583
1584 /*
1585 * Create the ensemble mapping dictionary and the ensemble command procs.
1586 */
1587
1588 if (ensemble != NULL) {
1589 Tcl_Obj *mapDict, *toObj;
1590 Command *cmdPtr;
1591
1592 TclDStringAppendLiteral(&buf, "::");
1593 TclNewObj(mapDict);
1594 for (i=0 ; map[i].name != NULL ; i++) {
1595 TclNewStringObj(toObj, Tcl_DStringValue(&buf),
1596 Tcl_DStringLength(&buf));
1597 Tcl_AppendToObj(toObj, map[i].name, -1);
1598 TclDictPut(NULL, mapDict, map[i].name, toObj);
1599
1600 if (map[i].proc || map[i].nreProc) {
1601 /*
1602 * If the command is unsafe, hide it when we're in a safe
1603 * interpreter. The code to do this is really hokey! It also
1604 * doesn't work properly yet; this function is always
1605 * currently called before the safe-interp flag is set so the
1606 * Tcl_IsSafe check fails.
1607 */
1608
1609 if (map[i].unsafe && Tcl_IsSafe(interp)) {
1610 cmdPtr = (Command *)
1611 Tcl_NRCreateCommand(interp, "___tmp", map[i].proc,
1612 map[i].nreProc, map[i].clientData, NULL);
1613 Tcl_DStringSetLength(&hiddenBuf, hiddenLen);
1614 if (Tcl_HideCommand(interp, "___tmp",
1615 Tcl_DStringAppend(&hiddenBuf, map[i].name, -1))) {
1616 Tcl_Panic("%s", Tcl_GetString(Tcl_GetObjResult(interp)));
1617 }
1618 /* don't compile unsafe subcommands in safe interp */
1619 cmdPtr->compileProc = NULL;
1620 } else {
1621 /*
1622 * Not hidden, so just create it. Yay!
1623 */
1624
1625 cmdPtr = (Command *)
1626 Tcl_NRCreateCommand(interp, TclGetString(toObj),
1627 map[i].proc, map[i].nreProc, map[i].clientData,
1628 NULL);
1629 cmdPtr->compileProc = map[i].compileProc;
1630 }
1631 }
1632 }
1633 Tcl_SetEnsembleMappingDict(interp, ensemble, mapDict);
1634 }
1635
1636 Tcl_DStringFree(&buf);
1637 Tcl_DStringFree(&hiddenBuf);
1638 if (nameParts != NULL) {
1639 ckfree((char *) nameParts);
1640 }
1641 return ensemble;
1642 }
1643
1644 /*
1645 *----------------------------------------------------------------------
1646 *
1647 * NsEnsembleImplementationCmd --
1648 *
1649 * Implements an ensemble of commands (being those exported by a
1650 * namespace other than the global namespace) as a command with the same
1651 * (short) name as the namespace in the parent namespace.
1652 *
1653 * Results:
1654 * A standard Tcl result code. Will be TCL_ERROR if the command is not an
1655 * unambiguous prefix of any command exported by the ensemble's
1656 * namespace.
1657 *
1658 * Side effects:
1659 * Depends on the command within the namespace that gets executed. If the
1660 * ensemble itself returns TCL_ERROR, a descriptive error message will be
1661 * placed in the interpreter's result.
1662 *
1663 *----------------------------------------------------------------------
1664 */
1665
1666 static int
1667 NsEnsembleImplementationCmd(
1668 ClientData clientData,
1669 Tcl_Interp *interp,
1670 int objc,
1671 Tcl_Obj *const objv[])
1672 {
1673 return Tcl_NRCallObjProc(interp, NsEnsembleImplementationCmdNR,
1674 clientData, objc, objv);
1675 }
1676
1677 static int
1678 NsEnsembleImplementationCmdNR(
1679 ClientData clientData,
1680 Tcl_Interp *interp,
1681 int objc,
1682 Tcl_Obj *const objv[])
1683 {
1684 EnsembleConfig *ensemblePtr = (EnsembleConfig *)clientData;
1685 /* The ensemble itself. */
1686 Tcl_Obj *prefixObj; /* An object containing the prefix words of
1687 * the command that implements the
1688 * subcommand. */
1689 Tcl_HashEntry *hPtr; /* Used for efficient lookup of fully
1690 * specified but not yet cached command
1691 * names. */
1692 int reparseCount = 0; /* Number of reparses. */
1693 Tcl_Obj *errorObj; /* Used for building error messages. */
1694 Tcl_Obj *subObj;
1695 int subIdx;
1696
1697 /*
1698 * Must recheck objc since numParameters might have changed. See test
1699 * namespace-53.9.
1700 */
1701
1702 restartEnsembleParse:
1703 subIdx = 1 + ensemblePtr->numParameters;
1704 if (objc < subIdx + 1) {
1705 /*
1706 * No subcommand argument. Make error message.
1707 */
1708
1709 Tcl_DString buf; /* Message being built */
1710
1711 Tcl_DStringInit(&buf);
1712 if (ensemblePtr->parameterList) {
1713 Tcl_DStringAppend(&buf,
1714 TclGetString(ensemblePtr->parameterList), -1);
1715 TclDStringAppendLiteral(&buf, " ");
1716 }
1717 TclDStringAppendLiteral(&buf, "subcommand ?arg ...?");
1718 Tcl_WrongNumArgs(interp, 1, objv, Tcl_DStringValue(&buf));
1719 Tcl_DStringFree(&buf);
1720
1721 return TCL_ERROR;
1722 }
1723
1724 if (ensemblePtr->nsPtr->flags & NS_DYING) {
1725 /*
1726 * Don't know how we got here, but make things give up quickly.
1727 */
1728
1729 if (!Tcl_InterpDeleted(interp)) {
1730 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1731 "ensemble activated for deleted namespace", -1));
1732 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "DEAD", (char *)NULL);
1733 }
1734 return TCL_ERROR;
1735 }
1736
1737 /*
1738 * If the table of subcommands is valid just lookup up the command there
1739 * and go to dispatch.
1740 */
1741
1742 subObj = objv[subIdx];
1743
1744 if (ensemblePtr->epoch == ensemblePtr->nsPtr->exportLookupEpoch) {
1745 /*
1746 * Table of subcommands is still valid so if the internal representtion
1747 * is an ensembleCmd, just call it.
1748 */
1749
1750 if (subObj->typePtr==&ensembleCmdType){
1751 EnsembleCmdRep *ensembleCmd = (EnsembleCmdRep *)subObj->internalRep.twoPtrValue.ptr1;
1752
1753 if (ensembleCmd->epoch == ensemblePtr->epoch &&
1754 ensembleCmd->token == (Command *)ensemblePtr->token) {
1755 prefixObj = (Tcl_Obj *)Tcl_GetHashValue(ensembleCmd->hPtr);
1756 Tcl_IncrRefCount(prefixObj);
1757 if (ensembleCmd->fix) {
1758 TclSpellFix(interp, objv, objc, subIdx, subObj, ensembleCmd->fix);
1759 }
1760 goto runResultingSubcommand;
1761 }
1762 }
1763 } else {
1764 BuildEnsembleConfig(ensemblePtr);
1765 ensemblePtr->epoch = ensemblePtr->nsPtr->exportLookupEpoch;
1766 }
1767
1768 /*
1769 * Look in the hashtable for the named subcommand. This is the fastest
1770 * path if there is no cache in operation.
1771 */
1772
1773 hPtr = Tcl_FindHashEntry(&ensemblePtr->subcommandTable,
1774 TclGetString(subObj));
1775 if (hPtr != NULL) {
1776
1777 /*
1778 * Cache ensemble in the subcommand object for later.
1779 */
1780
1781 MakeCachedEnsembleCommand(subObj, ensemblePtr, hPtr, NULL);
1782 } else if (!(ensemblePtr->flags & TCL_ENSEMBLE_PREFIX)) {
1783 /*
1784 * Could not map. No prefixing. Go to unknown/error handling.
1785 */
1786
1787 goto unknownOrAmbiguousSubcommand;
1788 } else {
1789 /*
1790 * If the command isn't yet confirmed with the hash as part of building
1791 * the export table, scan the sorted array for matches.
1792 */
1793
1794 const char *subcmdName; /* Name of the subcommand or unique prefix of
1795 * it (a non-unique prefix produces an error).
1796 */
1797 char *fullName = NULL; /* Full name of the subcommand. */
1798 int stringLength, i;
1799 int tableLength = ensemblePtr->subcommandTable.numEntries;
1800 Tcl_Obj *fix;
1801
1802 subcmdName = Tcl_GetStringFromObj(subObj, &stringLength);
1803 for (i=0 ; i<tableLength ; i++) {
1804 int cmp = strncmp(subcmdName,
1805 ensemblePtr->subcommandArrayPtr[i],
1806 stringLength);
1807
1808 if (cmp == 0) {
1809 if (fullName != NULL) {
1810 /*
1811 * Hash search filters out the exact-match case, so getting
1812 * here indicates that the subcommand is an ambiguous
1813 * prefix of at least two exported subcommands, which is an
1814 * error case.
1815 */
1816
1817 goto unknownOrAmbiguousSubcommand;
1818 }
1819 fullName = ensemblePtr->subcommandArrayPtr[i];
1820 } else if (cmp < 0) {
1821 /*
1822 * The table is sorted so stop searching because a match would
1823 * have been found already.
1824 */
1825
1826 break;
1827 }
1828 }
1829 if (fullName == NULL) {
1830 /*
1831 * The subcommand is not a prefix of anything. Bail out!
1832 */
1833
1834 goto unknownOrAmbiguousSubcommand;
1835 }
1836 hPtr = Tcl_FindHashEntry(&ensemblePtr->subcommandTable, fullName);
1837 if (hPtr == NULL) {
1838 Tcl_Panic("full name %s not found in supposedly synchronized hash",
1839 fullName);
1840 }
1841
1842 /*
1843 * Record the spelling correction for usage message.
1844 */
1845
1846 fix = Tcl_NewStringObj(fullName, -1);
1847
1848 /*
1849 * Cache for later in the subcommand object.
1850 */
1851
1852 MakeCachedEnsembleCommand(subObj, ensemblePtr, hPtr, fix);
1853 TclSpellFix(interp, objv, objc, subIdx, subObj, fix);
1854 }
1855
1856 prefixObj = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
1857 Tcl_IncrRefCount(prefixObj);
1858 runResultingSubcommand:
1859
1860 /*
1861 * Execute the subcommand by populating an array of objects, which might
1862 * not be the same length as the number of arguments to this ensemble
1863 * command, and then handing it to the main command-lookup engine. In
1864 * theory, the command could be looked up right here using the namespace in
1865 * which it is guaranteed to exist,
1866 *
1867 * ((Q: That's not true if the -map option is used, is it?))
1868 *
1869 * but don't do that because caching of the command object should help.
1870 */
1871
1872 {
1873 Tcl_Obj *copyPtr; /* The list of words to dispatch on.
1874 * Will be freed by the dispatch engine. */
1875 Tcl_Obj **copyObjv;
1876 int copyObjc, prefixObjc;
1877
1878 TclListObjLength(NULL, prefixObj, &prefixObjc);
1879
1880 if (objc == 2) {
1881 copyPtr = TclListObjCopy(NULL, prefixObj);
1882 } else {
1883 copyPtr = Tcl_NewListObj(objc - 2 + prefixObjc, NULL);
1884 Tcl_ListObjAppendList(NULL, copyPtr, prefixObj);
1885 Tcl_ListObjReplace(NULL, copyPtr, LIST_MAX, 0,
1886 ensemblePtr->numParameters, objv + 1);
1887 Tcl_ListObjReplace(NULL, copyPtr, LIST_MAX, 0,
1888 objc - 2 - ensemblePtr->numParameters,
1889 objv + 2 + ensemblePtr->numParameters);
1890 }
1891 Tcl_IncrRefCount(copyPtr);
1892 TclNRAddCallback(interp, TclNRReleaseValues, copyPtr, NULL, NULL, NULL);
1893 TclDecrRefCount(prefixObj);
1894
1895 /*
1896 * Record the words of the command as given so that routines like
1897 * Tcl_WrongNumArgs can produce the correct error message. Parameters
1898 * count both as inserted and removed arguments.
1899 */
1900
1901 if (TclInitRewriteEnsemble(interp, 2 + ensemblePtr->numParameters,
1902 prefixObjc + ensemblePtr->numParameters, objv)) {
1903 TclNRAddCallback(interp, TclClearRootEnsemble, NULL, NULL, NULL,
1904 NULL);
1905 }
1906
1907 /*
1908 * Hand off to the target command.
1909 */
1910
1911 TclSkipTailcall(interp);
1912 TclListObjGetElements(NULL, copyPtr, &copyObjc, &copyObjv);
1913 ((Interp *)interp)->lookupNsPtr = ensemblePtr->nsPtr;
1914 return TclNREvalObjv(interp, copyObjc, copyObjv, TCL_EVAL_INVOKE, NULL);
1915 }
1916
1917 unknownOrAmbiguousSubcommand:
1918 /*
1919 * The named subcommand did not match any exported command. If there is a
1920 * handler registered unknown subcommands, call it, but not more than once
1921 * for this call.
1922 */
1923
1924 if (ensemblePtr->unknownHandler != NULL && reparseCount++ < 1) {
1925 switch (EnsembleUnknownCallback(interp, ensemblePtr, objc, objv,
1926 &prefixObj)) {
1927 case TCL_OK:
1928 goto runResultingSubcommand;
1929 case TCL_ERROR:
1930 return TCL_ERROR;
1931 case TCL_CONTINUE:
1932 goto restartEnsembleParse;
1933 }
1934 }
1935
1936 /*
1937 * Could not find a routine for the named subcommand so generate a standard
1938 * failure message. The one odd case compared with a standard
1939 * ensemble-like command is where a namespace has no exported commands at
1940 * all...
1941 */
1942
1943 Tcl_ResetResult(interp);
1944 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "SUBCOMMAND",
1945 TclGetString(subObj), (char *)NULL);
1946 if (ensemblePtr->subcommandTable.numEntries == 0) {
1947 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1948 "unknown subcommand \"%s\": namespace %s does not"
1949 " export any commands", TclGetString(subObj),
1950 ensemblePtr->nsPtr->fullName));
1951 return TCL_ERROR;
1952 }
1953 errorObj = Tcl_ObjPrintf("unknown%s subcommand \"%s\": must be ",
1954 (ensemblePtr->flags & TCL_ENSEMBLE_PREFIX ? " or ambiguous" : ""),
1955 TclGetString(subObj));
1956 if (ensemblePtr->subcommandTable.numEntries == 1) {
1957 Tcl_AppendToObj(errorObj, ensemblePtr->subcommandArrayPtr[0], -1);
1958 } else {
1959 int i;
1960
1961 for (i=0 ; i<ensemblePtr->subcommandTable.numEntries-1 ; i++) {
1962 Tcl_AppendToObj(errorObj, ensemblePtr->subcommandArrayPtr[i], -1);
1963 Tcl_AppendToObj(errorObj, ", ", 2);
1964 }
1965 Tcl_AppendPrintfToObj(errorObj, "or %s",
1966 ensemblePtr->subcommandArrayPtr[i]);
1967 }
1968 Tcl_SetObjResult(interp, errorObj);
1969 return TCL_ERROR;
1970 }
1971
1972 int
1973 TclClearRootEnsemble(
1974 ClientData data[],
1975 Tcl_Interp *interp,
1976 int result)
1977 {
1978 TclResetRewriteEnsemble(interp, 1);
1979 return result;
1980 }
1981
1982 /*
1983 *----------------------------------------------------------------------
1984 *
1985 * TclInitRewriteEnsemble --
1986 *
1987 * Applies a rewrite of arguments so that an ensemble subcommand
1988 * correctly reports any error messages for the overall command.
1989 *
1990 * Results:
1991 * Whether this is the first rewrite applied, a value which must be
1992 * passed to TclResetRewriteEnsemble when undoing this command's
1993 * behaviour.
1994 *
1995 * Side effects:
1996 * None.
1997 *
1998 *----------------------------------------------------------------------
1999 */
2000
2001 int
2002 TclInitRewriteEnsemble(
2003 Tcl_Interp *interp,
2004 int numRemoved,
2005 int numInserted,
2006 Tcl_Obj *const *objv)
2007 {
2008 Interp *iPtr = (Interp *) interp;
2009
2010 int isRootEnsemble = (iPtr->ensembleRewrite.sourceObjs == NULL);
2011
2012 if (isRootEnsemble) {
2013 iPtr->ensembleRewrite.sourceObjs = objv;
2014 iPtr->ensembleRewrite.numRemovedObjs = numRemoved;
2015 iPtr->ensembleRewrite.numInsertedObjs = numInserted;
2016 } else {
2017 int numIns = iPtr->ensembleRewrite.numInsertedObjs;
2018
2019 if (numIns < numRemoved) {
2020 iPtr->ensembleRewrite.numRemovedObjs += numRemoved - numIns;
2021 iPtr->ensembleRewrite.numInsertedObjs = numInserted;
2022 } else {
2023 iPtr->ensembleRewrite.numInsertedObjs += numInserted - numRemoved;
2024 }
2025 }
2026 return isRootEnsemble;
2027 }
2028
2029 /*
2030 *----------------------------------------------------------------------
2031 *
2032 * TclResetRewriteEnsemble --
2033 *
2034 * Removes any rewrites applied to support proper reporting of error
2035 * messages used in ensembles. Should be paired with
2036 * TclInitRewriteEnsemble.
2037 *
2038 * Results:
2039 * None.
2040 *
2041 * Side effects:
2042 * None.
2043 *
2044 *----------------------------------------------------------------------
2045 */
2046
2047 void
2048 TclResetRewriteEnsemble(
2049 Tcl_Interp *interp,
2050 int isRootEnsemble)
2051 {
2052 Interp *iPtr = (Interp *) interp;
2053
2054 if (isRootEnsemble) {
2055 iPtr->ensembleRewrite.sourceObjs = NULL;
2056 iPtr->ensembleRewrite.numRemovedObjs = 0;
2057 iPtr->ensembleRewrite.numInsertedObjs = 0;
2058 }
2059 }
2060
2061 /*
2062 *----------------------------------------------------------------------
2063 *
2064 * TclSpellFix --
2065 *
2066 * Records a spelling correction that needs making in the generation of
2067 * the WrongNumArgs usage message.
2068 *
2069 * Results:
2070 * None.
2071 *
2072 * Side effects:
2073 * Can create an alternative ensemble rewrite structure.
2074 *
2075 *----------------------------------------------------------------------
2076 */
2077
2078 static int
2079 FreeER(
2080 ClientData data[],
2081 Tcl_Interp *interp,
2082 int result)
2083 {
2084 Tcl_Obj **tmp = (Tcl_Obj **) data[0];
2085 Tcl_Obj **store = (Tcl_Obj **) data[1];
2086
2087 ckfree(store);
2088 ckfree(tmp);
2089 return result;
2090 }
2091
2092 void
2093 TclSpellFix(
2094 Tcl_Interp *interp,
2095 Tcl_Obj *const *objv,
2096 int objc,
2097 int badIdx,
2098 Tcl_Obj *bad,
2099 Tcl_Obj *fix)
2100 {
2101 Interp *iPtr = (Interp *) interp;
2102 Tcl_Obj *const *search;
2103 Tcl_Obj **store;
2104 int idx;
2105 int size;
2106
2107 if (iPtr->ensembleRewrite.sourceObjs == NULL) {
2108 iPtr->ensembleRewrite.sourceObjs = objv;
2109 iPtr->ensembleRewrite.numRemovedObjs = 0;
2110 iPtr->ensembleRewrite.numInsertedObjs = 0;
2111 }
2112
2113 /*
2114 * Compute the valid length of the ensemble root.
2115 */
2116
2117 size = iPtr->ensembleRewrite.numRemovedObjs + objc
2118 - iPtr->ensembleRewrite.numInsertedObjs;
2119
2120 search = iPtr->ensembleRewrite.sourceObjs;
2121 if (search[0] == NULL) {
2122 /*
2123 * Awful casting abuse here!
2124 */
2125
2126 search = (Tcl_Obj *const *) search[1];
2127 }
2128
2129 if (badIdx < iPtr->ensembleRewrite.numInsertedObjs) {
2130 /*
2131 * Misspelled value was inserted. Cannot directly jump to the bad
2132 * value. Must search.
2133 */
2134
2135 idx = 1;
2136 while (idx < size) {
2137 if (search[idx] == bad) {
2138 break;
2139 }
2140 idx++;
2141 }
2142 if (idx == size) {
2143 return;
2144 }
2145 } else {
2146 /*
2147 * Jump to the misspelled value.
2148 */
2149
2150 idx = iPtr->ensembleRewrite.numRemovedObjs + badIdx
2151 - iPtr->ensembleRewrite.numInsertedObjs;
2152
2153 /* Verify */
2154 if (search[idx] != bad) {
2155 Tcl_Panic("SpellFix: programming error");
2156 }
2157 }
2158
2159 search = iPtr->ensembleRewrite.sourceObjs;
2160 if (search[0] == NULL) {
2161 store = (Tcl_Obj **) search[2];
2162 } else {
2163 Tcl_Obj **tmp = (Tcl_Obj **)ckalloc(3 * sizeof(Tcl_Obj *));
2164
2165 store = (Tcl_Obj **)ckalloc(size * sizeof(Tcl_Obj *));
2166 memcpy(store, iPtr->ensembleRewrite.sourceObjs,
2167 size * sizeof(Tcl_Obj *));
2168
2169 /*
2170 * Awful casting abuse here! Note that the NULL in the first element
2171 * indicates that the initial objects are a raw array in the second
2172 * element and the rewritten ones are a raw array in the third.
2173 */
2174
2175 tmp[0] = NULL;
2176 tmp[1] = (Tcl_Obj *) iPtr->ensembleRewrite.sourceObjs;
2177 tmp[2] = (Tcl_Obj *) store;
2178 iPtr->ensembleRewrite.sourceObjs = (Tcl_Obj *const *) tmp;
2179
2180 TclNRAddCallback(interp, FreeER, tmp, store, NULL, NULL);
2181 }
2182
2183 store[idx] = fix;
2184 Tcl_IncrRefCount(fix);
2185 TclNRAddCallback(interp, TclNRReleaseValues, fix, NULL, NULL, NULL);
2186 }
2187
2188 Tcl_Obj *const *TclEnsembleGetRewriteValues(
2189 Tcl_Interp *interp /* Current interpreter. */
2190 )
2191 {
2192 Interp *iPtr = (Interp *) interp;
2193 Tcl_Obj *const *origObjv = iPtr->ensembleRewrite.sourceObjs;
2194 if (origObjv[0] == NULL) {
2195 origObjv = (Tcl_Obj *const *)origObjv[2];
2196 }
2197 return origObjv;
2198 }
2199
2200 /*
2201 *----------------------------------------------------------------------
2202 *
2203 * TclFetchEnsembleRoot --
2204 *
2205 * Returns the root of ensemble rewriting, if any.
2206 * If no root exists, returns objv instead.
2207 *
2208 * Results:
2209 * None.
2210 *
2211 * Side effects:
2212 * None.
2213 *
2214 *----------------------------------------------------------------------
2215 */
2216
2217 Tcl_Obj *const *
2218 TclFetchEnsembleRoot(
2219 Tcl_Interp *interp,
2220 Tcl_Obj *const *objv,
2221 int objc,
2222 int *objcPtr)
2223 {
2224 Tcl_Obj *const *sourceObjs;
2225 Interp *iPtr = (Interp *) interp;
2226
2227 if (iPtr->ensembleRewrite.sourceObjs) {
2228 *objcPtr = objc + iPtr->ensembleRewrite.numRemovedObjs
2229 - iPtr->ensembleRewrite.numInsertedObjs;
2230 if (iPtr->ensembleRewrite.sourceObjs[0] == NULL) {
2231 sourceObjs = (Tcl_Obj *const *)iPtr->ensembleRewrite.sourceObjs[1];
2232 } else {
2233 sourceObjs = iPtr->ensembleRewrite.sourceObjs;
2234 }
2235 return sourceObjs;
2236 }
2237 *objcPtr = objc;
2238 return objv;
2239 }
2240
2241 /*
2242 * ----------------------------------------------------------------------
2243 *
2244 * EnsembleUnknownCallback --
2245 *
2246 * Helper for the ensemble engine. Calls the routine registered for
2247 * "ensemble unknown" case. See the user documentation of the
2248 * ensemble unknown handler for details. Only called when such a
2249 * function is defined, and is only called once per ensemble dispatch.
2250 * I.e. even if a reparse still fails, this isn't called again.
2251 *
2252 * Results:
2253 * TCL_OK - *prefixObjPtr contains the command words to dispatch
2254 * to.
2255 * TCL_CONTINUE - Need to reparse, i.e. *prefixObjPtr is invalid
2256 * TCL_ERROR - Something went wrong. Error message in interpreter.
2257 *
2258 * Side effects:
2259 * Arbitrary, due to evaluation of script provided by client.
2260 *
2261 * ----------------------------------------------------------------------
2262 */
2263
2264 static inline int
2265 EnsembleUnknownCallback(
2266 Tcl_Interp *interp,
2267 EnsembleConfig *ensemblePtr,
2268 int objc,
2269 Tcl_Obj *const objv[],
2270 Tcl_Obj **prefixObjPtr)
2271 {
2272 int paramc;
2273 int result;
2274 int i, prefixObjc;
2275 Tcl_Obj **paramv, *unknownCmd, *ensObj;
2276
2277 /*
2278 * Create the "unknown" command callback to determine what to do.
2279 */
2280
2281 unknownCmd = Tcl_DuplicateObj(ensemblePtr->unknownHandler);
2282 TclNewObj(ensObj);
2283 Tcl_GetCommandFullName(interp, ensemblePtr->token, ensObj);
2284 Tcl_ListObjAppendElement(NULL, unknownCmd, ensObj);
2285 for (i = 1 ; i < objc ; i++) {
2286 Tcl_ListObjAppendElement(NULL, unknownCmd, objv[i]);
2287 }
2288 TclListObjGetElements(NULL, unknownCmd, &paramc, &paramv);
2289 Tcl_IncrRefCount(unknownCmd);
2290
2291 /*
2292 * Call the "unknown" handler. No attempt to NRE-enable this as deep
2293 * recursion through unknown handlers is perverse. It is always an error
2294 * for an unknown handler to delete its ensemble. Don't do that.
2295 */
2296
2297 Tcl_Preserve(ensemblePtr);
2298 TclSkipTailcall(interp);
2299 result = Tcl_EvalObjv(interp, paramc, paramv, 0);
2300 if ((result == TCL_OK) && (ensemblePtr->flags & ENSEMBLE_DEAD)) {
2301 if (!Tcl_InterpDeleted(interp)) {
2302 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2303 "unknown subcommand handler deleted its ensemble", -1));
2304 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "UNKNOWN_DELETED",
2305 (char *)NULL);
2306 }
2307 result = TCL_ERROR;
2308 }
2309 Tcl_Release(ensemblePtr);
2310
2311 /*
2312 * On success the result is a list of words that form the command to be
2313 * executed. If the list is empty, the ensemble should have been updated,
2314 * so ask the ensemble engine to reparse the original command.
2315 */
2316
2317 if (result == TCL_OK) {
2318 *prefixObjPtr = Tcl_GetObjResult(interp);
2319 Tcl_IncrRefCount(*prefixObjPtr);
2320 TclDecrRefCount(unknownCmd);
2321 Tcl_ResetResult(interp);
2322
2323 /* A non-empty list is the replacement command. */
2324
2325 if (TclListObjLength(interp, *prefixObjPtr, &prefixObjc) != TCL_OK) {
2326 TclDecrRefCount(*prefixObjPtr);
2327 Tcl_AddErrorInfo(interp, "\n while parsing result of "
2328 "ensemble unknown subcommand handler");
2329 return TCL_ERROR;
2330 }
2331 if (prefixObjc > 0) {
2332 return TCL_OK;
2333 }
2334
2335 /*
2336 * Empty result => reparse.
2337 */
2338
2339 TclDecrRefCount(*prefixObjPtr);
2340 return TCL_CONTINUE;
2341 }
2342
2343 /*
2344 * Convert exceptional result to an error.
2345 */
2346
2347 if (!Tcl_InterpDeleted(interp)) {
2348 if (result != TCL_ERROR) {
2349 Tcl_ResetResult(interp);
2350 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2351 "unknown subcommand handler returned bad code: ", -1));
2352 switch (result) {
2353 case TCL_RETURN:
2354 Tcl_AppendToObj(Tcl_GetObjResult(interp), "return", -1);
2355 break;
2356 case TCL_BREAK:
2357 Tcl_AppendToObj(Tcl_GetObjResult(interp), "break", -1);
2358 break;
2359 case TCL_CONTINUE:
2360 Tcl_AppendToObj(Tcl_GetObjResult(interp), "continue", -1);
2361 break;
2362 default:
2363 Tcl_AppendPrintfToObj(Tcl_GetObjResult(interp), "%d", result);
2364 }
2365 Tcl_AddErrorInfo(interp, "\n result of "
2366 "ensemble unknown subcommand handler: ");
2367 Tcl_AppendObjToErrorInfo(interp, unknownCmd);
2368 Tcl_SetErrorCode(interp, "TCL", "ENSEMBLE", "UNKNOWN_RESULT",
2369 (char *)NULL);
2370 } else {
2371 Tcl_AddErrorInfo(interp,
2372 "\n (ensemble unknown subcommand handler)");
2373 }
2374 }
2375 TclDecrRefCount(unknownCmd);
2376 return TCL_ERROR;
2377 }
2378
2379 /*
2380 *----------------------------------------------------------------------
2381 *
2382 * MakeCachedEnsembleCommand --
2383 *
2384 * Caches what has been computed so far to minimize string copying.
2385 * Starts by deleting any existing representation but reusing the existing
2386 * structure if it is an ensembleCmd.
2387 *
2388 * Results:
2389 * None.
2390 *
2391 * Side effects:
2392 * Converts the internal representation of the given object to an
2393 * ensembleCmd.
2394 *
2395 *----------------------------------------------------------------------
2396 */
2397
2398 static void
2399 MakeCachedEnsembleCommand(
2400 Tcl_Obj *objPtr,
2401 EnsembleConfig *ensemblePtr,
2402 Tcl_HashEntry *hPtr,
2403 Tcl_Obj *fix)
2404 {
2405 EnsembleCmdRep *ensembleCmd;
2406
2407 if (objPtr->typePtr == &ensembleCmdType) {
2408 ensembleCmd = (EnsembleCmdRep *)objPtr->internalRep.twoPtrValue.ptr1;
2409 TclCleanupCommandMacro(ensembleCmd->token);
2410 if (ensembleCmd->fix) {
2411 Tcl_DecrRefCount(ensembleCmd->fix);
2412 }
2413 } else {
2414 /*
2415 * Replace any old internal representation with a new one.
2416 */
2417
2418 TclFreeIntRep(objPtr);
2419 ensembleCmd = (EnsembleCmdRep *)ckalloc(sizeof(EnsembleCmdRep));
2420 objPtr->internalRep.twoPtrValue.ptr1 = ensembleCmd;
2421 objPtr->typePtr = &ensembleCmdType;
2422 }
2423
2424 /*
2425 * Populate the internal rep.
2426 */
2427
2428 ensembleCmd->epoch = ensemblePtr->epoch;
2429 ensembleCmd->token = (Command *) ensemblePtr->token;
2430 ensembleCmd->token->refCount++;
2431 if (fix) {
2432 Tcl_IncrRefCount(fix);
2433 }
2434 ensembleCmd->fix = fix;
2435 ensembleCmd->hPtr = hPtr;
2436 }
2437
2438 /*
2439 *----------------------------------------------------------------------
2440 *
2441 * DeleteEnsembleConfig --
2442 *
2443 * Destroys the data structure used to represent an ensemble. Called when
2444 * the procedure for the ensemble is deleted, which happens automatically
2445 * if the namespace for the ensemble is deleted. Deleting the procedure
2446 * for an ensemble is the right way to initiate cleanup.
2447 *
2448 * Results:
2449 * None.
2450 *
2451 * Side effects:
2452 * Memory is eventually deallocated.
2453 *
2454 *----------------------------------------------------------------------
2455 */
2456
2457 static void
2458 ClearTable(
2459 EnsembleConfig *ensemblePtr)
2460 {
2461 Tcl_HashTable *hash = &ensemblePtr->subcommandTable;
2462
2463 if (hash->numEntries != 0) {
2464 Tcl_HashSearch search;
2465 Tcl_HashEntry *hPtr = Tcl_FirstHashEntry(hash, &search);
2466
2467 while (hPtr != NULL) {
2468 Tcl_Obj *prefixObj = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
2469 Tcl_DecrRefCount(prefixObj);
2470 hPtr = Tcl_NextHashEntry(&search);
2471 }
2472 ckfree((char *) ensemblePtr->subcommandArrayPtr);
2473 }
2474 Tcl_DeleteHashTable(hash);
2475 }
2476
2477 static void
2478 DeleteEnsembleConfig(
2479 ClientData clientData)
2480 {
2481 EnsembleConfig *ensemblePtr = (EnsembleConfig *)clientData;
2482 Namespace *nsPtr = ensemblePtr->nsPtr;
2483
2484 /* Unlink from the ensemble chain if it not already marked as unlinked. */
2485
2486 if (ensemblePtr->next != ensemblePtr) {
2487 EnsembleConfig *ensPtr = (EnsembleConfig *) nsPtr->ensembles;
2488
2489 if (ensPtr == ensemblePtr) {
2490 nsPtr->ensembles = (Tcl_Ensemble *) ensemblePtr->next;
2491 } else {
2492 while (ensPtr != NULL) {
2493 if (ensPtr->next == ensemblePtr) {
2494 ensPtr->next = ensemblePtr->next;
2495 break;
2496 }
2497 ensPtr = ensPtr->next;
2498 }
2499 }
2500 }
2501
2502 /*
2503 * Mark the namespace as dead so code that uses Tcl_Preserve() can tell
2504 * whether disaster happened anyway.
2505 */
2506
2507 ensemblePtr->flags |= ENSEMBLE_DEAD;
2508
2509 /*
2510 * Release the fields that contain pointers.
2511 */
2512
2513 ClearTable(ensemblePtr);
2514 if (ensemblePtr->subcmdList != NULL) {
2515 Tcl_DecrRefCount(ensemblePtr->subcmdList);
2516 }
2517 if (ensemblePtr->parameterList != NULL) {
2518 Tcl_DecrRefCount(ensemblePtr->parameterList);
2519 }
2520 if (ensemblePtr->subcommandDict != NULL) {
2521 Tcl_DecrRefCount(ensemblePtr->subcommandDict);
2522 }
2523 if (ensemblePtr->unknownHandler != NULL) {
2524 Tcl_DecrRefCount(ensemblePtr->unknownHandler);
2525 }
2526
2527 /*
2528 * Arrange for the structure to be reclaimed. This is complex because it is
2529 * necessary to react sensibly when an ensemble is deleted during its
2530 * initialisation, particularly in the case of an unknown callback.
2531 */
2532
2533 Tcl_EventuallyFree(ensemblePtr, TCL_DYNAMIC);
2534 }
2535
2536 /*
2537 *----------------------------------------------------------------------
2538 *
2539 * BuildEnsembleConfig --
2540 *
2541 * Creates the internal data structures that describe how an ensemble
2542 * looks. The structures are a hash map from the full command name to the
2543 * Tcl list that describes the implementation prefix words, and a sorted
2544 * array of all the full command names to allow for reasonably efficient
2545 * handling of an unambiguous prefix.
2546 *
2547 * Results:
2548 * None.
2549 *
2550 * Side effects:
2551 * Reallocates and rebuilds the hash table and array stored at the
2552 * ensemblePtr argument. For large ensembles or large namespaces, this is
2553 * may be an expensive operation.
2554 *
2555 *----------------------------------------------------------------------
2556 */
2557
2558 static void
2559 BuildEnsembleConfig(
2560 EnsembleConfig *ensemblePtr)
2561 {
2562 Tcl_HashSearch search; /* Used for scanning the commands in
2563 * the namespace for this ensemble. */
2564 int i, j;
2565 int isNew;
2566 Tcl_HashTable *hash = &ensemblePtr->subcommandTable;
2567 Tcl_HashEntry *hPtr;
2568 Tcl_Obj *mapDict = ensemblePtr->subcommandDict;
2569 Tcl_Obj *subList = ensemblePtr->subcmdList;
2570
2571 ClearTable(ensemblePtr);
2572 Tcl_InitHashTable(hash, TCL_STRING_KEYS);
2573
2574 if (subList) {
2575 int subc;
2576 Tcl_Obj **subv, *target, *cmdObj, *cmdPrefixObj;
2577 const char *name;
2578
2579 /*
2580 * There is a list of exactly what subcommands go in the table.
2581 * Determine the target for each.
2582 */
2583
2584 TclListObjGetElements(NULL, subList, &subc, &subv);
2585 if (subList == mapDict) {
2586 /*
2587 * Unusual case where explicit list of subcommands is same value
2588 * as the dict mapping to targets.
2589 */
2590
2591 for (i = 0; i < subc; i += 2) {
2592 name = TclGetString(subv[i]);
2593 hPtr = Tcl_CreateHashEntry(hash, name, &isNew);
2594 if (!isNew) {
2595 cmdObj = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
2596 Tcl_DecrRefCount(cmdObj);
2597 }
2598 Tcl_SetHashValue(hPtr, subv[i+1]);
2599 Tcl_IncrRefCount(subv[i+1]);
2600
2601 name = TclGetString(subv[i+1]);
2602 hPtr = Tcl_CreateHashEntry(hash, name, &isNew);
2603 if (isNew) {
2604 cmdObj = Tcl_NewStringObj(name, -1);
2605 cmdPrefixObj = Tcl_NewListObj(1, &cmdObj);
2606 Tcl_SetHashValue(hPtr, cmdPrefixObj);
2607 Tcl_IncrRefCount(cmdPrefixObj);
2608 }
2609 }
2610 } else {
2611 /* Usual case where we can freely act on the list and dict. */
2612
2613 for (i = 0; i < subc; i++) {
2614 name = TclGetString(subv[i]);
2615 hPtr = Tcl_CreateHashEntry(hash, name, &isNew);
2616 if (!isNew) {
2617 continue;
2618 }
2619
2620 /* Lookup target in the dictionary */
2621 if (mapDict) {
2622 Tcl_DictObjGet(NULL, mapDict, subv[i], &target);
2623 if (target) {
2624 Tcl_SetHashValue(hPtr, target);
2625 Tcl_IncrRefCount(target);
2626 continue;
2627 }
2628 }
2629
2630 /*
2631 * Target was not in the dictionary. Map onto the namespace.
2632 * In this case there is no guarantee that the command
2633 * is actually there. It is the responsibility of the
2634 * programmer (or [::unknown] of course) to provide the procedure.
2635 */
2636
2637 cmdObj = Tcl_NewStringObj(name, -1);
2638 cmdPrefixObj = Tcl_NewListObj(1, &cmdObj);
2639 Tcl_SetHashValue(hPtr, cmdPrefixObj);
2640 Tcl_IncrRefCount(cmdPrefixObj);
2641 }
2642 }
2643 } else if (mapDict) {
2644 /*
2645 * No subcmd list, but there is a mapping dictionary, so
2646 * use the keys of that. Convert the contents of the dictionary into the
2647 * form required for the internal hashtable of the ensemble.
2648 */
2649
2650 Tcl_DictSearch dictSearch;
2651 Tcl_Obj *keyObj, *valueObj;
2652 int done;
2653
2654 Tcl_DictObjFirst(NULL, ensemblePtr->subcommandDict, &dictSearch,
2655 &keyObj, &valueObj, &done);
2656 while (!done) {
2657 const char *name = TclGetString(keyObj);
2658
2659 hPtr = Tcl_CreateHashEntry(hash, name, &isNew);
2660 Tcl_SetHashValue(hPtr, valueObj);
2661 Tcl_IncrRefCount(valueObj);
2662 Tcl_DictObjNext(&dictSearch, &keyObj, &valueObj, &done);
2663 }
2664 } else {
2665 /*
2666 * Use the array of patterns and the hash table whose keys are the
2667 * commands exported by the namespace. The corresponding values do not
2668 * matter here. Filter the commands in the namespace against the
2669 * patterns in the export list to find out what commands are actually
2670 * exported. Use an intermediate hash table to make memory management
2671 * easier and to make exact matching much easier.
2672 *
2673 * Suggestion for future enhancement: Compute the unique prefixes and
2674 * place them in the hash too for even faster matching.
2675 */
2676
2677 hPtr = Tcl_FirstHashEntry(&ensemblePtr->nsPtr->cmdTable, &search);
2678 for (; hPtr!= NULL ; hPtr=Tcl_NextHashEntry(&search)) {
2679 char *nsCmdName = (char *) /* Name of command in namespace. */
2680 Tcl_GetHashKey(&ensemblePtr->nsPtr->cmdTable, hPtr);
2681
2682 for (i=0 ; i<ensemblePtr->nsPtr->numExportPatterns ; i++) {
2683 if (Tcl_StringMatch(nsCmdName,
2684 ensemblePtr->nsPtr->exportArrayPtr[i])) {
2685 hPtr = Tcl_CreateHashEntry(hash, nsCmdName, &isNew);
2686
2687 /*
2688 * Remember, hash entries have a full reference to the
2689 * substituted part of the command (as a list) as their
2690 * content!
2691 */
2692
2693 if (isNew) {
2694 Tcl_Obj *cmdObj, *cmdPrefixObj;
2695
2696 TclNewObj(cmdObj);
2697 Tcl_AppendStringsToObj(cmdObj,
2698 ensemblePtr->nsPtr->fullName,
2699 (ensemblePtr->nsPtr->parentPtr ? "::" : ""),
2700 nsCmdName, (char *)NULL);
2701 cmdPrefixObj = Tcl_NewListObj(1, &cmdObj);
2702 Tcl_SetHashValue(hPtr, cmdPrefixObj);
2703 Tcl_IncrRefCount(cmdPrefixObj);
2704 }
2705 break;
2706 }
2707 }
2708 }
2709 }
2710
2711 if (hash->numEntries == 0) {
2712 ensemblePtr->subcommandArrayPtr = NULL;
2713 return;
2714 }
2715
2716 /*
2717 * Create a sorted array of all subcommands in the ensemble. Hash tables
2718 * are all very well for a quick look for an exact match, but they can't
2719 * determine things like whether a string is a prefix of another, at least
2720 * not without a lot of preparation, and they're not useful for generating
2721 * the error message either.
2722 *
2723 * Do this by filling an array with the names: Use the hash keys
2724 * directly to save a copy since any time we change the array we change
2725 * the hash too, and vice versa, and run quicksort over the array.
2726 */
2727
2728 ensemblePtr->subcommandArrayPtr = (char **)
2729 ckalloc(sizeof(char *) * hash->numEntries);
2730
2731 /*
2732 * Fill the array from both ends as this reduces the likelihood of
2733 * performance problems in qsort(). This makes this code much more opaque,
2734 * but the naive alternatve:
2735 *
2736 * for (hPtr=Tcl_FirstHashEntry(hash,&search),i=0 ;
2737 * hPtr!=NULL ; hPtr=Tcl_NextHashEntry(&search),i++) {
2738 * ensemblePtr->subcommandArrayPtr[i] = Tcl_GetHashKey(hash, &hPtr);
2739 * }
2740 *
2741 * can produce long runs of precisely ordered table entries when the
2742 * commands in the namespace are declared in a sorted fashion, which is an
2743 * ordering some people like, and the hashing functions or the command
2744 * names themselves are fairly unfortunate. Filling from both ends means
2745 * that it requires active malice, and probably a debugger, to get qsort()
2746 * to have awful runtime behaviour.
2747 */
2748
2749 i = 0;
2750 j = hash->numEntries;
2751 hPtr = Tcl_FirstHashEntry(hash, &search);
2752 while (hPtr != NULL) {
2753 ensemblePtr->subcommandArrayPtr[i++] = (char *)Tcl_GetHashKey(hash, hPtr);
2754 hPtr = Tcl_NextHashEntry(&search);
2755 if (hPtr == NULL) {
2756 break;
2757 }
2758 ensemblePtr->subcommandArrayPtr[--j] = (char *)Tcl_GetHashKey(hash, hPtr);
2759 hPtr = Tcl_NextHashEntry(&search);
2760 }
2761 if (hash->numEntries > 1) {
2762 qsort(ensemblePtr->subcommandArrayPtr, hash->numEntries,
2763 sizeof(char *), NsEnsembleStringOrder);
2764 }
2765 }
2766
2767 /*
2768 *----------------------------------------------------------------------
2769 *
2770 * NsEnsembleStringOrder --
2771 *
2772 * Helper to for uset with sort() that compares two string pointers.
2773 *
2774 * Results:
2775 * -1 if the first string is smaller, 1 if the second string is smaller,
2776 * and 0 if they are equal.
2777 *
2778 * Side effects:
2779 * None.
2780 *
2781 *----------------------------------------------------------------------
2782 */
2783
2784 static int
2785 NsEnsembleStringOrder(
2786 const void *strPtr1,
2787 const void *strPtr2)
2788 {
2789 return strcmp(*(const char **)strPtr1, *(const char **)strPtr2);
2790 }
2791
2792 /*
2793 *----------------------------------------------------------------------
2794 *
2795 * FreeEnsembleCmdRep --
2796 *
2797 * Destroys the internal representation of a Tcl_Obj that has been
2798 * holding information about a command in an ensemble.
2799 *
2800 * Results:
2801 * None.
2802 *
2803 * Side effects:
2804 * Memory is deallocated. If this held the last reference to a
2805 * namespace's main structure, that main structure will also be
2806 * destroyed.
2807 *
2808 *----------------------------------------------------------------------
2809 */
2810
2811 static void
2812 FreeEnsembleCmdRep(
2813 Tcl_Obj *objPtr)
2814 {
2815 EnsembleCmdRep *ensembleCmd = (EnsembleCmdRep *)objPtr->internalRep.twoPtrValue.ptr1;
2816
2817 TclCleanupCommandMacro(ensembleCmd->token);
2818 if (ensembleCmd->fix) {
2819 Tcl_DecrRefCount(ensembleCmd->fix);
2820 }
2821 ckfree(ensembleCmd);
2822 objPtr->typePtr = NULL;
2823 }
2824
2825 /*
2826 *----------------------------------------------------------------------
2827 *
2828 * DupEnsembleCmdRep --
2829 *
2830 * Makes one Tcl_Obj into a copy of another that is a subcommand of an
2831 * ensemble.
2832 *
2833 * Results:
2834 * None.
2835 *
2836 * Side effects:
2837 * Memory is allocated, and the namespace that the ensemble is built on
2838 * top of gains another reference.
2839 *
2840 *----------------------------------------------------------------------
2841 */
2842
2843 static void
2844 DupEnsembleCmdRep(
2845 Tcl_Obj *objPtr,
2846 Tcl_Obj *copyPtr)
2847 {
2848 EnsembleCmdRep *ensembleCmd = (EnsembleCmdRep *)objPtr->internalRep.twoPtrValue.ptr1;
2849 EnsembleCmdRep *ensembleCopy = (EnsembleCmdRep *)ckalloc(sizeof(EnsembleCmdRep));
2850
2851 copyPtr->typePtr = &ensembleCmdType;
2852 copyPtr->internalRep.twoPtrValue.ptr1 = ensembleCopy;
2853 ensembleCopy->epoch = ensembleCmd->epoch;
2854 ensembleCopy->token = ensembleCmd->token;
2855 ensembleCopy->token->refCount++;
2856 ensembleCopy->fix = ensembleCmd->fix;
2857 if (ensembleCopy->fix) {
2858 Tcl_IncrRefCount(ensembleCopy->fix);
2859 }
2860 ensembleCopy->hPtr = ensembleCmd->hPtr;
2861 }
2862
2863 /*
2864 *----------------------------------------------------------------------
2865 *
2866 * TclCompileEnsemble --
2867 *
2868 * Procedure called to compile an ensemble command. Note that most
2869 * ensembles are not compiled, since modifying a compiled ensemble causes
2870 * a invalidation of all existing bytecode (expensive!) which is not
2871 * normally warranted.
2872 *
2873 * Results:
2874 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2875 * evaluation to runtime.
2876 *
2877 * Side effects:
2878 * Instructions are added to envPtr to execute the subcommands of the
2879 * ensemble at runtime if a compile-time mapping is possible.
2880 *
2881 *----------------------------------------------------------------------
2882 */
2883
2884 int
2885 TclCompileEnsemble(
2886 Tcl_Interp *interp, /* Used for error reporting. */
2887 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2888 * created by Tcl_ParseCommand. */
2889 Command *cmdPtr, /* Points to definition of command being
2890 * compiled. */
2891 CompileEnv *envPtr) /* Holds resulting instructions. */
2892 {
2893 DefineLineInformation;
2894 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
2895 Tcl_Obj *mapObj, *subcmdObj, *targetCmdObj, *listObj, **elems;
2896 Tcl_Obj *replaced, *replacement;
2897 Tcl_Command ensemble = (Tcl_Command) cmdPtr;
2898 Command *oldCmdPtr = cmdPtr, *newCmdPtr;
2899 int len, result, flags = 0, i, depth = 1, invokeAnyway = 0;
2900 int ourResult = TCL_ERROR;
2901 unsigned numBytes;
2902 const char *word;
2903
2904 TclNewObj(replaced);
2905 Tcl_IncrRefCount(replaced);
2906 if (parsePtr->numWords <= depth) {
2907 goto tryCompileToInv;
2908 }
2909 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2910 /*
2911 * Too hard.
2912 */
2913
2914 goto tryCompileToInv;
2915 }
2916
2917 /*
2918 * This is where we return to if we are parsing multiple nested compiled
2919 * ensembles. [info object] is such a beast.
2920 */
2921
2922 checkNextWord:
2923 word = tokenPtr[1].start;
2924 numBytes = tokenPtr[1].size;
2925
2926 /*
2927 * There's a sporting chance we'll be able to compile this. But now we
2928 * must check properly. To do that, check that we're compiling an ensemble
2929 * that has a compilable command as its appropriate subcommand.
2930 */
2931
2932 if (Tcl_GetEnsembleMappingDict(NULL, ensemble, &mapObj) != TCL_OK
2933 || mapObj == NULL) {
2934 /*
2935 * Either not an ensemble or a mapping isn't installed. Crud. Too hard
2936 * to proceed.
2937 */
2938
2939 goto tryCompileToInv;
2940 }
2941
2942 /*
2943 * Also refuse to compile anything that uses a formal parameter list for
2944 * now, on the grounds that it is too complex.
2945 */
2946
2947 if (Tcl_GetEnsembleParameterList(NULL, ensemble, &listObj) != TCL_OK
2948 || listObj != NULL) {
2949 /*
2950 * Figuring out how to compile this has become too much. Bail out.
2951 */
2952
2953 goto tryCompileToInv;
2954 }
2955
2956 /*
2957 * Next, get the flags. We need them on several code paths so that we can
2958 * know whether we're to do prefix matching.
2959 */
2960
2961 (void) Tcl_GetEnsembleFlags(NULL, ensemble, &flags);
2962
2963 /*
2964 * Check to see if there's also a subcommand list; must check to see if
2965 * the subcommand we are calling is in that list if it exists, since that
2966 * list filters the entries in the map.
2967 */
2968
2969 (void) Tcl_GetEnsembleSubcommandList(NULL, ensemble, &listObj);
2970 if (listObj != NULL) {
2971 int sclen;
2972 const char *str;
2973 Tcl_Obj *matchObj = NULL;
2974
2975 if (TclListObjGetElements(NULL, listObj, &len, &elems) != TCL_OK) {
2976 goto tryCompileToInv;
2977 }
2978 for (i=0 ; i<len ; i++) {
2979 str = Tcl_GetStringFromObj(elems[i], &sclen);
2980 if ((sclen == (int)numBytes) && !memcmp(word, str, numBytes)) {
2981 /*
2982 * Exact match! Excellent!
2983 */
2984
2985 result = Tcl_DictObjGet(NULL, mapObj,elems[i], &targetCmdObj);
2986 if (result != TCL_OK || targetCmdObj == NULL) {
2987 goto tryCompileToInv;
2988 }
2989 replacement = elems[i];
2990 goto doneMapLookup;
2991 }
2992
2993 /*
2994 * Check to see if we've got a prefix match. A single prefix match
2995 * is fine, and allows us to refine our dictionary lookup, but
2996 * multiple prefix matches is a Bad Thing and will prevent us from
2997 * making progress. Note that we cannot do the lookup immediately
2998 * in the prefix case; might be another entry later in the list
2999 * that causes things to fail.
3000 */
3001
3002 if ((flags & TCL_ENSEMBLE_PREFIX)
3003 && strncmp(word, str, numBytes) == 0) {
3004 if (matchObj != NULL) {
3005 goto tryCompileToInv;
3006 }
3007 matchObj = elems[i];
3008 }
3009 }
3010 if (matchObj == NULL) {
3011 goto tryCompileToInv;
3012 }
3013 result = Tcl_DictObjGet(NULL, mapObj, matchObj, &targetCmdObj);
3014 if (result != TCL_OK || targetCmdObj == NULL) {
3015 goto tryCompileToInv;
3016 }
3017 replacement = matchObj;
3018 } else {
3019 Tcl_DictSearch s;
3020 int done, matched;
3021 Tcl_Obj *tmpObj;
3022
3023 /*
3024 * No map, so check the dictionary directly.
3025 */
3026
3027 TclNewStringObj(subcmdObj, word, numBytes);
3028 result = Tcl_DictObjGet(NULL, mapObj, subcmdObj, &targetCmdObj);
3029 if (result == TCL_OK && targetCmdObj != NULL) {
3030 /*
3031 * Got it. Skip the fiddling around with prefixes.
3032 */
3033
3034 replacement = subcmdObj;
3035 goto doneMapLookup;
3036 }
3037 TclDecrRefCount(subcmdObj);
3038
3039 /*
3040 * We've not literally got a valid subcommand. But maybe we have a
3041 * prefix. Check if prefix matches are allowed.
3042 */
3043
3044 if (!(flags & TCL_ENSEMBLE_PREFIX)) {
3045 goto tryCompileToInv;
3046 }
3047
3048 /*
3049 * Iterate over the keys in the dictionary, checking to see if we're a
3050 * prefix.
3051 */
3052
3053 Tcl_DictObjFirst(NULL, mapObj, &s, &subcmdObj, &tmpObj, &done);
3054 matched = 0;
3055 replacement = NULL; /* Silence, fool compiler! */
3056 while (!done) {
3057 if (strncmp(TclGetString(subcmdObj), word, numBytes) == 0) {
3058 if (matched++) {
3059 /*
3060 * Must have matched twice! Not unique, so no point
3061 * looking further.
3062 */
3063
3064 break;
3065 }
3066 replacement = subcmdObj;
3067 targetCmdObj = tmpObj;
3068 }
3069 Tcl_DictObjNext(&s, &subcmdObj, &tmpObj, &done);
3070 }
3071 Tcl_DictObjDone(&s);
3072
3073 /*
3074 * If we have anything other than a single match, we've failed the
3075 * unique prefix check.
3076 */
3077
3078 if (matched != 1) {
3079 invokeAnyway = 1;
3080 goto tryCompileToInv;
3081 }
3082 }
3083
3084 /*
3085 * OK, we definitely map to something. But what?
3086 *
3087 * The command we map to is the first word out of the map element. Note
3088 * that we also reject dealing with multi-element rewrites if we are in a
3089 * safe interpreter, as there is otherwise a (highly gnarly!) way to make
3090 * Tcl crash open to exploit.
3091 */
3092
3093 doneMapLookup:
3094 Tcl_ListObjAppendElement(NULL, replaced, replacement);
3095 if (TclListObjGetElements(NULL, targetCmdObj, &len, &elems) != TCL_OK) {
3096 goto tryCompileToInv;
3097 } else if (len != 1) {
3098 /*
3099 * Note that at this point we know we can't issue any special
3100 * instruction sequence as the mapping isn't one that we support at
3101 * the compiled level.
3102 */
3103
3104 goto cleanup;
3105 }
3106 targetCmdObj = elems[0];
3107
3108 oldCmdPtr = cmdPtr;
3109 Tcl_IncrRefCount(targetCmdObj);
3110 newCmdPtr = (Command *) Tcl_GetCommandFromObj(interp, targetCmdObj);
3111 TclDecrRefCount(targetCmdObj);
3112 if (newCmdPtr == NULL || (Tcl_IsSafe(interp) && !cmdPtr->compileProc)
3113 || newCmdPtr->nsPtr->flags & NS_SUPPRESS_COMPILATION
3114 || newCmdPtr->flags & CMD_HAS_EXEC_TRACES
3115 || ((Interp *)interp)->flags & DONT_COMPILE_CMDS_INLINE) {
3116 /*
3117 * Maps to an undefined command or a command without a compiler.
3118 * Cannot compile.
3119 */
3120 goto cleanup;
3121 }
3122 cmdPtr = newCmdPtr;
3123 depth++;
3124
3125 /*
3126 * See whether we have a nested ensemble. If we do, we can go round the
3127 * mulberry bush again, consuming the next word.
3128 */
3129
3130 if (cmdPtr->compileProc == TclCompileEnsemble) {
3131 tokenPtr = TokenAfter(tokenPtr);
3132 if (parsePtr->numWords < depth + 1
3133 || tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
3134 /*
3135 * Too hard because the user has done something unpleasant like
3136 * omitting the sub-ensemble's command name or used a non-constant
3137 * name for a sub-ensemble's command name; we respond by bailing
3138 * out completely (this is a rare case). [Bug 6d2f249a01]
3139 */
3140
3141 goto cleanup;
3142 }
3143 ensemble = (Tcl_Command) cmdPtr;
3144 goto checkNextWord;
3145 }
3146
3147 /*
3148 * Now that the mapping process is done we actually try to compile.
3149 * If there is a subcommand compiler and that successfully produces code,
3150 * we'll use that. Otherwise, we fall back to generating opcodes to do the
3151 * invoke at runtime.
3152 */
3153
3154 invokeAnyway = 1;
3155 if (TCL_OK == TclAttemptCompileProc(interp, parsePtr, depth, cmdPtr,
3156 envPtr)) {
3157 ourResult = TCL_OK;
3158 goto cleanup;
3159 }
3160
3161 /*
3162 * Throw out any line information generated by the failed compile attempt.
3163 */
3164
3165 while (mapPtr->nuloc > eclIndex + 1) {
3166 mapPtr->nuloc--;
3167 ckfree(mapPtr->loc[mapPtr->nuloc].line);
3168 mapPtr->loc[mapPtr->nuloc].line = NULL;
3169 }
3170
3171 /*
3172 * Reset the index of next command. Toss out any from failed nested
3173 * partial compiles.
3174 */
3175
3176 envPtr->numCommands = mapPtr->nuloc;
3177
3178 /*
3179 * Failed to do a full compile for some reason. Try to do a direct invoke
3180 * instead of going through the ensemble lookup process again.
3181 */
3182
3183 tryCompileToInv:
3184 if (depth < 250) {
3185 if (depth > 1) {
3186 if (!invokeAnyway) {
3187 cmdPtr = oldCmdPtr;
3188 depth--;
3189 }
3190 }
3191 /*
3192 * The length of the "replaced" list must be depth-1. Trim back
3193 * any extra elements that might have been appended by failing
3194 * pathways above.
3195 */
3196 (void) Tcl_ListObjReplace(NULL, replaced, depth-1, LIST_MAX, 0, NULL);
3197
3198 /*
3199 * TODO: Reconsider whether we ought to call CompileToInvokedCommand()
3200 * when depth==1. In that case we are choosing to emit the
3201 * INST_INVOKE_REPLACE bytecode when there is in fact no replacing
3202 * to be done. It would be equally functional and presumably more
3203 * performant to fall through to cleanup below, return TCL_ERROR,
3204 * and let the compiler harness emit the INST_INVOKE_STK
3205 * implementation for us.
3206 */
3207
3208 CompileToInvokedCommand(interp, parsePtr, replaced, cmdPtr, envPtr);
3209 ourResult = TCL_OK;
3210 }
3211
3212 /*
3213 * Release the memory we allocated. If we've got here, we've either done
3214 * something useful or we're in a case that we can't compile at all and
3215 * we're just giving up.
3216 */
3217
3218 cleanup:
3219 Tcl_DecrRefCount(replaced);
3220 return ourResult;
3221 }
3222
3223 int
3224 TclAttemptCompileProc(
3225 Tcl_Interp *interp,
3226 Tcl_Parse *parsePtr,
3227 int depth,
3228 Command *cmdPtr,
3229 CompileEnv *envPtr) /* Holds resulting instructions. */
3230 {
3231 DefineLineInformation;
3232 int result;
3233 int i;
3234 Tcl_Token *saveTokenPtr = parsePtr->tokenPtr;
3235 int savedStackDepth = envPtr->currStackDepth;
3236 unsigned savedCodeNext = envPtr->codeNext - envPtr->codeStart;
3237 int savedAuxDataArrayNext = envPtr->auxDataArrayNext;
3238 int savedExceptArrayNext = envPtr->exceptArrayNext;
3239 #ifdef TCL_COMPILE_DEBUG
3240 int savedExceptDepth = envPtr->exceptDepth;
3241 #endif
3242
3243 if (cmdPtr->compileProc == NULL) {
3244 return TCL_ERROR;
3245 }
3246
3247 /*
3248 * Advance parsePtr->tokenPtr so that it points at the last subcommand.
3249 * This will be wrong but it will not matter, and it will put the
3250 * tokens for the arguments in the right place without the need to
3251 * allocate a synthetic Tcl_Parse struct or copy tokens around.
3252 */
3253
3254 for (i = 0; i < depth - 1; i++) {
3255 parsePtr->tokenPtr = TokenAfter(parsePtr->tokenPtr);
3256 }
3257 parsePtr->numWords -= (depth - 1);
3258
3259 /*
3260 * Shift the line information arrays to account for different word
3261 * index values.
3262 */
3263
3264 mapPtr->loc[eclIndex].line += (depth - 1);
3265 mapPtr->loc[eclIndex].next += (depth - 1);
3266
3267 /*
3268 * Hand off compilation to the subcommand compiler. At last!
3269 */
3270
3271 result = cmdPtr->compileProc(interp, parsePtr, cmdPtr, envPtr);
3272
3273 /*
3274 * Undo the shift.
3275 */
3276
3277 mapPtr->loc[eclIndex].line -= (depth - 1);
3278 mapPtr->loc[eclIndex].next -= (depth - 1);
3279
3280 parsePtr->numWords += (depth - 1);
3281 parsePtr->tokenPtr = saveTokenPtr;
3282
3283 /*
3284 * If our target failed to compile, revert any data from failed partial
3285 * compiles. Note that envPtr->numCommands need not be checked because
3286 * we avoid compiling subcommands that recursively call TclCompileScript().
3287 */
3288
3289 #ifdef TCL_COMPILE_DEBUG
3290 if (envPtr->exceptDepth != savedExceptDepth) {
3291 Tcl_Panic("ExceptionRange Starts and Ends do not balance");
3292 }
3293 #endif
3294
3295 if (result != TCL_OK) {
3296 ExceptionAux *auxPtr = envPtr->exceptAuxArrayPtr;
3297
3298 for (i = 0; i < savedExceptArrayNext; i++) {
3299 while (auxPtr->numBreakTargets > 0
3300 && auxPtr->breakTargets[auxPtr->numBreakTargets - 1]
3301 >= savedCodeNext) {
3302 auxPtr->numBreakTargets--;
3303 }
3304 while (auxPtr->numContinueTargets > 0
3305 && auxPtr->continueTargets[auxPtr->numContinueTargets - 1]
3306 >= savedCodeNext) {
3307 auxPtr->numContinueTargets--;
3308 }
3309 auxPtr++;
3310 }
3311 envPtr->exceptArrayNext = savedExceptArrayNext;
3312
3313 if (savedAuxDataArrayNext != envPtr->auxDataArrayNext) {
3314 AuxData *auxDataPtr = envPtr->auxDataArrayPtr;
3315 AuxData *auxDataEnd = auxDataPtr;
3316
3317 auxDataPtr += savedAuxDataArrayNext;
3318 auxDataEnd += envPtr->auxDataArrayNext;
3319
3320 while (auxDataPtr < auxDataEnd) {
3321 if (auxDataPtr->type->freeProc != NULL) {
3322 auxDataPtr->type->freeProc(auxDataPtr->clientData);
3323 }
3324 auxDataPtr++;
3325 }
3326 envPtr->auxDataArrayNext = savedAuxDataArrayNext;
3327 }
3328 envPtr->currStackDepth = savedStackDepth;
3329 envPtr->codeNext = envPtr->codeStart + savedCodeNext;
3330 #ifdef TCL_COMPILE_DEBUG
3331 } else {
3332 /*
3333 * Confirm that the command compiler generated a single value on
3334 * the stack as its result. This is only done in debugging mode,
3335 * as it *should* be correct and normal users have no reasonable
3336 * way to fix it anyway.
3337 */
3338
3339 int diff = envPtr->currStackDepth - savedStackDepth;
3340
3341 if (diff != 1) {
3342 Tcl_Panic("bad stack adjustment when compiling"
3343 " %.*s (was %d instead of 1)", parsePtr->tokenPtr->size,
3344 parsePtr->tokenPtr->start, diff);
3345 }
3346 #endif
3347 }
3348
3349 return result;
3350 }
3351
3352 /*
3353 * How to compile a subcommand to a _replacing_ invoke of its implementation
3354 * command.
3355 */
3356
3357 static void
3358 CompileToInvokedCommand(
3359 Tcl_Interp *interp,
3360 Tcl_Parse *parsePtr,
3361 Tcl_Obj *replacements,
3362 Command *cmdPtr,
3363 CompileEnv *envPtr) /* Holds resulting instructions. */
3364 {
3365 DefineLineInformation;
3366 Tcl_Token *tokPtr;
3367 Tcl_Obj *objPtr, **words;
3368 char *bytes;
3369 int cmdLit, extraLiteralFlags = LITERAL_CMD_NAME;
3370 int i, numWords, length;
3371
3372 /*
3373 * Push the words of the command. Take care; the command words may be
3374 * scripts that have backslashes in them, and [info frame 0] can see the
3375 * difference. Hence the call to TclContinuationsEnterDerived...
3376 */
3377
3378 TclListObjGetElements(NULL, replacements, &numWords, &words);
3379 for (i = 0, tokPtr = parsePtr->tokenPtr; i < parsePtr->numWords;
3380 i++, tokPtr = TokenAfter(tokPtr)) {
3381 if (i > 0 && i <= numWords) {
3382 bytes = Tcl_GetStringFromObj(words[i-1], &length);
3383 PushLiteral(envPtr, bytes, length);
3384 continue;
3385 }
3386
3387 SetLineInformation(i);
3388 if (tokPtr->type == TCL_TOKEN_SIMPLE_WORD) {
3389 int literal = TclRegisterNewLiteral(envPtr,
3390 tokPtr[1].start, tokPtr[1].size);
3391
3392 if (envPtr->clNext) {
3393 TclContinuationsEnterDerived(
3394 TclFetchLiteral(envPtr, literal),
3395 tokPtr[1].start - envPtr->source,
3396 envPtr->clNext);
3397 }
3398 TclEmitPush(literal, envPtr);
3399 } else {
3400 CompileTokens(envPtr, tokPtr, interp);
3401 }
3402 }
3403
3404 /*
3405 * Push the name of the command we're actually dispatching to as part of
3406 * the implementation.
3407 */
3408
3409 TclNewObj(objPtr);
3410 Tcl_GetCommandFullName(interp, (Tcl_Command) cmdPtr, objPtr);
3411 bytes = Tcl_GetStringFromObj(objPtr, &length);
3412 if ((cmdPtr != NULL) && (cmdPtr->flags & CMD_VIA_RESOLVER)) {
3413 extraLiteralFlags |= LITERAL_UNSHARED;
3414 }
3415 cmdLit = TclRegisterLiteral(envPtr, bytes, length, extraLiteralFlags);
3416 TclSetCmdNameObj(interp, TclFetchLiteral(envPtr, cmdLit), cmdPtr);
3417 TclEmitPush(cmdLit, envPtr);
3418 TclDecrRefCount(objPtr);
3419
3420 /*
3421 * Do the replacing dispatch.
3422 */
3423
3424 TclEmitInvoke(envPtr, INST_INVOKE_REPLACE, parsePtr->numWords,numWords+1);
3425 }
3426
3427 /*
3428 * Helpers that do issuing of instructions for commands that "don't have
3429 * compilers" (well, they do; these). They all work by just generating base
3430 * code to invoke the command; they're intended for ensemble subcommands so
3431 * that the costs of INST_INVOKE_REPLACE can be avoided where we can work out
3432 * that they're not needed.
3433 *
3434 * Note that these are NOT suitable for commands where there's an argument
3435 * that is a script, as an [info level] or [info frame] in the inner context
3436 * can see the difference.
3437 */
3438
3439 static int
3440 CompileBasicNArgCommand(
3441 Tcl_Interp *interp, /* Used for error reporting. */
3442 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3443 * created by Tcl_ParseCommand. */
3444 Command *cmdPtr, /* Points to definition of command being
3445 * compiled. */
3446 CompileEnv *envPtr) /* Holds resulting instructions. */
3447 {
3448 Tcl_Obj *objPtr;
3449
3450 TclNewObj(objPtr);
3451 Tcl_IncrRefCount(objPtr);
3452 Tcl_GetCommandFullName(interp, (Tcl_Command) cmdPtr, objPtr);
3453 TclCompileInvocation(interp, parsePtr->tokenPtr, objPtr,
3454 parsePtr->numWords, envPtr);
3455 Tcl_DecrRefCount(objPtr);
3456 return TCL_OK;
3457 }
3458
3459 int
3460 TclCompileBasic0ArgCmd(
3461 Tcl_Interp *interp, /* Used for error reporting. */
3462 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3463 * created by Tcl_ParseCommand. */
3464 Command *cmdPtr, /* Points to definition of command being
3465 * compiled. */
3466 CompileEnv *envPtr) /* Holds resulting instructions. */
3467 {
3468 /*
3469 * Verify that the number of arguments is correct; that's the only case
3470 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3471 * which is the only code that sees the shenanigans of ensemble dispatch.
3472 */
3473
3474 if (parsePtr->numWords != 1) {
3475 return TCL_ERROR;
3476 }
3477
3478 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3479 }
3480
3481 int
3482 TclCompileBasic1ArgCmd(
3483 Tcl_Interp *interp, /* Used for error reporting. */
3484 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3485 * created by Tcl_ParseCommand. */
3486 Command *cmdPtr, /* Points to definition of command being
3487 * compiled. */
3488 CompileEnv *envPtr) /* Holds resulting instructions. */
3489 {
3490 /*
3491 * Verify that the number of arguments is correct; that's the only case
3492 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3493 * which is the only code that sees the shenanigans of ensemble dispatch.
3494 */
3495
3496 if (parsePtr->numWords != 2) {
3497 return TCL_ERROR;
3498 }
3499
3500 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3501 }
3502
3503 int
3504 TclCompileBasic2ArgCmd(
3505 Tcl_Interp *interp, /* Used for error reporting. */
3506 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3507 * created by Tcl_ParseCommand. */
3508 Command *cmdPtr, /* Points to definition of command being
3509 * compiled. */
3510 CompileEnv *envPtr) /* Holds resulting instructions. */
3511 {
3512 /*
3513 * Verify that the number of arguments is correct; that's the only case
3514 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3515 * which is the only code that sees the shenanigans of ensemble dispatch.
3516 */
3517
3518 if (parsePtr->numWords != 3) {
3519 return TCL_ERROR;
3520 }
3521
3522 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3523 }
3524
3525 int
3526 TclCompileBasic3ArgCmd(
3527 Tcl_Interp *interp, /* Used for error reporting. */
3528 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3529 * created by Tcl_ParseCommand. */
3530 Command *cmdPtr, /* Points to definition of command being
3531 * compiled. */
3532 CompileEnv *envPtr) /* Holds resulting instructions. */
3533 {
3534 /*
3535 * Verify that the number of arguments is correct; that's the only case
3536 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3537 * which is the only code that sees the shenanigans of ensemble dispatch.
3538 */
3539
3540 if (parsePtr->numWords != 4) {
3541 return TCL_ERROR;
3542 }
3543
3544 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3545 }
3546
3547 int
3548 TclCompileBasic0Or1ArgCmd(
3549 Tcl_Interp *interp, /* Used for error reporting. */
3550 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3551 * created by Tcl_ParseCommand. */
3552 Command *cmdPtr, /* Points to definition of command being
3553 * compiled. */
3554 CompileEnv *envPtr) /* Holds resulting instructions. */
3555 {
3556 /*
3557 * Verify that the number of arguments is correct; that's the only case
3558 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3559 * which is the only code that sees the shenanigans of ensemble dispatch.
3560 */
3561
3562 if (parsePtr->numWords != 1 && parsePtr->numWords != 2) {
3563 return TCL_ERROR;
3564 }
3565
3566 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3567 }
3568
3569 int
3570 TclCompileBasic1Or2ArgCmd(
3571 Tcl_Interp *interp, /* Used for error reporting. */
3572 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3573 * created by Tcl_ParseCommand. */
3574 Command *cmdPtr, /* Points to definition of command being
3575 * compiled. */
3576 CompileEnv *envPtr) /* Holds resulting instructions. */
3577 {
3578 /*
3579 * Verify that the number of arguments is correct; that's the only case
3580 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3581 * which is the only code that sees the shenanigans of ensemble dispatch.
3582 */
3583
3584 if (parsePtr->numWords != 2 && parsePtr->numWords != 3) {
3585 return TCL_ERROR;
3586 }
3587
3588 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3589 }
3590
3591 int
3592 TclCompileBasic2Or3ArgCmd(
3593 Tcl_Interp *interp, /* Used for error reporting. */
3594 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3595 * created by Tcl_ParseCommand. */
3596 Command *cmdPtr, /* Points to definition of command being
3597 * compiled. */
3598 CompileEnv *envPtr) /* Holds resulting instructions. */
3599 {
3600 /*
3601 * Verify that the number of arguments is correct; that's the only case
3602 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3603 * which is the only code that sees the shenanigans of ensemble dispatch.
3604 */
3605
3606 if (parsePtr->numWords != 3 && parsePtr->numWords != 4) {
3607 return TCL_ERROR;
3608 }
3609
3610 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3611 }
3612
3613 int
3614 TclCompileBasic0To2ArgCmd(
3615 Tcl_Interp *interp, /* Used for error reporting. */
3616 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3617 * created by Tcl_ParseCommand. */
3618 Command *cmdPtr, /* Points to definition of command being
3619 * compiled. */
3620 CompileEnv *envPtr) /* Holds resulting instructions. */
3621 {
3622 /*
3623 * Verify that the number of arguments is correct; that's the only case
3624 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3625 * which is the only code that sees the shenanigans of ensemble dispatch.
3626 */
3627
3628 if (parsePtr->numWords < 1 || parsePtr->numWords > 3) {
3629 return TCL_ERROR;
3630 }
3631
3632 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3633 }
3634
3635 int
3636 TclCompileBasic1To3ArgCmd(
3637 Tcl_Interp *interp, /* Used for error reporting. */
3638 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3639 * created by Tcl_ParseCommand. */
3640 Command *cmdPtr, /* Points to definition of command being
3641 * compiled. */
3642 CompileEnv *envPtr) /* Holds resulting instructions. */
3643 {
3644 /*
3645 * Verify that the number of arguments is correct; that's the only case
3646 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3647 * which is the only code that sees the shenanigans of ensemble dispatch.
3648 */
3649
3650 if (parsePtr->numWords < 2 || parsePtr->numWords > 4) {
3651 return TCL_ERROR;
3652 }
3653
3654 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3655 }
3656
3657 int
3658 TclCompileBasicMin0ArgCmd(
3659 Tcl_Interp *interp, /* Used for error reporting. */
3660 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3661 * created by Tcl_ParseCommand. */
3662 Command *cmdPtr, /* Points to definition of command being
3663 * compiled. */
3664 CompileEnv *envPtr) /* Holds resulting instructions. */
3665 {
3666 /*
3667 * Verify that the number of arguments is correct; that's the only case
3668 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3669 * which is the only code that sees the shenanigans of ensemble dispatch.
3670 */
3671
3672 if (parsePtr->numWords < 1) {
3673 return TCL_ERROR;
3674 }
3675
3676 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3677 }
3678
3679 int
3680 TclCompileBasicMin1ArgCmd(
3681 Tcl_Interp *interp, /* Used for error reporting. */
3682 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3683 * created by Tcl_ParseCommand. */
3684 Command *cmdPtr, /* Points to definition of command being
3685 * compiled. */
3686 CompileEnv *envPtr) /* Holds resulting instructions. */
3687 {
3688 /*
3689 * Verify that the number of arguments is correct; that's the only case
3690 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3691 * which is the only code that sees the shenanigans of ensemble dispatch.
3692 */
3693
3694 if (parsePtr->numWords < 2) {
3695 return TCL_ERROR;
3696 }
3697
3698 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3699 }
3700
3701 int
3702 TclCompileBasicMin2ArgCmd(
3703 Tcl_Interp *interp, /* Used for error reporting. */
3704 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3705 * created by Tcl_ParseCommand. */
3706 Command *cmdPtr, /* Points to definition of command being
3707 * compiled. */
3708 CompileEnv *envPtr) /* Holds resulting instructions. */
3709 {
3710 /*
3711 * Verify that the number of arguments is correct; that's the only case
3712 * that we know will avoid the call to Tcl_WrongNumArgs() at invoke time,
3713 * which is the only code that sees the shenanigans of ensemble dispatch.
3714 */
3715
3716 if (parsePtr->numWords < 3) {
3717 return TCL_ERROR;
3718 }
3719
3720 return CompileBasicNArgCommand(interp, parsePtr, cmdPtr, envPtr);
3721 }
3722
3723 /*
3724 * Local Variables:
3725 * mode: c
3726 * c-basic-offset: 4
3727 * fill-column: 78
3728 * End:
3729 */