Debian Codegraph @

pTk/mTk/tclGeneric/tclCmdMZ.c

raw symbols SCIP
1 /*
2 * tclCmdMZ.c --
3 *
4 * This file contains the top-level command routines for most of
5 * the Tcl built-in commands whose names begin with the letters
6 * M to Z. It contains only commands in the generic core (i.e.
7 * those that don't depend much upon UNIX facilities).
8 *
9 * Copyright (c) 1987-1993 The Regents of the University of California.
10 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
11 * Copyright (c) 1998-2000 Scriptics Corporation.
12 * Copyright (c) 2002 ActiveState Corporation.
13 *
14 * See the file "license.terms" for information on usage and redistribution
15 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
16 *
17 * RCS: @(#) $Id: tclCmdMZ.c,v 1.82.2.9 2003/10/14 18:21:59 vincentdarley Exp $
18 */
19
20 #include "tclInt.h"
21 #include "tclPort.h"
22 #include "tclRegexp.h"
23
24 /*
25 * Structure used to hold information about variable traces:
26 */
27
28 typedef struct {
29 int flags; /* Operations for which Tcl command is
30 * to be invoked. */
31 size_t length; /* Number of non-NULL chars. in command. */
32 char command[4]; /* Space for Tcl command to invoke. Actual
33 * size will be as large as necessary to
34 * hold command. This field must be the
35 * last in the structure, so that it can
36 * be larger than 4 bytes. */
37 } TraceVarInfo;
38
39 /*
40 * Structure used to hold information about command traces:
41 */
42
43 typedef struct {
44 int flags; /* Operations for which Tcl command is
45 * to be invoked. */
46 size_t length; /* Number of non-NULL chars. in command. */
47 Tcl_Trace stepTrace; /* Used for execution traces, when tracing
48 * inside the given command */
49 int startLevel; /* Used for bookkeeping with step execution
50 * traces, store the level at which the step
51 * trace was invoked */
52 char *startCmd; /* Used for bookkeeping with step execution
53 * traces, store the command name which invoked
54 * step trace */
55 int curFlags; /* Trace flags for the current command */
56 int curCode; /* Return code for the current command */
57 int refCount; /* Used to ensure this structure is
58 * not deleted too early. Keeps track
59 * of how many pieces of code have
60 * a pointer to this structure. */
61 char command[4]; /* Space for Tcl command to invoke. Actual
62 * size will be as large as necessary to
63 * hold command. This field must be the
64 * last in the structure, so that it can
65 * be larger than 4 bytes. */
66 } TraceCommandInfo;
67
68 /*
69 * Used by command execution traces. Note that we assume in the code
70 * that the first two defines are exactly 4 times the
71 * 'TCL_TRACE_ENTER_EXEC' and 'TCL_TRACE_LEAVE_EXEC' constants.
72 *
73 * TCL_TRACE_ENTER_DURING_EXEC - Trace each command inside the command
74 * currently being traced, before execution.
75 * TCL_TRACE_LEAVE_DURING_EXEC - Trace each command inside the command
76 * currently being traced, after execution.
77 * TCL_TRACE_ANY_EXEC - OR'd combination of all EXEC flags.
78 * TCL_TRACE_EXEC_IN_PROGRESS - The callback procedure on this trace
79 * is currently executing. Therefore we
80 * don't let further traces execute.
81 * TCL_TRACE_EXEC_DIRECT - This execution trace is triggered directly
82 * by the command being traced, not because
83 * of an internal trace.
84 * The flags 'TCL_TRACE_DESTROYED' and 'TCL_INTERP_DESTROYED' may also
85 * be used in command execution traces.
86 */
87 #define TCL_TRACE_ENTER_DURING_EXEC 4
88 #define TCL_TRACE_LEAVE_DURING_EXEC 8
89 #define TCL_TRACE_ANY_EXEC 15
90 #define TCL_TRACE_EXEC_IN_PROGRESS 0x10
91 #define TCL_TRACE_EXEC_DIRECT 0x20
92
93 /*
94 * Forward declarations for procedures defined in this file:
95 */
96
97 typedef int (Tcl_TraceTypeObjCmd) _ANSI_ARGS_((Tcl_Interp *interp,
98 int optionIndex, int objc, Tcl_Obj *CONST objv[]));
99
100 Tcl_TraceTypeObjCmd TclTraceVariableObjCmd;
101 Tcl_TraceTypeObjCmd TclTraceCommandObjCmd;
102 Tcl_TraceTypeObjCmd TclTraceExecutionObjCmd;
103
104 /*
105 * Each subcommand has a number of 'types' to which it can apply.
106 * Currently 'execution', 'command' and 'variable' are the only
107 * types supported. These three arrays MUST be kept in sync!
108 * In the future we may provide an API to add to the list of
109 * supported trace types.
110 */
111 static CONST char *traceTypeOptions[] = {
112 "execution", "command", "variable", (char*) NULL
113 };
114 static Tcl_TraceTypeObjCmd* traceSubCmds[] = {
115 TclTraceExecutionObjCmd,
116 TclTraceCommandObjCmd,
117 TclTraceVariableObjCmd,
118 };
119
120 /*
121 * Declarations for local procedures to this file:
122 */
123 static int CallTraceProcedure _ANSI_ARGS_((Tcl_Interp *interp,
124 Trace *tracePtr, Command *cmdPtr,
125 CONST char *command, int numChars,
126 int objc, Tcl_Obj *CONST objv[]));
127 static char * TraceVarProc _ANSI_ARGS_((ClientData clientData,
128 Tcl_Interp *interp, CONST char *name1,
129 CONST char *name2, int flags));
130 static void TraceCommandProc _ANSI_ARGS_((ClientData clientData,
131 Tcl_Interp *interp, CONST char *oldName,
132 CONST char *newName, int flags));
133 static Tcl_CmdObjTraceProc TraceExecutionProc;
134
135 /*
136 *----------------------------------------------------------------------
137 *
138 * Tcl_PwdObjCmd --
139 *
140 * This procedure is invoked to process the "pwd" Tcl command.
141 * See the user documentation for details on what it does.
142 *
143 * Results:
144 * A standard Tcl result.
145 *
146 * Side effects:
147 * See the user documentation.
148 *
149 *----------------------------------------------------------------------
150 */
151
152 /* ARGSUSED */
153 int
154 Tcl_PwdObjCmd(dummy, interp, objc, objv)
155 ClientData dummy; /* Not used. */
156 Tcl_Interp *interp; /* Current interpreter. */
157 int objc; /* Number of arguments. */
158 Tcl_Obj *CONST objv[]; /* Argument objects. */
159 {
160 Tcl_Obj *retVal;
161
162 if (objc != 1) {
163 Tcl_WrongNumArgs(interp, 1, objv, NULL);
164 return TCL_ERROR;
165 }
166
167 retVal = Tcl_FSGetCwd(interp);
168 if (retVal == NULL) {
169 return TCL_ERROR;
170 }
171 Tcl_SetObjResult(interp, retVal);
172 Tcl_DecrRefCount(retVal);
173 return TCL_OK;
174 }
175
176 /*
177 *----------------------------------------------------------------------
178 *
179 * Tcl_RegexpObjCmd --
180 *
181 * This procedure is invoked to process the "regexp" Tcl command.
182 * See the user documentation for details on what it does.
183 *
184 * Results:
185 * A standard Tcl result.
186 *
187 * Side effects:
188 * See the user documentation.
189 *
190 *----------------------------------------------------------------------
191 */
192
193 /* ARGSUSED */
194 int
195 Tcl_RegexpObjCmd(dummy, interp, objc, objv)
196 ClientData dummy; /* Not used. */
197 Tcl_Interp *interp; /* Current interpreter. */
198 int objc; /* Number of arguments. */
199 Tcl_Obj *CONST objv[]; /* Argument objects. */
200 {
201 int i, indices, match, about, offset, all, doinline, numMatchesSaved;
202 int cflags, eflags, stringLength;
203 Tcl_RegExp regExpr;
204 Tcl_Obj *objPtr, *resultPtr;
205 Tcl_RegExpInfo info;
206 static CONST char *options[] = {
207 "-all", "-about", "-indices", "-inline",
208 "-expanded", "-line", "-linestop", "-lineanchor",
209 "-nocase", "-start", "--", (char *) NULL
210 };
211 enum options {
212 REGEXP_ALL, REGEXP_ABOUT, REGEXP_INDICES, REGEXP_INLINE,
213 REGEXP_EXPANDED,REGEXP_LINE, REGEXP_LINESTOP,REGEXP_LINEANCHOR,
214 REGEXP_NOCASE, REGEXP_START, REGEXP_LAST
215 };
216
217 indices = 0;
218 about = 0;
219 cflags = TCL_REG_ADVANCED;
220 eflags = 0;
221 offset = 0;
222 all = 0;
223 doinline = 0;
224
225 for (i = 1; i < objc; i++) {
226 char *name;
227 int index;
228
229 name = Tcl_GetString(objv[i]);
230 if (name[0] != '-') {
231 break;
232 }
233 if (Tcl_GetIndexFromObj(interp, objv[i], options, "switch", TCL_EXACT,
234 &index) != TCL_OK) {
235 return TCL_ERROR;
236 }
237 switch ((enum options) index) {
238 case REGEXP_ALL: {
239 all = 1;
240 break;
241 }
242 case REGEXP_INDICES: {
243 indices = 1;
244 break;
245 }
246 case REGEXP_INLINE: {
247 doinline = 1;
248 break;
249 }
250 case REGEXP_NOCASE: {
251 cflags |= TCL_REG_NOCASE;
252 break;
253 }
254 case REGEXP_ABOUT: {
255 about = 1;
256 break;
257 }
258 case REGEXP_EXPANDED: {
259 cflags |= TCL_REG_EXPANDED;
260 break;
261 }
262 case REGEXP_LINE: {
263 cflags |= TCL_REG_NEWLINE;
264 break;
265 }
266 case REGEXP_LINESTOP: {
267 cflags |= TCL_REG_NLSTOP;
268 break;
269 }
270 case REGEXP_LINEANCHOR: {
271 cflags |= TCL_REG_NLANCH;
272 break;
273 }
274 case REGEXP_START: {
275 if (++i >= objc) {
276 goto endOfForLoop;
277 }
278 if (Tcl_GetIntFromObj(interp, objv[i], &offset) != TCL_OK) {
279 return TCL_ERROR;
280 }
281 if (offset < 0) {
282 offset = 0;
283 }
284 break;
285 }
286 case REGEXP_LAST: {
287 i++;
288 goto endOfForLoop;
289 }
290 }
291 }
292
293 endOfForLoop:
294 if ((objc - i) < (2 - about)) {
295 Tcl_WrongNumArgs(interp, 1, objv,
296 "?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?");
297 return TCL_ERROR;
298 }
299 objc -= i;
300 objv += i;
301
302 if (doinline && ((objc - 2) != 0)) {
303 /*
304 * User requested -inline, but specified match variables - a no-no.
305 */
306 Tcl_AppendResult(interp, "regexp match variables not allowed",
307 " when using -inline", (char *) NULL);
308 return TCL_ERROR;
309 }
310
311 /*
312 * Handle the odd about case separately.
313 */
314 if (about) {
315 regExpr = Tcl_GetRegExpFromObj(interp, objv[0], cflags);
316 if ((regExpr == NULL) || (TclRegAbout(interp, regExpr) < 0)) {
317 return TCL_ERROR;
318 }
319 return TCL_OK;
320 }
321
322 /*
323 * Get the length of the string that we are matching against so
324 * we can do the termination test for -all matches. Do this before
325 * getting the regexp to avoid shimmering problems.
326 */
327 objPtr = objv[1];
328 stringLength = Tcl_GetCharLength(objPtr);
329
330 regExpr = Tcl_GetRegExpFromObj(interp, objv[0], cflags);
331 if (regExpr == NULL) {
332 return TCL_ERROR;
333 }
334
335 if (offset > 0) {
336 /*
337 * Add flag if using offset (string is part of a larger string),
338 * so that "^" won't match.
339 */
340 eflags |= TCL_REG_NOTBOL;
341 }
342
343 objc -= 2;
344 objv += 2;
345 resultPtr = Tcl_GetObjResult(interp);
346
347 if (doinline) {
348 /*
349 * Save all the subexpressions, as we will return them as a list
350 */
351 numMatchesSaved = -1;
352 } else {
353 /*
354 * Save only enough subexpressions for matches we want to keep,
355 * expect in the case of -all, where we need to keep at least
356 * one to know where to move the offset.
357 */
358 numMatchesSaved = (objc == 0) ? all : objc;
359 }
360
361 /*
362 * The following loop is to handle multiple matches within the
363 * same source string; each iteration handles one match. If "-all"
364 * hasn't been specified then the loop body only gets executed once.
365 * We terminate the loop when the starting offset is past the end of the
366 * string.
367 */
368
369 while (1) {
370 match = Tcl_RegExpExecObj(interp, regExpr, objPtr,
371 offset /* offset */, numMatchesSaved, eflags
372 | ((offset > 0 &&
373 (Tcl_GetUniChar(objPtr,offset-1) != (Tcl_UniChar)'\n'))
374 ? TCL_REG_NOTBOL : 0));
375
376 if (match < 0) {
377 return TCL_ERROR;
378 }
379
380 if (match == 0) {
381 /*
382 * We want to set the value of the intepreter result only when
383 * this is the first time through the loop.
384 */
385 if (all <= 1) {
386 /*
387 * If inlining, set the interpreter's object result to an
388 * empty list, otherwise set it to an integer object w/
389 * value 0.
390 */
391 if (doinline) {
392 Tcl_SetListObj(resultPtr, 0, NULL);
393 } else {
394 Tcl_SetIntObj(resultPtr, 0);
395 }
396 return TCL_OK;
397 }
398 break;
399 }
400
401 /*
402 * If additional variable names have been specified, return
403 * index information in those variables.
404 */
405
406 Tcl_RegExpGetInfo(regExpr, &info);
407 if (doinline) {
408 /*
409 * It's the number of substitutions, plus one for the matchVar
410 * at index 0
411 */
412 objc = info.nsubs + 1;
413 }
414 for (i = 0; i < objc; i++) {
415 Tcl_Obj *newPtr;
416
417 if (indices) {
418 int start, end;
419 Tcl_Obj *objs[2];
420
421 /*
422 * Only adjust the match area if there was a match for
423 * that area. (Scriptics Bug 4391/SF Bug #219232)
424 */
425 if (i <= info.nsubs && info.matches[i].start >= 0) {
426 start = offset + info.matches[i].start;
427 end = offset + info.matches[i].end;
428
429 /*
430 * Adjust index so it refers to the last character in the
431 * match instead of the first character after the match.
432 */
433
434 if (end >= offset) {
435 end--;
436 }
437 } else {
438 start = -1;
439 end = -1;
440 }
441
442 objs[0] = Tcl_NewLongObj(start);
443 objs[1] = Tcl_NewLongObj(end);
444
445 newPtr = Tcl_NewListObj(2, objs);
446 } else {
447 if (i <= info.nsubs) {
448 newPtr = Tcl_GetRange(objPtr,
449 offset + info.matches[i].start,
450 offset + info.matches[i].end - 1);
451 } else {
452 newPtr = Tcl_NewObj();
453 }
454 }
455 if (doinline) {
456 if (Tcl_ListObjAppendElement(interp, resultPtr, newPtr)
457 != TCL_OK) {
458 Tcl_DecrRefCount(newPtr);
459 return TCL_ERROR;
460 }
461 } else {
462 Tcl_Obj *valuePtr;
463 valuePtr = Tcl_ObjSetVar2(interp, objv[i], NULL, newPtr, 0);
464 if (valuePtr == NULL) {
465 Tcl_DecrRefCount(newPtr);
466 Tcl_AppendResult(interp, "couldn't set variable \"",
467 Tcl_GetString(objv[i]), "\"", (char *) NULL);
468 return TCL_ERROR;
469 }
470 }
471 }
472
473 if (all == 0) {
474 break;
475 }
476 /*
477 * Adjust the offset to the character just after the last one
478 * in the matchVar and increment all to count how many times
479 * we are making a match. We always increment the offset by at least
480 * one to prevent endless looping (as in the case:
481 * regexp -all {a*} a). Otherwise, when we match the NULL string at
482 * the end of the input string, we will loop indefinately (because the
483 * length of the match is 0, so offset never changes).
484 */
485 if (info.matches[0].end == 0) {
486 offset++;
487 }
488 offset += info.matches[0].end;
489 all++;
490 eflags |= TCL_REG_NOTBOL;
491 if (offset >= stringLength) {
492 break;
493 }
494 }
495
496 /*
497 * Set the interpreter's object result to an integer object
498 * with value 1 if -all wasn't specified, otherwise it's all-1
499 * (the number of times through the while - 1).
500 * Get the resultPtr again as the Tcl_ObjSetVar2 above may have
501 * cause the result to change. [Patch #558324] (watson).
502 */
503
504 if (!doinline) {
505 resultPtr = Tcl_GetObjResult(interp);
506 Tcl_SetIntObj(resultPtr, (all ? all-1 : 1));
507 }
508 return TCL_OK;
509 }
510
511 /*
512 *----------------------------------------------------------------------
513 *
514 * Tcl_RegsubObjCmd --
515 *
516 * This procedure is invoked to process the "regsub" Tcl command.
517 * See the user documentation for details on what it does.
518 *
519 * Results:
520 * A standard Tcl result.
521 *
522 * Side effects:
523 * See the user documentation.
524 *
525 *----------------------------------------------------------------------
526 */
527
528 /* ARGSUSED */
529 int
530 Tcl_RegsubObjCmd(dummy, interp, objc, objv)
531 ClientData dummy; /* Not used. */
532 Tcl_Interp *interp; /* Current interpreter. */
533 int objc; /* Number of arguments. */
534 Tcl_Obj *CONST objv[]; /* Argument objects. */
535 {
536 int idx, result, cflags, all, wlen, wsublen, numMatches, offset;
537 int start, end, subStart, subEnd, match;
538 Tcl_RegExp regExpr;
539 Tcl_RegExpInfo info;
540 Tcl_Obj *resultPtr, *subPtr, *objPtr;
541 Tcl_UniChar ch, *wsrc, *wfirstChar, *wstring, *wsubspec, *wend;
542
543 static CONST char *options[] = {
544 "-all", "-nocase", "-expanded",
545 "-line", "-linestop", "-lineanchor", "-start",
546 "--", NULL
547 };
548 enum options {
549 REGSUB_ALL, REGSUB_NOCASE, REGSUB_EXPANDED,
550 REGSUB_LINE, REGSUB_LINESTOP, REGSUB_LINEANCHOR, REGSUB_START,
551 REGSUB_LAST
552 };
553
554 cflags = TCL_REG_ADVANCED;
555 all = 0;
556 offset = 0;
557 resultPtr = NULL;
558
559 for (idx = 1; idx < objc; idx++) {
560 char *name;
561 int index;
562
563 name = Tcl_GetString(objv[idx]);
564 if (name[0] != '-') {
565 break;
566 }
567 if (Tcl_GetIndexFromObj(interp, objv[idx], options, "switch",
568 TCL_EXACT, &index) != TCL_OK) {
569 return TCL_ERROR;
570 }
571 switch ((enum options) index) {
572 case REGSUB_ALL: {
573 all = 1;
574 break;
575 }
576 case REGSUB_NOCASE: {
577 cflags |= TCL_REG_NOCASE;
578 break;
579 }
580 case REGSUB_EXPANDED: {
581 cflags |= TCL_REG_EXPANDED;
582 break;
583 }
584 case REGSUB_LINE: {
585 cflags |= TCL_REG_NEWLINE;
586 break;
587 }
588 case REGSUB_LINESTOP: {
589 cflags |= TCL_REG_NLSTOP;
590 break;
591 }
592 case REGSUB_LINEANCHOR: {
593 cflags |= TCL_REG_NLANCH;
594 break;
595 }
596 case REGSUB_START: {
597 if (++idx >= objc) {
598 goto endOfForLoop;
599 }
600 if (Tcl_GetIntFromObj(interp, objv[idx], &offset) != TCL_OK) {
601 return TCL_ERROR;
602 }
603 if (offset < 0) {
604 offset = 0;
605 }
606 break;
607 }
608 case REGSUB_LAST: {
609 idx++;
610 goto endOfForLoop;
611 }
612 }
613 }
614 endOfForLoop:
615 if (objc-idx < 3 || objc-idx > 4) {
616 Tcl_WrongNumArgs(interp, 1, objv,
617 "?switches? exp string subSpec ?varName?");
618 return TCL_ERROR;
619 }
620
621 objc -= idx;
622 objv += idx;
623
624 if (all && (offset == 0)
625 && (strpbrk(Tcl_GetString(objv[2]), "&\\") == NULL)
626 && (strpbrk(Tcl_GetString(objv[0]), "*+?{}()[].\\|^$") == NULL)) {
627 /*
628 * This is a simple one pair string map situation. We make use of
629 * a slightly modified version of the one pair STR_MAP code.
630 */
631 int slen, nocase;
632 int (*strCmpFn)_ANSI_ARGS_((CONST Tcl_UniChar *, CONST Tcl_UniChar *,
633 unsigned long));
634 Tcl_UniChar *p, wsrclc;
635
636 numMatches = 0;
637 nocase = (cflags & TCL_REG_NOCASE);
638 strCmpFn = nocase ? Tcl_UniCharNcasecmp : Tcl_UniCharNcmp;
639
640 wsrc = Tcl_GetUnicodeFromObj(objv[0], &slen);
641 wstring = Tcl_GetUnicodeFromObj(objv[1], &wlen);
642 wsubspec = Tcl_GetUnicodeFromObj(objv[2], &wsublen);
643 wend = wstring + wlen - (slen ? slen - 1 : 0);
644 result = TCL_OK;
645
646 if (slen == 0) {
647 /*
648 * regsub behavior for "" matches between each character.
649 * 'string map' skips the "" case.
650 */
651 if (wstring < wend) {
652 resultPtr = Tcl_NewUnicodeObj(wstring, 0);
653 Tcl_IncrRefCount(resultPtr);
654 for (; wstring < wend; wstring++) {
655 Tcl_AppendUnicodeToObj(resultPtr, wsubspec, wsublen);
656 Tcl_AppendUnicodeToObj(resultPtr, wstring, 1);
657 numMatches++;
658 }
659 wlen = 0;
660 }
661 } else {
662 wsrclc = Tcl_UniCharToLower(*wsrc);
663 for (p = wfirstChar = wstring; wstring < wend; wstring++) {
664 if (((*wstring == *wsrc) ||
665 (nocase && (Tcl_UniCharToLower(*wstring) ==
666 wsrclc))) &&
667 ((slen == 1) || (strCmpFn(wstring, wsrc,
668 (unsigned long) slen) == 0))) {
669 if (numMatches == 0) {
670 resultPtr = Tcl_NewUnicodeObj(wstring, 0);
671 Tcl_IncrRefCount(resultPtr);
672 }
673 if (p != wstring) {
674 Tcl_AppendUnicodeToObj(resultPtr, p, wstring - p);
675 p = wstring + slen;
676 } else {
677 p += slen;
678 }
679 wstring = p - 1;
680
681 Tcl_AppendUnicodeToObj(resultPtr, wsubspec, wsublen);
682 numMatches++;
683 }
684 }
685 if (numMatches) {
686 wlen = wfirstChar + wlen - p;
687 wstring = p;
688 }
689 }
690 objPtr = NULL;
691 subPtr = NULL;
692 goto regsubDone;
693 }
694
695 regExpr = Tcl_GetRegExpFromObj(interp, objv[0], cflags);
696 if (regExpr == NULL) {
697 return TCL_ERROR;
698 }
699
700 /*
701 * Make sure to avoid problems where the objects are shared. This
702 * can cause RegExpObj <> UnicodeObj shimmering that causes data
703 * corruption. [Bug #461322]
704 */
705
706 if (objv[1] == objv[0]) {
707 objPtr = Tcl_DuplicateObj(objv[1]);
708 } else {
709 objPtr = objv[1];
710 }
711 wstring = Tcl_GetUnicodeFromObj(objPtr, &wlen);
712 if (objv[2] == objv[0]) {
713 subPtr = Tcl_DuplicateObj(objv[2]);
714 } else {
715 subPtr = objv[2];
716 }
717 wsubspec = Tcl_GetUnicodeFromObj(subPtr, &wsublen);
718
719 result = TCL_OK;
720
721 /*
722 * The following loop is to handle multiple matches within the
723 * same source string; each iteration handles one match and its
724 * corresponding substitution. If "-all" hasn't been specified
725 * then the loop body only gets executed once. We must use
726 * 'offset <= wlen' in particular for the case where the regexp
727 * pattern can match the empty string - this is useful when
728 * doing, say, 'regsub -- ^ $str ...' when $str might be empty.
729 */
730
731 numMatches = 0;
732 for ( ; offset <= wlen; ) {
733
734 /*
735 * The flags argument is set if string is part of a larger string,
736 * so that "^" won't match.
737 */
738
739 match = Tcl_RegExpExecObj(interp, regExpr, objPtr, offset,
740 10 /* matches */, ((offset > 0 &&
741 (wstring[offset-1] != (Tcl_UniChar)'\n'))
742 ? TCL_REG_NOTBOL : 0));
743
744 if (match < 0) {
745 result = TCL_ERROR;
746 goto done;
747 }
748 if (match == 0) {
749 break;
750 }
751 if (numMatches == 0) {
752 resultPtr = Tcl_NewUnicodeObj(wstring, 0);
753 Tcl_IncrRefCount(resultPtr);
754 if (offset > 0) {
755 /*
756 * Copy the initial portion of the string in if an offset
757 * was specified.
758 */
759 Tcl_AppendUnicodeToObj(resultPtr, wstring, offset);
760 }
761 }
762 numMatches++;
763
764 /*
765 * Copy the portion of the source string before the match to the
766 * result variable.
767 */
768
769 Tcl_RegExpGetInfo(regExpr, &info);
770 start = info.matches[0].start;
771 end = info.matches[0].end;
772 Tcl_AppendUnicodeToObj(resultPtr, wstring + offset, start);
773
774 /*
775 * Append the subSpec argument to the variable, making appropriate
776 * substitutions. This code is a bit hairy because of the backslash
777 * conventions and because the code saves up ranges of characters in
778 * subSpec to reduce the number of calls to Tcl_SetVar.
779 */
780
781 wsrc = wfirstChar = wsubspec;
782 wend = wsubspec + wsublen;
783 for (ch = *wsrc; wsrc != wend; wsrc++, ch = *wsrc) {
784 if (ch == '&') {
785 idx = 0;
786 } else if (ch == '\\') {
787 ch = wsrc[1];
788 if ((ch >= '0') && (ch <= '9')) {
789 idx = ch - '0';
790 } else if ((ch == '\\') || (ch == '&')) {
791 *wsrc = ch;
792 Tcl_AppendUnicodeToObj(resultPtr, wfirstChar,
793 wsrc - wfirstChar + 1);
794 *wsrc = '\\';
795 wfirstChar = wsrc + 2;
796 wsrc++;
797 continue;
798 } else {
799 continue;
800 }
801 } else {
802 continue;
803 }
804 if (wfirstChar != wsrc) {
805 Tcl_AppendUnicodeToObj(resultPtr, wfirstChar,
806 wsrc - wfirstChar);
807 }
808 if (idx <= info.nsubs) {
809 subStart = info.matches[idx].start;
810 subEnd = info.matches[idx].end;
811 if ((subStart >= 0) && (subEnd >= 0)) {
812 Tcl_AppendUnicodeToObj(resultPtr,
813 wstring + offset + subStart, subEnd - subStart);
814 }
815 }
816 if (*wsrc == '\\') {
817 wsrc++;
818 }
819 wfirstChar = wsrc + 1;
820 }
821 if (wfirstChar != wsrc) {
822 Tcl_AppendUnicodeToObj(resultPtr, wfirstChar, wsrc - wfirstChar);
823 }
824 if (end == 0) {
825 /*
826 * Always consume at least one character of the input string
827 * in order to prevent infinite loops.
828 */
829
830 if (offset < wlen) {
831 Tcl_AppendUnicodeToObj(resultPtr, wstring + offset, 1);
832 }
833 offset++;
834 } else {
835 offset += end;
836 if (start == end) {
837 /*
838 * We matched an empty string, which means we must go
839 * forward one more step so we don't match again at the
840 * same spot.
841 */
842 if (offset < wlen) {
843 Tcl_AppendUnicodeToObj(resultPtr, wstring + offset, 1);
844 }
845 offset++;
846 }
847 }
848 if (!all) {
849 break;
850 }
851 }
852
853 /*
854 * Copy the portion of the source string after the last match to the
855 * result variable.
856 */
857 regsubDone:
858 if (numMatches == 0) {
859 /*
860 * On zero matches, just ignore the offset, since it shouldn't
861 * matter to us in this case, and the user may have skewed it.
862 */
863 resultPtr = objv[1];
864 Tcl_IncrRefCount(resultPtr);
865 } else if (offset < wlen) {
866 Tcl_AppendUnicodeToObj(resultPtr, wstring + offset, wlen - offset);
867 }
868 if (objc == 4) {
869 if (Tcl_ObjSetVar2(interp, objv[3], NULL, resultPtr, 0) == NULL) {
870 Tcl_AppendResult(interp, "couldn't set variable \"",
871 Tcl_GetString(objv[3]), "\"", (char *) NULL);
872 result = TCL_ERROR;
873 } else {
874 /*
875 * Set the interpreter's object result to an integer object
876 * holding the number of matches.
877 */
878
879 Tcl_SetIntObj(Tcl_GetObjResult(interp), numMatches);
880 }
881 } else {
882 /*
883 * No varname supplied, so just return the modified string.
884 */
885 Tcl_SetObjResult(interp, resultPtr);
886 }
887
888 done:
889 if (objPtr && (objv[1] == objv[0])) { Tcl_DecrRefCount(objPtr); }
890 if (subPtr && (objv[2] == objv[0])) { Tcl_DecrRefCount(subPtr); }
891 if (resultPtr) { Tcl_DecrRefCount(resultPtr); }
892 return result;
893 }
894
895 /*
896 *----------------------------------------------------------------------
897 *
898 * Tcl_RenameObjCmd --
899 *
900 * This procedure is invoked to process the "rename" Tcl command.
901 * See the user documentation for details on what it does.
902 *
903 * Results:
904 * A standard Tcl object result.
905 *
906 * Side effects:
907 * See the user documentation.
908 *
909 *----------------------------------------------------------------------
910 */
911
912 /* ARGSUSED */
913 int
914 Tcl_RenameObjCmd(dummy, interp, objc, objv)
915 ClientData dummy; /* Arbitrary value passed to the command. */
916 Tcl_Interp *interp; /* Current interpreter. */
917 int objc; /* Number of arguments. */
918 Tcl_Obj *CONST objv[]; /* Argument objects. */
919 {
920 char *oldName, *newName;
921
922 if (objc != 3) {
923 Tcl_WrongNumArgs(interp, 1, objv, "oldName newName");
924 return TCL_ERROR;
925 }
926
927 oldName = Tcl_GetString(objv[1]);
928 newName = Tcl_GetString(objv[2]);
929 return TclRenameCommand(interp, oldName, newName);
930 }
931
932 /*
933 *----------------------------------------------------------------------
934 *
935 * Tcl_ReturnObjCmd --
936 *
937 * This object-based procedure is invoked to process the "return" Tcl
938 * command. See the user documentation for details on what it does.
939 *
940 * Results:
941 * A standard Tcl object result.
942 *
943 * Side effects:
944 * See the user documentation.
945 *
946 *----------------------------------------------------------------------
947 */
948
949 /* ARGSUSED */
950 int
951 Tcl_ReturnObjCmd(dummy, interp, objc, objv)
952 ClientData dummy; /* Not used. */
953 Tcl_Interp *interp; /* Current interpreter. */
954 int objc; /* Number of arguments. */
955 Tcl_Obj *CONST objv[]; /* Argument objects. */
956 {
957 Interp *iPtr = (Interp *) interp;
958 int optionLen, argLen, code, result;
959
960 if (iPtr->errorInfo != NULL) {
961 ckfree(iPtr->errorInfo);
962 iPtr->errorInfo = NULL;
963 }
964 if (iPtr->errorCode != NULL) {
965 ckfree(iPtr->errorCode);
966 iPtr->errorCode = NULL;
967 }
968 code = TCL_OK;
969
970 for (objv++, objc--; objc > 1; objv += 2, objc -= 2) {
971 char *option = Tcl_GetStringFromObj(objv[0], &optionLen);
972 char *arg = Tcl_GetStringFromObj(objv[1], &argLen);
973
974 if (strcmp(option, "-code") == 0) {
975 register int c = arg[0];
976 if ((c == 'o') && (strcmp(arg, "ok") == 0)) {
977 code = TCL_OK;
978 } else if ((c == 'e') && (strcmp(arg, "error") == 0)) {
979 code = TCL_ERROR;
980 } else if ((c == 'r') && (strcmp(arg, "return") == 0)) {
981 code = TCL_RETURN;
982 } else if ((c == 'b') && (strcmp(arg, "break") == 0)) {
983 code = TCL_BREAK;
984 } else if ((c == 'c') && (strcmp(arg, "continue") == 0)) {
985 code = TCL_CONTINUE;
986 } else {
987 result = Tcl_GetIntFromObj((Tcl_Interp *) NULL, objv[1],
988 &code);
989 if (result != TCL_OK) {
990 Tcl_ResetResult(interp);
991 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
992 "bad completion code \"",
993 Tcl_GetString(objv[1]),
994 "\": must be ok, error, return, break, ",
995 "continue, or an integer", (char *) NULL);
996 return result;
997 }
998 }
999 } else if (strcmp(option, "-errorinfo") == 0) {
1000 iPtr->errorInfo =
1001 (char *) ckalloc((unsigned) (strlen(arg) + 1));
1002 strcpy(iPtr->errorInfo, arg);
1003 } else if (strcmp(option, "-errorcode") == 0) {
1004 iPtr->errorCode =
1005 (char *) ckalloc((unsigned) (strlen(arg) + 1));
1006 strcpy(iPtr->errorCode, arg);
1007 } else {
1008 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1009 "bad option \"", option,
1010 "\": must be -code, -errorcode, or -errorinfo",
1011 (char *) NULL);
1012 return TCL_ERROR;
1013 }
1014 }
1015
1016 if (objc == 1) {
1017 /*
1018 * Set the interpreter's object result. An inline version of
1019 * Tcl_SetObjResult.
1020 */
1021
1022 Tcl_SetObjResult(interp, objv[0]);
1023 }
1024 iPtr->returnCode = code;
1025 return TCL_RETURN;
1026 }
1027
1028 /*
1029 *----------------------------------------------------------------------
1030 *
1031 * Tcl_SourceObjCmd --
1032 *
1033 * This procedure is invoked to process the "source" Tcl command.
1034 * See the user documentation for details on what it does.
1035 *
1036 * Results:
1037 * A standard Tcl object result.
1038 *
1039 * Side effects:
1040 * See the user documentation.
1041 *
1042 *----------------------------------------------------------------------
1043 */
1044
1045 /* ARGSUSED */
1046 int
1047 Tcl_SourceObjCmd(dummy, interp, objc, objv)
1048 ClientData dummy; /* Not used. */
1049 Tcl_Interp *interp; /* Current interpreter. */
1050 int objc; /* Number of arguments. */
1051 Tcl_Obj *CONST objv[]; /* Argument objects. */
1052 {
1053 if (objc != 2) {
1054 Tcl_WrongNumArgs(interp, 1, objv, "fileName");
1055 return TCL_ERROR;
1056 }
1057
1058 return Tcl_FSEvalFile(interp, objv[1]);
1059 }
1060
1061 /*
1062 *----------------------------------------------------------------------
1063 *
1064 * Tcl_SplitObjCmd --
1065 *
1066 * This procedure is invoked to process the "split" Tcl command.
1067 * See the user documentation for details on what it does.
1068 *
1069 * Results:
1070 * A standard Tcl result.
1071 *
1072 * Side effects:
1073 * See the user documentation.
1074 *
1075 *----------------------------------------------------------------------
1076 */
1077
1078 /* ARGSUSED */
1079 int
1080 Tcl_SplitObjCmd(dummy, interp, objc, objv)
1081 ClientData dummy; /* Not used. */
1082 Tcl_Interp *interp; /* Current interpreter. */
1083 int objc; /* Number of arguments. */
1084 Tcl_Obj *CONST objv[]; /* Argument objects. */
1085 {
1086 Tcl_UniChar ch;
1087 int len;
1088 char *splitChars, *string, *end;
1089 int splitCharLen, stringLen;
1090 Tcl_Obj *listPtr, *objPtr;
1091
1092 if (objc == 2) {
1093 splitChars = " \n\t\r";
1094 splitCharLen = 4;
1095 } else if (objc == 3) {
1096 splitChars = Tcl_GetStringFromObj(objv[2], &splitCharLen);
1097 } else {
1098 Tcl_WrongNumArgs(interp, 1, objv, "string ?splitChars?");
1099 return TCL_ERROR;
1100 }
1101
1102 string = Tcl_GetStringFromObj(objv[1], &stringLen);
1103 end = string + stringLen;
1104 listPtr = Tcl_GetObjResult(interp);
1105
1106 if (stringLen == 0) {
1107 /*
1108 * Do nothing.
1109 */
1110 } else if (splitCharLen == 0) {
1111 Tcl_HashTable charReuseTable;
1112 Tcl_HashEntry *hPtr;
1113 int isNew;
1114
1115 /*
1116 * Handle the special case of splitting on every character.
1117 *
1118 * Uses a hash table to ensure that each kind of character has
1119 * only one Tcl_Obj instance (multiply-referenced) in the
1120 * final list. This is a *major* win when splitting on a long
1121 * string (especially in the megabyte range!) - DKF
1122 */
1123
1124 Tcl_InitHashTable(&charReuseTable, TCL_ONE_WORD_KEYS);
1125 for ( ; string < end; string += len) {
1126 len = TclUtfToUniChar(string, &ch);
1127 /* Assume Tcl_UniChar is an integral type... */
1128 hPtr = Tcl_CreateHashEntry(&charReuseTable, (char*)0 + ch, &isNew);
1129 if (isNew) {
1130 objPtr = Tcl_NewStringObj(string, len);
1131 /* Don't need to fiddle with refcount... */
1132 Tcl_SetHashValue(hPtr, (ClientData) objPtr);
1133 } else {
1134 objPtr = (Tcl_Obj*) Tcl_GetHashValue(hPtr);
1135 }
1136 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1137 }
1138 Tcl_DeleteHashTable(&charReuseTable);
1139 } else if (splitCharLen == 1) {
1140 char *p;
1141
1142 /*
1143 * Handle the special case of splitting on a single character.
1144 * This is only true for the one-char ASCII case, as one unicode
1145 * char is > 1 byte in length.
1146 */
1147
1148 while (*string && (p = strchr(string, (int) *splitChars)) != NULL) {
1149 objPtr = Tcl_NewStringObj(string, p - string);
1150 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1151 string = p + 1;
1152 }
1153 objPtr = Tcl_NewStringObj(string, end - string);
1154 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1155 } else {
1156 char *element, *p, *splitEnd;
1157 int splitLen;
1158 Tcl_UniChar splitChar;
1159
1160 /*
1161 * Normal case: split on any of a given set of characters.
1162 * Discard instances of the split characters.
1163 */
1164
1165 splitEnd = splitChars + splitCharLen;
1166
1167 for (element = string; string < end; string += len) {
1168 len = TclUtfToUniChar(string, &ch);
1169 for (p = splitChars; p < splitEnd; p += splitLen) {
1170 splitLen = TclUtfToUniChar(p, &splitChar);
1171 if (ch == splitChar) {
1172 objPtr = Tcl_NewStringObj(element, string - element);
1173 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1174 element = string + len;
1175 break;
1176 }
1177 }
1178 }
1179 objPtr = Tcl_NewStringObj(element, string - element);
1180 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1181 }
1182 return TCL_OK;
1183 }
1184
1185 /*
1186 *----------------------------------------------------------------------
1187 *
1188 * Tcl_StringObjCmd --
1189 *
1190 * This procedure is invoked to process the "string" Tcl command.
1191 * See the user documentation for details on what it does. Note
1192 * that this command only functions correctly on properly formed
1193 * Tcl UTF strings.
1194 *
1195 * Note that the primary methods here (equal, compare, match, ...)
1196 * have bytecode equivalents. You will find the code for those in
1197 * tclExecute.c. The code here will only be used in the non-bc
1198 * case (like in an 'eval').
1199 *
1200 * Results:
1201 * A standard Tcl result.
1202 *
1203 * Side effects:
1204 * See the user documentation.
1205 *
1206 *----------------------------------------------------------------------
1207 */
1208
1209 /* ARGSUSED */
1210 int
1211 Tcl_StringObjCmd(dummy, interp, objc, objv)
1212 ClientData dummy; /* Not used. */
1213 Tcl_Interp *interp; /* Current interpreter. */
1214 int objc; /* Number of arguments. */
1215 Tcl_Obj *CONST objv[]; /* Argument objects. */
1216 {
1217 int index, left, right;
1218 Tcl_Obj *resultPtr;
1219 char *string1, *string2;
1220 int length1, length2;
1221 static CONST char *options[] = {
1222 "bytelength", "compare", "equal", "first",
1223 "index", "is", "last", "length",
1224 "map", "match", "range", "repeat",
1225 "replace", "tolower", "toupper", "totitle",
1226 "trim", "trimleft", "trimright",
1227 "wordend", "wordstart", (char *) NULL
1228 };
1229 enum options {
1230 STR_BYTELENGTH, STR_COMPARE, STR_EQUAL, STR_FIRST,
1231 STR_INDEX, STR_IS, STR_LAST, STR_LENGTH,
1232 STR_MAP, STR_MATCH, STR_RANGE, STR_REPEAT,
1233 STR_REPLACE, STR_TOLOWER, STR_TOUPPER, STR_TOTITLE,
1234 STR_TRIM, STR_TRIMLEFT, STR_TRIMRIGHT,
1235 STR_WORDEND, STR_WORDSTART
1236 };
1237
1238 if (objc < 2) {
1239 Tcl_WrongNumArgs(interp, 1, objv, "option arg ?arg ...?");
1240 return TCL_ERROR;
1241 }
1242
1243 if (Tcl_GetIndexFromObj(interp, objv[1], options, "option", 0,
1244 &index) != TCL_OK) {
1245 return TCL_ERROR;
1246 }
1247
1248 resultPtr = Tcl_GetObjResult(interp);
1249 switch ((enum options) index) {
1250 case STR_EQUAL:
1251 case STR_COMPARE: {
1252 /*
1253 * Remember to keep code here in some sync with the
1254 * byte-compiled versions in tclExecute.c (INST_STR_EQ,
1255 * INST_STR_NEQ and INST_STR_CMP as well as the expr string
1256 * comparison in INST_EQ/INST_NEQ/INST_LT/...).
1257 */
1258 int i, match, length, nocase = 0, reqlength = -1;
1259 int (*strCmpFn)();
1260
1261 if (objc < 4 || objc > 7) {
1262 str_cmp_args:
1263 Tcl_WrongNumArgs(interp, 2, objv,
1264 "?-nocase? ?-length int? string1 string2");
1265 return TCL_ERROR;
1266 }
1267
1268 for (i = 2; i < objc-2; i++) {
1269 string2 = Tcl_GetStringFromObj(objv[i], &length2);
1270 if ((length2 > 1)
1271 && strncmp(string2, "-nocase", (size_t)length2) == 0) {
1272 nocase = 1;
1273 } else if ((length2 > 1)
1274 && strncmp(string2, "-length", (size_t)length2) == 0) {
1275 if (i+1 >= objc-2) {
1276 goto str_cmp_args;
1277 }
1278 if (Tcl_GetIntFromObj(interp, objv[++i],
1279 &reqlength) != TCL_OK) {
1280 return TCL_ERROR;
1281 }
1282 } else {
1283 Tcl_AppendStringsToObj(resultPtr, "bad option \"",
1284 string2, "\": must be -nocase or -length",
1285 (char *) NULL);
1286 return TCL_ERROR;
1287 }
1288 }
1289
1290 /*
1291 * From now on, we only access the two objects at the end
1292 * of the argument array.
1293 */
1294 objv += objc-2;
1295
1296 if ((reqlength == 0) || (objv[0] == objv[1])) {
1297 /*
1298 * Alway match at 0 chars of if it is the same obj.
1299 */
1300
1301 Tcl_SetBooleanObj(resultPtr,
1302 ((enum options) index == STR_EQUAL));
1303 break;
1304 } else if (!nocase && objv[0]->typePtr == &tclByteArrayType &&
1305 objv[1]->typePtr == &tclByteArrayType) {
1306 /*
1307 * Use binary versions of comparisons since that won't
1308 * cause undue type conversions and it is much faster.
1309 * Only do this if we're case-sensitive (which is all
1310 * that really makes sense with byte arrays anyway, and
1311 * we have no memcasecmp() for some reason... :^)
1312 */
1313 string1 = (char*) Tcl_GetByteArrayFromObj(objv[0], &length1);
1314 string2 = (char*) Tcl_GetByteArrayFromObj(objv[1], &length2);
1315 strCmpFn = memcmp;
1316 } else if ((objv[0]->typePtr == &tclStringType)
1317 && (objv[1]->typePtr == &tclStringType)) {
1318 /*
1319 * Do a unicode-specific comparison if both of the args
1320 * are of String type. In benchmark testing this proved
1321 * the most efficient check between the unicode and
1322 * string comparison operations.
1323 */
1324 string1 = (char*) Tcl_GetUnicodeFromObj(objv[0], &length1);
1325 string2 = (char*) Tcl_GetUnicodeFromObj(objv[1], &length2);
1326 strCmpFn = nocase ? Tcl_UniCharNcasecmp : Tcl_UniCharNcmp;
1327 } else {
1328 /*
1329 * As a catch-all we will work with UTF-8. We cannot use
1330 * memcmp() as that is unsafe with any string containing
1331 * NULL (\xC0\x80 in Tcl's utf rep). We can use the more
1332 * efficient TclpUtfNcmp2 if we are case-sensitive and no
1333 * specific length was requested.
1334 */
1335 string1 = (char*) Tcl_GetStringFromObj(objv[0], &length1);
1336 string2 = (char*) Tcl_GetStringFromObj(objv[1], &length2);
1337 if ((reqlength < 0) && !nocase) {
1338 strCmpFn = TclpUtfNcmp2;
1339 } else {
1340 length1 = Tcl_NumUtfChars(string1, length1);
1341 length2 = Tcl_NumUtfChars(string2, length2);
1342 strCmpFn = nocase ? Tcl_UtfNcasecmp : Tcl_UtfNcmp;
1343 }
1344 }
1345
1346 if (((enum options) index == STR_EQUAL)
1347 && (reqlength < 0) && (length1 != length2)) {
1348 match = 1; /* this will be reversed below */
1349 } else {
1350 length = (length1 < length2) ? length1 : length2;
1351 if (reqlength > 0 && reqlength < length) {
1352 length = reqlength;
1353 } else if (reqlength < 0) {
1354 /*
1355 * The requested length is negative, so we ignore it by
1356 * setting it to length + 1 so we correct the match var.
1357 */
1358 reqlength = length + 1;
1359 }
1360 match = strCmpFn(string1, string2, (unsigned) length);
1361 if ((match == 0) && (reqlength > length)) {
1362 match = length1 - length2;
1363 }
1364 }
1365
1366 if ((enum options) index == STR_EQUAL) {
1367 Tcl_SetBooleanObj(resultPtr, (match) ? 0 : 1);
1368 } else {
1369 Tcl_SetIntObj(resultPtr, ((match > 0) ? 1 :
1370 (match < 0) ? -1 : 0));
1371 }
1372 break;
1373 }
1374 case STR_FIRST: {
1375 Tcl_UniChar *ustring1, *ustring2;
1376 int match, start;
1377
1378 if (objc < 4 || objc > 5) {
1379 Tcl_WrongNumArgs(interp, 2, objv,
1380 "subString string ?startIndex?");
1381 return TCL_ERROR;
1382 }
1383
1384 /*
1385 * We are searching string2 for the sequence string1.
1386 */
1387
1388 match = -1;
1389 start = 0;
1390 length2 = -1;
1391
1392 ustring1 = Tcl_GetUnicodeFromObj(objv[2], &length1);
1393 ustring2 = Tcl_GetUnicodeFromObj(objv[3], &length2);
1394
1395 if (objc == 5) {
1396 /*
1397 * If a startIndex is specified, we will need to fast
1398 * forward to that point in the string before we think
1399 * about a match
1400 */
1401 if (TclGetIntForIndex(interp, objv[4], length2 - 1,
1402 &start) != TCL_OK) {
1403 return TCL_ERROR;
1404 }
1405 if (start >= length2) {
1406 goto str_first_done;
1407 } else if (start > 0) {
1408 ustring2 += start;
1409 length2 -= start;
1410 } else if (start < 0) {
1411 /*
1412 * Invalid start index mapped to string start;
1413 * Bug #423581
1414 */
1415 start = 0;
1416 }
1417 }
1418
1419 if (length1 > 0) {
1420 register Tcl_UniChar *p, *end;
1421
1422 end = ustring2 + length2 - length1 + 1;
1423 for (p = ustring2; p < end; p++) {
1424 /*
1425 * Scan forward to find the first character.
1426 */
1427 if ((*p == *ustring1) &&
1428 (TclUniCharNcmp(ustring1, p,
1429 (unsigned long) length1) == 0)) {
1430 match = p - ustring2;
1431 break;
1432 }
1433 }
1434 }
1435 /*
1436 * Compute the character index of the matching string by
1437 * counting the number of characters before the match.
1438 */
1439 if ((match != -1) && (objc == 5)) {
1440 match += start;
1441 }
1442
1443 str_first_done:
1444 Tcl_SetIntObj(resultPtr, match);
1445 break;
1446 }
1447 case STR_INDEX: {
1448 if (objc != 4) {
1449 Tcl_WrongNumArgs(interp, 2, objv, "string charIndex");
1450 return TCL_ERROR;
1451 }
1452
1453 /*
1454 * If we have a ByteArray object, avoid indexing in the
1455 * Utf string since the byte array contains one byte per
1456 * character. Otherwise, use the Unicode string rep to
1457 * get the index'th char.
1458 */
1459
1460 if (objv[2]->typePtr == &tclByteArrayType) {
1461 string1 = (char *) Tcl_GetByteArrayFromObj(objv[2], &length1);
1462
1463 if (TclGetIntForIndex(interp, objv[3], length1 - 1,
1464 &index) != TCL_OK) {
1465 return TCL_ERROR;
1466 }
1467 if ((index >= 0) && (index < length1)) {
1468 Tcl_SetByteArrayObj(resultPtr,
1469 (unsigned char *)(&string1[index]), 1);
1470 }
1471 } else {
1472 /*
1473 * Get Unicode char length to calulate what 'end' means.
1474 */
1475 length1 = Tcl_GetCharLength(objv[2]);
1476
1477 if (TclGetIntForIndex(interp, objv[3], length1 - 1,
1478 &index) != TCL_OK) {
1479 return TCL_ERROR;
1480 }
1481 if ((index >= 0) && (index < length1)) {
1482 char buf[TCL_UTF_MAX];
1483 Tcl_UniChar ch;
1484
1485 ch = Tcl_GetUniChar(objv[2], index);
1486 length1 = Tcl_UniCharToUtf(ch, buf);
1487 Tcl_SetStringObj(resultPtr, buf, length1);
1488 }
1489 }
1490 break;
1491 }
1492 case STR_IS: {
1493 char *end;
1494 Tcl_UniChar ch;
1495
1496 /*
1497 * The UniChar comparison function
1498 */
1499
1500 int (*chcomp)_ANSI_ARGS_((int)) = NULL;
1501 int i, failat = 0, result = 1, strict = 0;
1502 Tcl_Obj *objPtr, *failVarObj = NULL;
1503
1504 static CONST char *isOptions[] = {
1505 "alnum", "alpha", "ascii", "control",
1506 "boolean", "digit", "double", "false",
1507 "graph", "integer", "lower", "print",
1508 "punct", "space", "true", "upper",
1509 "wordchar", "xdigit", (char *) NULL
1510 };
1511 enum isOptions {
1512 STR_IS_ALNUM, STR_IS_ALPHA, STR_IS_ASCII, STR_IS_CONTROL,
1513 STR_IS_BOOL, STR_IS_DIGIT, STR_IS_DOUBLE, STR_IS_FALSE,
1514 STR_IS_GRAPH, STR_IS_INT, STR_IS_LOWER, STR_IS_PRINT,
1515 STR_IS_PUNCT, STR_IS_SPACE, STR_IS_TRUE, STR_IS_UPPER,
1516 STR_IS_WORD, STR_IS_XDIGIT
1517 };
1518
1519 if (objc < 4 || objc > 7) {
1520 Tcl_WrongNumArgs(interp, 2, objv,
1521 "class ?-strict? ?-failindex var? str");
1522 return TCL_ERROR;
1523 }
1524 if (Tcl_GetIndexFromObj(interp, objv[2], isOptions, "class", 0,
1525 &index) != TCL_OK) {
1526 return TCL_ERROR;
1527 }
1528 if (objc != 4) {
1529 for (i = 3; i < objc-1; i++) {
1530 string2 = Tcl_GetStringFromObj(objv[i], &length2);
1531 if ((length2 > 1) &&
1532 strncmp(string2, "-strict", (size_t) length2) == 0) {
1533 strict = 1;
1534 } else if ((length2 > 1) &&
1535 strncmp(string2, "-failindex",
1536 (size_t) length2) == 0) {
1537 if (i+1 >= objc-1) {
1538 Tcl_WrongNumArgs(interp, 3, objv,
1539 "?-strict? ?-failindex var? str");
1540 return TCL_ERROR;
1541 }
1542 failVarObj = objv[++i];
1543 } else {
1544 Tcl_AppendStringsToObj(resultPtr, "bad option \"",
1545 string2, "\": must be -strict or -failindex",
1546 (char *) NULL);
1547 return TCL_ERROR;
1548 }
1549 }
1550 }
1551
1552 /*
1553 * We get the objPtr so that we can short-cut for some classes
1554 * by checking the object type (int and double), but we need
1555 * the string otherwise, because we don't want any conversion
1556 * of type occuring (as, for example, Tcl_Get*FromObj would do
1557 */
1558 objPtr = objv[objc-1];
1559 string1 = Tcl_GetStringFromObj(objPtr, &length1);
1560 if (length1 == 0) {
1561 if (strict) {
1562 result = 0;
1563 }
1564 goto str_is_done;
1565 }
1566 end = string1 + length1;
1567
1568 /*
1569 * When entering here, result == 1 and failat == 0
1570 */
1571 switch ((enum isOptions) index) {
1572 case STR_IS_ALNUM:
1573 chcomp = Tcl_UniCharIsAlnum;
1574 break;
1575 case STR_IS_ALPHA:
1576 chcomp = Tcl_UniCharIsAlpha;
1577 break;
1578 case STR_IS_ASCII:
1579 for (; string1 < end; string1++, failat++) {
1580 /*
1581 * This is a valid check in unicode, because all
1582 * bytes < 0xC0 are single byte chars (but isascii
1583 * limits that def'n to 0x80).
1584 */
1585 if (*((unsigned char *)string1) >= 0x80) {
1586 result = 0;
1587 break;
1588 }
1589 }
1590 break;
1591 case STR_IS_BOOL:
1592 case STR_IS_TRUE:
1593 case STR_IS_FALSE:
1594 if (objPtr->typePtr == &tclBooleanType) {
1595 if ((((enum isOptions) index == STR_IS_TRUE) &&
1596 objPtr->internalRep.longValue == 0) ||
1597 (((enum isOptions) index == STR_IS_FALSE) &&
1598 objPtr->internalRep.longValue != 0)) {
1599 result = 0;
1600 }
1601 } else if ((Tcl_GetBoolean(NULL, string1, &i)
1602 == TCL_ERROR) ||
1603 (((enum isOptions) index == STR_IS_TRUE) &&
1604 i == 0) ||
1605 (((enum isOptions) index == STR_IS_FALSE) &&
1606 i != 0)) {
1607 result = 0;
1608 }
1609 break;
1610 case STR_IS_CONTROL:
1611 chcomp = Tcl_UniCharIsControl;
1612 break;
1613 case STR_IS_DIGIT:
1614 chcomp = Tcl_UniCharIsDigit;
1615 break;
1616 case STR_IS_DOUBLE: {
1617 char *stop;
1618
1619 if ((objPtr->typePtr == &tclDoubleType) ||
1620 (objPtr->typePtr == &tclIntType)) {
1621 break;
1622 }
1623 /*
1624 * This is adapted from Tcl_GetDouble
1625 *
1626 * The danger in this function is that
1627 * "12345678901234567890" is an acceptable 'double',
1628 * but will later be interp'd as an int by something
1629 * like [expr]. Therefore, we check to see if it looks
1630 * like an int, and if so we do a range check on it.
1631 * If strtoul gets to the end, we know we either
1632 * received an acceptable int, or over/underflow
1633 */
1634 if (TclLooksLikeInt(string1, length1)) {
1635 errno = 0;
1636 #ifdef TCL_WIDE_INT_IS_LONG
1637 strtoul(string1, &stop, 0); /* INTL: Tcl source. */
1638 #else
1639 strtoull(string1, &stop, 0); /* INTL: Tcl source. */
1640 #endif
1641 if (stop == end) {
1642 if (errno == ERANGE) {
1643 result = 0;
1644 failat = -1;
1645 }
1646 break;
1647 }
1648 }
1649 errno = 0;
1650 strtod(string1, &stop); /* INTL: Tcl source. */
1651 if (errno == ERANGE) {
1652 /*
1653 * if (errno == ERANGE), then it was an over/underflow
1654 * problem, but in this method, we only want to know
1655 * yes or no, so bad flow returns 0 (false) and sets
1656 * the failVarObj to the string length.
1657 */
1658 result = 0;
1659 failat = -1;
1660 } else if (stop == string1) {
1661 /*
1662 * In this case, nothing like a number was found
1663 */
1664 result = 0;
1665 failat = 0;
1666 } else {
1667 /*
1668 * Assume we sucked up one char per byte
1669 * and then we go onto SPACE, since we are
1670 * allowed trailing whitespace
1671 */
1672 failat = stop - string1;
1673 string1 = stop;
1674 chcomp = Tcl_UniCharIsSpace;
1675 }
1676 break;
1677 }
1678 case STR_IS_GRAPH:
1679 chcomp = Tcl_UniCharIsGraph;
1680 break;
1681 case STR_IS_INT: {
1682 char *stop;
1683 long int l = 0;
1684
1685 if (TCL_OK == Tcl_GetIntFromObj(NULL, objPtr, &i)) {
1686 break;
1687 }
1688 /*
1689 * Like STR_IS_DOUBLE, but we use strtoul.
1690 * Since Tcl_GetIntFromObj already failed,
1691 * we set result to 0.
1692 */
1693 result = 0;
1694 errno = 0;
1695 l = strtol(string1, &stop, 0); /* INTL: Tcl source. */
1696 if ((errno == ERANGE) || (l > INT_MAX) || (l < INT_MIN)) {
1697 /*
1698 * if (errno == ERANGE), then it was an over/underflow
1699 * problem, but in this method, we only want to know
1700 * yes or no, so bad flow returns 0 (false) and sets
1701 * the failVarObj to the string length.
1702 */
1703 failat = -1;
1704
1705 } else if (stop == string1) {
1706 /*
1707 * In this case, nothing like a number was found
1708 */
1709 failat = 0;
1710 } else {
1711 /*
1712 * Assume we sucked up one char per byte
1713 * and then we go onto SPACE, since we are
1714 * allowed trailing whitespace
1715 */
1716 failat = stop - string1;
1717 string1 = stop;
1718 chcomp = Tcl_UniCharIsSpace;
1719 }
1720 break;
1721 }
1722 case STR_IS_LOWER:
1723 chcomp = Tcl_UniCharIsLower;
1724 break;
1725 case STR_IS_PRINT:
1726 chcomp = Tcl_UniCharIsPrint;
1727 break;
1728 case STR_IS_PUNCT:
1729 chcomp = Tcl_UniCharIsPunct;
1730 break;
1731 case STR_IS_SPACE:
1732 chcomp = Tcl_UniCharIsSpace;
1733 break;
1734 case STR_IS_UPPER:
1735 chcomp = Tcl_UniCharIsUpper;
1736 break;
1737 case STR_IS_WORD:
1738 chcomp = Tcl_UniCharIsWordChar;
1739 break;
1740 case STR_IS_XDIGIT: {
1741 for (; string1 < end; string1++, failat++) {
1742 /* INTL: We assume unicode is bad for this class */
1743 if ((*((unsigned char *)string1) >= 0xC0) ||
1744 !isxdigit(*(unsigned char *)string1)) {
1745 result = 0;
1746 break;
1747 }
1748 }
1749 break;
1750 }
1751 }
1752 if (chcomp != NULL) {
1753 for (; string1 < end; string1 += length2, failat++) {
1754 length2 = TclUtfToUniChar(string1, &ch);
1755 if (!chcomp(ch)) {
1756 result = 0;
1757 break;
1758 }
1759 }
1760 }
1761 str_is_done:
1762 /*
1763 * Only set the failVarObj when we will return 0
1764 * and we have indicated a valid fail index (>= 0)
1765 */
1766 if ((result == 0) && (failVarObj != NULL) &&
1767 Tcl_ObjSetVar2(interp, failVarObj, NULL, Tcl_NewIntObj(failat),
1768 TCL_LEAVE_ERR_MSG) == NULL) {
1769 return TCL_ERROR;
1770 }
1771 Tcl_SetBooleanObj(resultPtr, result);
1772 break;
1773 }
1774 case STR_LAST: {
1775 Tcl_UniChar *ustring1, *ustring2, *p;
1776 int match, start;
1777
1778 if (objc < 4 || objc > 5) {
1779 Tcl_WrongNumArgs(interp, 2, objv,
1780 "subString string ?startIndex?");
1781 return TCL_ERROR;
1782 }
1783
1784 /*
1785 * We are searching string2 for the sequence string1.
1786 */
1787
1788 match = -1;
1789 start = 0;
1790 length2 = -1;
1791
1792 ustring1 = Tcl_GetUnicodeFromObj(objv[2], &length1);
1793 ustring2 = Tcl_GetUnicodeFromObj(objv[3], &length2);
1794
1795 if (objc == 5) {
1796 /*
1797 * If a startIndex is specified, we will need to restrict
1798 * the string range to that char index in the string
1799 */
1800 if (TclGetIntForIndex(interp, objv[4], length2 - 1,
1801 &start) != TCL_OK) {
1802 return TCL_ERROR;
1803 }
1804 if (start < 0) {
1805 goto str_last_done;
1806 } else if (start < length2) {
1807 p = ustring2 + start + 1 - length1;
1808 } else {
1809 p = ustring2 + length2 - length1;
1810 }
1811 } else {
1812 p = ustring2 + length2 - length1;
1813 }
1814
1815 if (length1 > 0) {
1816 for (; p >= ustring2; p--) {
1817 /*
1818 * Scan backwards to find the first character.
1819 */
1820 if ((*p == *ustring1) &&
1821 (memcmp((char *) ustring1, (char *) p, (size_t)
1822 (length1 * sizeof(Tcl_UniChar))) == 0)) {
1823 match = p - ustring2;
1824 break;
1825 }
1826 }
1827 }
1828
1829 str_last_done:
1830 Tcl_SetIntObj(resultPtr, match);
1831 break;
1832 }
1833 case STR_BYTELENGTH:
1834 case STR_LENGTH: {
1835 if (objc != 3) {
1836 Tcl_WrongNumArgs(interp, 2, objv, "string");
1837 return TCL_ERROR;
1838 }
1839
1840 if ((enum options) index == STR_BYTELENGTH) {
1841 (void) Tcl_GetStringFromObj(objv[2], &length1);
1842 } else {
1843 /*
1844 * If we have a ByteArray object, avoid recomputing the
1845 * string since the byte array contains one byte per
1846 * character. Otherwise, use the Unicode string rep to
1847 * calculate the length.
1848 */
1849
1850 if (objv[2]->typePtr == &tclByteArrayType) {
1851 (void) Tcl_GetByteArrayFromObj(objv[2], &length1);
1852 } else {
1853 length1 = Tcl_GetCharLength(objv[2]);
1854 }
1855 }
1856 Tcl_SetIntObj(resultPtr, length1);
1857 break;
1858 }
1859 case STR_MAP: {
1860 int mapElemc, nocase = 0;
1861 Tcl_Obj **mapElemv;
1862 Tcl_UniChar *ustring1, *ustring2, *p, *end;
1863 int (*strCmpFn)_ANSI_ARGS_((CONST Tcl_UniChar*,
1864 CONST Tcl_UniChar*, unsigned long));
1865
1866 if (objc < 4 || objc > 5) {
1867 Tcl_WrongNumArgs(interp, 2, objv, "?-nocase? charMap string");
1868 return TCL_ERROR;
1869 }
1870
1871 if (objc == 5) {
1872 string2 = Tcl_GetStringFromObj(objv[2], &length2);
1873 if ((length2 > 1) &&
1874 strncmp(string2, "-nocase", (size_t) length2) == 0) {
1875 nocase = 1;
1876 } else {
1877 Tcl_AppendStringsToObj(resultPtr, "bad option \"",
1878 string2, "\": must be -nocase",
1879 (char *) NULL);
1880 return TCL_ERROR;
1881 }
1882 }
1883
1884 if (Tcl_ListObjGetElements(interp, objv[objc-2], &mapElemc,
1885 &mapElemv) != TCL_OK) {
1886 return TCL_ERROR;
1887 }
1888 if (mapElemc == 0) {
1889 /*
1890 * empty charMap, just return whatever string was given
1891 */
1892 Tcl_SetObjResult(interp, objv[objc-1]);
1893 return TCL_OK;
1894 } else if (mapElemc & 1) {
1895 /*
1896 * The charMap must be an even number of key/value items
1897 */
1898 Tcl_SetStringObj(resultPtr, "char map list unbalanced", -1);
1899 return TCL_ERROR;
1900 }
1901 objc--;
1902
1903 ustring1 = Tcl_GetUnicodeFromObj(objv[objc], &length1);
1904 if (length1 == 0) {
1905 /*
1906 * Empty input string, just stop now
1907 */
1908 break;
1909 }
1910 end = ustring1 + length1;
1911
1912 strCmpFn = nocase ? Tcl_UniCharNcasecmp : Tcl_UniCharNcmp;
1913
1914 /*
1915 * Force result to be Unicode
1916 */
1917 Tcl_SetUnicodeObj(resultPtr, ustring1, 0);
1918
1919 if (mapElemc == 2) {
1920 /*
1921 * Special case for one map pair which avoids the extra
1922 * for loop and extra calls to get Unicode data. The
1923 * algorithm is otherwise identical to the multi-pair case.
1924 * This will be >30% faster on larger strings.
1925 */
1926 int mapLen;
1927 Tcl_UniChar *mapString, u2lc;
1928
1929 ustring2 = Tcl_GetUnicodeFromObj(mapElemv[0], &length2);
1930 p = ustring1;
1931 if (length2 == 0) {
1932 ustring1 = end;
1933 } else {
1934 mapString = Tcl_GetUnicodeFromObj(mapElemv[1], &mapLen);
1935 u2lc = (nocase ? Tcl_UniCharToLower(*ustring2) : 0);
1936 for (; ustring1 < end; ustring1++) {
1937 if (((*ustring1 == *ustring2) ||
1938 (nocase && (Tcl_UniCharToLower(*ustring1) ==
1939 u2lc))) &&
1940 ((length2 == 1) || strCmpFn(ustring1, ustring2,
1941 (unsigned long) length2) == 0)) {
1942 if (p != ustring1) {
1943 Tcl_AppendUnicodeToObj(resultPtr, p,
1944 ustring1 - p);
1945 p = ustring1 + length2;
1946 } else {
1947 p += length2;
1948 }
1949 ustring1 = p - 1;
1950
1951 Tcl_AppendUnicodeToObj(resultPtr, mapString,
1952 mapLen);
1953 }
1954 }
1955 }
1956 } else {
1957 Tcl_UniChar **mapStrings, *u2lc = NULL;
1958 int *mapLens;
1959 /*
1960 * Precompute pointers to the unicode string and length.
1961 * This saves us repeated function calls later,
1962 * significantly speeding up the algorithm. We only need
1963 * the lowercase first char in the nocase case.
1964 */
1965 mapStrings = (Tcl_UniChar **) ckalloc((mapElemc * 2)
1966 * sizeof(Tcl_UniChar *));
1967 mapLens = (int *) ckalloc((mapElemc * 2) * sizeof(int));
1968 if (nocase) {
1969 u2lc = (Tcl_UniChar *)
1970 ckalloc((mapElemc) * sizeof(Tcl_UniChar));
1971 }
1972 for (index = 0; index < mapElemc; index++) {
1973 mapStrings[index] = Tcl_GetUnicodeFromObj(mapElemv[index],
1974 &(mapLens[index]));
1975 if (nocase && ((index % 2) == 0)) {
1976 u2lc[index/2] = Tcl_UniCharToLower(*mapStrings[index]);
1977 }
1978 }
1979 for (p = ustring1; ustring1 < end; ustring1++) {
1980 for (index = 0; index < mapElemc; index += 2) {
1981 /*
1982 * Get the key string to match on.
1983 */
1984 ustring2 = mapStrings[index];
1985 length2 = mapLens[index];
1986 if ((length2 > 0) && ((*ustring1 == *ustring2) ||
1987 (nocase && (Tcl_UniCharToLower(*ustring1) ==
1988 u2lc[index/2]))) &&
1989 ((length2 == 1) || strCmpFn(ustring2, ustring1,
1990 (unsigned long) length2) == 0)) {
1991 if (p != ustring1) {
1992 /*
1993 * Put the skipped chars onto the result first
1994 */
1995 Tcl_AppendUnicodeToObj(resultPtr, p,
1996 ustring1 - p);
1997 p = ustring1 + length2;
1998 } else {
1999 p += length2;
2000 }
2001 /*
2002 * Adjust len to be full length of matched string
2003 */
2004 ustring1 = p - 1;
2005
2006 /*
2007 * Append the map value to the unicode string
2008 */
2009 Tcl_AppendUnicodeToObj(resultPtr,
2010 mapStrings[index+1], mapLens[index+1]);
2011 break;
2012 }
2013 }
2014 }
2015 ckfree((char *) mapStrings);
2016 ckfree((char *) mapLens);
2017 if (nocase) {
2018 ckfree((char *) u2lc);
2019 }
2020 }
2021 if (p != ustring1) {
2022 /*
2023 * Put the rest of the unmapped chars onto result
2024 */
2025 Tcl_AppendUnicodeToObj(resultPtr, p, ustring1 - p);
2026 }
2027 break;
2028 }
2029 case STR_MATCH: {
2030 Tcl_UniChar *ustring1, *ustring2;
2031 int nocase = 0;
2032
2033 if (objc < 4 || objc > 5) {
2034 Tcl_WrongNumArgs(interp, 2, objv, "?-nocase? pattern string");
2035 return TCL_ERROR;
2036 }
2037
2038 if (objc == 5) {
2039 string2 = Tcl_GetStringFromObj(objv[2], &length2);
2040 if ((length2 > 1) &&
2041 strncmp(string2, "-nocase", (size_t) length2) == 0) {
2042 nocase = 1;
2043 } else {
2044 Tcl_AppendStringsToObj(resultPtr, "bad option \"",
2045 string2, "\": must be -nocase",
2046 (char *) NULL);
2047 return TCL_ERROR;
2048 }
2049 }
2050 ustring1 = Tcl_GetUnicodeFromObj(objv[objc-1], &length1);
2051 ustring2 = Tcl_GetUnicodeFromObj(objv[objc-2], &length2);
2052 Tcl_SetBooleanObj(resultPtr, TclUniCharMatch(ustring1, length1,
2053 ustring2, length2, nocase));
2054 break;
2055 }
2056 case STR_RANGE: {
2057 int first, last;
2058
2059 if (objc != 5) {
2060 Tcl_WrongNumArgs(interp, 2, objv, "string first last");
2061 return TCL_ERROR;
2062 }
2063
2064 /*
2065 * If we have a ByteArray object, avoid indexing in the
2066 * Utf string since the byte array contains one byte per
2067 * character. Otherwise, use the Unicode string rep to
2068 * get the range.
2069 */
2070
2071 if (objv[2]->typePtr == &tclByteArrayType) {
2072 string1 = (char *)Tcl_GetByteArrayFromObj(objv[2], &length1);
2073 length1--;
2074 } else {
2075 /*
2076 * Get the length in actual characters.
2077 */
2078 string1 = NULL;
2079 length1 = Tcl_GetCharLength(objv[2]) - 1;
2080 }
2081
2082 if ((TclGetIntForIndex(interp, objv[3], length1, &first) != TCL_OK)
2083 || (TclGetIntForIndex(interp, objv[4], length1,
2084 &last) != TCL_OK)) {
2085 return TCL_ERROR;
2086 }
2087
2088 if (first < 0) {
2089 first = 0;
2090 }
2091 if (last >= length1) {
2092 last = length1;
2093 }
2094 if (last >= first) {
2095 if (string1 != NULL) {
2096 int numBytes = last - first + 1;
2097 resultPtr = Tcl_NewByteArrayObj(
2098 (unsigned char *) &string1[first], numBytes);
2099 Tcl_SetObjResult(interp, resultPtr);
2100 } else {
2101 Tcl_SetObjResult(interp,
2102 Tcl_GetRange(objv[2], first, last));
2103 }
2104 }
2105 break;
2106 }
2107 case STR_REPEAT: {
2108 int count;
2109
2110 if (objc != 4) {
2111 Tcl_WrongNumArgs(interp, 2, objv, "string count");
2112 return TCL_ERROR;
2113 }
2114
2115 if (Tcl_GetIntFromObj(interp, objv[3], &count) != TCL_OK) {
2116 return TCL_ERROR;
2117 }
2118
2119 if (count == 1) {
2120 Tcl_SetObjResult(interp, objv[2]);
2121 } else if (count > 1) {
2122 string1 = Tcl_GetStringFromObj(objv[2], &length1);
2123 if (length1 > 0) {
2124 /*
2125 * Only build up a string that has data. Instead of
2126 * building it up with repeated appends, we just allocate
2127 * the necessary space once and copy the string value in.
2128 * Check for overflow with back-division. [Bug #714106]
2129 */
2130 length2 = length1 * count;
2131 if ((length2 / count) != length1) {
2132 char buf[TCL_INTEGER_SPACE+1];
2133 sprintf(buf, "%d", INT_MAX);
2134 Tcl_AppendStringsToObj(resultPtr,
2135 "string size overflow, must be less than ",
2136 buf, (char *) NULL);
2137 return TCL_ERROR;
2138 }
2139 /*
2140 * Include space for the NULL
2141 */
2142 string2 = (char *) ckalloc((size_t) length2+1);
2143 for (index = 0; index < count; index++) {
2144 memcpy(string2 + (length1 * index), string1,
2145 (size_t) length1);
2146 }
2147 string2[length2] = '\0';
2148 /*
2149 * We have to directly assign this instead of using
2150 * Tcl_SetStringObj (and indirectly TclInitStringRep)
2151 * because that makes another copy of the data.
2152 */
2153 resultPtr = Tcl_NewObj();
2154 resultPtr->bytes = string2;
2155 resultPtr->length = length2;
2156 Tcl_SetObjResult(interp, resultPtr);
2157 }
2158 }
2159 break;
2160 }
2161 case STR_REPLACE: {
2162 Tcl_UniChar *ustring1;
2163 int first, last;
2164
2165 if (objc < 5 || objc > 6) {
2166 Tcl_WrongNumArgs(interp, 2, objv,
2167 "string first last ?string?");
2168 return TCL_ERROR;
2169 }
2170
2171 ustring1 = Tcl_GetUnicodeFromObj(objv[2], &length1);
2172 length1--;
2173
2174 if ((TclGetIntForIndex(interp, objv[3], length1, &first) != TCL_OK)
2175 || (TclGetIntForIndex(interp, objv[4], length1,
2176 &last) != TCL_OK)) {
2177 return TCL_ERROR;
2178 }
2179
2180 if ((last < first) || (last < 0) || (first > length1)) {
2181 Tcl_SetObjResult(interp, objv[2]);
2182 } else {
2183 if (first < 0) {
2184 first = 0;
2185 }
2186
2187 Tcl_SetUnicodeObj(resultPtr, ustring1, first);
2188 if (objc == 6) {
2189 Tcl_AppendObjToObj(resultPtr, objv[5]);
2190 }
2191 if (last < length1) {
2192 Tcl_AppendUnicodeToObj(resultPtr, ustring1 + last + 1,
2193 length1 - last);
2194 }
2195 }
2196 break;
2197 }
2198 case STR_TOLOWER:
2199 case STR_TOUPPER:
2200 case STR_TOTITLE:
2201 if (objc < 3 || objc > 5) {
2202 Tcl_WrongNumArgs(interp, 2, objv, "string ?first? ?last?");
2203 return TCL_ERROR;
2204 }
2205
2206 string1 = Tcl_GetStringFromObj(objv[2], &length1);
2207
2208 if (objc == 3) {
2209 /*
2210 * Since the result object is not a shared object, it is
2211 * safe to copy the string into the result and do the
2212 * conversion in place. The conversion may change the length
2213 * of the string, so reset the length after conversion.
2214 */
2215
2216 Tcl_SetStringObj(resultPtr, string1, length1);
2217 if ((enum options) index == STR_TOLOWER) {
2218 length1 = Tcl_UtfToLower(Tcl_GetString(resultPtr));
2219 } else if ((enum options) index == STR_TOUPPER) {
2220 length1 = Tcl_UtfToUpper(Tcl_GetString(resultPtr));
2221 } else {
2222 length1 = Tcl_UtfToTitle(Tcl_GetString(resultPtr));
2223 }
2224 Tcl_SetObjLength(resultPtr, length1);
2225 } else {
2226 int first, last;
2227 CONST char *start, *end;
2228
2229 length1 = Tcl_NumUtfChars(string1, length1) - 1;
2230 if (TclGetIntForIndex(interp, objv[3], length1,
2231 &first) != TCL_OK) {
2232 return TCL_ERROR;
2233 }
2234 if (first < 0) {
2235 first = 0;
2236 }
2237 last = first;
2238 if ((objc == 5) && (TclGetIntForIndex(interp, objv[4], length1,
2239 &last) != TCL_OK)) {
2240 return TCL_ERROR;
2241 }
2242 if (last >= length1) {
2243 last = length1;
2244 }
2245 if (last < first) {
2246 Tcl_SetObjResult(interp, objv[2]);
2247 break;
2248 }
2249 start = Tcl_UtfAtIndex(string1, first);
2250 end = Tcl_UtfAtIndex(start, last - first + 1);
2251 length2 = end-start;
2252 string2 = ckalloc((size_t) length2+1);
2253 memcpy(string2, start, (size_t) length2);
2254 string2[length2] = '\0';
2255 if ((enum options) index == STR_TOLOWER) {
2256 length2 = Tcl_UtfToLower(string2);
2257 } else if ((enum options) index == STR_TOUPPER) {
2258 length2 = Tcl_UtfToUpper(string2);
2259 } else {
2260 length2 = Tcl_UtfToTitle(string2);
2261 }
2262 Tcl_SetStringObj(resultPtr, string1, start - string1);
2263 Tcl_AppendToObj(resultPtr, string2, length2);
2264 Tcl_AppendToObj(resultPtr, end, -1);
2265 ckfree(string2);
2266 }
2267 break;
2268
2269 case STR_TRIM: {
2270 Tcl_UniChar ch, trim;
2271 register CONST char *p, *end;
2272 char *check, *checkEnd;
2273 int offset;
2274
2275 left = 1;
2276 right = 1;
2277
2278 dotrim:
2279 if (objc == 4) {
2280 string2 = Tcl_GetStringFromObj(objv[3], &length2);
2281 } else if (objc == 3) {
2282 string2 = " \t\n\r";
2283 length2 = strlen(string2);
2284 } else {
2285 Tcl_WrongNumArgs(interp, 2, objv, "string ?chars?");
2286 return TCL_ERROR;
2287 }
2288 string1 = Tcl_GetStringFromObj(objv[2], &length1);
2289 checkEnd = string2 + length2;
2290
2291 if (left) {
2292 end = string1 + length1;
2293 /*
2294 * The outer loop iterates over the string. The inner
2295 * loop iterates over the trim characters. The loops
2296 * terminate as soon as a non-trim character is discovered
2297 * and string1 is left pointing at the first non-trim
2298 * character.
2299 */
2300
2301 for (p = string1; p < end; p += offset) {
2302 offset = TclUtfToUniChar(p, &ch);
2303
2304 for (check = string2; ; ) {
2305 if (check >= checkEnd) {
2306 p = end;
2307 break;
2308 }
2309 check += TclUtfToUniChar(check, &trim);
2310 if (ch == trim) {
2311 length1 -= offset;
2312 string1 += offset;
2313 break;
2314 }
2315 }
2316 }
2317 }
2318 if (right) {
2319 end = string1;
2320
2321 /*
2322 * The outer loop iterates over the string. The inner
2323 * loop iterates over the trim characters. The loops
2324 * terminate as soon as a non-trim character is discovered
2325 * and length1 marks the last non-trim character.
2326 */
2327
2328 for (p = string1 + length1; p > end; ) {
2329 p = Tcl_UtfPrev(p, string1);
2330 offset = TclUtfToUniChar(p, &ch);
2331 for (check = string2; ; ) {
2332 if (check >= checkEnd) {
2333 p = end;
2334 break;
2335 }
2336 check += TclUtfToUniChar(check, &trim);
2337 if (ch == trim) {
2338 length1 -= offset;
2339 break;
2340 }
2341 }
2342 }
2343 }
2344 Tcl_SetStringObj(resultPtr, string1, length1);
2345 break;
2346 }
2347 case STR_TRIMLEFT: {
2348 left = 1;
2349 right = 0;
2350 goto dotrim;
2351 }
2352 case STR_TRIMRIGHT: {
2353 left = 0;
2354 right = 1;
2355 goto dotrim;
2356 }
2357 case STR_WORDEND: {
2358 int cur;
2359 Tcl_UniChar ch;
2360 CONST char *p, *end;
2361 int numChars;
2362
2363 if (objc != 4) {
2364 Tcl_WrongNumArgs(interp, 2, objv, "string index");
2365 return TCL_ERROR;
2366 }
2367
2368 string1 = Tcl_GetStringFromObj(objv[2], &length1);
2369 numChars = Tcl_NumUtfChars(string1, length1);
2370 if (TclGetIntForIndex(interp, objv[3], numChars-1,
2371 &index) != TCL_OK) {
2372 return TCL_ERROR;
2373 }
2374 if (index < 0) {
2375 index = 0;
2376 }
2377 if (index < numChars) {
2378 p = Tcl_UtfAtIndex(string1, index);
2379 end = string1+length1;
2380 for (cur = index; p < end; cur++) {
2381 p += TclUtfToUniChar(p, &ch);
2382 if (!Tcl_UniCharIsWordChar(ch)) {
2383 break;
2384 }
2385 }
2386 if (cur == index) {
2387 cur++;
2388 }
2389 } else {
2390 cur = numChars;
2391 }
2392 Tcl_SetIntObj(resultPtr, cur);
2393 break;
2394 }
2395 case STR_WORDSTART: {
2396 int cur;
2397 Tcl_UniChar ch;
2398 CONST char *p;
2399 int numChars;
2400
2401 if (objc != 4) {
2402 Tcl_WrongNumArgs(interp, 2, objv, "string index");
2403 return TCL_ERROR;
2404 }
2405
2406 string1 = Tcl_GetStringFromObj(objv[2], &length1);
2407 numChars = Tcl_NumUtfChars(string1, length1);
2408 if (TclGetIntForIndex(interp, objv[3], numChars-1,
2409 &index) != TCL_OK) {
2410 return TCL_ERROR;
2411 }
2412 if (index >= numChars) {
2413 index = numChars - 1;
2414 }
2415 cur = 0;
2416 if (index > 0) {
2417 p = Tcl_UtfAtIndex(string1, index);
2418 for (cur = index; cur >= 0; cur--) {
2419 TclUtfToUniChar(p, &ch);
2420 if (!Tcl_UniCharIsWordChar(ch)) {
2421 break;
2422 }
2423 p = Tcl_UtfPrev(p, string1);
2424 }
2425 if (cur != index) {
2426 cur += 1;
2427 }
2428 }
2429 Tcl_SetIntObj(resultPtr, cur);
2430 break;
2431 }
2432 }
2433 return TCL_OK;
2434 }
2435
2436 /*
2437 *----------------------------------------------------------------------
2438 *
2439 * Tcl_SubstObjCmd --
2440 *
2441 * This procedure is invoked to process the "subst" Tcl command.
2442 * See the user documentation for details on what it does. This
2443 * command relies on Tcl_SubstObj() for its implementation.
2444 *
2445 * Results:
2446 * A standard Tcl result.
2447 *
2448 * Side effects:
2449 * See the user documentation.
2450 *
2451 *----------------------------------------------------------------------
2452 */
2453
2454 /* ARGSUSED */
2455 int
2456 Tcl_SubstObjCmd(dummy, interp, objc, objv)
2457 ClientData dummy; /* Not used. */
2458 Tcl_Interp *interp; /* Current interpreter. */
2459 int objc; /* Number of arguments. */
2460 Tcl_Obj *CONST objv[]; /* Argument objects. */
2461 {
2462 static CONST char *substOptions[] = {
2463 "-nobackslashes", "-nocommands", "-novariables", (char *) NULL
2464 };
2465 enum substOptions {
2466 SUBST_NOBACKSLASHES, SUBST_NOCOMMANDS, SUBST_NOVARS
2467 };
2468 Tcl_Obj *resultPtr;
2469 int optionIndex, flags, i;
2470
2471 /*
2472 * Parse command-line options.
2473 */
2474
2475 flags = TCL_SUBST_ALL;
2476 for (i = 1; i < (objc-1); i++) {
2477 if (Tcl_GetIndexFromObj(interp, objv[i], substOptions,
2478 "switch", 0, &optionIndex) != TCL_OK) {
2479
2480 return TCL_ERROR;
2481 }
2482 switch (optionIndex) {
2483 case SUBST_NOBACKSLASHES: {
2484 flags &= ~TCL_SUBST_BACKSLASHES;
2485 break;
2486 }
2487 case SUBST_NOCOMMANDS: {
2488 flags &= ~TCL_SUBST_COMMANDS;
2489 break;
2490 }
2491 case SUBST_NOVARS: {
2492 flags &= ~TCL_SUBST_VARIABLES;
2493 break;
2494 }
2495 default: {
2496 panic("Tcl_SubstObjCmd: bad option index to SubstOptions");
2497 }
2498 }
2499 }
2500 if (i != (objc-1)) {
2501 Tcl_WrongNumArgs(interp, 1, objv,
2502 "?-nobackslashes? ?-nocommands? ?-novariables? string");
2503 return TCL_ERROR;
2504 }
2505
2506 /*
2507 * Perform the substitution.
2508 */
2509 resultPtr = Tcl_SubstObj(interp, objv[i], flags);
2510
2511 if (resultPtr == NULL) {
2512 return TCL_ERROR;
2513 }
2514 Tcl_SetObjResult(interp, resultPtr);
2515 return TCL_OK;
2516 }
2517
2518 /*
2519 *----------------------------------------------------------------------
2520 *
2521 * Tcl_SubstObj --
2522 *
2523 * This function performs the substitutions specified on the
2524 * given string as described in the user documentation for the
2525 * "subst" Tcl command. This code is heavily based on an
2526 * implementation by Andrew Payne. Note that if a command
2527 * substitution returns TCL_CONTINUE or TCL_RETURN from its
2528 * evaluation and is not completely well-formed, the results are
2529 * not defined (or at least hard to characterise.) This fault
2530 * will be fixed at some point, but the cost of the only sane
2531 * fix (well-formedness check first) is such that you need to
2532 * "precompile and cache" to stop everyone from being hit with
2533 * the consequences every time through. Note that the current
2534 * behaviour is not a security hole; it just restarts parsing
2535 * the string following the substitution in a mildly surprising
2536 * place, and it is a very bad idea to count on this remaining
2537 * the same in future...
2538 *
2539 * Results:
2540 * A Tcl_Obj* containing the substituted string, or NULL to
2541 * indicate that an error occurred.
2542 *
2543 * Side effects:
2544 * See the user documentation.
2545 *
2546 *----------------------------------------------------------------------
2547 */
2548
2549 Tcl_Obj *
2550 Tcl_SubstObj(interp, objPtr, flags)
2551 Tcl_Interp *interp;
2552 Tcl_Obj *objPtr;
2553 int flags;
2554 {
2555 Tcl_Obj *resultObj;
2556 char *p, *old;
2557 int length;
2558
2559 old = p = Tcl_GetStringFromObj(objPtr, &length);
2560 resultObj = Tcl_NewStringObj("", 0);
2561 while (length) {
2562 switch (*p) {
2563 case '\\':
2564 if (flags & TCL_SUBST_BACKSLASHES) {
2565 char buf[TCL_UTF_MAX];
2566 int count;
2567
2568 if (p != old) {
2569 Tcl_AppendToObj(resultObj, old, p-old);
2570 }
2571 Tcl_AppendToObj(resultObj, buf,
2572 Tcl_UtfBackslash(p, &count, buf));
2573 p += count; length -= count;
2574 old = p;
2575 } else {
2576 p++; length--;
2577 }
2578 break;
2579
2580 case '$':
2581 if (flags & TCL_SUBST_VARIABLES) {
2582 Tcl_Parse parse;
2583 int code;
2584
2585 /*
2586 * Code is simpler overall if we (effectively) inline
2587 * Tcl_ParseVar, particularly as that allows us to use
2588 * a non-string interface when we come to appending
2589 * the variable contents to the result object. There
2590 * are a few other optimisations that doing this
2591 * enables (like being able to continue the run of
2592 * unsubstituted characters straight through if a '$'
2593 * does not precede a variable name.)
2594 */
2595 if (Tcl_ParseVarName(interp, p, -1, &parse, 0) != TCL_OK) {
2596 goto errorResult;
2597 }
2598 if (parse.numTokens == 1) {
2599 /*
2600 * There isn't a variable name after all: the $ is
2601 * just a $.
2602 */
2603 p++; length--;
2604 break;
2605 }
2606 if (p != old) {
2607 Tcl_AppendToObj(resultObj, old, p-old);
2608 }
2609 p += parse.tokenPtr->size;
2610 length -= parse.tokenPtr->size;
2611 code = Tcl_EvalTokensStandard(interp, parse.tokenPtr,
2612 parse.numTokens);
2613 if (code == TCL_ERROR) {
2614 goto errorResult;
2615 }
2616 if (code == TCL_BREAK) {
2617 Tcl_ResetResult(interp);
2618 return resultObj;
2619 }
2620 if (code != TCL_CONTINUE) {
2621 Tcl_AppendObjToObj(resultObj, Tcl_GetObjResult(interp));
2622 }
2623 Tcl_ResetResult(interp);
2624 old = p;
2625 } else {
2626 p++; length--;
2627 }
2628 break;
2629
2630 case '[':
2631 if (flags & TCL_SUBST_COMMANDS) {
2632 Interp *iPtr = (Interp *) interp;
2633 int code;
2634
2635 if (p != old) {
2636 Tcl_AppendToObj(resultObj, old, p-old);
2637 }
2638 iPtr->evalFlags = TCL_BRACKET_TERM;
2639 code = Tcl_EvalEx(interp, p+1, -1, 0);
2640 switch (code) {
2641 case TCL_ERROR:
2642 goto errorResult;
2643 case TCL_BREAK:
2644 Tcl_ResetResult(interp);
2645 return resultObj;
2646 default:
2647 Tcl_AppendObjToObj(resultObj, Tcl_GetObjResult(interp));
2648 case TCL_CONTINUE:
2649 Tcl_ResetResult(interp);
2650 old = p = (p+1 + iPtr->termOffset + 1);
2651 length -= (iPtr->termOffset + 2);
2652 }
2653 } else {
2654 p++; length--;
2655 }
2656 break;
2657 default:
2658 p++; length--;
2659 break;
2660 }
2661 }
2662 if (p != old) {
2663 Tcl_AppendToObj(resultObj, old, p-old);
2664 }
2665 return resultObj;
2666
2667 errorResult:
2668 Tcl_DecrRefCount(resultObj);
2669 return NULL;
2670 }
2671
2672 /*
2673 *----------------------------------------------------------------------
2674 *
2675 * Tcl_SwitchObjCmd --
2676 *
2677 * This object-based procedure is invoked to process the "switch" Tcl
2678 * command. See the user documentation for details on what it does.
2679 *
2680 * Results:
2681 * A standard Tcl object result.
2682 *
2683 * Side effects:
2684 * See the user documentation.
2685 *
2686 *----------------------------------------------------------------------
2687 */
2688
2689 /* ARGSUSED */
2690 int
2691 Tcl_SwitchObjCmd(dummy, interp, objc, objv)
2692 ClientData dummy; /* Not used. */
2693 Tcl_Interp *interp; /* Current interpreter. */
2694 int objc; /* Number of arguments. */
2695 Tcl_Obj *CONST objv[]; /* Argument objects. */
2696 {
2697 int i, j, index, mode, matched, result, splitObjs;
2698 char *string, *pattern;
2699 Tcl_Obj *stringObj;
2700 Tcl_Obj *CONST *savedObjv = objv;
2701 static CONST char *options[] = {
2702 "-exact", "-glob", "-regexp", "--",
2703 NULL
2704 };
2705 enum options {
2706 OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_LAST
2707 };
2708
2709 mode = OPT_EXACT;
2710 for (i = 1; i < objc; i++) {
2711 string = Tcl_GetString(objv[i]);
2712 if (string[0] != '-') {
2713 break;
2714 }
2715 if (Tcl_GetIndexFromObj(interp, objv[i], options, "option", 0,
2716 &index) != TCL_OK) {
2717 return TCL_ERROR;
2718 }
2719 if (index == OPT_LAST) {
2720 i++;
2721 break;
2722 }
2723 mode = index;
2724 }
2725
2726 if (objc - i < 2) {
2727 Tcl_WrongNumArgs(interp, 1, objv,
2728 "?switches? string pattern body ... ?default body?");
2729 return TCL_ERROR;
2730 }
2731
2732 stringObj = objv[i];
2733 objc -= i + 1;
2734 objv += i + 1;
2735
2736 /*
2737 * If all of the pattern/command pairs are lumped into a single
2738 * argument, split them out again.
2739 */
2740
2741 splitObjs = 0;
2742 if (objc == 1) {
2743 Tcl_Obj **listv;
2744
2745 if (Tcl_ListObjGetElements(interp, objv[0], &objc, &listv) != TCL_OK) {
2746 return TCL_ERROR;
2747 }
2748
2749 /*
2750 * Ensure that the list is non-empty.
2751 */
2752
2753 if (objc < 1) {
2754 Tcl_WrongNumArgs(interp, 1, savedObjv,
2755 "?switches? string {pattern body ... ?default body?}");
2756 return TCL_ERROR;
2757 }
2758 objv = listv;
2759 splitObjs = 1;
2760 }
2761
2762 /*
2763 * Complain if there is an odd number of words in the list of
2764 * patterns and bodies.
2765 */
2766
2767 if (objc % 2) {
2768 Tcl_ResetResult(interp);
2769 Tcl_AppendResult(interp, "extra switch pattern with no body", NULL);
2770
2771 /*
2772 * Check if this can be due to a badly placed comment
2773 * in the switch block.
2774 *
2775 * The following is an heuristic to detect the infamous
2776 * "comment in switch" error: just check if a pattern
2777 * begins with '#'.
2778 */
2779
2780 if (splitObjs) {
2781 for (i=0 ; i<objc ; i+=2) {
2782 if (Tcl_GetString(objv[i])[0] == '#') {
2783 Tcl_AppendResult(interp, ", this may be due to a ",
2784 "comment incorrectly placed outside of a ",
2785 "switch body - see the \"switch\" ",
2786 "documentation", NULL);
2787 break;
2788 }
2789 }
2790 }
2791
2792 return TCL_ERROR;
2793 }
2794
2795 /*
2796 * Complain if the last body is a continuation. Note that this
2797 * check assumes that the list is non-empty!
2798 */
2799
2800 if (strcmp(Tcl_GetString(objv[objc-1]), "-") == 0) {
2801 Tcl_ResetResult(interp);
2802 Tcl_AppendResult(interp, "no body specified for pattern \"",
2803 Tcl_GetString(objv[objc-2]), "\"", NULL);
2804 return TCL_ERROR;
2805 }
2806
2807 for (i = 0; i < objc; i += 2) {
2808 /*
2809 * See if the pattern matches the string.
2810 */
2811
2812 pattern = Tcl_GetString(objv[i]);
2813
2814 matched = 0;
2815 if ((i == objc - 2)
2816 && (*pattern == 'd')
2817 && (strcmp(pattern, "default") == 0)) {
2818 matched = 1;
2819 } else {
2820 switch (mode) {
2821 case OPT_EXACT:
2822 matched = (strcmp(Tcl_GetString(stringObj), pattern) == 0);
2823 break;
2824 case OPT_GLOB:
2825 matched = Tcl_StringMatch(Tcl_GetString(stringObj),
2826 pattern);
2827 break;
2828 case OPT_REGEXP:
2829 matched = Tcl_RegExpMatchObj(interp, stringObj, objv[i]);
2830 if (matched < 0) {
2831 return TCL_ERROR;
2832 }
2833 break;
2834 }
2835 }
2836 if (matched == 0) {
2837 continue;
2838 }
2839
2840 /*
2841 * We've got a match. Find a body to execute, skipping bodies
2842 * that are "-".
2843 */
2844
2845 for (j = i + 1; ; j += 2) {
2846 if (j >= objc) {
2847 /*
2848 * This shouldn't happen since we've checked that the
2849 * last body is not a continuation...
2850 */
2851 panic("fall-out when searching for body to match pattern");
2852 }
2853 if (strcmp(Tcl_GetString(objv[j]), "-") != 0) {
2854 break;
2855 }
2856 }
2857 result = Tcl_EvalObjEx(interp, objv[j], 0);
2858 if (result == TCL_ERROR) {
2859 char msg[100 + TCL_INTEGER_SPACE];
2860
2861 sprintf(msg, "\n (\"%.50s\" arm line %d)", pattern,
2862 interp->errorLine);
2863 Tcl_AddObjErrorInfo(interp, msg, -1);
2864 }
2865 return result;
2866 }
2867 return TCL_OK;
2868 }
2869
2870 /*
2871 *----------------------------------------------------------------------
2872 *
2873 * Tcl_TimeObjCmd --
2874 *
2875 * This object-based procedure is invoked to process the "time" Tcl
2876 * command. See the user documentation for details on what it does.
2877 *
2878 * Results:
2879 * A standard Tcl object result.
2880 *
2881 * Side effects:
2882 * See the user documentation.
2883 *
2884 *----------------------------------------------------------------------
2885 */
2886
2887 /* ARGSUSED */
2888 int
2889 Tcl_TimeObjCmd(dummy, interp, objc, objv)
2890 ClientData dummy; /* Not used. */
2891 Tcl_Interp *interp; /* Current interpreter. */
2892 int objc; /* Number of arguments. */
2893 Tcl_Obj *CONST objv[]; /* Argument objects. */
2894 {
2895 register Tcl_Obj *objPtr;
2896 register int i, result;
2897 int count;
2898 double totalMicroSec;
2899 Tcl_Time start, stop;
2900 char buf[100];
2901
2902 if (objc == 2) {
2903 count = 1;
2904 } else if (objc == 3) {
2905 result = Tcl_GetIntFromObj(interp, objv[2], &count);
2906 if (result != TCL_OK) {
2907 return result;
2908 }
2909 } else {
2910 Tcl_WrongNumArgs(interp, 1, objv, "command ?count?");
2911 return TCL_ERROR;
2912 }
2913
2914 objPtr = objv[1];
2915 i = count;
2916 Tcl_GetTime(&start);
2917 while (i-- > 0) {
2918 result = Tcl_EvalObjEx(interp, objPtr, 0);
2919 if (result != TCL_OK) {
2920 return result;
2921 }
2922 }
2923 Tcl_GetTime(&stop);
2924
2925 totalMicroSec = ( ( (double) ( stop.sec - start.sec ) ) * 1.0e6
2926 + ( stop.usec - start.usec ) );
2927 sprintf(buf, "%.0f microseconds per iteration",
2928 ((count <= 0) ? 0 : totalMicroSec/count));
2929 Tcl_ResetResult(interp);
2930 Tcl_AppendToObj(Tcl_GetObjResult(interp), buf, -1);
2931 return TCL_OK;
2932 }
2933
2934 /*
2935 *----------------------------------------------------------------------
2936 *
2937 * Tcl_TraceObjCmd --
2938 *
2939 * This procedure is invoked to process the "trace" Tcl command.
2940 * See the user documentation for details on what it does.
2941 *
2942 * Standard syntax as of Tcl 8.4 is
2943 *
2944 * trace {add|info|remove} {command|variable} name ops cmd
2945 *
2946 *
2947 * Results:
2948 * A standard Tcl result.
2949 *
2950 * Side effects:
2951 * See the user documentation.
2952 *----------------------------------------------------------------------
2953 */
2954
2955 /* ARGSUSED */
2956 int
2957 Tcl_TraceObjCmd(dummy, interp, objc, objv)
2958 ClientData dummy; /* Not used. */
2959 Tcl_Interp *interp; /* Current interpreter. */
2960 int objc; /* Number of arguments. */
2961 Tcl_Obj *CONST objv[]; /* Argument objects. */
2962 {
2963 int optionIndex, commandLength;
2964 char *name, *flagOps, *command, *p;
2965 size_t length;
2966 /* Main sub commands to 'trace' */
2967 static CONST char *traceOptions[] = {
2968 "add", "info", "remove",
2969 #ifndef TCL_REMOVE_OBSOLETE_TRACES
2970 "variable", "vdelete", "vinfo",
2971 #endif
2972 (char *) NULL
2973 };
2974 /* 'OLD' options are pre-Tcl-8.4 style */
2975 enum traceOptions {
2976 TRACE_ADD, TRACE_INFO, TRACE_REMOVE,
2977 #ifndef TCL_REMOVE_OBSOLETE_TRACES
2978 TRACE_OLD_VARIABLE, TRACE_OLD_VDELETE, TRACE_OLD_VINFO
2979 #endif
2980 };
2981
2982 if (objc < 2) {
2983 Tcl_WrongNumArgs(interp, 1, objv, "option ?arg arg ...?");
2984 return TCL_ERROR;
2985 }
2986
2987 if (Tcl_GetIndexFromObj(interp, objv[1], traceOptions,
2988 "option", 0, &optionIndex) != TCL_OK) {
2989 return TCL_ERROR;
2990 }
2991 switch ((enum traceOptions) optionIndex) {
2992 case TRACE_ADD:
2993 case TRACE_REMOVE:
2994 case TRACE_INFO: {
2995 /*
2996 * All sub commands of trace add/remove must take at least
2997 * one more argument. Beyond that we let the subcommand itself
2998 * control the argument structure.
2999 */
3000 int typeIndex;
3001 if (objc < 3) {
3002 Tcl_WrongNumArgs(interp, 2, objv, "type ?arg arg ...?");
3003 return TCL_ERROR;
3004 }
3005 if (Tcl_GetIndexFromObj(interp, objv[2], traceTypeOptions,
3006 "option", 0, &typeIndex) != TCL_OK) {
3007 return TCL_ERROR;
3008 }
3009 return (traceSubCmds[typeIndex])(interp, optionIndex, objc, objv);
3010 }
3011 #ifndef TCL_REMOVE_OBSOLETE_TRACES
3012 case TRACE_OLD_VARIABLE: {
3013 int flags;
3014 TraceVarInfo *tvarPtr;
3015 if (objc != 5) {
3016 Tcl_WrongNumArgs(interp, 2, objv, "name ops command");
3017 return TCL_ERROR;
3018 }
3019
3020 flags = 0;
3021 flagOps = Tcl_GetString(objv[3]);
3022 for (p = flagOps; *p != 0; p++) {
3023 if (*p == 'r') {
3024 flags |= TCL_TRACE_READS;
3025 } else if (*p == 'w') {
3026 flags |= TCL_TRACE_WRITES;
3027 } else if (*p == 'u') {
3028 flags |= TCL_TRACE_UNSETS;
3029 } else if (*p == 'a') {
3030 flags |= TCL_TRACE_ARRAY;
3031 } else {
3032 goto badVarOps;
3033 }
3034 }
3035 if (flags == 0) {
3036 goto badVarOps;
3037 }
3038 flags |= TCL_TRACE_OLD_STYLE;
3039
3040 command = Tcl_GetStringFromObj(objv[4], &commandLength);
3041 length = (size_t) commandLength;
3042 tvarPtr = (TraceVarInfo *) ckalloc((unsigned)
3043 (sizeof(TraceVarInfo) - sizeof(tvarPtr->command)
3044 + length + 1));
3045 tvarPtr->flags = flags;
3046 tvarPtr->length = length;
3047 flags |= TCL_TRACE_UNSETS | TCL_TRACE_RESULT_OBJECT;
3048 strcpy(tvarPtr->command, command);
3049 name = Tcl_GetString(objv[2]);
3050 if (Tcl_TraceVar(interp, name, flags, TraceVarProc,
3051 (ClientData) tvarPtr) != TCL_OK) {
3052 ckfree((char *) tvarPtr);
3053 return TCL_ERROR;
3054 }
3055 break;
3056 }
3057 case TRACE_OLD_VDELETE: {
3058 int flags;
3059 TraceVarInfo *tvarPtr;
3060 ClientData clientData;
3061
3062 if (objc != 5) {
3063 Tcl_WrongNumArgs(interp, 2, objv, "name ops command");
3064 return TCL_ERROR;
3065 }
3066
3067 flags = 0;
3068 flagOps = Tcl_GetString(objv[3]);
3069 for (p = flagOps; *p != 0; p++) {
3070 if (*p == 'r') {
3071 flags |= TCL_TRACE_READS;
3072 } else if (*p == 'w') {
3073 flags |= TCL_TRACE_WRITES;
3074 } else if (*p == 'u') {
3075 flags |= TCL_TRACE_UNSETS;
3076 } else if (*p == 'a') {
3077 flags |= TCL_TRACE_ARRAY;
3078 } else {
3079 goto badVarOps;
3080 }
3081 }
3082 if (flags == 0) {
3083 goto badVarOps;
3084 }
3085 flags |= TCL_TRACE_OLD_STYLE;
3086
3087 /*
3088 * Search through all of our traces on this variable to
3089 * see if there's one with the given command. If so, then
3090 * delete the first one that matches.
3091 */
3092
3093 command = Tcl_GetStringFromObj(objv[4], &commandLength);
3094 length = (size_t) commandLength;
3095 clientData = 0;
3096 name = Tcl_GetString(objv[2]);
3097 while ((clientData = Tcl_VarTraceInfo(interp, name, 0,
3098 TraceVarProc, clientData)) != 0) {
3099 tvarPtr = (TraceVarInfo *) clientData;
3100 if ((tvarPtr->length == length) && (tvarPtr->flags == flags)
3101 && (strncmp(command, tvarPtr->command,
3102 (size_t) length) == 0)) {
3103 Tcl_UntraceVar2(interp, name, NULL,
3104 flags | TCL_TRACE_UNSETS | TCL_TRACE_RESULT_OBJECT,
3105 TraceVarProc, clientData);
3106 Tcl_EventuallyFree((ClientData) tvarPtr, TCL_DYNAMIC);
3107 break;
3108 }
3109 }
3110 break;
3111 }
3112 case TRACE_OLD_VINFO: {
3113 ClientData clientData;
3114 char ops[5];
3115 Tcl_Obj *resultListPtr, *pairObjPtr, *elemObjPtr;
3116
3117 if (objc != 3) {
3118 Tcl_WrongNumArgs(interp, 2, objv, "name");
3119 return TCL_ERROR;
3120 }
3121 resultListPtr = Tcl_GetObjResult(interp);
3122 clientData = 0;
3123 name = Tcl_GetString(objv[2]);
3124 while ((clientData = Tcl_VarTraceInfo(interp, name, 0,
3125 TraceVarProc, clientData)) != 0) {
3126
3127 TraceVarInfo *tvarPtr = (TraceVarInfo *) clientData;
3128
3129 pairObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3130 p = ops;
3131 if (tvarPtr->flags & TCL_TRACE_READS) {
3132 *p = 'r';
3133 p++;
3134 }
3135 if (tvarPtr->flags & TCL_TRACE_WRITES) {
3136 *p = 'w';
3137 p++;
3138 }
3139 if (tvarPtr->flags & TCL_TRACE_UNSETS) {
3140 *p = 'u';
3141 p++;
3142 }
3143 if (tvarPtr->flags & TCL_TRACE_ARRAY) {
3144 *p = 'a';
3145 p++;
3146 }
3147 *p = '\0';
3148
3149 /*
3150 * Build a pair (2-item list) with the ops string as
3151 * the first obj element and the tvarPtr->command string
3152 * as the second obj element. Append the pair (as an
3153 * element) to the end of the result object list.
3154 */
3155
3156 elemObjPtr = Tcl_NewStringObj(ops, -1);
3157 Tcl_ListObjAppendElement(NULL, pairObjPtr, elemObjPtr);
3158 elemObjPtr = Tcl_NewStringObj(tvarPtr->command, -1);
3159 Tcl_ListObjAppendElement(NULL, pairObjPtr, elemObjPtr);
3160 Tcl_ListObjAppendElement(interp, resultListPtr, pairObjPtr);
3161 }
3162 Tcl_SetObjResult(interp, resultListPtr);
3163 break;
3164 }
3165 #endif /* TCL_REMOVE_OBSOLETE_TRACES */
3166 }
3167 return TCL_OK;
3168
3169 badVarOps:
3170 Tcl_AppendResult(interp, "bad operations \"", flagOps,
3171 "\": should be one or more of rwua", (char *) NULL);
3172 return TCL_ERROR;
3173 }
3174
3175
3176 /*
3177 *----------------------------------------------------------------------
3178 *
3179 * TclTraceExecutionObjCmd --
3180 *
3181 * Helper function for Tcl_TraceObjCmd; implements the
3182 * [trace {add|remove|info} execution ...] subcommands.
3183 * See the user documentation for details on what these do.
3184 *
3185 * Results:
3186 * Standard Tcl result.
3187 *
3188 * Side effects:
3189 * Depends on the operation (add, remove, or info) being performed;
3190 * may add or remove command traces on a command.
3191 *
3192 *----------------------------------------------------------------------
3193 */
3194
3195 int
3196 TclTraceExecutionObjCmd(interp, optionIndex, objc, objv)
3197 Tcl_Interp *interp; /* Current interpreter. */
3198 int optionIndex; /* Add, info or remove */
3199 int objc; /* Number of arguments. */
3200 Tcl_Obj *CONST objv[]; /* Argument objects. */
3201 {
3202 int commandLength, index;
3203 char *name, *command;
3204 size_t length;
3205 enum traceOptions { TRACE_ADD, TRACE_INFO, TRACE_REMOVE };
3206 static CONST char *opStrings[] = { "enter", "leave",
3207 "enterstep", "leavestep", (char *) NULL };
3208 enum operations { TRACE_EXEC_ENTER, TRACE_EXEC_LEAVE,
3209 TRACE_EXEC_ENTER_STEP, TRACE_EXEC_LEAVE_STEP };
3210
3211 switch ((enum traceOptions) optionIndex) {
3212 case TRACE_ADD:
3213 case TRACE_REMOVE: {
3214 int flags = 0;
3215 int i, listLen, result;
3216 Tcl_Obj **elemPtrs;
3217 if (objc != 6) {
3218 Tcl_WrongNumArgs(interp, 3, objv, "name opList command");
3219 return TCL_ERROR;
3220 }
3221 /*
3222 * Make sure the ops argument is a list object; get its length and
3223 * a pointer to its array of element pointers.
3224 */
3225
3226 result = Tcl_ListObjGetElements(interp, objv[4], &listLen,
3227 &elemPtrs);
3228 if (result != TCL_OK) {
3229 return result;
3230 }
3231 if (listLen == 0) {
3232 Tcl_SetResult(interp, "bad operation list \"\": must be "
3233 "one or more of enter, leave, enterstep, or leavestep",
3234 TCL_STATIC);
3235 return TCL_ERROR;
3236 }
3237 for (i = 0; i < listLen; i++) {
3238 if (Tcl_GetIndexFromObj(interp, elemPtrs[i], opStrings,
3239 "operation", TCL_EXACT, &index) != TCL_OK) {
3240 return TCL_ERROR;
3241 }
3242 switch ((enum operations) index) {
3243 case TRACE_EXEC_ENTER:
3244 flags |= TCL_TRACE_ENTER_EXEC;
3245 break;
3246 case TRACE_EXEC_LEAVE:
3247 flags |= TCL_TRACE_LEAVE_EXEC;
3248 break;
3249 case TRACE_EXEC_ENTER_STEP:
3250 flags |= TCL_TRACE_ENTER_DURING_EXEC;
3251 break;
3252 case TRACE_EXEC_LEAVE_STEP:
3253 flags |= TCL_TRACE_LEAVE_DURING_EXEC;
3254 break;
3255 }
3256 }
3257 command = Tcl_GetStringFromObj(objv[5], &commandLength);
3258 length = (size_t) commandLength;
3259 if ((enum traceOptions) optionIndex == TRACE_ADD) {
3260 TraceCommandInfo *tcmdPtr;
3261 tcmdPtr = (TraceCommandInfo *) ckalloc((unsigned)
3262 (sizeof(TraceCommandInfo) - sizeof(tcmdPtr->command)
3263 + length + 1));
3264 tcmdPtr->flags = flags;
3265 tcmdPtr->stepTrace = NULL;
3266 tcmdPtr->startLevel = 0;
3267 tcmdPtr->startCmd = NULL;
3268 tcmdPtr->length = length;
3269 tcmdPtr->refCount = 1;
3270 flags |= TCL_TRACE_DELETE;
3271 if (flags & (TCL_TRACE_ENTER_DURING_EXEC |
3272 TCL_TRACE_LEAVE_DURING_EXEC)) {
3273 flags |= (TCL_TRACE_ENTER_EXEC |
3274 TCL_TRACE_LEAVE_EXEC);
3275 }
3276 strcpy(tcmdPtr->command, command);
3277 name = Tcl_GetString(objv[3]);
3278 if (Tcl_TraceCommand(interp, name, flags, TraceCommandProc,
3279 (ClientData) tcmdPtr) != TCL_OK) {
3280 ckfree((char *) tcmdPtr);
3281 return TCL_ERROR;
3282 }
3283 } else {
3284 /*
3285 * Search through all of our traces on this command to
3286 * see if there's one with the given command. If so, then
3287 * delete the first one that matches.
3288 */
3289
3290 TraceCommandInfo *tcmdPtr;
3291 ClientData clientData = NULL;
3292 name = Tcl_GetString(objv[3]);
3293
3294 /* First ensure the name given is valid */
3295 if (Tcl_FindCommand(interp, name, NULL,
3296 TCL_LEAVE_ERR_MSG) == NULL) {
3297 return TCL_ERROR;
3298 }
3299
3300 while ((clientData = Tcl_CommandTraceInfo(interp, name, 0,
3301 TraceCommandProc, clientData)) != NULL) {
3302 tcmdPtr = (TraceCommandInfo *) clientData;
3303 /*
3304 * In checking the 'flags' field we must remove any
3305 * extraneous flags which may have been temporarily
3306 * added by various pieces of the trace mechanism.
3307 */
3308 if ((tcmdPtr->length == length)
3309 && ((tcmdPtr->flags & (TCL_TRACE_ANY_EXEC |
3310 TCL_TRACE_RENAME |
3311 TCL_TRACE_DELETE)) == flags)
3312 && (strncmp(command, tcmdPtr->command,
3313 (size_t) length) == 0)) {
3314 flags |= TCL_TRACE_DELETE;
3315 if (flags & (TCL_TRACE_ENTER_DURING_EXEC |
3316 TCL_TRACE_LEAVE_DURING_EXEC)) {
3317 flags |= (TCL_TRACE_ENTER_EXEC |
3318 TCL_TRACE_LEAVE_EXEC);
3319 }
3320 Tcl_UntraceCommand(interp, name,
3321 flags, TraceCommandProc, clientData);
3322 if (tcmdPtr->stepTrace != NULL) {
3323 /*
3324 * We need to remove the interpreter-wide trace
3325 * which we created to allow 'step' traces.
3326 */
3327 Tcl_DeleteTrace(interp, tcmdPtr->stepTrace);
3328 tcmdPtr->stepTrace = NULL;
3329 if (tcmdPtr->startCmd != NULL) {
3330 ckfree((char *)tcmdPtr->startCmd);
3331 }
3332 }
3333 if (tcmdPtr->flags & TCL_TRACE_EXEC_IN_PROGRESS) {
3334 /* Postpone deletion */
3335 tcmdPtr->flags = 0;
3336 }
3337 tcmdPtr->refCount--;
3338 if (tcmdPtr->refCount < 0) {
3339 Tcl_Panic("TclTraceExecutionObjCmd: negative TraceCommandInfo refCount");
3340 }
3341 if (tcmdPtr->refCount == 0) {
3342 ckfree((char*)tcmdPtr);
3343 }
3344 break;
3345 }
3346 }
3347 }
3348 break;
3349 }
3350 case TRACE_INFO: {
3351 ClientData clientData;
3352 Tcl_Obj *resultListPtr, *eachTraceObjPtr, *elemObjPtr;
3353 if (objc != 4) {
3354 Tcl_WrongNumArgs(interp, 3, objv, "name");
3355 return TCL_ERROR;
3356 }
3357
3358 clientData = NULL;
3359 name = Tcl_GetString(objv[3]);
3360
3361 /* First ensure the name given is valid */
3362 if (Tcl_FindCommand(interp, name, NULL,
3363 TCL_LEAVE_ERR_MSG) == NULL) {
3364 return TCL_ERROR;
3365 }
3366
3367 resultListPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3368 while ((clientData = Tcl_CommandTraceInfo(interp, name, 0,
3369 TraceCommandProc, clientData)) != NULL) {
3370 int numOps = 0;
3371
3372 TraceCommandInfo *tcmdPtr = (TraceCommandInfo *) clientData;
3373
3374 eachTraceObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3375
3376 /*
3377 * Build a list with the ops list as the first obj
3378 * element and the tcmdPtr->command string as the
3379 * second obj element. Append this list (as an
3380 * element) to the end of the result object list.
3381 */
3382
3383 elemObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3384 Tcl_IncrRefCount(elemObjPtr);
3385 if (tcmdPtr->flags & TCL_TRACE_ENTER_EXEC) {
3386 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3387 Tcl_NewStringObj("enter",5));
3388 }
3389 if (tcmdPtr->flags & TCL_TRACE_LEAVE_EXEC) {
3390 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3391 Tcl_NewStringObj("leave",5));
3392 }
3393 if (tcmdPtr->flags & TCL_TRACE_ENTER_DURING_EXEC) {
3394 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3395 Tcl_NewStringObj("enterstep",9));
3396 }
3397 if (tcmdPtr->flags & TCL_TRACE_LEAVE_DURING_EXEC) {
3398 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3399 Tcl_NewStringObj("leavestep",9));
3400 }
3401 Tcl_ListObjLength(NULL, elemObjPtr, &numOps);
3402 if (0 == numOps) {
3403 Tcl_DecrRefCount(elemObjPtr);
3404 continue;
3405 }
3406 Tcl_ListObjAppendElement(NULL, eachTraceObjPtr, elemObjPtr);
3407 Tcl_DecrRefCount(elemObjPtr);
3408 elemObjPtr = NULL;
3409
3410 Tcl_ListObjAppendElement(NULL, eachTraceObjPtr,
3411 Tcl_NewStringObj(tcmdPtr->command, -1));
3412 Tcl_ListObjAppendElement(interp, resultListPtr,
3413 eachTraceObjPtr);
3414 }
3415 Tcl_SetObjResult(interp, resultListPtr);
3416 break;
3417 }
3418 }
3419 return TCL_OK;
3420 }
3421
3422
3423 /*
3424 *----------------------------------------------------------------------
3425 *
3426 * TclTraceCommandObjCmd --
3427 *
3428 * Helper function for Tcl_TraceObjCmd; implements the
3429 * [trace {add|info|remove} command ...] subcommands.
3430 * See the user documentation for details on what these do.
3431 *
3432 * Results:
3433 * Standard Tcl result.
3434 *
3435 * Side effects:
3436 * Depends on the operation (add, remove, or info) being performed;
3437 * may add or remove command traces on a command.
3438 *
3439 *----------------------------------------------------------------------
3440 */
3441
3442 int
3443 TclTraceCommandObjCmd(interp, optionIndex, objc, objv)
3444 Tcl_Interp *interp; /* Current interpreter. */
3445 int optionIndex; /* Add, info or remove */
3446 int objc; /* Number of arguments. */
3447 Tcl_Obj *CONST objv[]; /* Argument objects. */
3448 {
3449 int commandLength, index;
3450 char *name, *command;
3451 size_t length;
3452 enum traceOptions { TRACE_ADD, TRACE_INFO, TRACE_REMOVE };
3453 static CONST char *opStrings[] = { "delete", "rename", (char *) NULL };
3454 enum operations { TRACE_CMD_DELETE, TRACE_CMD_RENAME };
3455
3456 switch ((enum traceOptions) optionIndex) {
3457 case TRACE_ADD:
3458 case TRACE_REMOVE: {
3459 int flags = 0;
3460 int i, listLen, result;
3461 Tcl_Obj **elemPtrs;
3462 if (objc != 6) {
3463 Tcl_WrongNumArgs(interp, 3, objv, "name opList command");
3464 return TCL_ERROR;
3465 }
3466 /*
3467 * Make sure the ops argument is a list object; get its length and
3468 * a pointer to its array of element pointers.
3469 */
3470
3471 result = Tcl_ListObjGetElements(interp, objv[4], &listLen,
3472 &elemPtrs);
3473 if (result != TCL_OK) {
3474 return result;
3475 }
3476 if (listLen == 0) {
3477 Tcl_SetResult(interp, "bad operation list \"\": must be "
3478 "one or more of delete or rename", TCL_STATIC);
3479 return TCL_ERROR;
3480 }
3481 for (i = 0; i < listLen; i++) {
3482 if (Tcl_GetIndexFromObj(interp, elemPtrs[i], opStrings,
3483 "operation", TCL_EXACT, &index) != TCL_OK) {
3484 return TCL_ERROR;
3485 }
3486 switch ((enum operations) index) {
3487 case TRACE_CMD_RENAME:
3488 flags |= TCL_TRACE_RENAME;
3489 break;
3490 case TRACE_CMD_DELETE:
3491 flags |= TCL_TRACE_DELETE;
3492 break;
3493 }
3494 }
3495 command = Tcl_GetStringFromObj(objv[5], &commandLength);
3496 length = (size_t) commandLength;
3497 if ((enum traceOptions) optionIndex == TRACE_ADD) {
3498 TraceCommandInfo *tcmdPtr;
3499 tcmdPtr = (TraceCommandInfo *) ckalloc((unsigned)
3500 (sizeof(TraceCommandInfo) - sizeof(tcmdPtr->command)
3501 + length + 1));
3502 tcmdPtr->flags = flags;
3503 tcmdPtr->stepTrace = NULL;
3504 tcmdPtr->startLevel = 0;
3505 tcmdPtr->startCmd = NULL;
3506 tcmdPtr->length = length;
3507 tcmdPtr->refCount = 1;
3508 flags |= TCL_TRACE_DELETE;
3509 strcpy(tcmdPtr->command, command);
3510 name = Tcl_GetString(objv[3]);
3511 if (Tcl_TraceCommand(interp, name, flags, TraceCommandProc,
3512 (ClientData) tcmdPtr) != TCL_OK) {
3513 ckfree((char *) tcmdPtr);
3514 return TCL_ERROR;
3515 }
3516 } else {
3517 /*
3518 * Search through all of our traces on this command to
3519 * see if there's one with the given command. If so, then
3520 * delete the first one that matches.
3521 */
3522
3523 TraceCommandInfo *tcmdPtr;
3524 ClientData clientData = NULL;
3525 name = Tcl_GetString(objv[3]);
3526
3527 /* First ensure the name given is valid */
3528 if (Tcl_FindCommand(interp, name, NULL,
3529 TCL_LEAVE_ERR_MSG) == NULL) {
3530 return TCL_ERROR;
3531 }
3532
3533 while ((clientData = Tcl_CommandTraceInfo(interp, name, 0,
3534 TraceCommandProc, clientData)) != NULL) {
3535 tcmdPtr = (TraceCommandInfo *) clientData;
3536 if ((tcmdPtr->length == length)
3537 && (tcmdPtr->flags == flags)
3538 && (strncmp(command, tcmdPtr->command,
3539 (size_t) length) == 0)) {
3540 Tcl_UntraceCommand(interp, name,
3541 flags | TCL_TRACE_DELETE,
3542 TraceCommandProc, clientData);
3543 tcmdPtr->flags |= TCL_TRACE_DESTROYED;
3544 tcmdPtr->refCount--;
3545 if (tcmdPtr->refCount < 0) {
3546 Tcl_Panic("TclTraceCommandObjCmd: negative TraceCommandInfo refCount");
3547 }
3548 if (tcmdPtr->refCount == 0) {
3549 ckfree((char *) tcmdPtr);
3550 }
3551 break;
3552 }
3553 }
3554 }
3555 break;
3556 }
3557 case TRACE_INFO: {
3558 ClientData clientData;
3559 Tcl_Obj *resultListPtr, *eachTraceObjPtr, *elemObjPtr;
3560 if (objc != 4) {
3561 Tcl_WrongNumArgs(interp, 3, objv, "name");
3562 return TCL_ERROR;
3563 }
3564
3565 clientData = NULL;
3566 name = Tcl_GetString(objv[3]);
3567
3568 /* First ensure the name given is valid */
3569 if (Tcl_FindCommand(interp, name, NULL,
3570 TCL_LEAVE_ERR_MSG) == NULL) {
3571 return TCL_ERROR;
3572 }
3573
3574 resultListPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3575 while ((clientData = Tcl_CommandTraceInfo(interp, name, 0,
3576 TraceCommandProc, clientData)) != NULL) {
3577 int numOps = 0;
3578
3579 TraceCommandInfo *tcmdPtr = (TraceCommandInfo *) clientData;
3580
3581 eachTraceObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3582
3583 /*
3584 * Build a list with the ops list as
3585 * the first obj element and the tcmdPtr->command string
3586 * as the second obj element. Append this list (as an
3587 * element) to the end of the result object list.
3588 */
3589
3590 elemObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3591 Tcl_IncrRefCount(elemObjPtr);
3592 if (tcmdPtr->flags & TCL_TRACE_RENAME) {
3593 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3594 Tcl_NewStringObj("rename",6));
3595 }
3596 if (tcmdPtr->flags & TCL_TRACE_DELETE) {
3597 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3598 Tcl_NewStringObj("delete",6));
3599 }
3600 Tcl_ListObjLength(NULL, elemObjPtr, &numOps);
3601 if (0 == numOps) {
3602 Tcl_DecrRefCount(elemObjPtr);
3603 continue;
3604 }
3605 Tcl_ListObjAppendElement(NULL, eachTraceObjPtr, elemObjPtr);
3606 Tcl_DecrRefCount(elemObjPtr);
3607
3608 elemObjPtr = Tcl_NewStringObj(tcmdPtr->command, -1);
3609 Tcl_ListObjAppendElement(NULL, eachTraceObjPtr, elemObjPtr);
3610 Tcl_ListObjAppendElement(interp, resultListPtr,
3611 eachTraceObjPtr);
3612 }
3613 Tcl_SetObjResult(interp, resultListPtr);
3614 break;
3615 }
3616 }
3617 return TCL_OK;
3618 }
3619
3620
3621 /*
3622 *----------------------------------------------------------------------
3623 *
3624 * TclTraceVariableObjCmd --
3625 *
3626 * Helper function for Tcl_TraceObjCmd; implements the
3627 * [trace {add|info|remove} variable ...] subcommands.
3628 * See the user documentation for details on what these do.
3629 *
3630 * Results:
3631 * Standard Tcl result.
3632 *
3633 * Side effects:
3634 * Depends on the operation (add, remove, or info) being performed;
3635 * may add or remove variable traces on a variable.
3636 *
3637 *----------------------------------------------------------------------
3638 */
3639
3640 int
3641 TclTraceVariableObjCmd(interp, optionIndex, objc, objv)
3642 Tcl_Interp *interp; /* Current interpreter. */
3643 int optionIndex; /* Add, info or remove */
3644 int objc; /* Number of arguments. */
3645 Tcl_Obj *CONST objv[]; /* Argument objects. */
3646 {
3647 int commandLength, index;
3648 char *name, *command;
3649 size_t length;
3650 enum traceOptions { TRACE_ADD, TRACE_INFO, TRACE_REMOVE };
3651 static CONST char *opStrings[] = { "array", "read", "unset", "write",
3652 (char *) NULL };
3653 enum operations { TRACE_VAR_ARRAY, TRACE_VAR_READ, TRACE_VAR_UNSET,
3654 TRACE_VAR_WRITE };
3655
3656 switch ((enum traceOptions) optionIndex) {
3657 case TRACE_ADD:
3658 case TRACE_REMOVE: {
3659 int flags = 0;
3660 int i, listLen, result;
3661 Tcl_Obj **elemPtrs;
3662 if (objc != 6) {
3663 Tcl_WrongNumArgs(interp, 3, objv, "name opList command");
3664 return TCL_ERROR;
3665 }
3666 /*
3667 * Make sure the ops argument is a list object; get its length and
3668 * a pointer to its array of element pointers.
3669 */
3670
3671 result = Tcl_ListObjGetElements(interp, objv[4], &listLen,
3672 &elemPtrs);
3673 if (result != TCL_OK) {
3674 return result;
3675 }
3676 if (listLen == 0) {
3677 Tcl_SetResult(interp, "bad operation list \"\": must be "
3678 "one or more of array, read, unset, or write",
3679 TCL_STATIC);
3680 return TCL_ERROR;
3681 }
3682 for (i = 0; i < listLen ; i++) {
3683 if (Tcl_GetIndexFromObj(interp, elemPtrs[i], opStrings,
3684 "operation", TCL_EXACT, &index) != TCL_OK) {
3685 return TCL_ERROR;
3686 }
3687 switch ((enum operations) index) {
3688 case TRACE_VAR_ARRAY:
3689 flags |= TCL_TRACE_ARRAY;
3690 break;
3691 case TRACE_VAR_READ:
3692 flags |= TCL_TRACE_READS;
3693 break;
3694 case TRACE_VAR_UNSET:
3695 flags |= TCL_TRACE_UNSETS;
3696 break;
3697 case TRACE_VAR_WRITE:
3698 flags |= TCL_TRACE_WRITES;
3699 break;
3700 }
3701 }
3702 command = Tcl_GetStringFromObj(objv[5], &commandLength);
3703 length = (size_t) commandLength;
3704 if ((enum traceOptions) optionIndex == TRACE_ADD) {
3705 TraceVarInfo *tvarPtr;
3706 tvarPtr = (TraceVarInfo *) ckalloc((unsigned)
3707 (sizeof(TraceVarInfo) - sizeof(tvarPtr->command)
3708 + length + 1));
3709 tvarPtr->flags = flags;
3710 tvarPtr->length = length;
3711 flags |= TCL_TRACE_UNSETS | TCL_TRACE_RESULT_OBJECT;
3712 strcpy(tvarPtr->command, command);
3713 name = Tcl_GetString(objv[3]);
3714 if (Tcl_TraceVar(interp, name, flags, TraceVarProc,
3715 (ClientData) tvarPtr) != TCL_OK) {
3716 ckfree((char *) tvarPtr);
3717 return TCL_ERROR;
3718 }
3719 } else {
3720 /*
3721 * Search through all of our traces on this variable to
3722 * see if there's one with the given command. If so, then
3723 * delete the first one that matches.
3724 */
3725
3726 TraceVarInfo *tvarPtr;
3727 ClientData clientData = 0;
3728 name = Tcl_GetString(objv[3]);
3729 while ((clientData = Tcl_VarTraceInfo(interp, name, 0,
3730 TraceVarProc, clientData)) != 0) {
3731 tvarPtr = (TraceVarInfo *) clientData;
3732 if ((tvarPtr->length == length)
3733 && (tvarPtr->flags == flags)
3734 && (strncmp(command, tvarPtr->command,
3735 (size_t) length) == 0)) {
3736 Tcl_UntraceVar2(interp, name, NULL,
3737 flags | TCL_TRACE_UNSETS | TCL_TRACE_RESULT_OBJECT,
3738 TraceVarProc, clientData);
3739 Tcl_EventuallyFree((ClientData) tvarPtr, TCL_DYNAMIC);
3740 break;
3741 }
3742 }
3743 }
3744 break;
3745 }
3746 case TRACE_INFO: {
3747 ClientData clientData;
3748 Tcl_Obj *resultListPtr, *eachTraceObjPtr, *elemObjPtr;
3749 if (objc != 4) {
3750 Tcl_WrongNumArgs(interp, 3, objv, "name");
3751 return TCL_ERROR;
3752 }
3753
3754 resultListPtr = Tcl_GetObjResult(interp);
3755 clientData = 0;
3756 name = Tcl_GetString(objv[3]);
3757 while ((clientData = Tcl_VarTraceInfo(interp, name, 0,
3758 TraceVarProc, clientData)) != 0) {
3759
3760 TraceVarInfo *tvarPtr = (TraceVarInfo *) clientData;
3761
3762 eachTraceObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3763 /*
3764 * Build a list with the ops list as
3765 * the first obj element and the tcmdPtr->command string
3766 * as the second obj element. Append this list (as an
3767 * element) to the end of the result object list.
3768 */
3769
3770 elemObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
3771 if (tvarPtr->flags & TCL_TRACE_ARRAY) {
3772 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3773 Tcl_NewStringObj("array", 5));
3774 }
3775 if (tvarPtr->flags & TCL_TRACE_READS) {
3776 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3777 Tcl_NewStringObj("read", 4));
3778 }
3779 if (tvarPtr->flags & TCL_TRACE_WRITES) {
3780 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3781 Tcl_NewStringObj("write", 5));
3782 }
3783 if (tvarPtr->flags & TCL_TRACE_UNSETS) {
3784 Tcl_ListObjAppendElement(NULL, elemObjPtr,
3785 Tcl_NewStringObj("unset", 5));
3786 }
3787 Tcl_ListObjAppendElement(NULL, eachTraceObjPtr, elemObjPtr);
3788
3789 elemObjPtr = Tcl_NewStringObj(tvarPtr->command, -1);
3790 Tcl_ListObjAppendElement(NULL, eachTraceObjPtr, elemObjPtr);
3791 Tcl_ListObjAppendElement(interp, resultListPtr,
3792 eachTraceObjPtr);
3793 }
3794 Tcl_SetObjResult(interp, resultListPtr);
3795 break;
3796 }
3797 }
3798 return TCL_OK;
3799 }
3800
3801
3802 /*
3803 *----------------------------------------------------------------------
3804 *
3805 * Tcl_CommandTraceInfo --
3806 *
3807 * Return the clientData value associated with a trace on a
3808 * command. This procedure can also be used to step through
3809 * all of the traces on a particular command that have the
3810 * same trace procedure.
3811 *
3812 * Results:
3813 * The return value is the clientData value associated with
3814 * a trace on the given command. Information will only be
3815 * returned for a trace with proc as trace procedure. If
3816 * the clientData argument is NULL then the first such trace is
3817 * returned; otherwise, the next relevant one after the one
3818 * given by clientData will be returned. If the command
3819 * doesn't exist then an error message is left in the interpreter
3820 * and NULL is returned. Also, if there are no (more) traces for
3821 * the given command, NULL is returned.
3822 *
3823 * Side effects:
3824 * None.
3825 *
3826 *----------------------------------------------------------------------
3827 */
3828
3829 ClientData
3830 Tcl_CommandTraceInfo(interp, cmdName, flags, proc, prevClientData)
3831 Tcl_Interp *interp; /* Interpreter containing command. */
3832 CONST char *cmdName; /* Name of command. */
3833 int flags; /* OR-ed combo or TCL_GLOBAL_ONLY,
3834 * TCL_NAMESPACE_ONLY (can be 0). */
3835 Tcl_CommandTraceProc *proc; /* Procedure assocated with trace. */
3836 ClientData prevClientData; /* If non-NULL, gives last value returned
3837 * by this procedure, so this call will
3838 * return the next trace after that one.
3839 * If NULL, this call will return the
3840 * first trace. */
3841 {
3842 Command *cmdPtr;
3843 register CommandTrace *tracePtr;
3844
3845 cmdPtr = (Command*)Tcl_FindCommand(interp, cmdName,
3846 NULL, TCL_LEAVE_ERR_MSG);
3847 if (cmdPtr == NULL) {
3848 return NULL;
3849 }
3850
3851 /*
3852 * Find the relevant trace, if any, and return its clientData.
3853 */
3854
3855 tracePtr = cmdPtr->tracePtr;
3856 if (prevClientData != NULL) {
3857 for ( ; tracePtr != NULL; tracePtr = tracePtr->nextPtr) {
3858 if ((tracePtr->clientData == prevClientData)
3859 && (tracePtr->traceProc == proc)) {
3860 tracePtr = tracePtr->nextPtr;
3861 break;
3862 }
3863 }
3864 }
3865 for ( ; tracePtr != NULL; tracePtr = tracePtr->nextPtr) {
3866 if (tracePtr->traceProc == proc) {
3867 return tracePtr->clientData;
3868 }
3869 }
3870 return NULL;
3871 }
3872
3873 /*
3874 *----------------------------------------------------------------------
3875 *
3876 * Tcl_TraceCommand --
3877 *
3878 * Arrange for rename/deletes to a command to cause a
3879 * procedure to be invoked, which can monitor the operations.
3880 *
3881 * Also optionally arrange for execution of that command
3882 * to cause a procedure to be invoked.
3883 *
3884 * Results:
3885 * A standard Tcl return value.
3886 *
3887 * Side effects:
3888 * A trace is set up on the command given by cmdName, such that
3889 * future changes to the command will be intermediated by
3890 * proc. See the manual entry for complete details on the calling
3891 * sequence for proc.
3892 *
3893 *----------------------------------------------------------------------
3894 */
3895
3896 int
3897 Tcl_TraceCommand(interp, cmdName, flags, proc, clientData)
3898 Tcl_Interp *interp; /* Interpreter in which command is
3899 * to be traced. */
3900 CONST char *cmdName; /* Name of command. */
3901 int flags; /* OR-ed collection of bits, including any
3902 * of TCL_TRACE_RENAME, TCL_TRACE_DELETE,
3903 * and any of the TRACE_*_EXEC flags */
3904 Tcl_CommandTraceProc *proc; /* Procedure to call when specified ops are
3905 * invoked upon varName. */
3906 ClientData clientData; /* Arbitrary argument to pass to proc. */
3907 {
3908 Command *cmdPtr;
3909 register CommandTrace *tracePtr;
3910
3911 cmdPtr = (Command*)Tcl_FindCommand(interp, cmdName,
3912 NULL, TCL_LEAVE_ERR_MSG);
3913 if (cmdPtr == NULL) {
3914 return TCL_ERROR;
3915 }
3916
3917 /*
3918 * Set up trace information.
3919 */
3920
3921 tracePtr = (CommandTrace *) ckalloc(sizeof(CommandTrace));
3922 tracePtr->traceProc = proc;
3923 tracePtr->clientData = clientData;
3924 tracePtr->flags = flags & (TCL_TRACE_RENAME | TCL_TRACE_DELETE
3925 | TCL_TRACE_ANY_EXEC);
3926 tracePtr->nextPtr = cmdPtr->tracePtr;
3927 tracePtr->refCount = 1;
3928 cmdPtr->tracePtr = tracePtr;
3929 if (tracePtr->flags & TCL_TRACE_ANY_EXEC) {
3930 cmdPtr->flags |= CMD_HAS_EXEC_TRACES;
3931 }
3932 return TCL_OK;
3933 }
3934
3935 /*
3936 *----------------------------------------------------------------------
3937 *
3938 * Tcl_UntraceCommand --
3939 *
3940 * Remove a previously-created trace for a command.
3941 *
3942 * Results:
3943 * None.
3944 *
3945 * Side effects:
3946 * If there exists a trace for the command given by cmdName
3947 * with the given flags, proc, and clientData, then that trace
3948 * is removed.
3949 *
3950 *----------------------------------------------------------------------
3951 */
3952
3953 void
3954 Tcl_UntraceCommand(interp, cmdName, flags, proc, clientData)
3955 Tcl_Interp *interp; /* Interpreter containing command. */
3956 CONST char *cmdName; /* Name of command. */
3957 int flags; /* OR-ed collection of bits, including any
3958 * of TCL_TRACE_RENAME, TCL_TRACE_DELETE,
3959 * and any of the TRACE_*_EXEC flags */
3960 Tcl_CommandTraceProc *proc; /* Procedure assocated with trace. */
3961 ClientData clientData; /* Arbitrary argument to pass to proc. */
3962 {
3963 register CommandTrace *tracePtr;
3964 CommandTrace *prevPtr;
3965 Command *cmdPtr;
3966 Interp *iPtr = (Interp *) interp;
3967 ActiveCommandTrace *activePtr;
3968 int hasExecTraces = 0;
3969
3970 cmdPtr = (Command*)Tcl_FindCommand(interp, cmdName,
3971 NULL, TCL_LEAVE_ERR_MSG);
3972 if (cmdPtr == NULL) {
3973 return;
3974 }
3975
3976 flags &= (TCL_TRACE_RENAME | TCL_TRACE_DELETE | TCL_TRACE_ANY_EXEC);
3977
3978 for (tracePtr = cmdPtr->tracePtr, prevPtr = NULL; ;
3979 prevPtr = tracePtr, tracePtr = tracePtr->nextPtr) {
3980 if (tracePtr == NULL) {
3981 return;
3982 }
3983 if ((tracePtr->traceProc == proc)
3984 && ((tracePtr->flags & (TCL_TRACE_RENAME | TCL_TRACE_DELETE |
3985 TCL_TRACE_ANY_EXEC)) == flags)
3986 && (tracePtr->clientData == clientData)) {
3987 if (tracePtr->flags & TCL_TRACE_ANY_EXEC) {
3988 hasExecTraces = 1;
3989 }
3990 break;
3991 }
3992 }
3993
3994 /*
3995 * The code below makes it possible to delete traces while traces
3996 * are active: it makes sure that the deleted trace won't be
3997 * processed by CallCommandTraces.
3998 */
3999
4000 for (activePtr = iPtr->activeCmdTracePtr; activePtr != NULL;
4001 activePtr = activePtr->nextPtr) {
4002 if (activePtr->nextTracePtr == tracePtr) {
4003 activePtr->nextTracePtr = tracePtr->nextPtr;
4004 }
4005 }
4006 if (prevPtr == NULL) {
4007 cmdPtr->tracePtr = tracePtr->nextPtr;
4008 } else {
4009 prevPtr->nextPtr = tracePtr->nextPtr;
4010 }
4011 tracePtr->flags = 0;
4012
4013 if ((--tracePtr->refCount) <= 0) {
4014 ckfree((char*)tracePtr);
4015 }
4016
4017 if (hasExecTraces) {
4018 for (tracePtr = cmdPtr->tracePtr, prevPtr = NULL; tracePtr != NULL ;
4019 prevPtr = tracePtr, tracePtr = tracePtr->nextPtr) {
4020 if (tracePtr->flags & TCL_TRACE_ANY_EXEC) {
4021 return;
4022 }
4023 }
4024 /*
4025 * None of the remaining traces on this command are execution
4026 * traces. We therefore remove this flag:
4027 */
4028 cmdPtr->flags &= ~CMD_HAS_EXEC_TRACES;
4029 }
4030 }
4031
4032 /*
4033 *----------------------------------------------------------------------
4034 *
4035 * TraceCommandProc --
4036 *
4037 * This procedure is called to handle command changes that have
4038 * been traced using the "trace" command, when using the
4039 * 'rename' or 'delete' options.
4040 *
4041 * Results:
4042 * None.
4043 *
4044 * Side effects:
4045 * Depends on the command associated with the trace.
4046 *
4047 *----------------------------------------------------------------------
4048 */
4049
4050 /* ARGSUSED */
4051 static void
4052 TraceCommandProc(clientData, interp, oldName, newName, flags)
4053 ClientData clientData; /* Information about the command trace. */
4054 Tcl_Interp *interp; /* Interpreter containing command. */
4055 CONST char *oldName; /* Name of command being changed. */
4056 CONST char *newName; /* New name of command. Empty string
4057 * or NULL means command is being deleted
4058 * (renamed to ""). */
4059 int flags; /* OR-ed bits giving operation and other
4060 * information. */
4061 {
4062 Interp *iPtr = (Interp *) interp;
4063 int stateCode;
4064 Tcl_SavedResult state;
4065 TraceCommandInfo *tcmdPtr = (TraceCommandInfo *) clientData;
4066 int code;
4067 Tcl_DString cmd;
4068
4069 tcmdPtr->refCount++;
4070
4071 if ((tcmdPtr->flags & flags) && !(flags & TCL_INTERP_DESTROYED)) {
4072 /*
4073 * Generate a command to execute by appending list elements
4074 * for the old and new command name and the operation.
4075 */
4076
4077 Tcl_DStringInit(&cmd);
4078 Tcl_DStringAppend(&cmd, tcmdPtr->command, (int) tcmdPtr->length);
4079 Tcl_DStringAppendElement(&cmd, oldName);
4080 Tcl_DStringAppendElement(&cmd, (newName ? newName : ""));
4081 if (flags & TCL_TRACE_RENAME) {
4082 Tcl_DStringAppend(&cmd, " rename", 7);
4083 } else if (flags & TCL_TRACE_DELETE) {
4084 Tcl_DStringAppend(&cmd, " delete", 7);
4085 }
4086
4087 /*
4088 * Execute the command. Save the interp's result used for the
4089 * command, including the value of iPtr->returnCode which may be
4090 * modified when Tcl_Eval is invoked. We discard any object
4091 * result the command returns.
4092 *
4093 * Add the TCL_TRACE_DESTROYED flag to tcmdPtr to indicate to
4094 * other areas that this will be destroyed by us, otherwise a
4095 * double-free might occur depending on what the eval does.
4096 */
4097
4098 Tcl_SaveResult(interp, &state);
4099 stateCode = iPtr->returnCode;
4100 if (flags & TCL_TRACE_DESTROYED) {
4101 tcmdPtr->flags |= TCL_TRACE_DESTROYED;
4102 }
4103
4104 code = Tcl_EvalEx(interp, Tcl_DStringValue(&cmd),
4105 Tcl_DStringLength(&cmd), 0);
4106 if (code != TCL_OK) {
4107 /* We ignore errors in these traced commands */
4108 }
4109
4110 Tcl_RestoreResult(interp, &state);
4111 iPtr->returnCode = stateCode;
4112
4113 Tcl_DStringFree(&cmd);
4114 }
4115 /*
4116 * We delete when the trace was destroyed or if this is a delete trace,
4117 * because command deletes are unconditional, so the trace must go away.
4118 */
4119 if (flags & (TCL_TRACE_DESTROYED | TCL_TRACE_DELETE)) {
4120 int untraceFlags = tcmdPtr->flags;
4121
4122 if (tcmdPtr->stepTrace != NULL) {
4123 Tcl_DeleteTrace(interp, tcmdPtr->stepTrace);
4124 tcmdPtr->stepTrace = NULL;
4125 if (tcmdPtr->startCmd != NULL) {
4126 ckfree((char *)tcmdPtr->startCmd);
4127 }
4128 }
4129 if (tcmdPtr->flags & TCL_TRACE_EXEC_IN_PROGRESS) {
4130 /* Postpone deletion, until exec trace returns */
4131 tcmdPtr->flags = 0;
4132 }
4133
4134 /*
4135 * We need to construct the same flags for Tcl_UntraceCommand
4136 * as were passed to Tcl_TraceCommand. Reproduce the processing
4137 * of [trace add execution/command]. Be careful to keep this
4138 * code in sync with that.
4139 */
4140
4141 if (untraceFlags & TCL_TRACE_ANY_EXEC) {
4142 untraceFlags |= TCL_TRACE_DELETE;
4143 if (untraceFlags & (TCL_TRACE_ENTER_DURING_EXEC
4144 | TCL_TRACE_LEAVE_DURING_EXEC)) {
4145 untraceFlags |= (TCL_TRACE_ENTER_EXEC | TCL_TRACE_LEAVE_EXEC);
4146 }
4147 } else if (untraceFlags & TCL_TRACE_RENAME) {
4148 untraceFlags |= TCL_TRACE_DELETE;
4149 }
4150
4151 /*
4152 * Remove the trace since TCL_TRACE_DESTROYED tells us to, or the
4153 * command we're tracing has just gone away. Then decrement the
4154 * clientData refCount that was set up by trace creation.
4155 */
4156 Tcl_UntraceCommand(interp, oldName, untraceFlags,
4157 TraceCommandProc, clientData);
4158 tcmdPtr->refCount--;
4159 }
4160 tcmdPtr->refCount--;
4161 if (tcmdPtr->refCount < 0) {
4162 Tcl_Panic("TraceCommandProc: negative TraceCommandInfo refCount");
4163 }
4164 if (tcmdPtr->refCount == 0) {
4165 ckfree((char*)tcmdPtr);
4166 }
4167 return;
4168 }
4169
4170 /*
4171 *----------------------------------------------------------------------
4172 *
4173 * TclCheckExecutionTraces --
4174 *
4175 * Checks on all current command execution traces, and invokes
4176 * procedures which have been registered. This procedure can be
4177 * used by other code which performs execution to unify the
4178 * tracing system, so that execution traces will function for that
4179 * other code.
4180 *
4181 * For instance extensions like [incr Tcl] which use their
4182 * own execution technique can make use of Tcl's tracing.
4183 *
4184 * This procedure is called by 'TclEvalObjvInternal'
4185 *
4186 * Results:
4187 * The return value is a standard Tcl completion code such as
4188 * TCL_OK or TCL_ERROR, etc.
4189 *
4190 * Side effects:
4191 * Those side effects made by any trace procedures called.
4192 *
4193 *----------------------------------------------------------------------
4194 */
4195 int
4196 TclCheckExecutionTraces(interp, command, numChars, cmdPtr, code,
4197 traceFlags, objc, objv)
4198 Tcl_Interp *interp; /* The current interpreter. */
4199 CONST char *command; /* Pointer to beginning of the current
4200 * command string. */
4201 int numChars; /* The number of characters in 'command'
4202 * which are part of the command string. */
4203 Command *cmdPtr; /* Points to command's Command struct. */
4204 int code; /* The current result code. */
4205 int traceFlags; /* Current tracing situation. */
4206 int objc; /* Number of arguments for the command. */
4207 Tcl_Obj *CONST objv[]; /* Pointers to Tcl_Obj of each argument. */
4208 {
4209 Interp *iPtr = (Interp *) interp;
4210 CommandTrace *tracePtr, *lastTracePtr;
4211 ActiveCommandTrace active;
4212 int curLevel;
4213 int traceCode = TCL_OK;
4214 TraceCommandInfo* tcmdPtr;
4215
4216 if (command == NULL || cmdPtr->tracePtr == NULL) {
4217 return traceCode;
4218 }
4219
4220 curLevel = ((iPtr->varFramePtr == NULL) ? 0 : iPtr->varFramePtr->level);
4221
4222 active.nextPtr = iPtr->activeCmdTracePtr;
4223 iPtr->activeCmdTracePtr = &active;
4224
4225 active.cmdPtr = cmdPtr;
4226 lastTracePtr = NULL;
4227 for (tracePtr = cmdPtr->tracePtr;
4228 (traceCode == TCL_OK) && (tracePtr != NULL);
4229 tracePtr = active.nextTracePtr) {
4230 if (traceFlags & TCL_TRACE_LEAVE_EXEC) {
4231 /* execute the trace command in order of creation for "leave" */
4232 active.nextTracePtr = NULL;
4233 tracePtr = cmdPtr->tracePtr;
4234 while (tracePtr->nextPtr != lastTracePtr) {
4235 active.nextTracePtr = tracePtr;
4236 tracePtr = tracePtr->nextPtr;
4237 }
4238 } else {
4239 active.nextTracePtr = tracePtr->nextPtr;
4240 }
4241 tcmdPtr = (TraceCommandInfo*)tracePtr->clientData;
4242 if (tcmdPtr->flags != 0) {
4243 tcmdPtr->curFlags = traceFlags | TCL_TRACE_EXEC_DIRECT;
4244 tcmdPtr->curCode = code;
4245 tcmdPtr->refCount++;
4246 traceCode = TraceExecutionProc((ClientData)tcmdPtr, interp,
4247 curLevel, command, (Tcl_Command)cmdPtr, objc, objv);
4248 tcmdPtr->refCount--;
4249 if (tcmdPtr->refCount < 0) {
4250 Tcl_Panic("TclCheckExecutionTraces: negative TraceCommandInfo refCount");
4251 }
4252 if (tcmdPtr->refCount == 0) {
4253 ckfree((char*)tcmdPtr);
4254 }
4255 }
4256 lastTracePtr = tracePtr;
4257 }
4258 iPtr->activeCmdTracePtr = active.nextPtr;
4259 return(traceCode);
4260 }
4261
4262 /*
4263 *----------------------------------------------------------------------
4264 *
4265 * TclCheckInterpTraces --
4266 *
4267 * Checks on all current traces, and invokes procedures which
4268 * have been registered. This procedure can be used by other
4269 * code which performs execution to unify the tracing system.
4270 * For instance extensions like [incr Tcl] which use their
4271 * own execution technique can make use of Tcl's tracing.
4272 *
4273 * This procedure is called by 'TclEvalObjvInternal'
4274 *
4275 * Results:
4276 * The return value is a standard Tcl completion code such as
4277 * TCL_OK or TCL_ERROR, etc.
4278 *
4279 * Side effects:
4280 * Those side effects made by any trace procedures called.
4281 *
4282 *----------------------------------------------------------------------
4283 */
4284 int
4285 TclCheckInterpTraces(interp, command, numChars, cmdPtr, code,
4286 traceFlags, objc, objv)
4287 Tcl_Interp *interp; /* The current interpreter. */
4288 CONST char *command; /* Pointer to beginning of the current
4289 * command string. */
4290 int numChars; /* The number of characters in 'command'
4291 * which are part of the command string. */
4292 Command *cmdPtr; /* Points to command's Command struct. */
4293 int code; /* The current result code. */
4294 int traceFlags; /* Current tracing situation. */
4295 int objc; /* Number of arguments for the command. */
4296 Tcl_Obj *CONST objv[]; /* Pointers to Tcl_Obj of each argument. */
4297 {
4298 Interp *iPtr = (Interp *) interp;
4299 Trace *tracePtr, *lastTracePtr;
4300 ActiveInterpTrace active;
4301 int curLevel;
4302 int traceCode = TCL_OK;
4303 TraceCommandInfo* tcmdPtr;
4304
4305 if (command == NULL || iPtr->tracePtr == NULL ||
4306 (iPtr->flags & INTERP_TRACE_IN_PROGRESS)) {
4307 return(traceCode);
4308 }
4309
4310 curLevel = ((iPtr->varFramePtr == NULL) ? 0 : iPtr->varFramePtr->level);
4311
4312 active.nextPtr = iPtr->activeInterpTracePtr;
4313 iPtr->activeInterpTracePtr = &active;
4314
4315 lastTracePtr = NULL;
4316 for ( tracePtr = iPtr->tracePtr;
4317 (traceCode == TCL_OK) && (tracePtr != NULL);
4318 tracePtr = active.nextTracePtr) {
4319 if (traceFlags & TCL_TRACE_ENTER_EXEC) {
4320 /*
4321 * Execute the trace command in reverse order of creation
4322 * for "enterstep" operation. The order is changed for
4323 * "enterstep" instead of for "leavestep" as was done in
4324 * TclCheckExecutionTraces because for step traces,
4325 * Tcl_CreateObjTrace creates one more linked list of traces
4326 * which results in one more reversal of trace invocation.
4327 */
4328 active.nextTracePtr = NULL;
4329 tracePtr = iPtr->tracePtr;
4330 while (tracePtr->nextPtr != lastTracePtr) {
4331 active.nextTracePtr = tracePtr;
4332 tracePtr = tracePtr->nextPtr;
4333 }
4334 } else {
4335 active.nextTracePtr = tracePtr->nextPtr;
4336 }
4337 if (tracePtr->level > 0 && curLevel > tracePtr->level) {
4338 continue;
4339 }
4340 if (!(tracePtr->flags & TCL_TRACE_EXEC_IN_PROGRESS)) {
4341 /*
4342 * The proc invoked might delete the traced command which
4343 * which might try to free tracePtr. We want to use tracePtr
4344 * until the end of this if section, so we use
4345 * Tcl_Preserve() and Tcl_Release() to be sure it is not
4346 * freed while we still need it.
4347 */
4348 Tcl_Preserve((ClientData) tracePtr);
4349 tracePtr->flags |= TCL_TRACE_EXEC_IN_PROGRESS;
4350
4351 if (tracePtr->flags & (TCL_TRACE_ENTER_EXEC | TCL_TRACE_LEAVE_EXEC)) {
4352 /* New style trace */
4353 if ((tracePtr->flags != TCL_TRACE_EXEC_IN_PROGRESS) &&
4354 ((tracePtr->flags & traceFlags) != 0)) {
4355 tcmdPtr = (TraceCommandInfo*)tracePtr->clientData;
4356 tcmdPtr->curFlags = traceFlags;
4357 tcmdPtr->curCode = code;
4358 traceCode = (tracePtr->proc)((ClientData)tcmdPtr,
4359 (Tcl_Interp*)interp,
4360 curLevel, command,
4361 (Tcl_Command)cmdPtr,
4362 objc, objv);
4363 }
4364 } else {
4365 /* Old-style trace */
4366
4367 if (traceFlags & TCL_TRACE_ENTER_EXEC) {
4368 /*
4369 * Old-style interpreter-wide traces only trigger
4370 * before the command is executed.
4371 */
4372 traceCode = CallTraceProcedure(interp, tracePtr, cmdPtr,
4373 command, numChars, objc, objv);
4374 }
4375 }
4376 tracePtr->flags &= ~TCL_TRACE_EXEC_IN_PROGRESS;
4377 Tcl_Release((ClientData) tracePtr);
4378 }
4379 lastTracePtr = tracePtr;
4380 }
4381 iPtr->activeInterpTracePtr = active.nextPtr;
4382 return(traceCode);
4383 }
4384
4385 /*
4386 *----------------------------------------------------------------------
4387 *
4388 * CallTraceProcedure --
4389 *
4390 * Invokes a trace procedure registered with an interpreter. These
4391 * procedures trace command execution. Currently this trace procedure
4392 * is called with the address of the string-based Tcl_CmdProc for the
4393 * command, not the Tcl_ObjCmdProc.
4394 *
4395 * Results:
4396 * None.
4397 *
4398 * Side effects:
4399 * Those side effects made by the trace procedure.
4400 *
4401 *----------------------------------------------------------------------
4402 */
4403
4404 static int
4405 CallTraceProcedure(interp, tracePtr, cmdPtr, command, numChars, objc, objv)
4406 Tcl_Interp *interp; /* The current interpreter. */
4407 register Trace *tracePtr; /* Describes the trace procedure to call. */
4408 Command *cmdPtr; /* Points to command's Command struct. */
4409 CONST char *command; /* Points to the first character of the
4410 * command's source before substitutions. */
4411 int numChars; /* The number of characters in the
4412 * command's source. */
4413 register int objc; /* Number of arguments for the command. */
4414 Tcl_Obj *CONST objv[]; /* Pointers to Tcl_Obj of each argument. */
4415 {
4416 Interp *iPtr = (Interp *) interp;
4417 char *commandCopy;
4418 int traceCode;
4419
4420 /*
4421 * Copy the command characters into a new string.
4422 */
4423
4424 commandCopy = (char *) ckalloc((unsigned) (numChars + 1));
4425 memcpy((VOID *) commandCopy, (VOID *) command, (size_t) numChars);
4426 commandCopy[numChars] = '\0';
4427
4428 /*
4429 * Call the trace procedure then free allocated storage.
4430 */
4431
4432 traceCode = (tracePtr->proc)( tracePtr->clientData, (Tcl_Interp*) iPtr,
4433 iPtr->numLevels, commandCopy,
4434 (Tcl_Command) cmdPtr, objc, objv );
4435
4436 ckfree((char *) commandCopy);
4437 return(traceCode);
4438 }
4439
4440 /*
4441 *----------------------------------------------------------------------
4442 *
4443 * CommandObjTraceDeleted --
4444 *
4445 * Ensure the trace is correctly deleted by decrementing its
4446 * refCount and only deleting if no other references exist.
4447 *
4448 * Results:
4449 * None.
4450 *
4451 * Side effects:
4452 * May release memory.
4453 *
4454 *----------------------------------------------------------------------
4455 */
4456 static void
4457 CommandObjTraceDeleted(ClientData clientData) {
4458 TraceCommandInfo* tcmdPtr = (TraceCommandInfo*)clientData;
4459 tcmdPtr->refCount--;
4460 if (tcmdPtr->refCount < 0) {
4461 Tcl_Panic("CommandObjTraceDeleted: negative TraceCommandInfo refCount");
4462 }
4463 if (tcmdPtr->refCount == 0) {
4464 ckfree((char*)tcmdPtr);
4465 }
4466 }
4467
4468 /*
4469 *----------------------------------------------------------------------
4470 *
4471 * TraceExecutionProc --
4472 *
4473 * This procedure is invoked whenever code relevant to a
4474 * 'trace execution' command is executed. It is called in one
4475 * of two ways in Tcl's core:
4476 *
4477 * (i) by the TclCheckExecutionTraces, when an execution trace
4478 * has been triggered.
4479 * (ii) by TclCheckInterpTraces, when a prior execution trace has
4480 * created a trace of the internals of a procedure, passing in
4481 * this procedure as the one to be called.
4482 *
4483 * Results:
4484 * The return value is a standard Tcl completion code such as
4485 * TCL_OK or TCL_ERROR, etc.
4486 *
4487 * Side effects:
4488 * May invoke an arbitrary Tcl procedure, and may create or
4489 * delete an interpreter-wide trace.
4490 *
4491 *----------------------------------------------------------------------
4492 */
4493 static int
4494 TraceExecutionProc(ClientData clientData, Tcl_Interp *interp,
4495 int level, CONST char* command, Tcl_Command cmdInfo,
4496 int objc, struct Tcl_Obj *CONST objv[]) {
4497 int call = 0;
4498 Interp *iPtr = (Interp *) interp;
4499 TraceCommandInfo* tcmdPtr = (TraceCommandInfo*)clientData;
4500 int flags = tcmdPtr->curFlags;
4501 int code = tcmdPtr->curCode;
4502 int traceCode = TCL_OK;
4503
4504 if (tcmdPtr->flags & TCL_TRACE_EXEC_IN_PROGRESS) {
4505 /*
4506 * Inside any kind of execution trace callback, we do
4507 * not allow any further execution trace callbacks to
4508 * be called for the same trace.
4509 */
4510 return traceCode;
4511 }
4512
4513 if (!(flags & TCL_INTERP_DESTROYED)) {
4514 /*
4515 * Check whether the current call is going to eval arbitrary
4516 * Tcl code with a generated trace, or whether we are only
4517 * going to setup interpreter-wide traces to implement the
4518 * 'step' traces. This latter situation can happen if
4519 * we create a command trace without either before or after
4520 * operations, but with either of the step operations.
4521 */
4522 if (flags & TCL_TRACE_EXEC_DIRECT) {
4523 call = flags & tcmdPtr->flags
4524 & (TCL_TRACE_ENTER_EXEC | TCL_TRACE_LEAVE_EXEC);
4525 } else {
4526 call = 1;
4527 }
4528 /*
4529 * First, if we have returned back to the level at which we
4530 * created an interpreter trace for enterstep and/or leavestep
4531 * execution traces, we remove it here.
4532 */
4533 if (flags & TCL_TRACE_LEAVE_EXEC) {
4534 if ((tcmdPtr->stepTrace != NULL) && (level == tcmdPtr->startLevel)
4535 && (strcmp(command, tcmdPtr->startCmd) == 0)) {
4536 Tcl_DeleteTrace(interp, tcmdPtr->stepTrace);
4537 tcmdPtr->stepTrace = NULL;
4538 if (tcmdPtr->startCmd != NULL) {
4539 ckfree((char *)tcmdPtr->startCmd);
4540 }
4541 }
4542 }
4543
4544 /*
4545 * Second, create the tcl callback, if required.
4546 */
4547 if (call) {
4548 Tcl_SavedResult state;
4549 int stateCode;
4550 Tcl_DString cmd;
4551 Tcl_DString sub;
4552 int i;
4553
4554 Tcl_DStringInit(&cmd);
4555 Tcl_DStringAppend(&cmd, tcmdPtr->command, (int)tcmdPtr->length);
4556 /* Append command with arguments */
4557 Tcl_DStringInit(&sub);
4558 for (i = 0; i < objc; i++) {
4559 char* str;
4560 int len;
4561 str = Tcl_GetStringFromObj(objv[i],&len);
4562 Tcl_DStringAppendElement(&sub, str);
4563 }
4564 Tcl_DStringAppendElement(&cmd, Tcl_DStringValue(&sub));
4565 Tcl_DStringFree(&sub);
4566
4567 if (flags & TCL_TRACE_ENTER_EXEC) {
4568 /* Append trace operation */
4569 if (flags & TCL_TRACE_EXEC_DIRECT) {
4570 Tcl_DStringAppendElement(&cmd, "enter");
4571 } else {
4572 Tcl_DStringAppendElement(&cmd, "enterstep");
4573 }
4574 } else if (flags & TCL_TRACE_LEAVE_EXEC) {
4575 Tcl_Obj* resultCode;
4576 char* resultCodeStr;
4577
4578 /* Append result code */
4579 resultCode = Tcl_NewIntObj(code);
4580 resultCodeStr = Tcl_GetString(resultCode);
4581 Tcl_DStringAppendElement(&cmd, resultCodeStr);
4582 Tcl_DecrRefCount(resultCode);
4583
4584 /* Append result string */
4585 Tcl_DStringAppendElement(&cmd, Tcl_GetStringResult(interp));
4586 /* Append trace operation */
4587 if (flags & TCL_TRACE_EXEC_DIRECT) {
4588 Tcl_DStringAppendElement(&cmd, "leave");
4589 } else {
4590 Tcl_DStringAppendElement(&cmd, "leavestep");
4591 }
4592 } else {
4593 panic("TraceExecutionProc: bad flag combination");
4594 }
4595
4596 /*
4597 * Execute the command. Save the interp's result used for
4598 * the command, including the value of iPtr->returnCode which
4599 * may be modified when Tcl_Eval is invoked. We discard any
4600 * object result the command returns.
4601 */
4602
4603 Tcl_SaveResult(interp, &state);
4604 stateCode = iPtr->returnCode;
4605
4606 tcmdPtr->flags |= TCL_TRACE_EXEC_IN_PROGRESS;
4607 iPtr->flags |= INTERP_TRACE_IN_PROGRESS;
4608 tcmdPtr->refCount++;
4609 /*
4610 * This line can have quite arbitrary side-effects,
4611 * including deleting the trace, the command being
4612 * traced, or even the interpreter.
4613 */
4614 traceCode = Tcl_Eval(interp, Tcl_DStringValue(&cmd));
4615 tcmdPtr->flags &= ~TCL_TRACE_EXEC_IN_PROGRESS;
4616 iPtr->flags &= ~INTERP_TRACE_IN_PROGRESS;
4617 if (tcmdPtr->flags == 0) {
4618 flags |= TCL_TRACE_DESTROYED;
4619 }
4620
4621 if (traceCode == TCL_OK) {
4622 /* Restore result if trace execution was successful */
4623 Tcl_RestoreResult(interp, &state);
4624 iPtr->returnCode = stateCode;
4625 } else {
4626 Tcl_DiscardResult(&state);
4627 }
4628
4629 Tcl_DStringFree(&cmd);
4630 }
4631
4632 /*
4633 * Third, if there are any step execution traces for this proc,
4634 * we register an interpreter trace to invoke enterstep and/or
4635 * leavestep traces.
4636 * We also need to save the current stack level and the proc
4637 * string in startLevel and startCmd so that we can delete this
4638 * interpreter trace when it reaches the end of this proc.
4639 */
4640 if ((flags & TCL_TRACE_ENTER_EXEC) && (tcmdPtr->stepTrace == NULL)
4641 && (tcmdPtr->flags & (TCL_TRACE_ENTER_DURING_EXEC |
4642 TCL_TRACE_LEAVE_DURING_EXEC))) {
4643 tcmdPtr->startLevel = level;
4644 tcmdPtr->startCmd =
4645 (char *) ckalloc((unsigned) (strlen(command) + 1));
4646 strcpy(tcmdPtr->startCmd, command);
4647 tcmdPtr->refCount++;
4648 tcmdPtr->stepTrace = Tcl_CreateObjTrace(interp, 0,
4649 (tcmdPtr->flags & TCL_TRACE_ANY_EXEC) >> 2,
4650 TraceExecutionProc, (ClientData)tcmdPtr,
4651 CommandObjTraceDeleted);
4652 }
4653 }
4654 if (flags & TCL_TRACE_DESTROYED) {
4655 if (tcmdPtr->stepTrace != NULL) {
4656 Tcl_DeleteTrace(interp, tcmdPtr->stepTrace);
4657 tcmdPtr->stepTrace = NULL;
4658 if (tcmdPtr->startCmd != NULL) {
4659 ckfree((char *)tcmdPtr->startCmd);
4660 }
4661 }
4662 }
4663 if (call) {
4664 tcmdPtr->refCount--;
4665 if (tcmdPtr->refCount < 0) {
4666 Tcl_Panic("TraceExecutionProc: negative TraceCommandInfo refCount");
4667 }
4668 if (tcmdPtr->refCount == 0) {
4669 ckfree((char*)tcmdPtr);
4670 }
4671 }
4672 return traceCode;
4673 }
4674
4675 /*
4676 *----------------------------------------------------------------------
4677 *
4678 * TraceVarProc --
4679 *
4680 * This procedure is called to handle variable accesses that have
4681 * been traced using the "trace" command.
4682 *
4683 * Results:
4684 * Normally returns NULL. If the trace command returns an error,
4685 * then this procedure returns an error string.
4686 *
4687 * Side effects:
4688 * Depends on the command associated with the trace.
4689 *
4690 *----------------------------------------------------------------------
4691 */
4692
4693 /* ARGSUSED */
4694 static char *
4695 TraceVarProc(clientData, interp, name1, name2, flags)
4696 ClientData clientData; /* Information about the variable trace. */
4697 Tcl_Interp *interp; /* Interpreter containing variable. */
4698 CONST char *name1; /* Name of variable or array. */
4699 CONST char *name2; /* Name of element within array; NULL means
4700 * scalar variable is being referenced. */
4701 int flags; /* OR-ed bits giving operation and other
4702 * information. */
4703 {
4704 Tcl_SavedResult state;
4705 TraceVarInfo *tvarPtr = (TraceVarInfo *) clientData;
4706 char *result;
4707 int code;
4708 Tcl_DString cmd;
4709
4710 /*
4711 * We might call Tcl_Eval() below, and that might evaluate
4712 * [trace vdelete] which might try to free tvarPtr. We want
4713 * to use tvarPtr until the end of this function, so we use
4714 * Tcl_Preserve() and Tcl_Release() to be sure it is not
4715 * freed while we still need it.
4716 */
4717
4718 Tcl_Preserve((ClientData) tvarPtr);
4719
4720 result = NULL;
4721 if ((tvarPtr->flags & flags) && !(flags & TCL_INTERP_DESTROYED)) {
4722 if (tvarPtr->length != (size_t) 0) {
4723 /*
4724 * Generate a command to execute by appending list elements
4725 * for the two variable names and the operation.
4726 */
4727
4728 Tcl_DStringInit(&cmd);
4729 Tcl_DStringAppend(&cmd, tvarPtr->command, (int) tvarPtr->length);
4730 Tcl_DStringAppendElement(&cmd, name1);
4731 Tcl_DStringAppendElement(&cmd, (name2 ? name2 : ""));
4732 #ifndef TCL_REMOVE_OBSOLETE_TRACES
4733 if (tvarPtr->flags & TCL_TRACE_OLD_STYLE) {
4734 if (flags & TCL_TRACE_ARRAY) {
4735 Tcl_DStringAppend(&cmd, " a", 2);
4736 } else if (flags & TCL_TRACE_READS) {
4737 Tcl_DStringAppend(&cmd, " r", 2);
4738 } else if (flags & TCL_TRACE_WRITES) {
4739 Tcl_DStringAppend(&cmd, " w", 2);
4740 } else if (flags & TCL_TRACE_UNSETS) {
4741 Tcl_DStringAppend(&cmd, " u", 2);
4742 }
4743 } else {
4744 #endif
4745 if (flags & TCL_TRACE_ARRAY) {
4746 Tcl_DStringAppend(&cmd, " array", 6);
4747 } else if (flags & TCL_TRACE_READS) {
4748 Tcl_DStringAppend(&cmd, " read", 5);
4749 } else if (flags & TCL_TRACE_WRITES) {
4750 Tcl_DStringAppend(&cmd, " write", 6);
4751 } else if (flags & TCL_TRACE_UNSETS) {
4752 Tcl_DStringAppend(&cmd, " unset", 6);
4753 }
4754 #ifndef TCL_REMOVE_OBSOLETE_TRACES
4755 }
4756 #endif
4757
4758 /*
4759 * Execute the command. Save the interp's result used for
4760 * the command. We discard any object result the command returns.
4761 *
4762 * Add the TCL_TRACE_DESTROYED flag to tvarPtr to indicate to
4763 * other areas that this will be destroyed by us, otherwise a
4764 * double-free might occur depending on what the eval does.
4765 */
4766
4767 Tcl_SaveResult(interp, &state);
4768 if (flags & TCL_TRACE_DESTROYED) {
4769 tvarPtr->flags |= TCL_TRACE_DESTROYED;
4770 }
4771
4772 code = Tcl_EvalEx(interp, Tcl_DStringValue(&cmd),
4773 Tcl_DStringLength(&cmd), 0);
4774 if (code != TCL_OK) { /* copy error msg to result */
4775 register Tcl_Obj *errMsgObj = Tcl_GetObjResult(interp);
4776 Tcl_IncrRefCount(errMsgObj);
4777 result = (char *) errMsgObj;
4778 }
4779
4780 Tcl_RestoreResult(interp, &state);
4781
4782 Tcl_DStringFree(&cmd);
4783 }
4784 }
4785 if (flags & TCL_TRACE_DESTROYED) {
4786 if (result != NULL) {
4787 register Tcl_Obj *errMsgObj = (Tcl_Obj *) result;
4788
4789 Tcl_DecrRefCount(errMsgObj);
4790 result = NULL;
4791 }
4792 Tcl_EventuallyFree((ClientData) tvarPtr, TCL_DYNAMIC);
4793 }
4794 Tcl_Release((ClientData) tvarPtr);
4795 return result;
4796 }
4797
4798 /*
4799 *----------------------------------------------------------------------
4800 *
4801 * Tcl_WhileObjCmd --
4802 *
4803 * This procedure is invoked to process the "while" Tcl command.
4804 * See the user documentation for details on what it does.
4805 *
4806 * With the bytecode compiler, this procedure is only called when
4807 * a command name is computed at runtime, and is "while" or the name
4808 * to which "while" was renamed: e.g., "set z while; $z {$i<100} {}"
4809 *
4810 * Results:
4811 * A standard Tcl result.
4812 *
4813 * Side effects:
4814 * See the user documentation.
4815 *
4816 *----------------------------------------------------------------------
4817 */
4818
4819 /* ARGSUSED */
4820 int
4821 Tcl_WhileObjCmd(dummy, interp, objc, objv)
4822 ClientData dummy; /* Not used. */
4823 Tcl_Interp *interp; /* Current interpreter. */
4824 int objc; /* Number of arguments. */
4825 Tcl_Obj *CONST objv[]; /* Argument objects. */
4826 {
4827 int result, value;
4828
4829 if (objc != 3) {
4830 Tcl_WrongNumArgs(interp, 1, objv, "test command");
4831 return TCL_ERROR;
4832 }
4833
4834 while (1) {
4835 result = Tcl_ExprBooleanObj(interp, objv[1], &value);
4836 if (result != TCL_OK) {
4837 return result;
4838 }
4839 if (!value) {
4840 break;
4841 }
4842 result = Tcl_EvalObjEx(interp, objv[2], 0);
4843 if ((result != TCL_OK) && (result != TCL_CONTINUE)) {
4844 if (result == TCL_ERROR) {
4845 char msg[32 + TCL_INTEGER_SPACE];
4846
4847 sprintf(msg, "\n (\"while\" body line %d)",
4848 interp->errorLine);
4849 Tcl_AddErrorInfo(interp, msg);
4850 }
4851 break;
4852 }
4853 }
4854 if (result == TCL_BREAK) {
4855 result = TCL_OK;
4856 }
4857 if (result == TCL_OK) {
4858 Tcl_ResetResult(interp);
4859 }
4860 return result;
4861 }
4862