Debian Codegraph @

generic/tclCmdMZ.c

raw
1 /*
2 * tclCmdMZ.c --
3 *
4 * This file contains the top-level command routines for most of the Tcl
5 * built-in commands whose names begin with the letters M to Z. It
6 * contains only commands in the generic core (i.e. those that don't
7 * 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 * Copyright (c) 2003-2009 Donal K. Fellows.
14 *
15 * See the file "license.terms" for information on usage and redistribution of
16 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
17 */
18
19 #include "tclInt.h"
20 #include "tclCompile.h"
21 #include "tclRegexp.h"
22 #include "tclStringTrim.h"
23
24 static inline Tcl_Obj * During(Tcl_Interp *interp, int resultCode,
25 Tcl_Obj *oldOptions, Tcl_Obj *errorInfo);
26 static Tcl_NRPostProc SwitchPostProc;
27 static Tcl_NRPostProc TryPostBody;
28 static Tcl_NRPostProc TryPostFinal;
29 static Tcl_NRPostProc TryPostHandler;
30 static int UniCharIsAscii(int character);
31 static int UniCharIsHexDigit(int character);
32
33 /*
34 * Default set of characters to trim in [string trim] and friends. This is a
35 * UTF-8 literal string containing all Unicode space characters [TIP #413]
36 */
37
38 const char tclDefaultTrimSet[] =
39 "\x09\x0A\x0B\x0C\x0D " /* ASCII */
40 "\xC0\x80" /* nul (U+0000) */
41 "\xC2\x85" /* next line (U+0085) */
42 "\xC2\xA0" /* non-breaking space (U+00a0) */
43 "\xE1\x9A\x80" /* ogham space mark (U+1680) */
44 "\xE1\xA0\x8E" /* mongolian vowel separator (U+180e) */
45 "\xE2\x80\x80" /* en quad (U+2000) */
46 "\xE2\x80\x81" /* em quad (U+2001) */
47 "\xE2\x80\x82" /* en space (U+2002) */
48 "\xE2\x80\x83" /* em space (U+2003) */
49 "\xE2\x80\x84" /* three-per-em space (U+2004) */
50 "\xE2\x80\x85" /* four-per-em space (U+2005) */
51 "\xE2\x80\x86" /* six-per-em space (U+2006) */
52 "\xE2\x80\x87" /* figure space (U+2007) */
53 "\xE2\x80\x88" /* punctuation space (U+2008) */
54 "\xE2\x80\x89" /* thin space (U+2009) */
55 "\xE2\x80\x8A" /* hair space (U+200a) */
56 "\xE2\x80\x8B" /* zero width space (U+200b) */
57 "\xE2\x80\xA8" /* line separator (U+2028) */
58 "\xE2\x80\xA9" /* paragraph separator (U+2029) */
59 "\xE2\x80\xAF" /* narrow no-break space (U+202f) */
60 "\xE2\x81\x9F" /* medium mathematical space (U+205f) */
61 "\xE2\x81\xA0" /* word joiner (U+2060) */
62 "\xE3\x80\x80" /* ideographic space (U+3000) */
63 "\xEF\xBB\xBF" /* zero width no-break space (U+feff) */
64 ;
65
66 /*
67 *----------------------------------------------------------------------
68 *
69 * Tcl_PwdObjCmd --
70 *
71 * This procedure is invoked to process the "pwd" Tcl command. See the
72 * user documentation for details on what it does.
73 *
74 * Results:
75 * A standard Tcl result.
76 *
77 * Side effects:
78 * See the user documentation.
79 *
80 *----------------------------------------------------------------------
81 */
82
83 int
84 Tcl_PwdObjCmd(
85 ClientData dummy, /* Not used. */
86 Tcl_Interp *interp, /* Current interpreter. */
87 int objc, /* Number of arguments. */
88 Tcl_Obj *const objv[]) /* Argument objects. */
89 {
90 Tcl_Obj *retVal;
91
92 if (objc != 1) {
93 Tcl_WrongNumArgs(interp, 1, objv, NULL);
94 return TCL_ERROR;
95 }
96
97 retVal = Tcl_FSGetCwd(interp);
98 if (retVal == NULL) {
99 return TCL_ERROR;
100 }
101 Tcl_SetObjResult(interp, retVal);
102 Tcl_DecrRefCount(retVal);
103 return TCL_OK;
104 }
105
106 /*
107 *----------------------------------------------------------------------
108 *
109 * Tcl_RegexpObjCmd --
110 *
111 * This procedure is invoked to process the "regexp" Tcl command. See
112 * the user documentation for details on what it does.
113 *
114 * Results:
115 * A standard Tcl result.
116 *
117 * Side effects:
118 * See the user documentation.
119 *
120 *----------------------------------------------------------------------
121 */
122
123 int
124 Tcl_RegexpObjCmd(
125 ClientData dummy, /* Not used. */
126 Tcl_Interp *interp, /* Current interpreter. */
127 int objc, /* Number of arguments. */
128 Tcl_Obj *const objv[]) /* Argument objects. */
129 {
130 int i, indices, match, about, offset, all, doinline, numMatchesSaved;
131 int cflags, eflags, stringLength, matchLength;
132 Tcl_RegExp regExpr;
133 Tcl_Obj *objPtr, *startIndex = NULL, *resultPtr = NULL;
134 Tcl_RegExpInfo info;
135 static const char *const options[] = {
136 "-all", "-about", "-indices", "-inline",
137 "-expanded", "-line", "-linestop", "-lineanchor",
138 "-nocase", "-start", "--", NULL
139 };
140 enum regexpoptions {
141 REGEXP_ALL, REGEXP_ABOUT, REGEXP_INDICES, REGEXP_INLINE,
142 REGEXP_EXPANDED,REGEXP_LINE, REGEXP_LINESTOP,REGEXP_LINEANCHOR,
143 REGEXP_NOCASE, REGEXP_START, REGEXP_LAST
144 };
145
146 indices = 0;
147 about = 0;
148 cflags = TCL_REG_ADVANCED;
149 offset = 0;
150 all = 0;
151 doinline = 0;
152
153 for (i = 1; i < objc; i++) {
154 const char *name;
155 int index;
156
157 name = TclGetString(objv[i]);
158 if (name[0] != '-') {
159 break;
160 }
161 if (Tcl_GetIndexFromObj(interp, objv[i], options, "option", TCL_EXACT,
162 &index) != TCL_OK) {
163 goto optionError;
164 }
165 switch ((enum regexpoptions) index) {
166 case REGEXP_ALL:
167 all = 1;
168 break;
169 case REGEXP_INDICES:
170 indices = 1;
171 break;
172 case REGEXP_INLINE:
173 doinline = 1;
174 break;
175 case REGEXP_NOCASE:
176 cflags |= TCL_REG_NOCASE;
177 break;
178 case REGEXP_ABOUT:
179 about = 1;
180 break;
181 case REGEXP_EXPANDED:
182 cflags |= TCL_REG_EXPANDED;
183 break;
184 case REGEXP_LINE:
185 cflags |= TCL_REG_NEWLINE;
186 break;
187 case REGEXP_LINESTOP:
188 cflags |= TCL_REG_NLSTOP;
189 break;
190 case REGEXP_LINEANCHOR:
191 cflags |= TCL_REG_NLANCH;
192 break;
193 case REGEXP_START: {
194 int temp;
195 if (++i >= objc) {
196 goto endOfForLoop;
197 }
198 if (TclGetIntForIndexM(interp, objv[i], 0, &temp) != TCL_OK) {
199 goto optionError;
200 }
201 if (startIndex) {
202 Tcl_DecrRefCount(startIndex);
203 }
204 startIndex = objv[i];
205 Tcl_IncrRefCount(startIndex);
206 break;
207 }
208 case REGEXP_LAST:
209 i++;
210 goto endOfForLoop;
211 }
212 }
213
214 endOfForLoop:
215 if ((objc - i) < (2 - about)) {
216 Tcl_WrongNumArgs(interp, 1, objv,
217 "?-option ...? exp string ?matchVar? ?subMatchVar ...?");
218 goto optionError;
219 }
220 objc -= i;
221 objv += i;
222
223 /*
224 * Check if the user requested -inline, but specified match variables; a
225 * no-no.
226 */
227
228 if (doinline && ((objc - 2) != 0)) {
229 Tcl_SetObjResult(interp, Tcl_NewStringObj(
230 "regexp match variables not allowed when using -inline", -1));
231 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "REGEXP",
232 "MIX_VAR_INLINE", (char *)NULL);
233 goto optionError;
234 }
235
236 /*
237 * Handle the odd about case separately.
238 */
239
240 if (about) {
241 regExpr = Tcl_GetRegExpFromObj(interp, objv[0], cflags);
242 if ((regExpr == NULL) || (TclRegAbout(interp, regExpr) < 0)) {
243 optionError:
244 if (startIndex) {
245 Tcl_DecrRefCount(startIndex);
246 }
247 return TCL_ERROR;
248 }
249 return TCL_OK;
250 }
251
252 /*
253 * Get the length of the string that we are matching against so we can do
254 * the termination test for -all matches. Do this before getting the
255 * regexp to avoid shimmering problems.
256 */
257
258 objPtr = objv[1];
259 stringLength = Tcl_GetCharLength(objPtr);
260
261 if (startIndex) {
262 TclGetIntForIndexM(NULL, startIndex, stringLength, &offset);
263 Tcl_DecrRefCount(startIndex);
264 if (offset < 0) {
265 offset = 0;
266 }
267 }
268
269 regExpr = Tcl_GetRegExpFromObj(interp, objv[0], cflags);
270 if (regExpr == NULL) {
271 return TCL_ERROR;
272 }
273
274 objc -= 2;
275 objv += 2;
276
277 if (doinline) {
278 /*
279 * Save all the subexpressions, as we will return them as a list
280 */
281
282 numMatchesSaved = -1;
283 } else {
284 /*
285 * Save only enough subexpressions for matches we want to keep, expect
286 * in the case of -all, where we need to keep at least one to know
287 * where to move the offset.
288 */
289
290 numMatchesSaved = (objc == 0) ? all : objc;
291 }
292
293 /*
294 * The following loop is to handle multiple matches within the same source
295 * string; each iteration handles one match. If "-all" hasn't been
296 * specified then the loop body only gets executed once. We terminate the
297 * loop when the starting offset is past the end of the string.
298 */
299
300 while (1) {
301 /*
302 * Pass either 0 or TCL_REG_NOTBOL in the eflags. Passing
303 * TCL_REG_NOTBOL indicates that the character at offset should not be
304 * considered the start of the line. If for example the pattern {^} is
305 * passed and -start is positive, then the pattern will not match the
306 * start of the string unless the previous character is a newline.
307 */
308
309 if (offset == 0) {
310 eflags = 0;
311 } else if (offset > stringLength) {
312 eflags = TCL_REG_NOTBOL;
313 } else if (Tcl_GetUniChar(objPtr, offset-1) == '\n') {
314 eflags = 0;
315 } else {
316 eflags = TCL_REG_NOTBOL;
317 }
318
319 match = Tcl_RegExpExecObj(interp, regExpr, objPtr, offset,
320 numMatchesSaved, eflags);
321 if (match < 0) {
322 return TCL_ERROR;
323 }
324
325 if (match == 0) {
326 /*
327 * We want to set the value of the interpreter result only when
328 * this is the first time through the loop.
329 */
330
331 if (all <= 1) {
332 /*
333 * If inlining, the interpreter's object result remains an
334 * empty list, otherwise set it to an integer object w/ value
335 * 0.
336 */
337
338 if (!doinline) {
339 Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
340 }
341 return TCL_OK;
342 }
343 break;
344 }
345
346 /*
347 * If additional variable names have been specified, return index
348 * information in those variables.
349 */
350
351 Tcl_RegExpGetInfo(regExpr, &info);
352 if (doinline) {
353 /*
354 * It's the number of substitutions, plus one for the matchVar at
355 * index 0
356 */
357
358 objc = info.nsubs + 1;
359 if (all <= 1) {
360 TclNewObj(resultPtr);
361 }
362 }
363 for (i = 0; i < objc; i++) {
364 Tcl_Obj *newPtr;
365
366 if (indices) {
367 int start, end;
368 Tcl_Obj *objs[2];
369
370 /*
371 * Only adjust the match area if there was a match for that
372 * area. (Scriptics Bug 4391/SF Bug #219232)
373 */
374
375 if (i <= info.nsubs && info.matches[i].start >= 0) {
376 start = offset + info.matches[i].start;
377 end = offset + info.matches[i].end;
378
379 /*
380 * Adjust index so it refers to the last character in the
381 * match instead of the first character after the match.
382 */
383
384 if (end >= offset) {
385 end--;
386 }
387 } else {
388 start = -1;
389 end = -1;
390 }
391
392 objs[0] = Tcl_NewLongObj(start);
393 objs[1] = Tcl_NewLongObj(end);
394
395 newPtr = Tcl_NewListObj(2, objs);
396 } else {
397 if ((i <= info.nsubs) && (info.matches[i].end > 0)) {
398 newPtr = Tcl_GetRange(objPtr,
399 offset + info.matches[i].start,
400 offset + info.matches[i].end - 1);
401 } else {
402 TclNewObj(newPtr);
403 }
404 }
405 if (doinline) {
406 if (Tcl_ListObjAppendElement(interp, resultPtr, newPtr)
407 != TCL_OK) {
408 Tcl_DecrRefCount(newPtr);
409 Tcl_DecrRefCount(resultPtr);
410 return TCL_ERROR;
411 }
412 } else {
413 if (Tcl_ObjSetVar2(interp, objv[i], NULL, newPtr,
414 TCL_LEAVE_ERR_MSG) == NULL) {
415 return TCL_ERROR;
416 }
417 }
418 }
419
420 if (all == 0) {
421 break;
422 }
423
424 /*
425 * Adjust the offset to the character just after the last one in the
426 * matchVar and increment all to count how many times we are making a
427 * match. We always increment the offset by at least one to prevent
428 * endless looping (as in the case: regexp -all {a*} a). Otherwise,
429 * when we match the NULL string at the end of the input string, we
430 * will loop indefinitely (because the length of the match is 0, so
431 * offset never changes).
432 */
433
434 matchLength = (info.matches[0].end - info.matches[0].start);
435
436 offset += info.matches[0].end;
437
438 /*
439 * A match of length zero could happen for {^} {$} or {.*} and in
440 * these cases we always want to bump the index up one.
441 */
442
443 if (matchLength == 0) {
444 offset++;
445 }
446 all++;
447 if (offset >= stringLength) {
448 break;
449 }
450 }
451
452 /*
453 * Set the interpreter's object result to an integer object with value 1
454 * if -all wasn't specified, otherwise it's all-1 (the number of times
455 * through the while - 1).
456 */
457
458 if (doinline) {
459 Tcl_SetObjResult(interp, resultPtr);
460 } else {
461 Tcl_SetObjResult(interp, Tcl_NewIntObj(all ? all-1 : 1));
462 }
463 return TCL_OK;
464 }
465
466 /*
467 *----------------------------------------------------------------------
468 *
469 * Tcl_RegsubObjCmd --
470 *
471 * This procedure is invoked to process the "regsub" Tcl command. See the
472 * user documentation for details on what it does.
473 *
474 * Results:
475 * A standard Tcl result.
476 *
477 * Side effects:
478 * See the user documentation.
479 *
480 *----------------------------------------------------------------------
481 */
482
483 int
484 Tcl_RegsubObjCmd(
485 ClientData dummy, /* Not used. */
486 Tcl_Interp *interp, /* Current interpreter. */
487 int objc, /* Number of arguments. */
488 Tcl_Obj *const objv[]) /* Argument objects. */
489 {
490 int idx, result, cflags, all, wlen, wsublen, numMatches, offset;
491 int start, end, subStart, subEnd, match;
492 Tcl_RegExp regExpr;
493 Tcl_RegExpInfo info;
494 Tcl_Obj *resultPtr, *subPtr, *objPtr, *startIndex = NULL;
495 Tcl_UniChar ch, *wsrc, *wfirstChar, *wstring, *wsubspec, *wend;
496
497 static const char *const options[] = {
498 "-all", "-nocase", "-expanded",
499 "-line", "-linestop", "-lineanchor", "-start",
500 "--", NULL
501 };
502 enum options {
503 REGSUB_ALL, REGSUB_NOCASE, REGSUB_EXPANDED,
504 REGSUB_LINE, REGSUB_LINESTOP, REGSUB_LINEANCHOR, REGSUB_START,
505 REGSUB_LAST
506 };
507
508 cflags = TCL_REG_ADVANCED;
509 all = 0;
510 offset = 0;
511 resultPtr = NULL;
512
513 for (idx = 1; idx < objc; idx++) {
514 const char *name;
515 int index;
516
517 name = TclGetString(objv[idx]);
518 if (name[0] != '-') {
519 break;
520 }
521 if (Tcl_GetIndexFromObj(interp, objv[idx], options, "option",
522 TCL_EXACT, &index) != TCL_OK) {
523 goto optionError;
524 }
525 switch ((enum options) index) {
526 case REGSUB_ALL:
527 all = 1;
528 break;
529 case REGSUB_NOCASE:
530 cflags |= TCL_REG_NOCASE;
531 break;
532 case REGSUB_EXPANDED:
533 cflags |= TCL_REG_EXPANDED;
534 break;
535 case REGSUB_LINE:
536 cflags |= TCL_REG_NEWLINE;
537 break;
538 case REGSUB_LINESTOP:
539 cflags |= TCL_REG_NLSTOP;
540 break;
541 case REGSUB_LINEANCHOR:
542 cflags |= TCL_REG_NLANCH;
543 break;
544 case REGSUB_START: {
545 int temp;
546 if (++idx >= objc) {
547 goto endOfForLoop;
548 }
549 if (TclGetIntForIndexM(interp, objv[idx], 0, &temp) != TCL_OK) {
550 goto optionError;
551 }
552 if (startIndex) {
553 Tcl_DecrRefCount(startIndex);
554 }
555 startIndex = objv[idx];
556 Tcl_IncrRefCount(startIndex);
557 break;
558 }
559 case REGSUB_LAST:
560 idx++;
561 goto endOfForLoop;
562 }
563 }
564
565 endOfForLoop:
566 if (objc-idx < 3 || objc-idx > 4) {
567 Tcl_WrongNumArgs(interp, 1, objv,
568 "?-option ...? exp string subSpec ?varName?");
569 optionError:
570 if (startIndex) {
571 Tcl_DecrRefCount(startIndex);
572 }
573 return TCL_ERROR;
574 }
575
576 objc -= idx;
577 objv += idx;
578
579 if (startIndex) {
580 int stringLength = Tcl_GetCharLength(objv[1]);
581
582 TclGetIntForIndexM(NULL, startIndex, stringLength, &offset);
583 Tcl_DecrRefCount(startIndex);
584 if (offset < 0) {
585 offset = 0;
586 }
587 }
588
589 if (all && (offset == 0)
590 && (strpbrk(TclGetString(objv[2]), "&\\") == NULL)
591 && (strpbrk(TclGetString(objv[0]), "*+?{}()[].\\|^$") == NULL)) {
592 /*
593 * This is a simple one pair string map situation. We make use of a
594 * slightly modified version of the one pair STR_MAP code.
595 */
596
597 int slen, nocase;
598 int (*strCmpFn)(const Tcl_UniChar*,const Tcl_UniChar*,unsigned long);
599 Tcl_UniChar *p, wsrclc;
600
601 numMatches = 0;
602 nocase = (cflags & TCL_REG_NOCASE);
603 strCmpFn = nocase ? Tcl_UniCharNcasecmp : Tcl_UniCharNcmp;
604
605 wsrc = Tcl_GetUnicodeFromObj(objv[0], &slen);
606 wstring = Tcl_GetUnicodeFromObj(objv[1], &wlen);
607 wsubspec = Tcl_GetUnicodeFromObj(objv[2], &wsublen);
608 wend = wstring + wlen - (slen ? slen - 1 : 0);
609 result = TCL_OK;
610
611 if (slen == 0) {
612 /*
613 * regsub behavior for "" matches between each character. 'string
614 * map' skips the "" case.
615 */
616
617 if (wstring < wend) {
618 resultPtr = Tcl_NewUnicodeObj(wstring, 0);
619 Tcl_IncrRefCount(resultPtr);
620 for (; wstring < wend; wstring++) {
621 Tcl_AppendUnicodeToObj(resultPtr, wsubspec, wsublen);
622 Tcl_AppendUnicodeToObj(resultPtr, wstring, 1);
623 numMatches++;
624 }
625 wlen = 0;
626 }
627 } else {
628 wsrclc = Tcl_UniCharToLower(*wsrc);
629 for (p = wfirstChar = wstring; wstring < wend; wstring++) {
630 if ((*wstring == *wsrc ||
631 (nocase && Tcl_UniCharToLower(*wstring)==wsrclc)) &&
632 (slen==1 || (strCmpFn(wstring, wsrc,
633 (unsigned long) slen) == 0))) {
634 if (numMatches == 0) {
635 resultPtr = Tcl_NewUnicodeObj(wstring, 0);
636 Tcl_IncrRefCount(resultPtr);
637 }
638 if (p != wstring) {
639 Tcl_AppendUnicodeToObj(resultPtr, p, wstring - p);
640 p = wstring + slen;
641 } else {
642 p += slen;
643 }
644 wstring = p - 1;
645
646 Tcl_AppendUnicodeToObj(resultPtr, wsubspec, wsublen);
647 numMatches++;
648 }
649 }
650 if (numMatches) {
651 wlen = wfirstChar + wlen - p;
652 wstring = p;
653 }
654 }
655 objPtr = NULL;
656 subPtr = NULL;
657 goto regsubDone;
658 }
659
660 regExpr = Tcl_GetRegExpFromObj(interp, objv[0], cflags);
661 if (regExpr == NULL) {
662 return TCL_ERROR;
663 }
664
665 /*
666 * Make sure to avoid problems where the objects are shared. This can
667 * cause RegExpObj <> UnicodeObj shimmering that causes data corruption.
668 * [Bug #461322]
669 */
670
671 if (objv[1] == objv[0]) {
672 objPtr = Tcl_DuplicateObj(objv[1]);
673 } else {
674 objPtr = objv[1];
675 }
676 wstring = Tcl_GetUnicodeFromObj(objPtr, &wlen);
677 if (objv[2] == objv[0]) {
678 subPtr = Tcl_DuplicateObj(objv[2]);
679 } else {
680 subPtr = objv[2];
681 }
682 wsubspec = Tcl_GetUnicodeFromObj(subPtr, &wsublen);
683
684 result = TCL_OK;
685
686 /*
687 * The following loop is to handle multiple matches within the same source
688 * string; each iteration handles one match and its corresponding
689 * substitution. If "-all" hasn't been specified then the loop body only
690 * gets executed once. We must use 'offset <= wlen' in particular for the
691 * case where the regexp pattern can match the empty string - this is
692 * useful when doing, say, 'regsub -- ^ $str ...' when $str might be
693 * empty.
694 */
695
696 numMatches = 0;
697 for ( ; offset <= wlen; ) {
698
699 /*
700 * The flags argument is set if string is part of a larger string, so
701 * that "^" won't match.
702 */
703
704 match = Tcl_RegExpExecObj(interp, regExpr, objPtr, offset,
705 10 /* matches */, ((offset > 0 &&
706 (wstring[offset-1] != (Tcl_UniChar)'\n'))
707 ? TCL_REG_NOTBOL : 0));
708
709 if (match < 0) {
710 result = TCL_ERROR;
711 goto done;
712 }
713 if (match == 0) {
714 break;
715 }
716 if (numMatches == 0) {
717 resultPtr = Tcl_NewUnicodeObj(wstring, 0);
718 Tcl_IncrRefCount(resultPtr);
719 if (offset > 0) {
720 /*
721 * Copy the initial portion of the string in if an offset was
722 * specified.
723 */
724
725 Tcl_AppendUnicodeToObj(resultPtr, wstring, offset);
726 }
727 }
728 numMatches++;
729
730 /*
731 * Copy the portion of the source string before the match to the
732 * result variable.
733 */
734
735 Tcl_RegExpGetInfo(regExpr, &info);
736 start = info.matches[0].start;
737 end = info.matches[0].end;
738 Tcl_AppendUnicodeToObj(resultPtr, wstring + offset, start);
739
740 /*
741 * Append the subSpec argument to the variable, making appropriate
742 * substitutions. This code is a bit hairy because of the backslash
743 * conventions and because the code saves up ranges of characters in
744 * subSpec to reduce the number of calls to Tcl_SetVar.
745 */
746
747 wsrc = wfirstChar = wsubspec;
748 wend = wsubspec + wsublen;
749 for (ch = *wsrc; wsrc != wend; wsrc++, ch = *wsrc) {
750 if (ch == '&') {
751 idx = 0;
752 } else if (ch == '\\') {
753 ch = wsrc[1];
754 if ((ch >= '0') && (ch <= '9')) {
755 idx = ch - '0';
756 } else if ((ch == '\\') || (ch == '&')) {
757 *wsrc = ch;
758 Tcl_AppendUnicodeToObj(resultPtr, wfirstChar,
759 wsrc - wfirstChar + 1);
760 *wsrc = '\\';
761 wfirstChar = wsrc + 2;
762 wsrc++;
763 continue;
764 } else {
765 continue;
766 }
767 } else {
768 continue;
769 }
770
771 if (wfirstChar != wsrc) {
772 Tcl_AppendUnicodeToObj(resultPtr, wfirstChar,
773 wsrc - wfirstChar);
774 }
775
776 if (idx <= info.nsubs) {
777 subStart = info.matches[idx].start;
778 subEnd = info.matches[idx].end;
779 if ((subStart >= 0) && (subEnd >= 0)) {
780 Tcl_AppendUnicodeToObj(resultPtr,
781 wstring + offset + subStart, subEnd - subStart);
782 }
783 }
784
785 if (*wsrc == '\\') {
786 wsrc++;
787 }
788 wfirstChar = wsrc + 1;
789 }
790
791 if (wfirstChar != wsrc) {
792 Tcl_AppendUnicodeToObj(resultPtr, wfirstChar, wsrc - wfirstChar);
793 }
794
795 if (end == 0) {
796 /*
797 * Always consume at least one character of the input string in
798 * order to prevent infinite loops.
799 */
800
801 if (offset < wlen) {
802 Tcl_AppendUnicodeToObj(resultPtr, wstring + offset, 1);
803 }
804 offset++;
805 } else {
806 offset += end;
807 if (start == end) {
808 /*
809 * We matched an empty string, which means we must go forward
810 * one more step so we don't match again at the same spot.
811 */
812
813 if (offset < wlen) {
814 Tcl_AppendUnicodeToObj(resultPtr, wstring + offset, 1);
815 }
816 offset++;
817 }
818 }
819 if (!all) {
820 break;
821 }
822 }
823
824 /*
825 * Copy the portion of the source string after the last match to the
826 * result variable.
827 */
828
829 regsubDone:
830 if (numMatches == 0) {
831 /*
832 * On zero matches, just ignore the offset, since it shouldn't matter
833 * to us in this case, and the user may have skewed it.
834 */
835
836 resultPtr = objv[1];
837 Tcl_IncrRefCount(resultPtr);
838 } else if (offset < wlen) {
839 Tcl_AppendUnicodeToObj(resultPtr, wstring + offset, wlen - offset);
840 }
841 if (objc == 4) {
842 if (Tcl_ObjSetVar2(interp, objv[3], NULL, resultPtr,
843 TCL_LEAVE_ERR_MSG) == NULL) {
844 result = TCL_ERROR;
845 } else {
846 /*
847 * Set the interpreter's object result to an integer object
848 * holding the number of matches.
849 */
850
851 Tcl_SetObjResult(interp, Tcl_NewIntObj(numMatches));
852 }
853 } else {
854 /*
855 * No varname supplied, so just return the modified string.
856 */
857
858 Tcl_SetObjResult(interp, resultPtr);
859 }
860
861 done:
862 if (objPtr && (objv[1] == objv[0])) {
863 Tcl_DecrRefCount(objPtr);
864 }
865 if (subPtr && (objv[2] == objv[0])) {
866 Tcl_DecrRefCount(subPtr);
867 }
868 if (resultPtr) {
869 Tcl_DecrRefCount(resultPtr);
870 }
871 return result;
872 }
873
874 /*
875 *----------------------------------------------------------------------
876 *
877 * Tcl_RenameObjCmd --
878 *
879 * This procedure is invoked to process the "rename" Tcl command. See the
880 * user documentation for details on what it does.
881 *
882 * Results:
883 * A standard Tcl object result.
884 *
885 * Side effects:
886 * See the user documentation.
887 *
888 *----------------------------------------------------------------------
889 */
890
891 int
892 Tcl_RenameObjCmd(
893 ClientData dummy, /* Arbitrary value passed to the command. */
894 Tcl_Interp *interp, /* Current interpreter. */
895 int objc, /* Number of arguments. */
896 Tcl_Obj *const objv[]) /* Argument objects. */
897 {
898 const char *oldName, *newName;
899
900 if (objc != 3) {
901 Tcl_WrongNumArgs(interp, 1, objv, "oldName newName");
902 return TCL_ERROR;
903 }
904
905 oldName = TclGetString(objv[1]);
906 newName = TclGetString(objv[2]);
907 return TclRenameCommand(interp, oldName, newName);
908 }
909
910 /*
911 *----------------------------------------------------------------------
912 *
913 * Tcl_ReturnObjCmd --
914 *
915 * This object-based procedure is invoked to process the "return" Tcl
916 * command. See the user documentation for details on what it does.
917 *
918 * Results:
919 * A standard Tcl object result.
920 *
921 * Side effects:
922 * See the user documentation.
923 *
924 *----------------------------------------------------------------------
925 */
926
927 int
928 Tcl_ReturnObjCmd(
929 ClientData dummy, /* Not used. */
930 Tcl_Interp *interp, /* Current interpreter. */
931 int objc, /* Number of arguments. */
932 Tcl_Obj *const objv[]) /* Argument objects. */
933 {
934 int code, level;
935 Tcl_Obj *returnOpts;
936
937 /*
938 * General syntax: [return ?-option value ...? ?result?]
939 * An even number of words means an explicit result argument is present.
940 */
941
942 int explicitResult = (0 == (objc % 2));
943 int numOptionWords = objc - 1 - explicitResult;
944
945 if (TCL_ERROR == TclMergeReturnOptions(interp, numOptionWords, objv+1,
946 &returnOpts, &code, &level)) {
947 return TCL_ERROR;
948 }
949
950 code = TclProcessReturn(interp, code, level, returnOpts);
951 if (explicitResult) {
952 Tcl_SetObjResult(interp, objv[objc-1]);
953 }
954 return code;
955 }
956
957 /*
958 *----------------------------------------------------------------------
959 *
960 * Tcl_SourceObjCmd --
961 *
962 * This procedure is invoked to process the "source" Tcl command. See the
963 * user documentation for details on what it does.
964 *
965 * Results:
966 * A standard Tcl object result.
967 *
968 * Side effects:
969 * See the user documentation.
970 *
971 *----------------------------------------------------------------------
972 */
973
974 int
975 Tcl_SourceObjCmd(
976 ClientData dummy, /* Not used. */
977 Tcl_Interp *interp, /* Current interpreter. */
978 int objc, /* Number of arguments. */
979 Tcl_Obj *const objv[]) /* Argument objects. */
980 {
981 return Tcl_NRCallObjProc(interp, TclNRSourceObjCmd, dummy, objc, objv);
982 }
983
984 int
985 TclNRSourceObjCmd(
986 ClientData dummy, /* Not used. */
987 Tcl_Interp *interp, /* Current interpreter. */
988 int objc, /* Number of arguments. */
989 Tcl_Obj *const objv[]) /* Argument objects. */
990 {
991 const char *encodingName = NULL;
992 Tcl_Obj *fileName;
993
994 if (objc != 2 && objc !=4) {
995 Tcl_WrongNumArgs(interp, 1, objv, "?-encoding name? fileName");
996 return TCL_ERROR;
997 }
998
999 fileName = objv[objc-1];
1000
1001 if (objc == 4) {
1002 static const char *const options[] = {
1003 "-encoding", NULL
1004 };
1005 int index;
1006
1007 if (TCL_ERROR == Tcl_GetIndexFromObj(interp, objv[1], options,
1008 "option", TCL_EXACT, &index)) {
1009 return TCL_ERROR;
1010 }
1011 encodingName = TclGetString(objv[2]);
1012 }
1013
1014 return TclNREvalFile(interp, fileName, encodingName);
1015 }
1016
1017 /*
1018 *----------------------------------------------------------------------
1019 *
1020 * Tcl_SplitObjCmd --
1021 *
1022 * This procedure is invoked to process the "split" Tcl command. See the
1023 * user documentation for details on what it does.
1024 *
1025 * Results:
1026 * A standard Tcl result.
1027 *
1028 * Side effects:
1029 * See the user documentation.
1030 *
1031 *----------------------------------------------------------------------
1032 */
1033
1034 int
1035 Tcl_SplitObjCmd(
1036 ClientData dummy, /* Not used. */
1037 Tcl_Interp *interp, /* Current interpreter. */
1038 int objc, /* Number of arguments. */
1039 Tcl_Obj *const objv[]) /* Argument objects. */
1040 {
1041 Tcl_UniChar ch = 0;
1042 int len;
1043 const char *splitChars;
1044 const char *stringPtr;
1045 const char *end;
1046 int splitCharLen, stringLen;
1047 Tcl_Obj *listPtr, *objPtr;
1048
1049 if (objc == 2) {
1050 splitChars = " \n\t\r";
1051 splitCharLen = 4;
1052 } else if (objc == 3) {
1053 splitChars = TclGetStringFromObj(objv[2], &splitCharLen);
1054 } else {
1055 Tcl_WrongNumArgs(interp, 1, objv, "string ?splitChars?");
1056 return TCL_ERROR;
1057 }
1058
1059 stringPtr = TclGetStringFromObj(objv[1], &stringLen);
1060 end = stringPtr + stringLen;
1061 TclNewObj(listPtr);
1062
1063 if (stringLen == 0) {
1064 /*
1065 * Do nothing.
1066 */
1067 } else if (splitCharLen == 0) {
1068 Tcl_HashTable charReuseTable;
1069 Tcl_HashEntry *hPtr;
1070 int isNew;
1071
1072 /*
1073 * Handle the special case of splitting on every character.
1074 *
1075 * Uses a hash table to ensure that each kind of character has only
1076 * one Tcl_Obj instance (multiply-referenced) in the final list. This
1077 * is a *major* win when splitting on a long string (especially in the
1078 * megabyte range!) - DKF
1079 */
1080
1081 Tcl_InitHashTable(&charReuseTable, TCL_ONE_WORD_KEYS);
1082
1083 for ( ; stringPtr < end; stringPtr += len) {
1084 int ucs4;
1085
1086 len = TclUtfToUCS4(stringPtr, &ucs4);
1087 hPtr = Tcl_CreateHashEntry(&charReuseTable, INT2PTR(ucs4), &isNew);
1088 if (isNew) {
1089 TclNewStringObj(objPtr, stringPtr, len);
1090
1091 /*
1092 * Don't need to fiddle with refcount...
1093 */
1094
1095 Tcl_SetHashValue(hPtr, objPtr);
1096 } else {
1097 objPtr = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
1098 }
1099 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1100 }
1101 Tcl_DeleteHashTable(&charReuseTable);
1102
1103 } else if (splitCharLen == 1) {
1104 const char *p;
1105
1106 /*
1107 * Handle the special case of splitting on a single character. This is
1108 * only true for the one-char ASCII case, as one Unicode char is > 1
1109 * byte in length.
1110 */
1111
1112 while (*stringPtr && (p=strchr(stringPtr,(int)*splitChars)) != NULL) {
1113 objPtr = Tcl_NewStringObj(stringPtr, p - stringPtr);
1114 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1115 stringPtr = p + 1;
1116 }
1117 TclNewStringObj(objPtr, stringPtr, end - stringPtr);
1118 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1119 } else {
1120 const char *element, *p, *splitEnd;
1121 int splitLen;
1122 Tcl_UniChar splitChar = 0;
1123
1124 /*
1125 * Normal case: split on any of a given set of characters. Discard
1126 * instances of the split characters.
1127 */
1128
1129 splitEnd = splitChars + splitCharLen;
1130
1131 for (element = stringPtr; stringPtr < end; stringPtr += len) {
1132 len = TclUtfToUniChar(stringPtr, &ch);
1133 for (p = splitChars; p < splitEnd; p += splitLen) {
1134 splitLen = TclUtfToUniChar(p, &splitChar);
1135 if (ch == splitChar) {
1136 TclNewStringObj(objPtr, element, stringPtr - element);
1137 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1138 element = stringPtr + len;
1139 break;
1140 }
1141 }
1142 }
1143
1144 TclNewStringObj(objPtr, element, stringPtr - element);
1145 Tcl_ListObjAppendElement(NULL, listPtr, objPtr);
1146 }
1147 Tcl_SetObjResult(interp, listPtr);
1148 return TCL_OK;
1149 }
1150
1151 /*
1152 *----------------------------------------------------------------------
1153 *
1154 * StringFirstCmd --
1155 *
1156 * This procedure is invoked to process the "string first" Tcl command.
1157 * See the user documentation for details on what it does. Note that this
1158 * command only functions correctly on properly formed Tcl UTF strings.
1159 *
1160 * Results:
1161 * A standard Tcl result.
1162 *
1163 * Side effects:
1164 * See the user documentation.
1165 *
1166 *----------------------------------------------------------------------
1167 */
1168
1169 static int
1170 StringFirstCmd(
1171 ClientData dummy, /* Not used. */
1172 Tcl_Interp *interp, /* Current interpreter. */
1173 int objc, /* Number of arguments. */
1174 Tcl_Obj *const objv[]) /* Argument objects. */
1175 {
1176 Tcl_UniChar *needleStr, *haystackStr;
1177 int match, start, needleLen, haystackLen;
1178
1179 if (objc < 3 || objc > 4) {
1180 Tcl_WrongNumArgs(interp, 1, objv,
1181 "needleString haystackString ?startIndex?");
1182 return TCL_ERROR;
1183 }
1184
1185 /*
1186 * We are searching haystackStr for the sequence needleStr.
1187 */
1188
1189 match = -1;
1190 start = 0;
1191 haystackLen = -1;
1192
1193 needleStr = Tcl_GetUnicodeFromObj(objv[1], &needleLen);
1194 haystackStr = Tcl_GetUnicodeFromObj(objv[2], &haystackLen);
1195
1196 if (objc == 4) {
1197 /*
1198 * If a startIndex is specified, we will need to fast forward to that
1199 * point in the string before we think about a match.
1200 */
1201
1202 if (TclGetIntForIndexM(interp, objv[3], haystackLen-1,
1203 &start) != TCL_OK){
1204 return TCL_ERROR;
1205 }
1206
1207 /*
1208 * Reread to prevent shimmering problems.
1209 */
1210
1211 needleStr = Tcl_GetUnicodeFromObj(objv[1], &needleLen);
1212 haystackStr = Tcl_GetUnicodeFromObj(objv[2], &haystackLen);
1213
1214 if (start >= haystackLen) {
1215 goto str_first_done;
1216 } else if (start > 0) {
1217 haystackStr += start;
1218 haystackLen -= start;
1219 } else if (start < 0) {
1220 /*
1221 * Invalid start index mapped to string start; Bug #423581
1222 */
1223
1224 start = 0;
1225 }
1226 }
1227
1228 /*
1229 * If the length of the needle is more than the length of the haystack, it
1230 * cannot be contained in there so we can avoid searching. [Bug 2960021]
1231 */
1232
1233 if (needleLen > 0 && needleLen <= haystackLen) {
1234 Tcl_UniChar *p, *end;
1235
1236 end = haystackStr + haystackLen - needleLen + 1;
1237 for (p = haystackStr; p < end; p++) {
1238 /*
1239 * Scan forward to find the first character.
1240 */
1241
1242 if ((*p == *needleStr) && (TclUniCharNcmp(needleStr, p,
1243 needleLen) == 0)) {
1244 match = p - haystackStr;
1245 break;
1246 }
1247 }
1248 }
1249
1250 /*
1251 * Compute the character index of the matching string by counting the
1252 * number of characters before the match.
1253 */
1254
1255 if ((match != -1) && (objc == 4)) {
1256 match += start;
1257 }
1258
1259 str_first_done:
1260 Tcl_SetObjResult(interp, Tcl_NewIntObj(match));
1261 return TCL_OK;
1262 }
1263
1264 /*
1265 *----------------------------------------------------------------------
1266 *
1267 * StringLastCmd --
1268 *
1269 * This procedure is invoked to process the "string last" Tcl command.
1270 * See the user documentation for details on what it does. Note that this
1271 * command only functions correctly on properly formed Tcl UTF strings.
1272 *
1273 * Results:
1274 * A standard Tcl result.
1275 *
1276 * Side effects:
1277 * See the user documentation.
1278 *
1279 *----------------------------------------------------------------------
1280 */
1281
1282 static int
1283 StringLastCmd(
1284 ClientData dummy, /* Not used. */
1285 Tcl_Interp *interp, /* Current interpreter. */
1286 int objc, /* Number of arguments. */
1287 Tcl_Obj *const objv[]) /* Argument objects. */
1288 {
1289 Tcl_UniChar *needleStr, *haystackStr, *p;
1290 int match, start, needleLen, haystackLen;
1291
1292 if (objc < 3 || objc > 4) {
1293 Tcl_WrongNumArgs(interp, 1, objv,
1294 "needleString haystackString ?startIndex?");
1295 return TCL_ERROR;
1296 }
1297
1298 /*
1299 * We are searching haystackString for the sequence needleString.
1300 */
1301
1302 match = -1;
1303 start = 0;
1304 haystackLen = -1;
1305
1306 needleStr = Tcl_GetUnicodeFromObj(objv[1], &needleLen);
1307 haystackStr = Tcl_GetUnicodeFromObj(objv[2], &haystackLen);
1308
1309 if (objc == 4) {
1310 /*
1311 * If a startIndex is specified, we will need to restrict the string
1312 * range to that char index in the string
1313 */
1314
1315 if (TclGetIntForIndexM(interp, objv[3], haystackLen-1,
1316 &start) != TCL_OK){
1317 return TCL_ERROR;
1318 }
1319
1320 /*
1321 * Reread to prevent shimmering problems.
1322 */
1323
1324 needleStr = Tcl_GetUnicodeFromObj(objv[1], &needleLen);
1325 haystackStr = Tcl_GetUnicodeFromObj(objv[2], &haystackLen);
1326
1327 if (start < 0) {
1328 goto str_last_done;
1329 } else if (start < haystackLen) {
1330 p = haystackStr + start + 1 - needleLen;
1331 } else {
1332 p = haystackStr + haystackLen - needleLen;
1333 }
1334 } else {
1335 p = haystackStr + haystackLen - needleLen;
1336 }
1337
1338 /*
1339 * If the length of the needle is more than the length of the haystack, it
1340 * cannot be contained in there so we can avoid searching. [Bug 2960021]
1341 */
1342
1343 if (needleLen > 0 && needleLen <= haystackLen) {
1344 for (; p >= haystackStr; p--) {
1345 /*
1346 * Scan backwards to find the first character.
1347 */
1348
1349 if ((*p == *needleStr) && !memcmp(needleStr, p,
1350 sizeof(Tcl_UniChar) * (size_t)needleLen)) {
1351 match = p - haystackStr;
1352 break;
1353 }
1354 }
1355 }
1356
1357 str_last_done:
1358 Tcl_SetObjResult(interp, Tcl_NewIntObj(match));
1359 return TCL_OK;
1360 }
1361
1362 /*
1363 *----------------------------------------------------------------------
1364 *
1365 * StringIndexCmd --
1366 *
1367 * This procedure is invoked to process the "string index" Tcl command.
1368 * See the user documentation for details on what it does. Note that this
1369 * command only functions correctly on properly formed Tcl UTF strings.
1370 *
1371 * Results:
1372 * A standard Tcl result.
1373 *
1374 * Side effects:
1375 * See the user documentation.
1376 *
1377 *----------------------------------------------------------------------
1378 */
1379
1380 static int
1381 StringIndexCmd(
1382 ClientData dummy, /* Not used. */
1383 Tcl_Interp *interp, /* Current interpreter. */
1384 int objc, /* Number of arguments. */
1385 Tcl_Obj *const objv[]) /* Argument objects. */
1386 {
1387 int length, index;
1388
1389 if (objc != 3) {
1390 Tcl_WrongNumArgs(interp, 1, objv, "string charIndex");
1391 return TCL_ERROR;
1392 }
1393
1394 /*
1395 * Get the char length to calculate what 'end' means.
1396 */
1397
1398 length = Tcl_GetCharLength(objv[1]);
1399 if (TclGetIntForIndexM(interp, objv[2], length-1, &index) != TCL_OK) {
1400 return TCL_ERROR;
1401 }
1402
1403 if ((index >= 0) && (index < length)) {
1404 int ch = TclGetUCS4(objv[1], index);
1405
1406 /*
1407 * If we have a ByteArray object, we're careful to generate a new
1408 * bytearray for a result.
1409 */
1410
1411 if (TclIsPureByteArray(objv[1])) {
1412 unsigned char uch = UCHAR(ch);
1413
1414 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(&uch, 1));
1415 } else {
1416 char buf[8] = "";
1417
1418 length = TclUCS4ToUtf(ch, buf);
1419 Tcl_SetObjResult(interp, Tcl_NewStringObj(buf, length));
1420 }
1421 }
1422 return TCL_OK;
1423 }
1424
1425 /*
1426 *----------------------------------------------------------------------
1427 *
1428 * StringIsCmd --
1429 *
1430 * This procedure is invoked to process the "string is" Tcl command. See
1431 * the user documentation for details on what it does. Note that this
1432 * command only functions correctly on properly formed Tcl UTF strings.
1433 *
1434 * Results:
1435 * A standard Tcl result.
1436 *
1437 * Side effects:
1438 * See the user documentation.
1439 *
1440 *----------------------------------------------------------------------
1441 */
1442
1443 static int
1444 StringIsCmd(
1445 ClientData dummy, /* Not used. */
1446 Tcl_Interp *interp, /* Current interpreter. */
1447 int objc, /* Number of arguments. */
1448 Tcl_Obj *const objv[]) /* Argument objects. */
1449 {
1450 const char *string1, *end, *stop;
1451 int (*chcomp)(int) = NULL; /* The UniChar comparison function. */
1452 int i, failat = 0, result = 1, strict = 0, index, length1, length2;
1453 Tcl_Obj *objPtr, *failVarObj = NULL;
1454 Tcl_WideInt w;
1455
1456 static const char *const isClasses[] = {
1457 "alnum", "alpha", "ascii", "control",
1458 "boolean", "digit", "double", "entier",
1459 "false", "graph", "integer", "list",
1460 "lower", "print", "punct", "space",
1461 "true", "upper", "wideinteger", "wordchar",
1462 "xdigit", NULL
1463 };
1464 enum isClasses {
1465 STR_IS_ALNUM, STR_IS_ALPHA, STR_IS_ASCII, STR_IS_CONTROL,
1466 STR_IS_BOOL, STR_IS_DIGIT, STR_IS_DOUBLE, STR_IS_ENTIER,
1467 STR_IS_FALSE, STR_IS_GRAPH, STR_IS_INT, STR_IS_LIST,
1468 STR_IS_LOWER, STR_IS_PRINT, STR_IS_PUNCT, STR_IS_SPACE,
1469 STR_IS_TRUE, STR_IS_UPPER, STR_IS_WIDE, STR_IS_WORD,
1470 STR_IS_XDIGIT
1471 };
1472 static const char *const isOptions[] = {
1473 "-strict", "-failindex", NULL
1474 };
1475 enum isOptions {
1476 OPT_STRICT, OPT_FAILIDX
1477 };
1478
1479 if (objc < 3 || objc > 6) {
1480 Tcl_WrongNumArgs(interp, 1, objv,
1481 "class ?-strict? ?-failindex var? str");
1482 return TCL_ERROR;
1483 }
1484 if (Tcl_GetIndexFromObj(interp, objv[1], isClasses, "class", 0,
1485 &index) != TCL_OK) {
1486 return TCL_ERROR;
1487 }
1488
1489 if (objc != 3) {
1490 for (i = 2; i < objc-1; i++) {
1491 int idx2;
1492
1493 if (Tcl_GetIndexFromObj(interp, objv[i], isOptions, "option", 0,
1494 &idx2) != TCL_OK) {
1495 return TCL_ERROR;
1496 }
1497 switch ((enum isOptions) idx2) {
1498 case OPT_STRICT:
1499 strict = 1;
1500 break;
1501 case OPT_FAILIDX:
1502 if (i+1 >= objc-1) {
1503 Tcl_WrongNumArgs(interp, 2, objv,
1504 "?-strict? ?-failindex var? str");
1505 return TCL_ERROR;
1506 }
1507 failVarObj = objv[++i];
1508 break;
1509 }
1510 }
1511 }
1512
1513 /*
1514 * We get the objPtr so that we can short-cut for some classes by checking
1515 * the object type (int and double), but we need the string otherwise,
1516 * because we don't want any conversion of type occurring (as, for example,
1517 * Tcl_Get*FromObj would do).
1518 */
1519
1520 objPtr = objv[objc-1];
1521
1522 /*
1523 * When entering here, result == 1 and failat == 0.
1524 */
1525
1526 switch ((enum isClasses) index) {
1527 case STR_IS_ALNUM:
1528 chcomp = Tcl_UniCharIsAlnum;
1529 break;
1530 case STR_IS_ALPHA:
1531 chcomp = Tcl_UniCharIsAlpha;
1532 break;
1533 case STR_IS_ASCII:
1534 chcomp = UniCharIsAscii;
1535 break;
1536 case STR_IS_BOOL:
1537 case STR_IS_TRUE:
1538 case STR_IS_FALSE:
1539 if ((objPtr->typePtr != &tclBooleanType)
1540 && (TCL_OK != TclSetBooleanFromAny(NULL, objPtr))) {
1541 if (strict) {
1542 result = 0;
1543 } else {
1544 string1 = TclGetStringFromObj(objPtr, &length1);
1545 result = length1 == 0;
1546 }
1547 } else if (((index == STR_IS_TRUE) &&
1548 objPtr->internalRep.longValue == 0)
1549 || ((index == STR_IS_FALSE) &&
1550 objPtr->internalRep.longValue != 0)) {
1551 result = 0;
1552 }
1553 break;
1554 case STR_IS_CONTROL:
1555 chcomp = Tcl_UniCharIsControl;
1556 break;
1557 case STR_IS_DIGIT:
1558 chcomp = Tcl_UniCharIsDigit;
1559 break;
1560 case STR_IS_DOUBLE: {
1561 if ((objPtr->typePtr == &tclDoubleType) ||
1562 (objPtr->typePtr == &tclIntType) ||
1563 #ifndef TCL_WIDE_INT_IS_LONG
1564 (objPtr->typePtr == &tclWideIntType) ||
1565 #endif
1566 (objPtr->typePtr == &tclBignumType)) {
1567 break;
1568 }
1569 string1 = TclGetStringFromObj(objPtr, &length1);
1570 if (length1 == 0) {
1571 if (strict) {
1572 result = 0;
1573 }
1574 goto str_is_done;
1575 }
1576 end = string1 + length1;
1577 if (TclParseNumber(NULL, objPtr, NULL, NULL, -1,
1578 (const char **) &stop, 0) != TCL_OK) {
1579 result = 0;
1580 failat = 0;
1581 } else {
1582 failat = stop - string1;
1583 if (stop < end) {
1584 result = 0;
1585 TclFreeIntRep(objPtr);
1586 }
1587 }
1588 break;
1589 }
1590 case STR_IS_GRAPH:
1591 chcomp = Tcl_UniCharIsGraph;
1592 break;
1593 case STR_IS_INT:
1594 if (TCL_OK == TclGetIntFromObj(NULL, objPtr, &i)) {
1595 break;
1596 }
1597 goto failedIntParse;
1598 case STR_IS_ENTIER:
1599 if ((objPtr->typePtr == &tclIntType) ||
1600 #ifndef TCL_WIDE_INT_IS_LONG
1601 (objPtr->typePtr == &tclWideIntType) ||
1602 #endif
1603 (objPtr->typePtr == &tclBignumType)) {
1604 break;
1605 }
1606 string1 = TclGetStringFromObj(objPtr, &length1);
1607 if (length1 == 0) {
1608 if (strict) {
1609 result = 0;
1610 }
1611 goto str_is_done;
1612 }
1613 end = string1 + length1;
1614 if (TclParseNumber(NULL, objPtr, NULL, NULL, -1,
1615 (const char **) &stop, TCL_PARSE_INTEGER_ONLY) == TCL_OK) {
1616 if (stop == end) {
1617 /*
1618 * Entire string parses as an integer.
1619 */
1620
1621 break;
1622 } else {
1623 /*
1624 * Some prefix parsed as an integer, but not the whole string,
1625 * so return failure index as the point where parsing stopped.
1626 * Clear out the internal rep, since keeping it would leave
1627 * *objPtr in an inconsistent state.
1628 */
1629
1630 result = 0;
1631 failat = stop - string1;
1632 TclFreeIntRep(objPtr);
1633 }
1634 } else {
1635 /*
1636 * No prefix is a valid integer. Fail at beginning.
1637 */
1638
1639 result = 0;
1640 failat = 0;
1641 }
1642 break;
1643 case STR_IS_WIDE:
1644 if (TCL_OK == TclGetWideIntFromObj(NULL, objPtr, &w)) {
1645 break;
1646 }
1647
1648 failedIntParse:
1649 string1 = TclGetStringFromObj(objPtr, &length1);
1650 if (length1 == 0) {
1651 if (strict) {
1652 result = 0;
1653 }
1654 goto str_is_done;
1655 }
1656 result = 0;
1657 if (failVarObj == NULL) {
1658 /*
1659 * Don't bother computing the failure point if we're not going to
1660 * return it.
1661 */
1662
1663 break;
1664 }
1665 end = string1 + length1;
1666 if (TclParseNumber(NULL, objPtr, NULL, NULL, -1,
1667 (const char **) &stop, TCL_PARSE_INTEGER_ONLY) == TCL_OK) {
1668 if (stop == end) {
1669 /*
1670 * Entire string parses as an integer, but rejected by
1671 * Tcl_Get(Wide)IntFromObj() so we must have overflowed the
1672 * target type, and our convention is to return failure at
1673 * index -1 in that situation.
1674 */
1675
1676 failat = -1;
1677 } else {
1678 /*
1679 * Some prefix parsed as an integer, but not the whole string,
1680 * so return failure index as the point where parsing stopped.
1681 * Clear out the internal rep, since keeping it would leave
1682 * *objPtr in an inconsistent state.
1683 */
1684
1685 failat = stop - string1;
1686 TclFreeIntRep(objPtr);
1687 }
1688 } else {
1689 /*
1690 * No prefix is a valid integer. Fail at beginning.
1691 */
1692
1693 failat = 0;
1694 }
1695 break;
1696 case STR_IS_LIST:
1697 /*
1698 * We ignore the strictness here, since empty strings are always
1699 * well-formed lists.
1700 */
1701
1702 if (TCL_OK == TclListObjLength(NULL, objPtr, &length2)) {
1703 break;
1704 }
1705
1706 if (failVarObj != NULL) {
1707 /*
1708 * Need to figure out where the list parsing failed, which is
1709 * fairly expensive. This is adapted from the core of
1710 * SetListFromAny().
1711 */
1712
1713 const char *elemStart, *nextElem;
1714 int lenRemain, elemSize;
1715 const char *p;
1716
1717 string1 = TclGetStringFromObj(objPtr, &length1);
1718 end = string1 + length1;
1719 failat = -1;
1720 for (p=string1, lenRemain=length1; lenRemain > 0;
1721 p=nextElem, lenRemain=end-nextElem) {
1722 if (TCL_ERROR == TclFindElement(NULL, p, lenRemain,
1723 &elemStart, &nextElem, &elemSize, NULL)) {
1724 Tcl_Obj *tmpStr;
1725
1726 /*
1727 * This is the simplest way of getting the number of
1728 * characters parsed. Note that this is not the same as
1729 * the number of bytes when parsing strings with non-ASCII
1730 * characters in them.
1731 *
1732 * Skip leading spaces first. This is only really an issue
1733 * if it is the first "element" that has the failure.
1734 */
1735
1736 while (TclIsSpaceProcM(*p)) {
1737 p++;
1738 }
1739 TclNewStringObj(tmpStr, string1, p-string1);
1740 failat = Tcl_GetCharLength(tmpStr);
1741 TclDecrRefCount(tmpStr);
1742 break;
1743 }
1744 }
1745 }
1746 result = 0;
1747 break;
1748 case STR_IS_LOWER:
1749 chcomp = Tcl_UniCharIsLower;
1750 break;
1751 case STR_IS_PRINT:
1752 chcomp = Tcl_UniCharIsPrint;
1753 break;
1754 case STR_IS_PUNCT:
1755 chcomp = Tcl_UniCharIsPunct;
1756 break;
1757 case STR_IS_SPACE:
1758 chcomp = Tcl_UniCharIsSpace;
1759 break;
1760 case STR_IS_UPPER:
1761 chcomp = Tcl_UniCharIsUpper;
1762 break;
1763 case STR_IS_WORD:
1764 chcomp = Tcl_UniCharIsWordChar;
1765 break;
1766 case STR_IS_XDIGIT:
1767 chcomp = UniCharIsHexDigit;
1768 break;
1769 }
1770
1771 if (chcomp != NULL) {
1772 string1 = TclGetStringFromObj(objPtr, &length1);
1773 if (length1 == 0) {
1774 if (strict) {
1775 result = 0;
1776 }
1777 goto str_is_done;
1778 }
1779 end = string1 + length1;
1780 for (; string1 < end; string1 += length2, failat++) {
1781 int ucs4;
1782
1783 length2 = TclUtfToUCS4(string1, &ucs4);
1784 if (!chcomp(ucs4)) {
1785 result = 0;
1786 break;
1787 }
1788 }
1789 }
1790
1791 /*
1792 * Only set the failVarObj when we will return 0 and we have indicated a
1793 * valid fail index (>= 0).
1794 */
1795
1796 str_is_done:
1797 if ((result == 0) && (failVarObj != NULL) &&
1798 Tcl_ObjSetVar2(interp, failVarObj, NULL, Tcl_NewIntObj(failat),
1799 TCL_LEAVE_ERR_MSG) == NULL) {
1800 return TCL_ERROR;
1801 }
1802 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(result));
1803 return TCL_OK;
1804 }
1805
1806 static int
1807 UniCharIsAscii(
1808 int character)
1809 {
1810 return (character >= 0) && (character < 0x80);
1811 }
1812
1813 static int
1814 UniCharIsHexDigit(
1815 int character)
1816 {
1817 return (character >= 0) && (character < 0x80) && isxdigit(character);
1818 }
1819
1820 /*
1821 *----------------------------------------------------------------------
1822 *
1823 * StringMapCmd --
1824 *
1825 * This procedure is invoked to process the "string map" Tcl command. See
1826 * the user documentation for details on what it does. Note that this
1827 * command only functions correctly on properly formed Tcl UTF strings.
1828 *
1829 * Results:
1830 * A standard Tcl result.
1831 *
1832 * Side effects:
1833 * See the user documentation.
1834 *
1835 *----------------------------------------------------------------------
1836 */
1837
1838 static int
1839 StringMapCmd(
1840 ClientData dummy, /* Not used. */
1841 Tcl_Interp *interp, /* Current interpreter. */
1842 int objc, /* Number of arguments. */
1843 Tcl_Obj *const objv[]) /* Argument objects. */
1844 {
1845 int length1, length2, mapElemc, index;
1846 int nocase = 0, mapWithDict = 0, copySource = 0;
1847 Tcl_Obj **mapElemv, *sourceObj, *resultPtr;
1848 Tcl_UniChar *ustring1, *ustring2, *p, *end;
1849 int (*strCmpFn)(const Tcl_UniChar*, const Tcl_UniChar*, unsigned long);
1850
1851 if (objc < 3 || objc > 4) {
1852 Tcl_WrongNumArgs(interp, 1, objv, "?-nocase? charMap string");
1853 return TCL_ERROR;
1854 }
1855
1856 if (objc == 4) {
1857 const char *string = TclGetStringFromObj(objv[1], &length2);
1858
1859 if ((length2 > 1) &&
1860 strncmp(string, "-nocase", length2) == 0) {
1861 nocase = 1;
1862 } else {
1863 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1864 "bad option \"%s\": must be -nocase", string));
1865 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "INDEX", "option",
1866 string, (char *)NULL);
1867 return TCL_ERROR;
1868 }
1869 }
1870
1871 /*
1872 * This test is tricky, but has to be that way or you get other strange
1873 * inconsistencies (see test string-10.20 for illustration why!)
1874 */
1875
1876 if (objv[objc-2]->typePtr == &tclDictType && objv[objc-2]->bytes == NULL){
1877 int i, done;
1878 Tcl_DictSearch search;
1879
1880 /*
1881 * We know the type exactly, so all dict operations will succeed for
1882 * sure. This shortens this code quite a bit.
1883 */
1884
1885 Tcl_DictObjSize(interp, objv[objc-2], &mapElemc);
1886 if (mapElemc == 0) {
1887 /*
1888 * Empty charMap, just return whatever string was given.
1889 */
1890
1891 Tcl_SetObjResult(interp, objv[objc-1]);
1892 return TCL_OK;
1893 }
1894
1895 mapElemc *= 2;
1896 mapWithDict = 1;
1897
1898 /*
1899 * Copy the dictionary out into an array; that's the easiest way to
1900 * adapt this code...
1901 */
1902
1903 mapElemv = (Tcl_Obj **)TclStackAlloc(interp, sizeof(Tcl_Obj *) * mapElemc);
1904 Tcl_DictObjFirst(interp, objv[objc-2], &search, mapElemv+0,
1905 mapElemv+1, &done);
1906 for (i=2 ; i<mapElemc ; i+=2) {
1907 Tcl_DictObjNext(&search, mapElemv+i, mapElemv+i+1, &done);
1908 }
1909 Tcl_DictObjDone(&search);
1910 } else {
1911 if (TclListObjGetElements(interp, objv[objc-2], &mapElemc,
1912 &mapElemv) != TCL_OK) {
1913 return TCL_ERROR;
1914 }
1915 if (mapElemc == 0) {
1916 /*
1917 * empty charMap, just return whatever string was given.
1918 */
1919
1920 Tcl_SetObjResult(interp, objv[objc-1]);
1921 return TCL_OK;
1922 } else if (mapElemc & 1) {
1923 /*
1924 * The charMap must be an even number of key/value items.
1925 */
1926
1927 Tcl_SetObjResult(interp,
1928 Tcl_NewStringObj("char map list unbalanced", -1));
1929 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "MAP",
1930 "UNBALANCED", (char *)NULL);
1931 return TCL_ERROR;
1932 }
1933 }
1934
1935 /*
1936 * Take a copy of the source string object if it is the same as the map
1937 * string to cut out nasty sharing crashes. [Bug 1018562]
1938 */
1939
1940 if (objv[objc-2] == objv[objc-1]) {
1941 sourceObj = Tcl_DuplicateObj(objv[objc-1]);
1942 copySource = 1;
1943 } else {
1944 sourceObj = objv[objc-1];
1945 }
1946 ustring1 = Tcl_GetUnicodeFromObj(sourceObj, &length1);
1947 if (length1 == 0) {
1948 /*
1949 * Empty input string, just stop now.
1950 */
1951
1952 goto done;
1953 }
1954 end = ustring1 + length1;
1955
1956 strCmpFn = nocase ? Tcl_UniCharNcasecmp : Tcl_UniCharNcmp;
1957
1958 /*
1959 * Force result to be Unicode
1960 */
1961
1962 resultPtr = Tcl_NewUnicodeObj(ustring1, 0);
1963
1964 if (mapElemc == 2) {
1965 /*
1966 * Special case for one map pair which avoids the extra for loop and
1967 * extra calls to get Unicode data. The algorithm is otherwise
1968 * identical to the multi-pair case. This will be >30% faster on
1969 * larger strings.
1970 */
1971
1972 int mapLen;
1973 Tcl_UniChar *mapString, u2lc;
1974
1975 ustring2 = Tcl_GetUnicodeFromObj(mapElemv[0], &length2);
1976 p = ustring1;
1977 if ((length2 > length1) || (length2 == 0)) {
1978 /*
1979 * Match string is either longer than input or empty.
1980 */
1981
1982 ustring1 = end;
1983 } else {
1984 mapString = Tcl_GetUnicodeFromObj(mapElemv[1], &mapLen);
1985 u2lc = (nocase ? Tcl_UniCharToLower(*ustring2) : 0);
1986 for (; ustring1 < end; ustring1++) {
1987 if (((*ustring1 == *ustring2) ||
1988 (nocase&&Tcl_UniCharToLower(*ustring1)==u2lc)) &&
1989 (length2==1 || strCmpFn(ustring1, ustring2,
1990 (unsigned long) length2) == 0)) {
1991 if (p != ustring1) {
1992 Tcl_AppendUnicodeToObj(resultPtr, p, ustring1-p);
1993 p = ustring1 + length2;
1994 } else {
1995 p += length2;
1996 }
1997 ustring1 = p - 1;
1998
1999 Tcl_AppendUnicodeToObj(resultPtr, mapString, mapLen);
2000 }
2001 }
2002 }
2003 } else {
2004 Tcl_UniChar **mapStrings, *u2lc = NULL;
2005 int *mapLens;
2006
2007 /*
2008 * Precompute pointers to the Unicode string and length. This saves us
2009 * repeated function calls later, significantly speeding up the
2010 * algorithm. We only need the lowercase first char in the nocase
2011 * case.
2012 */
2013
2014 mapStrings = (Tcl_UniChar **)TclStackAlloc(interp, mapElemc*2*sizeof(Tcl_UniChar *));
2015 mapLens = (int *)TclStackAlloc(interp, mapElemc * 2 * sizeof(int));
2016 if (nocase) {
2017 u2lc = (Tcl_UniChar *)TclStackAlloc(interp, mapElemc * sizeof(Tcl_UniChar));
2018 }
2019 for (index = 0; index < mapElemc; index++) {
2020 mapStrings[index] = Tcl_GetUnicodeFromObj(mapElemv[index],
2021 mapLens+index);
2022 if (nocase && ((index % 2) == 0)) {
2023 u2lc[index/2] = Tcl_UniCharToLower(*mapStrings[index]);
2024 }
2025 }
2026 for (p = ustring1; ustring1 < end; ustring1++) {
2027 for (index = 0; index < mapElemc; index += 2) {
2028 /*
2029 * Get the key string to match on.
2030 */
2031
2032 ustring2 = mapStrings[index];
2033 length2 = mapLens[index];
2034 if ((length2 > 0) && ((*ustring1 == *ustring2) || (nocase &&
2035 (Tcl_UniCharToLower(*ustring1) == u2lc[index/2]))) &&
2036 /* Restrict max compare length. */
2037 (end-ustring1 >= length2) && ((length2 == 1) ||
2038 !strCmpFn(ustring2, ustring1, length2))) {
2039 if (p != ustring1) {
2040 /*
2041 * Put the skipped chars onto the result first.
2042 */
2043
2044 Tcl_AppendUnicodeToObj(resultPtr, p, ustring1-p);
2045 p = ustring1 + length2;
2046 } else {
2047 p += length2;
2048 }
2049
2050 /*
2051 * Adjust len to be full length of matched string.
2052 */
2053
2054 ustring1 = p - 1;
2055
2056 /*
2057 * Append the map value to the Unicode string.
2058 */
2059
2060 Tcl_AppendUnicodeToObj(resultPtr,
2061 mapStrings[index+1], mapLens[index+1]);
2062 break;
2063 }
2064 }
2065 }
2066 if (nocase) {
2067 TclStackFree(interp, u2lc);
2068 }
2069 TclStackFree(interp, mapLens);
2070 TclStackFree(interp, mapStrings);
2071 }
2072 if (p != ustring1) {
2073 /*
2074 * Put the rest of the unmapped chars onto result.
2075 */
2076
2077 Tcl_AppendUnicodeToObj(resultPtr, p, ustring1 - p);
2078 }
2079 Tcl_SetObjResult(interp, resultPtr);
2080 done:
2081 if (mapWithDict) {
2082 TclStackFree(interp, mapElemv);
2083 }
2084 if (copySource) {
2085 Tcl_DecrRefCount(sourceObj);
2086 }
2087 return TCL_OK;
2088 }
2089
2090 /*
2091 *----------------------------------------------------------------------
2092 *
2093 * StringMatchCmd --
2094 *
2095 * This procedure is invoked to process the "string match" Tcl command.
2096 * See the user documentation for details on what it does. Note that this
2097 * command only functions correctly on properly formed Tcl UTF strings.
2098 *
2099 * Results:
2100 * A standard Tcl result.
2101 *
2102 * Side effects:
2103 * See the user documentation.
2104 *
2105 *----------------------------------------------------------------------
2106 */
2107
2108 static int
2109 StringMatchCmd(
2110 ClientData dummy, /* Not used. */
2111 Tcl_Interp *interp, /* Current interpreter. */
2112 int objc, /* Number of arguments. */
2113 Tcl_Obj *const objv[]) /* Argument objects. */
2114 {
2115 int nocase = 0;
2116
2117 if (objc < 3 || objc > 4) {
2118 Tcl_WrongNumArgs(interp, 1, objv, "?-nocase? pattern string");
2119 return TCL_ERROR;
2120 }
2121
2122 if (objc == 4) {
2123 int length;
2124 const char *string = TclGetStringFromObj(objv[1], &length);
2125
2126 if ((length > 1) &&
2127 strncmp(string, "-nocase", length) == 0) {
2128 nocase = TCL_MATCH_NOCASE;
2129 } else {
2130 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2131 "bad option \"%s\": must be -nocase", string));
2132 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "INDEX", "option",
2133 string, (char *)NULL);
2134 return TCL_ERROR;
2135 }
2136 }
2137 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(
2138 TclStringMatchObj(objv[objc-1], objv[objc-2], nocase)));
2139 return TCL_OK;
2140 }
2141
2142 /*
2143 *----------------------------------------------------------------------
2144 *
2145 * StringRangeCmd --
2146 *
2147 * This procedure is invoked to process the "string range" Tcl command.
2148 * See the user documentation for details on what it does. Note that this
2149 * command only functions correctly on properly formed Tcl UTF strings.
2150 *
2151 * Results:
2152 * A standard Tcl result.
2153 *
2154 * Side effects:
2155 * See the user documentation.
2156 *
2157 *----------------------------------------------------------------------
2158 */
2159
2160 static int
2161 StringRangeCmd(
2162 ClientData dummy, /* Not used. */
2163 Tcl_Interp *interp, /* Current interpreter. */
2164 int objc, /* Number of arguments. */
2165 Tcl_Obj *const objv[]) /* Argument objects. */
2166 {
2167 int length, first, last;
2168
2169 if (objc != 4) {
2170 Tcl_WrongNumArgs(interp, 1, objv, "string first last");
2171 return TCL_ERROR;
2172 }
2173
2174 /*
2175 * Get the length in actual characters; Then reduce it by one because
2176 * 'end' refers to the last character, not one past it.
2177 */
2178
2179 length = Tcl_GetCharLength(objv[1]) - 1;
2180
2181 if (TclGetIntForIndexM(interp, objv[2], length, &first) != TCL_OK ||
2182 TclGetIntForIndexM(interp, objv[3], length, &last) != TCL_OK) {
2183 return TCL_ERROR;
2184 }
2185
2186 if (first < 0) {
2187 first = 0;
2188 }
2189 if (last >= length) {
2190 last = length;
2191 }
2192 if (last >= first) {
2193 Tcl_SetObjResult(interp, Tcl_GetRange(objv[1], first, last));
2194 }
2195 return TCL_OK;
2196 }
2197
2198 /*
2199 *----------------------------------------------------------------------
2200 *
2201 * StringReptCmd --
2202 *
2203 * This procedure is invoked to process the "string repeat" Tcl command.
2204 * See the user documentation for details on what it does. Note that this
2205 * command only functions correctly on properly formed Tcl UTF strings.
2206 *
2207 * Results:
2208 * A standard Tcl result.
2209 *
2210 * Side effects:
2211 * See the user documentation.
2212 *
2213 *----------------------------------------------------------------------
2214 */
2215
2216 static int
2217 StringReptCmd(
2218 ClientData dummy, /* Not used. */
2219 Tcl_Interp *interp, /* Current interpreter. */
2220 int objc, /* Number of arguments. */
2221 Tcl_Obj *const objv[]) /* Argument objects. */
2222 {
2223 const char *string1;
2224 char *string2;
2225 int count, index, length1, length2;
2226 Tcl_Obj *resultPtr;
2227
2228 if (objc != 3) {
2229 Tcl_WrongNumArgs(interp, 1, objv, "string count");
2230 return TCL_ERROR;
2231 }
2232
2233 if (TclGetIntFromObj(interp, objv[2], &count) != TCL_OK) {
2234 return TCL_ERROR;
2235 }
2236
2237 /*
2238 * Check for cases that allow us to skip copying stuff.
2239 */
2240
2241 if (count == 1) {
2242 Tcl_SetObjResult(interp, objv[1]);
2243 goto done;
2244 } else if (count < 1) {
2245 goto done;
2246 }
2247 string1 = TclGetStringFromObj(objv[1], &length1);
2248 if (length1 <= 0) {
2249 goto done;
2250 }
2251
2252 /*
2253 * Only build up a string that has data. Instead of building it up with
2254 * repeated appends, we just allocate the necessary space once and copy
2255 * the string value in.
2256 *
2257 * We have to worry about overflow [Bugs 714106, 2561746].
2258 * At this point we know 1 <= length1 <= INT_MAX and 2 <= count <= INT_MAX.
2259 * We need to keep 2 <= length2 <= INT_MAX.
2260 */
2261
2262 if (count > INT_MAX/length1) {
2263 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2264 "result exceeds max size for a Tcl value (%d bytes)",
2265 INT_MAX));
2266 Tcl_SetErrorCode(interp, "TCL", "MEMORY", (char *)NULL);
2267 return TCL_ERROR;
2268 }
2269 length2 = length1 * count;
2270
2271 /*
2272 * Include space for the NUL.
2273 */
2274
2275 string2 = (char *)attemptckalloc(length2 + 1);
2276 if (string2 == NULL) {
2277 /*
2278 * Alloc failed. Note that in this case we try to do an error message
2279 * since this is a case that's most likely when the alloc is large and
2280 * that's easy to do with this API. Note that if we fail allocating a
2281 * short string, this will likely keel over too (and fatally).
2282 */
2283
2284 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2285 "string size overflow, out of memory allocating %u bytes",
2286 length2 + 1));
2287 Tcl_SetErrorCode(interp, "TCL", "MEMORY", (char *)NULL);
2288 return TCL_ERROR;
2289 }
2290 for (index = 0; index < count; index++) {
2291 memcpy(string2 + (length1 * index), string1, length1);
2292 }
2293 string2[length2] = '\0';
2294
2295 /*
2296 * We have to directly assign this instead of using Tcl_SetStringObj (and
2297 * indirectly TclInitStringRep) because that makes another copy of the
2298 * data.
2299 */
2300
2301 TclNewObj(resultPtr);
2302 resultPtr->bytes = string2;
2303 resultPtr->length = length2;
2304 Tcl_SetObjResult(interp, resultPtr);
2305
2306 done:
2307 return TCL_OK;
2308 }
2309
2310 /*
2311 *----------------------------------------------------------------------
2312 *
2313 * StringRplcCmd --
2314 *
2315 * This procedure is invoked to process the "string replace" Tcl command.
2316 * See the user documentation for details on what it does. Note that this
2317 * command only functions correctly on properly formed Tcl UTF strings.
2318 *
2319 * Results:
2320 * A standard Tcl result.
2321 *
2322 * Side effects:
2323 * See the user documentation.
2324 *
2325 *----------------------------------------------------------------------
2326 */
2327
2328 static int
2329 StringRplcCmd(
2330 ClientData dummy, /* Not used. */
2331 Tcl_Interp *interp, /* Current interpreter. */
2332 int objc, /* Number of arguments. */
2333 Tcl_Obj *const objv[]) /* Argument objects. */
2334 {
2335 Tcl_UniChar *ustring;
2336 int first, last, length, end;
2337
2338 if (objc < 4 || objc > 5) {
2339 Tcl_WrongNumArgs(interp, 1, objv, "string first last ?string?");
2340 return TCL_ERROR;
2341 }
2342
2343 ustring = Tcl_GetUnicodeFromObj(objv[1], &length);
2344 end = length - 1;
2345
2346 if (TclGetIntForIndexM(interp, objv[2], end, &first) != TCL_OK ||
2347 TclGetIntForIndexM(interp, objv[3], end, &last) != TCL_OK){
2348 return TCL_ERROR;
2349 }
2350
2351 /*
2352 * The following test screens out most empty substrings as
2353 * candidates for replacement. When they are detected, no
2354 * replacement is done, and the result is the original string,
2355 */
2356 if ((last < 0) || /* Range ends before start of string */
2357 (first > end) || /* Range begins after end of string */
2358 (last < first)) { /* Range begins after it starts */
2359
2360 /*
2361 * BUT!!! when (end < 0) -- an empty original string -- we can
2362 * have (first <= end < 0 <= last) and an empty string is permitted
2363 * to be replaced.
2364 */
2365 Tcl_SetObjResult(interp, objv[1]);
2366 } else {
2367 Tcl_Obj *resultPtr;
2368
2369 /*
2370 * We are re-fetching in case the string argument is same value as
2371 * an index argument, and shimmering cost us our ustring.
2372 */
2373
2374 ustring = Tcl_GetUnicodeFromObj(objv[1], &length);
2375 end = length-1;
2376
2377 if (first < 0) {
2378 first = 0;
2379 }
2380
2381 resultPtr = Tcl_NewUnicodeObj(ustring, first);
2382 if (objc == 5) {
2383 Tcl_AppendObjToObj(resultPtr, objv[4]);
2384 }
2385 if (last < end) {
2386 Tcl_AppendUnicodeToObj(resultPtr, ustring + last + 1,
2387 end - last);
2388 }
2389 Tcl_SetObjResult(interp, resultPtr);
2390 }
2391 return TCL_OK;
2392 }
2393
2394 /*
2395 *----------------------------------------------------------------------
2396 *
2397 * StringRevCmd --
2398 *
2399 * This procedure is invoked to process the "string reverse" Tcl command.
2400 * See the user documentation for details on what it does. Note that this
2401 * command only functions correctly on properly formed Tcl UTF strings.
2402 *
2403 * Results:
2404 * A standard Tcl result.
2405 *
2406 * Side effects:
2407 * See the user documentation.
2408 *
2409 *----------------------------------------------------------------------
2410 */
2411
2412 static int
2413 StringRevCmd(
2414 ClientData dummy, /* Not used. */
2415 Tcl_Interp *interp, /* Current interpreter. */
2416 int objc, /* Number of arguments. */
2417 Tcl_Obj *const objv[]) /* Argument objects. */
2418 {
2419 if (objc != 2) {
2420 Tcl_WrongNumArgs(interp, 1, objv, "string");
2421 return TCL_ERROR;
2422 }
2423
2424 Tcl_SetObjResult(interp, TclStringReverse(objv[1]));
2425 return TCL_OK;
2426 }
2427
2428 /*
2429 *----------------------------------------------------------------------
2430 *
2431 * StringStartCmd --
2432 *
2433 * This procedure is invoked to process the "string wordstart" Tcl
2434 * command. See the user documentation for details on what it does. Note
2435 * that this command only functions correctly on properly formed Tcl UTF
2436 * strings.
2437 *
2438 * Results:
2439 * A standard Tcl result.
2440 *
2441 * Side effects:
2442 * See the user documentation.
2443 *
2444 *----------------------------------------------------------------------
2445 */
2446
2447 static int
2448 StringStartCmd(
2449 ClientData dummy, /* Not used. */
2450 Tcl_Interp *interp, /* Current interpreter. */
2451 int objc, /* Number of arguments. */
2452 Tcl_Obj *const objv[]) /* Argument objects. */
2453 {
2454 Tcl_UniChar ch = 0;
2455 const char *p, *string;
2456 int cur, index, length, numChars;
2457
2458 if (objc != 3) {
2459 Tcl_WrongNumArgs(interp, 1, objv, "string index");
2460 return TCL_ERROR;
2461 }
2462
2463 string = TclGetStringFromObj(objv[1], &length);
2464 numChars = Tcl_NumUtfChars(string, length);
2465 if (TclGetIntForIndexM(interp, objv[2], numChars-1, &index) != TCL_OK) {
2466 return TCL_ERROR;
2467 }
2468 string = TclGetStringFromObj(objv[1], &length);
2469 if (index >= numChars) {
2470 index = numChars - 1;
2471 }
2472 cur = 0;
2473 if (index > 0) {
2474 p = Tcl_UtfAtIndex(string, index);
2475
2476 TclUtfToUniChar(p, &ch);
2477 for (cur = index; cur >= 0; cur--) {
2478 int delta = 0;
2479 const char *next;
2480
2481 if (!Tcl_UniCharIsWordChar(ch)) {
2482 break;
2483 }
2484
2485 next = TclUtfPrev(p, string);
2486 do {
2487 next += delta;
2488 delta = TclUtfToUniChar(next, &ch);
2489 } while (next + delta < p);
2490 p = next;
2491 }
2492 if (cur != index) {
2493 cur += 1;
2494 }
2495 }
2496 Tcl_SetObjResult(interp, Tcl_NewIntObj(cur));
2497 return TCL_OK;
2498 }
2499
2500 /*
2501 *----------------------------------------------------------------------
2502 *
2503 * StringEndCmd --
2504 *
2505 * This procedure is invoked to process the "string wordend" Tcl command.
2506 * See the user documentation for details on what it does. Note that this
2507 * command only functions correctly on properly formed Tcl UTF strings.
2508 *
2509 * Results:
2510 * A standard Tcl result.
2511 *
2512 * Side effects:
2513 * See the user documentation.
2514 *
2515 *----------------------------------------------------------------------
2516 */
2517
2518 static int
2519 StringEndCmd(
2520 ClientData dummy, /* Not used. */
2521 Tcl_Interp *interp, /* Current interpreter. */
2522 int objc, /* Number of arguments. */
2523 Tcl_Obj *const objv[]) /* Argument objects. */
2524 {
2525 Tcl_UniChar ch = 0;
2526 const char *p, *end, *string;
2527 int cur, index, length, numChars;
2528
2529 if (objc != 3) {
2530 Tcl_WrongNumArgs(interp, 1, objv, "string index");
2531 return TCL_ERROR;
2532 }
2533
2534 string = TclGetStringFromObj(objv[1], &length);
2535 numChars = Tcl_NumUtfChars(string, length);
2536 if (TclGetIntForIndexM(interp, objv[2], numChars-1, &index) != TCL_OK) {
2537 return TCL_ERROR;
2538 }
2539 string = TclGetStringFromObj(objv[1], &length);
2540 if (index < 0) {
2541 index = 0;
2542 }
2543 if (index < numChars) {
2544 p = Tcl_UtfAtIndex(string, index);
2545 end = string+length;
2546 for (cur = index; p < end; cur++) {
2547 p += TclUtfToUniChar(p, &ch);
2548 if (!Tcl_UniCharIsWordChar(ch)) {
2549 break;
2550 }
2551 }
2552 if (cur == index) {
2553 cur++;
2554 }
2555 } else {
2556 cur = numChars;
2557 }
2558 Tcl_SetObjResult(interp, Tcl_NewIntObj(cur));
2559 return TCL_OK;
2560 }
2561
2562 /*
2563 *----------------------------------------------------------------------
2564 *
2565 * StringEqualCmd --
2566 *
2567 * This procedure is invoked to process the "string equal" Tcl command.
2568 * See the user documentation for details on what it does. Note that this
2569 * command only functions correctly on properly formed Tcl UTF strings.
2570 *
2571 * Results:
2572 * A standard Tcl result.
2573 *
2574 * Side effects:
2575 * See the user documentation.
2576 *
2577 *----------------------------------------------------------------------
2578 */
2579
2580 static int
2581 StringEqualCmd(
2582 ClientData dummy, /* Not used. */
2583 Tcl_Interp *interp, /* Current interpreter. */
2584 int objc, /* Number of arguments. */
2585 Tcl_Obj *const objv[]) /* Argument objects. */
2586 {
2587 /*
2588 * Remember to keep code here in some sync with the byte-compiled versions
2589 * in tclExecute.c (INST_STR_EQ, INST_STR_NEQ and INST_STR_CMP as well as
2590 * the expr string comparison in INST_EQ/INST_NEQ/INST_LT/...).
2591 */
2592
2593 const char *string2;
2594 int length2, i, match, nocase = 0, reqlength = -1;
2595
2596 if (objc < 3 || objc > 6) {
2597 str_cmp_args:
2598 Tcl_WrongNumArgs(interp, 1, objv,
2599 "?-nocase? ?-length int? string1 string2");
2600 return TCL_ERROR;
2601 }
2602
2603 for (i = 1; i < objc-2; i++) {
2604 string2 = TclGetStringFromObj(objv[i], &length2);
2605 if ((length2 > 1) && !strncmp(string2, "-nocase", length2)) {
2606 nocase = 1;
2607 } else if ((length2 > 1)
2608 && !strncmp(string2, "-length", length2)) {
2609 if (i+1 >= objc-2) {
2610 goto str_cmp_args;
2611 }
2612 i++;
2613 if (TclGetIntFromObj(interp, objv[i], &reqlength) != TCL_OK) {
2614 return TCL_ERROR;
2615 }
2616 } else {
2617 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2618 "bad option \"%s\": must be -nocase or -length",
2619 string2));
2620 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "INDEX", "option",
2621 string2, (char *)NULL);
2622 return TCL_ERROR;
2623 }
2624 }
2625
2626 /*
2627 * From now on, we only access the two objects at the end of the argument
2628 * array.
2629 */
2630
2631 objv += objc-2;
2632 match = TclStringCmp(objv[0], objv[1], 1, nocase, reqlength);
2633 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(match ? 0 : 1));
2634 return TCL_OK;
2635 }
2636
2637 /*
2638 *----------------------------------------------------------------------
2639 *
2640 * StringCmpCmd --
2641 *
2642 * This procedure is invoked to process the "string compare" Tcl command.
2643 * See the user documentation for details on what it does. Note that this
2644 * command only functions correctly on properly formed Tcl UTF strings.
2645 *
2646 * Results:
2647 * A standard Tcl result.
2648 *
2649 * Side effects:
2650 * See the user documentation.
2651 *
2652 *----------------------------------------------------------------------
2653 */
2654
2655 static int
2656 StringCmpCmd(
2657 ClientData dummy, /* Not used. */
2658 Tcl_Interp *interp, /* Current interpreter. */
2659 int objc, /* Number of arguments. */
2660 Tcl_Obj *const objv[]) /* Argument objects. */
2661 {
2662 /*
2663 * Remember to keep code here in some sync with the byte-compiled versions
2664 * in tclExecute.c (INST_STR_EQ, INST_STR_NEQ and INST_STR_CMP as well as
2665 * the expr string comparison in INST_EQ/INST_NEQ/INST_LT/...).
2666 */
2667
2668 int match, nocase, reqlength, status;
2669
2670 status = TclStringCmpOpts(interp, objc, objv, &nocase, &reqlength);
2671 if (status != TCL_OK) {
2672 return status;
2673 }
2674
2675 objv += objc-2;
2676 match = TclStringCmp(objv[0], objv[1], 0, nocase, reqlength);
2677 Tcl_SetObjResult(interp, Tcl_NewIntObj(match));
2678 return TCL_OK;
2679 }
2680
2681 /*
2682 *----------------------------------------------------------------------
2683 *
2684 * TclStringCmp --
2685 *
2686 * This is the core of Tcl's string comparison. It only handles byte
2687 * arrays, UNICODE strings and UTF-8 strings correctly.
2688 *
2689 * Results:
2690 * -1 if value1Ptr is less than value2Ptr, 0 if they are equal, or 1 if
2691 * value1Ptr is greater.
2692 *
2693 * Side effects:
2694 * May cause string representations of objects to be allocated.
2695 *
2696 *----------------------------------------------------------------------
2697 */
2698
2699 int
2700 TclStringCmp(
2701 Tcl_Obj *value1Ptr,
2702 Tcl_Obj *value2Ptr,
2703 int checkEq, /* comparison is only for equality */
2704 int nocase, /* comparison is not case sensitive */
2705 int reqlength) /* requested length in characters; -1 to
2706 * compare whole strings */
2707 {
2708 const char *s1, *s2;
2709 int empty, length, match, s1len, s2len;
2710 memCmpFn_t memCmpFn;
2711
2712 if ((reqlength == 0) || (value1Ptr == value2Ptr)) {
2713 /*
2714 * Always match at 0 chars or if it is the same obj.
2715 */
2716 return 0;
2717 }
2718
2719 if (!nocase && TclIsPureByteArray(value1Ptr)
2720 && TclIsPureByteArray(value2Ptr)) {
2721 /*
2722 * Use binary versions of comparisons since that won't cause undue
2723 * type conversions and it is much faster. Only do this if we're
2724 * case-sensitive (which is all that really makes sense with byte
2725 * arrays anyway, and we have no memcasecmp() for some reason... :^)
2726 */
2727
2728 s1 = (char *) Tcl_GetByteArrayFromObj(value1Ptr, &s1len);
2729 s2 = (char *) Tcl_GetByteArrayFromObj(value2Ptr, &s2len);
2730 memCmpFn = memcmp;
2731 } else if ((value1Ptr->typePtr == &tclStringType)
2732 && (value2Ptr->typePtr == &tclStringType)) {
2733 /*
2734 * Do a Unicode-specific comparison if both of the args are of String
2735 * type. If the char length == byte length, we can do a memcmp. In
2736 * benchmark testing this proved the most efficient check between the
2737 * Unicode and string comparison operations.
2738 */
2739
2740 if (nocase) {
2741 s1 = (char *) Tcl_GetUnicodeFromObj(value1Ptr, &s1len);
2742 s2 = (char *) Tcl_GetUnicodeFromObj(value2Ptr, &s2len);
2743 memCmpFn = TclUniCharNcasecmp;
2744 } else {
2745 s1len = Tcl_GetCharLength(value1Ptr);
2746 s2len = Tcl_GetCharLength(value2Ptr);
2747 if ((s1len == value1Ptr->length)
2748 && (value1Ptr->bytes != NULL)
2749 && (s2len == value2Ptr->length)
2750 && (value2Ptr->bytes != NULL)) {
2751 /* each byte represents one character so s1l3n, s2l3n, and
2752 * reqlength are in both bytes and characters
2753 */
2754 s1 = value1Ptr->bytes;
2755 s2 = value2Ptr->bytes;
2756 memCmpFn = memcmp;
2757 } else {
2758 s1 = (char *) Tcl_GetUnicode(value1Ptr);
2759 s2 = (char *) Tcl_GetUnicode(value2Ptr);
2760 if (
2761 #if defined(WORDS_BIGENDIAN) && (TCL_UTF_MAX != 4)
2762 1
2763 #else
2764 checkEq
2765 #endif /* WORDS_BIGENDIAN */
2766 ) {
2767 memCmpFn = memcmp;
2768 s1len *= sizeof(Tcl_UniChar);
2769 s2len *= sizeof(Tcl_UniChar);
2770 if (reqlength > 0) {
2771 reqlength *= sizeof(Tcl_UniChar);
2772 }
2773 } else {
2774 memCmpFn = TclUniCharNcmp;
2775 }
2776 }
2777 }
2778 } else {
2779 /*
2780 * Get the string representations, being careful in case we have
2781 * special empty string objects about.
2782 */
2783
2784 empty = TclCheckEmptyString(value1Ptr);
2785 if (empty > 0) {
2786 switch (TclCheckEmptyString(value2Ptr)) {
2787 case -1:
2788 s1 = "";
2789 s1len = 0;
2790 s2 = TclGetStringFromObj(value2Ptr, &s2len);
2791 break;
2792 case 0:
2793 return -1;
2794 default: /* avoid warn: `s2` may be used uninitialized */
2795 return 0;
2796 }
2797 } else if (TclCheckEmptyString(value2Ptr) > 0) {
2798 switch (empty) {
2799 case -1:
2800 s2 = "";
2801 s2len = 0;
2802 s1 = TclGetStringFromObj(value1Ptr, &s1len);
2803 break;
2804 case 0:
2805 return 1;
2806 default: /* avoid warn: `s1` may be used uninitialized */
2807 return 0;
2808 }
2809 } else {
2810 s1 = TclGetStringFromObj(value1Ptr, &s1len);
2811 s2 = TclGetStringFromObj(value2Ptr, &s2len);
2812 }
2813
2814 if (!nocase && checkEq && reqlength < 0) {
2815 /*
2816 * When we have equal-length we can check only for (in)equality.
2817 * We can use memcmp() in all (n)eq cases because we don't need to
2818 * worry about lexical LE/BE variance.
2819 */
2820 memCmpFn = memcmp;
2821 } else {
2822 /*
2823 * As a catch-all we will work with UTF-8. We cannot use memcmp()
2824 * as that is unsafe with any string containing NUL (\xC0\x80 in
2825 * Tcl's utf rep). We can use the more efficient TclUtfNcmp if
2826 * we are case-sensitive and no specific length was requested.
2827 */
2828
2829 if ((reqlength < 0) && !nocase) {
2830 memCmpFn = TclUtfNcmp2;
2831 } else {
2832 s1len = Tcl_NumUtfChars(s1, s1len);
2833 s2len = Tcl_NumUtfChars(s2, s2len);
2834 memCmpFn = nocase ? TclUtfNcasecmp : TclUtfNcmp;
2835 }
2836 }
2837 }
2838
2839 /* At this point s1len, s2len, and reqlength should by now have been
2840 * adjusted so that they are all in the units expected by the selected
2841 * comparison function.
2842 */
2843
2844 length = (s1len < s2len) ? s1len : s2len;
2845 if (reqlength > 0 && reqlength < length) {
2846 length = reqlength;
2847 } else if (reqlength < 0) {
2848 /*
2849 * The requested length is negative, so ignore it by setting it to
2850 * length + 1 to correct the match var.
2851 */
2852 reqlength = length + 1;
2853 }
2854
2855 if (checkEq && reqlength < 0 && (s1len != s2len)) {
2856 match = 1; /* This will be reversed below. */
2857 } else {
2858 /*
2859 * The comparison function should compare up to the minimum byte
2860 * length only.
2861 */
2862 match = memCmpFn(s1, s2, length);
2863 }
2864 if ((match == 0) && (reqlength > length)) {
2865 match = s1len - s2len;
2866 }
2867 return (match > 0) ? 1 : (match < 0) ? -1 : 0;
2868 }
2869
2870 int TclStringCmpOpts(
2871 Tcl_Interp *interp, /* Current interpreter. */
2872 int objc, /* Number of arguments. */
2873 Tcl_Obj *const objv[], /* Argument objects. */
2874 int *nocase,
2875 int *reqlength)
2876 {
2877 int i, length;
2878 const char *string;
2879
2880 *reqlength = -1;
2881 *nocase = 0;
2882 if (objc < 3 || objc > 6) {
2883 str_cmp_args:
2884 Tcl_WrongNumArgs(interp, 1, objv,
2885 "?-nocase? ?-length int? string1 string2");
2886 return TCL_ERROR;
2887 }
2888
2889 for (i = 1; i < objc-2; i++) {
2890 string = TclGetStringFromObj(objv[i], &length);
2891 if ((length > 1) && !strncmp(string, "-nocase", length)) {
2892 *nocase = 1;
2893 } else if ((length > 1)
2894 && !strncmp(string, "-length", length)) {
2895 if (i+1 >= objc-2) {
2896 goto str_cmp_args;
2897 }
2898 i++;
2899 if (TclGetIntFromObj(interp, objv[i], reqlength) != TCL_OK) {
2900 return TCL_ERROR;
2901 }
2902 } else {
2903 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2904 "bad option \"%s\": must be -nocase or -length",
2905 string));
2906 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "INDEX", "option",
2907 string, (char *)NULL);
2908 return TCL_ERROR;
2909 }
2910 }
2911 return TCL_OK;
2912 }
2913
2914 /*
2915 *----------------------------------------------------------------------
2916 *
2917 * StringCatCmd --
2918 *
2919 * This procedure is invoked to process the "string cat" Tcl command.
2920 * See the user documentation for details on what it does.
2921 *
2922 * Results:
2923 * A standard Tcl result.
2924 *
2925 * Side effects:
2926 * See the user documentation.
2927 *
2928 *----------------------------------------------------------------------
2929 */
2930
2931 static int
2932 StringCatCmd(
2933 ClientData dummy, /* Not used. */
2934 Tcl_Interp *interp, /* Current interpreter. */
2935 int objc, /* Number of arguments. */
2936 Tcl_Obj *const objv[]) /* Argument objects. */
2937 {
2938 int i;
2939 Tcl_Obj *objResultPtr;
2940
2941 if (objc < 2) {
2942 /*
2943 * If there are no args, the result is an empty object.
2944 * Just leave the preset empty interp result.
2945 */
2946 return TCL_OK;
2947 }
2948 if (objc == 2) {
2949 /*
2950 * Other trivial case, single arg, just return it.
2951 */
2952 Tcl_SetObjResult(interp, objv[1]);
2953 return TCL_OK;
2954 }
2955 objResultPtr = objv[1];
2956 if (Tcl_IsShared(objResultPtr)) {
2957 objResultPtr = Tcl_DuplicateObj(objResultPtr);
2958 }
2959 for(i = 2;i < objc;i++) {
2960 Tcl_AppendObjToObj(objResultPtr, objv[i]);
2961 }
2962 Tcl_SetObjResult(interp, objResultPtr);
2963
2964 return TCL_OK;
2965 }
2966
2967 /*
2968 *----------------------------------------------------------------------
2969 *
2970 * StringBytesCmd --
2971 *
2972 * This procedure is invoked to process the "string bytelength" Tcl
2973 * command. See the user documentation for details on what it does. Note
2974 * that this command only functions correctly on properly formed Tcl UTF
2975 * strings.
2976 *
2977 * Results:
2978 * A standard Tcl result.
2979 *
2980 * Side effects:
2981 * See the user documentation.
2982 *
2983 *----------------------------------------------------------------------
2984 */
2985
2986 static int
2987 StringBytesCmd(
2988 ClientData dummy, /* Not used. */
2989 Tcl_Interp *interp, /* Current interpreter. */
2990 int objc, /* Number of arguments. */
2991 Tcl_Obj *const objv[]) /* Argument objects. */
2992 {
2993 int length;
2994
2995 if (objc != 2) {
2996 Tcl_WrongNumArgs(interp, 1, objv, "string");
2997 return TCL_ERROR;
2998 }
2999
3000 (void) TclGetStringFromObj(objv[1], &length);
3001 Tcl_SetObjResult(interp, Tcl_NewIntObj(length));
3002 return TCL_OK;
3003 }
3004
3005 /*
3006 *----------------------------------------------------------------------
3007 *
3008 * StringLenCmd --
3009 *
3010 * This procedure is invoked to process the "string length" Tcl command.
3011 * See the user documentation for details on what it does. Note that this
3012 * command only functions correctly on properly formed Tcl UTF strings.
3013 *
3014 * Results:
3015 * A standard Tcl result.
3016 *
3017 * Side effects:
3018 * See the user documentation.
3019 *
3020 *----------------------------------------------------------------------
3021 */
3022
3023 static int
3024 StringLenCmd(
3025 ClientData dummy, /* Not used. */
3026 Tcl_Interp *interp, /* Current interpreter. */
3027 int objc, /* Number of arguments. */
3028 Tcl_Obj *const objv[]) /* Argument objects. */
3029 {
3030 if (objc != 2) {
3031 Tcl_WrongNumArgs(interp, 1, objv, "string");
3032 return TCL_ERROR;
3033 }
3034
3035 Tcl_SetObjResult(interp, Tcl_NewIntObj(Tcl_GetCharLength(objv[1])));
3036 return TCL_OK;
3037 }
3038
3039 /*
3040 *----------------------------------------------------------------------
3041 *
3042 * StringLowerCmd --
3043 *
3044 * This procedure is invoked to process the "string tolower" Tcl command.
3045 * See the user documentation for details on what it does. Note that this
3046 * command only functions correctly on properly formed Tcl UTF strings.
3047 *
3048 * Results:
3049 * A standard Tcl result.
3050 *
3051 * Side effects:
3052 * See the user documentation.
3053 *
3054 *----------------------------------------------------------------------
3055 */
3056
3057 static int
3058 StringLowerCmd(
3059 ClientData dummy, /* Not used. */
3060 Tcl_Interp *interp, /* Current interpreter. */
3061 int objc, /* Number of arguments. */
3062 Tcl_Obj *const objv[]) /* Argument objects. */
3063 {
3064 int length1, length2;
3065 const char *string1;
3066 char *string2;
3067
3068 if (objc < 2 || objc > 4) {
3069 Tcl_WrongNumArgs(interp, 1, objv, "string ?first? ?last?");
3070 return TCL_ERROR;
3071 }
3072
3073 string1 = TclGetStringFromObj(objv[1], &length1);
3074
3075 if (objc == 2) {
3076 Tcl_Obj *resultPtr = Tcl_NewStringObj(string1, length1);
3077
3078 length1 = Tcl_UtfToLower(TclGetString(resultPtr));
3079 Tcl_SetObjLength(resultPtr, length1);
3080 Tcl_SetObjResult(interp, resultPtr);
3081 } else {
3082 int first, last;
3083 const char *start, *end;
3084 Tcl_Obj *resultPtr;
3085
3086 length1 = Tcl_NumUtfChars(string1, length1) - 1;
3087 if (TclGetIntForIndexM(interp,objv[2],length1, &first) != TCL_OK) {
3088 return TCL_ERROR;
3089 }
3090 if (first < 0) {
3091 first = 0;
3092 }
3093 last = first;
3094
3095 if ((objc == 4) && (TclGetIntForIndexM(interp, objv[3], length1,
3096 &last) != TCL_OK)) {
3097 return TCL_ERROR;
3098 }
3099
3100 if (last >= length1) {
3101 last = length1;
3102 }
3103 if (last < first) {
3104 Tcl_SetObjResult(interp, objv[1]);
3105 return TCL_OK;
3106 }
3107
3108 string1 = TclGetStringFromObj(objv[1], &length1);
3109 start = Tcl_UtfAtIndex(string1, first);
3110 end = Tcl_UtfAtIndex(start, last - first + 1);
3111 resultPtr = Tcl_NewStringObj(string1, end - string1);
3112 string2 = TclGetString(resultPtr) + (start - string1);
3113
3114 length2 = Tcl_UtfToLower(string2);
3115 Tcl_SetObjLength(resultPtr, length2 + (start - string1));
3116
3117 Tcl_AppendToObj(resultPtr, end, -1);
3118 Tcl_SetObjResult(interp, resultPtr);
3119 }
3120
3121 return TCL_OK;
3122 }
3123
3124 /*
3125 *----------------------------------------------------------------------
3126 *
3127 * StringUpperCmd --
3128 *
3129 * This procedure is invoked to process the "string toupper" Tcl command.
3130 * See the user documentation for details on what it does. Note that this
3131 * command only functions correctly on properly formed Tcl UTF strings.
3132 *
3133 * Results:
3134 * A standard Tcl result.
3135 *
3136 * Side effects:
3137 * See the user documentation.
3138 *
3139 *----------------------------------------------------------------------
3140 */
3141
3142 static int
3143 StringUpperCmd(
3144 ClientData dummy, /* Not used. */
3145 Tcl_Interp *interp, /* Current interpreter. */
3146 int objc, /* Number of arguments. */
3147 Tcl_Obj *const objv[]) /* Argument objects. */
3148 {
3149 int length1, length2;
3150 const char *string1;
3151 char *string2;
3152
3153 if (objc < 2 || objc > 4) {
3154 Tcl_WrongNumArgs(interp, 1, objv, "string ?first? ?last?");
3155 return TCL_ERROR;
3156 }
3157
3158 string1 = TclGetStringFromObj(objv[1], &length1);
3159
3160 if (objc == 2) {
3161 Tcl_Obj *resultPtr = Tcl_NewStringObj(string1, length1);
3162
3163 length1 = Tcl_UtfToUpper(TclGetString(resultPtr));
3164 Tcl_SetObjLength(resultPtr, length1);
3165 Tcl_SetObjResult(interp, resultPtr);
3166 } else {
3167 int first, last;
3168 const char *start, *end;
3169 Tcl_Obj *resultPtr;
3170
3171 length1 = Tcl_NumUtfChars(string1, length1) - 1;
3172 if (TclGetIntForIndexM(interp,objv[2],length1, &first) != TCL_OK) {
3173 return TCL_ERROR;
3174 }
3175 if (first < 0) {
3176 first = 0;
3177 }
3178 last = first;
3179
3180 if ((objc == 4) && (TclGetIntForIndexM(interp, objv[3], length1,
3181 &last) != TCL_OK)) {
3182 return TCL_ERROR;
3183 }
3184
3185 if (last >= length1) {
3186 last = length1;
3187 }
3188 if (last < first) {
3189 Tcl_SetObjResult(interp, objv[1]);
3190 return TCL_OK;
3191 }
3192
3193 string1 = TclGetStringFromObj(objv[1], &length1);
3194 start = Tcl_UtfAtIndex(string1, first);
3195 end = Tcl_UtfAtIndex(start, last - first + 1);
3196 resultPtr = Tcl_NewStringObj(string1, end - string1);
3197 string2 = TclGetString(resultPtr) + (start - string1);
3198
3199 length2 = Tcl_UtfToUpper(string2);
3200 Tcl_SetObjLength(resultPtr, length2 + (start - string1));
3201
3202 Tcl_AppendToObj(resultPtr, end, -1);
3203 Tcl_SetObjResult(interp, resultPtr);
3204 }
3205
3206 return TCL_OK;
3207 }
3208
3209 /*
3210 *----------------------------------------------------------------------
3211 *
3212 * StringTitleCmd --
3213 *
3214 * This procedure is invoked to process the "string totitle" Tcl command.
3215 * See the user documentation for details on what it does. Note that this
3216 * command only functions correctly on properly formed Tcl UTF strings.
3217 *
3218 * Results:
3219 * A standard Tcl result.
3220 *
3221 * Side effects:
3222 * See the user documentation.
3223 *
3224 *----------------------------------------------------------------------
3225 */
3226
3227 static int
3228 StringTitleCmd(
3229 ClientData dummy, /* Not used. */
3230 Tcl_Interp *interp, /* Current interpreter. */
3231 int objc, /* Number of arguments. */
3232 Tcl_Obj *const objv[]) /* Argument objects. */
3233 {
3234 int length1, length2;
3235 const char *string1;
3236 char *string2;
3237
3238 if (objc < 2 || objc > 4) {
3239 Tcl_WrongNumArgs(interp, 1, objv, "string ?first? ?last?");
3240 return TCL_ERROR;
3241 }
3242
3243 string1 = TclGetStringFromObj(objv[1], &length1);
3244
3245 if (objc == 2) {
3246 Tcl_Obj *resultPtr = Tcl_NewStringObj(string1, length1);
3247
3248 length1 = Tcl_UtfToTitle(TclGetString(resultPtr));
3249 Tcl_SetObjLength(resultPtr, length1);
3250 Tcl_SetObjResult(interp, resultPtr);
3251 } else {
3252 int first, last;
3253 const char *start, *end;
3254 Tcl_Obj *resultPtr;
3255
3256 length1 = Tcl_NumUtfChars(string1, length1) - 1;
3257 if (TclGetIntForIndexM(interp,objv[2],length1, &first) != TCL_OK) {
3258 return TCL_ERROR;
3259 }
3260 if (first < 0) {
3261 first = 0;
3262 }
3263 last = first;
3264
3265 if ((objc == 4) && (TclGetIntForIndexM(interp, objv[3], length1,
3266 &last) != TCL_OK)) {
3267 return TCL_ERROR;
3268 }
3269
3270 if (last >= length1) {
3271 last = length1;
3272 }
3273 if (last < first) {
3274 Tcl_SetObjResult(interp, objv[1]);
3275 return TCL_OK;
3276 }
3277
3278 string1 = TclGetStringFromObj(objv[1], &length1);
3279 start = Tcl_UtfAtIndex(string1, first);
3280 end = Tcl_UtfAtIndex(start, last - first + 1);
3281 resultPtr = Tcl_NewStringObj(string1, end - string1);
3282 string2 = TclGetString(resultPtr) + (start - string1);
3283
3284 length2 = Tcl_UtfToTitle(string2);
3285 Tcl_SetObjLength(resultPtr, length2 + (start - string1));
3286
3287 Tcl_AppendToObj(resultPtr, end, -1);
3288 Tcl_SetObjResult(interp, resultPtr);
3289 }
3290
3291 return TCL_OK;
3292 }
3293
3294 /*
3295 *----------------------------------------------------------------------
3296 *
3297 * StringTrimCmd --
3298 *
3299 * This procedure is invoked to process the "string trim" Tcl command.
3300 * See the user documentation for details on what it does. Note that this
3301 * command only functions correctly on properly formed Tcl UTF strings.
3302 *
3303 * Results:
3304 * A standard Tcl result.
3305 *
3306 * Side effects:
3307 * See the user documentation.
3308 *
3309 *----------------------------------------------------------------------
3310 */
3311
3312 static int
3313 StringTrimCmd(
3314 ClientData dummy, /* Not used. */
3315 Tcl_Interp *interp, /* Current interpreter. */
3316 int objc, /* Number of arguments. */
3317 Tcl_Obj *const objv[]) /* Argument objects. */
3318 {
3319 const char *string1, *string2;
3320 int triml, trimr, length1, length2;
3321
3322 if (objc == 3) {
3323 string2 = TclGetStringFromObj(objv[2], &length2);
3324 } else if (objc == 2) {
3325 string2 = tclDefaultTrimSet;
3326 length2 = strlen(tclDefaultTrimSet);
3327 } else {
3328 Tcl_WrongNumArgs(interp, 1, objv, "string ?chars?");
3329 return TCL_ERROR;
3330 }
3331 string1 = TclGetStringFromObj(objv[1], &length1);
3332
3333 triml = TclTrim(string1, length1, string2, length2, &trimr);
3334
3335 Tcl_SetObjResult(interp,
3336 Tcl_NewStringObj(string1 + triml, length1 - triml - trimr));
3337 return TCL_OK;
3338 }
3339
3340 /*
3341 *----------------------------------------------------------------------
3342 *
3343 * StringTrimLCmd --
3344 *
3345 * This procedure is invoked to process the "string trimleft" Tcl
3346 * command. See the user documentation for details on what it does. Note
3347 * that this command only functions correctly on properly formed Tcl UTF
3348 * strings.
3349 *
3350 * Results:
3351 * A standard Tcl result.
3352 *
3353 * Side effects:
3354 * See the user documentation.
3355 *
3356 *----------------------------------------------------------------------
3357 */
3358
3359 static int
3360 StringTrimLCmd(
3361 ClientData dummy, /* Not used. */
3362 Tcl_Interp *interp, /* Current interpreter. */
3363 int objc, /* Number of arguments. */
3364 Tcl_Obj *const objv[]) /* Argument objects. */
3365 {
3366 const char *string1, *string2;
3367 int trim, length1, length2;
3368
3369 if (objc == 3) {
3370 string2 = TclGetStringFromObj(objv[2], &length2);
3371 } else if (objc == 2) {
3372 string2 = tclDefaultTrimSet;
3373 length2 = strlen(tclDefaultTrimSet);
3374 } else {
3375 Tcl_WrongNumArgs(interp, 1, objv, "string ?chars?");
3376 return TCL_ERROR;
3377 }
3378 string1 = TclGetStringFromObj(objv[1], &length1);
3379
3380 trim = TclTrimLeft(string1, length1, string2, length2);
3381
3382 Tcl_SetObjResult(interp, Tcl_NewStringObj(string1+trim, length1-trim));
3383 return TCL_OK;
3384 }
3385
3386 /*
3387 *----------------------------------------------------------------------
3388 *
3389 * StringTrimRCmd --
3390 *
3391 * This procedure is invoked to process the "string trimright" Tcl
3392 * command. See the user documentation for details on what it does. Note
3393 * that this command only functions correctly on properly formed Tcl UTF
3394 * strings.
3395 *
3396 * Results:
3397 * A standard Tcl result.
3398 *
3399 * Side effects:
3400 * See the user documentation.
3401 *
3402 *----------------------------------------------------------------------
3403 */
3404
3405 static int
3406 StringTrimRCmd(
3407 ClientData dummy, /* Not used. */
3408 Tcl_Interp *interp, /* Current interpreter. */
3409 int objc, /* Number of arguments. */
3410 Tcl_Obj *const objv[]) /* Argument objects. */
3411 {
3412 const char *string1, *string2;
3413 int trim, length1, length2;
3414
3415 if (objc == 3) {
3416 string2 = TclGetStringFromObj(objv[2], &length2);
3417 } else if (objc == 2) {
3418 string2 = tclDefaultTrimSet;
3419 length2 = strlen(tclDefaultTrimSet);
3420 } else {
3421 Tcl_WrongNumArgs(interp, 1, objv, "string ?chars?");
3422 return TCL_ERROR;
3423 }
3424 string1 = TclGetStringFromObj(objv[1], &length1);
3425
3426 trim = TclTrimRight(string1, length1, string2, length2);
3427
3428 Tcl_SetObjResult(interp, Tcl_NewStringObj(string1, length1-trim));
3429 return TCL_OK;
3430 }
3431
3432 /*
3433 *----------------------------------------------------------------------
3434 *
3435 * TclInitStringCmd --
3436 *
3437 * This procedure creates the "string" Tcl command. See the user
3438 * documentation for details on what it does. Note that this command only
3439 * functions correctly on properly formed Tcl UTF strings.
3440 *
3441 * Also note that the primary methods here (equal, compare, match, ...)
3442 * have bytecode equivalents. You will find the code for those in
3443 * tclExecute.c. The code here will only be used in the non-bc case (like
3444 * in an 'eval').
3445 *
3446 * Results:
3447 * A standard Tcl result.
3448 *
3449 * Side effects:
3450 * See the user documentation.
3451 *
3452 *----------------------------------------------------------------------
3453 */
3454
3455 Tcl_Command
3456 TclInitStringCmd(
3457 Tcl_Interp *interp) /* Current interpreter. */
3458 {
3459 static const EnsembleImplMap stringImplMap[] = {
3460 {"bytelength", StringBytesCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
3461 {"cat", StringCatCmd, TclCompileStringCatCmd, NULL, NULL, 0},
3462 {"compare", StringCmpCmd, TclCompileStringCmpCmd, NULL, NULL, 0},
3463 {"equal", StringEqualCmd, TclCompileStringEqualCmd, NULL, NULL, 0},
3464 {"first", StringFirstCmd, TclCompileStringFirstCmd, NULL, NULL, 0},
3465 {"index", StringIndexCmd, TclCompileStringIndexCmd, NULL, NULL, 0},
3466 {"is", StringIsCmd, TclCompileStringIsCmd, NULL, NULL, 0},
3467 {"last", StringLastCmd, TclCompileStringLastCmd, NULL, NULL, 0},
3468 {"length", StringLenCmd, TclCompileStringLenCmd, NULL, NULL, 0},
3469 {"map", StringMapCmd, TclCompileStringMapCmd, NULL, NULL, 0},
3470 {"match", StringMatchCmd, TclCompileStringMatchCmd, NULL, NULL, 0},
3471 {"range", StringRangeCmd, TclCompileStringRangeCmd, NULL, NULL, 0},
3472 {"repeat", StringReptCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0},
3473 {"replace", StringRplcCmd, TclCompileStringReplaceCmd, NULL, NULL, 0},
3474 {"reverse", StringRevCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0},
3475 {"tolower", StringLowerCmd, TclCompileStringToLowerCmd, NULL, NULL, 0},
3476 {"toupper", StringUpperCmd, TclCompileStringToUpperCmd, NULL, NULL, 0},
3477 {"totitle", StringTitleCmd, TclCompileStringToTitleCmd, NULL, NULL, 0},
3478 {"trim", StringTrimCmd, TclCompileStringTrimCmd, NULL, NULL, 0},
3479 {"trimleft", StringTrimLCmd, TclCompileStringTrimLCmd, NULL, NULL, 0},
3480 {"trimright", StringTrimRCmd, TclCompileStringTrimRCmd, NULL, NULL, 0},
3481 {"wordend", StringEndCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0},
3482 {"wordstart", StringStartCmd, TclCompileBasic2ArgCmd, NULL, NULL, 0},
3483 {NULL, NULL, NULL, NULL, NULL, 0}
3484 };
3485
3486 return TclMakeEnsemble(interp, "string", stringImplMap);
3487 }
3488
3489 /*
3490 *----------------------------------------------------------------------
3491 *
3492 * Tcl_SubstObjCmd --
3493 *
3494 * This procedure is invoked to process the "subst" Tcl command. See the
3495 * user documentation for details on what it does. This command relies on
3496 * Tcl_SubstObj() for its implementation.
3497 *
3498 * Results:
3499 * A standard Tcl result.
3500 *
3501 * Side effects:
3502 * See the user documentation.
3503 *
3504 *----------------------------------------------------------------------
3505 */
3506
3507 int
3508 TclSubstOptions(
3509 Tcl_Interp *interp,
3510 int numOpts,
3511 Tcl_Obj *const opts[],
3512 int *flagPtr)
3513 {
3514 static const char *const substOptions[] = {
3515 "-nobackslashes", "-nocommands", "-novariables", NULL
3516 };
3517 static const int optionFlags[] = {
3518 TCL_SUBST_BACKSLASHES, TCL_SUBST_COMMANDS, TCL_SUBST_VARIABLES
3519 };
3520 int i, flags = TCL_SUBST_ALL;
3521
3522 for (i = 0; i < numOpts; i++) {
3523 int optionIndex;
3524
3525 if (Tcl_GetIndexFromObj(interp, opts[i], substOptions, "option", 0,
3526 &optionIndex) != TCL_OK) {
3527 return TCL_ERROR;
3528 }
3529 flags &= ~optionFlags[optionIndex];
3530 }
3531 *flagPtr = flags;
3532 return TCL_OK;
3533 }
3534
3535 int
3536 Tcl_SubstObjCmd(
3537 ClientData dummy, /* Not used. */
3538 Tcl_Interp *interp, /* Current interpreter. */
3539 int objc, /* Number of arguments. */
3540 Tcl_Obj *const objv[]) /* Argument objects. */
3541 {
3542 return Tcl_NRCallObjProc(interp, TclNRSubstObjCmd, dummy, objc, objv);
3543 }
3544
3545 int
3546 TclNRSubstObjCmd(
3547 ClientData dummy, /* Not used. */
3548 Tcl_Interp *interp, /* Current interpreter. */
3549 int objc, /* Number of arguments. */
3550 Tcl_Obj *const objv[]) /* Argument objects. */
3551 {
3552 int flags;
3553
3554 if (objc < 2) {
3555 Tcl_WrongNumArgs(interp, 1, objv,
3556 "?-nobackslashes? ?-nocommands? ?-novariables? string");
3557 return TCL_ERROR;
3558 }
3559
3560 if (TclSubstOptions(interp, objc-2, objv+1, &flags) != TCL_OK) {
3561 return TCL_ERROR;
3562 }
3563 return Tcl_NRSubstObj(interp, objv[objc-1], flags);
3564 }
3565
3566 /*
3567 *----------------------------------------------------------------------
3568 *
3569 * Tcl_SwitchObjCmd --
3570 *
3571 * This object-based procedure is invoked to process the "switch" Tcl
3572 * command. See the user documentation for details on what it does.
3573 *
3574 * Results:
3575 * A standard Tcl object result.
3576 *
3577 * Side effects:
3578 * See the user documentation.
3579 *
3580 *----------------------------------------------------------------------
3581 */
3582
3583 int
3584 Tcl_SwitchObjCmd(
3585 ClientData dummy, /* Not used. */
3586 Tcl_Interp *interp, /* Current interpreter. */
3587 int objc, /* Number of arguments. */
3588 Tcl_Obj *const objv[]) /* Argument objects. */
3589 {
3590 return Tcl_NRCallObjProc(interp, TclNRSwitchObjCmd, dummy, objc, objv);
3591 }
3592 int
3593 TclNRSwitchObjCmd(
3594 ClientData dummy, /* Not used. */
3595 Tcl_Interp *interp, /* Current interpreter. */
3596 int objc, /* Number of arguments. */
3597 Tcl_Obj *const objv[]) /* Argument objects. */
3598 {
3599 int i,j, index, mode, foundmode, splitObjs, numMatchesSaved;
3600 int noCase, patternLength;
3601 const char *pattern;
3602 Tcl_Obj *stringObj, *indexVarObj, *matchVarObj;
3603 Tcl_Obj *const *savedObjv = objv;
3604 Tcl_RegExp regExpr = NULL;
3605 Interp *iPtr = (Interp *) interp;
3606 int pc = 0;
3607 int bidx = 0; /* Index of body argument. */
3608 Tcl_Obj *blist = NULL; /* List obj which is the body */
3609 CmdFrame *ctxPtr; /* Copy of the topmost cmdframe, to allow us
3610 * to mess with the line information */
3611
3612 /*
3613 * If you add options that make -e and -g not unique prefixes of -exact or
3614 * -glob, you *must* fix TclCompileSwitchCmd's option parser as well.
3615 */
3616
3617 static const char *const options[] = {
3618 "-exact", "-glob", "-indexvar", "-matchvar", "-nocase", "-regexp",
3619 "--", NULL
3620 };
3621 enum options {
3622 OPT_EXACT, OPT_GLOB, OPT_INDEXV, OPT_MATCHV, OPT_NOCASE, OPT_REGEXP,
3623 OPT_LAST
3624 };
3625 typedef int (*strCmpFn_t)(const char *, const char *);
3626 strCmpFn_t strCmpFn = strcmp;
3627
3628 mode = OPT_EXACT;
3629 foundmode = 0;
3630 indexVarObj = NULL;
3631 matchVarObj = NULL;
3632 numMatchesSaved = 0;
3633 noCase = 0;
3634 for (i = 1; i < objc-2; i++) {
3635 if (TclGetString(objv[i])[0] != '-') {
3636 break;
3637 }
3638 if (Tcl_GetIndexFromObj(interp, objv[i], options, "option", 0,
3639 &index) != TCL_OK) {
3640 return TCL_ERROR;
3641 }
3642 switch ((enum options) index) {
3643 /*
3644 * General options.
3645 */
3646
3647 case OPT_LAST:
3648 i++;
3649 goto finishedOptions;
3650 case OPT_NOCASE:
3651 strCmpFn = TclUtfCasecmp;
3652 noCase = 1;
3653 break;
3654
3655 /*
3656 * Handle the different switch mode options.
3657 */
3658
3659 default:
3660 if (foundmode) {
3661 /*
3662 * Mode already set via -exact, -glob, or -regexp.
3663 */
3664
3665 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3666 "bad option \"%s\": %s option already found",
3667 TclGetString(objv[i]), options[mode]));
3668 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SWITCH",
3669 "DOUBLEOPT", (char *)NULL);
3670 return TCL_ERROR;
3671 }
3672 foundmode = 1;
3673 mode = index;
3674 break;
3675
3676 /*
3677 * Check for TIP#75 options specifying the variables to write
3678 * regexp information into.
3679 */
3680
3681 case OPT_INDEXV:
3682 i++;
3683 if (i >= objc-2) {
3684 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3685 "missing variable name argument to %s option",
3686 "-indexvar"));
3687 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SWITCH",
3688 "NOVAR", (char *)NULL);
3689 return TCL_ERROR;
3690 }
3691 indexVarObj = objv[i];
3692 numMatchesSaved = -1;
3693 break;
3694 case OPT_MATCHV:
3695 i++;
3696 if (i >= objc-2) {
3697 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3698 "missing variable name argument to %s option",
3699 "-matchvar"));
3700 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SWITCH",
3701 "NOVAR", (char *)NULL);
3702 return TCL_ERROR;
3703 }
3704 matchVarObj = objv[i];
3705 numMatchesSaved = -1;
3706 break;
3707 }
3708 }
3709
3710 finishedOptions:
3711 if (objc - i < 2) {
3712 Tcl_WrongNumArgs(interp, 1, objv,
3713 "?-option ...? string ?pattern body ...? ?default body?");
3714 return TCL_ERROR;
3715 }
3716 if (indexVarObj != NULL && mode != OPT_REGEXP) {
3717 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3718 "%s option requires -regexp option", "-indexvar"));
3719 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SWITCH",
3720 "MODERESTRICTION", (char *)NULL);
3721 return TCL_ERROR;
3722 }
3723 if (matchVarObj != NULL && mode != OPT_REGEXP) {
3724 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3725 "%s option requires -regexp option", "-matchvar"));
3726 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SWITCH",
3727 "MODERESTRICTION", (char *)NULL);
3728 return TCL_ERROR;
3729 }
3730
3731 stringObj = objv[i];
3732 objc -= i + 1;
3733 objv += i + 1;
3734 bidx = i + 1; /* First after the match string. */
3735
3736 /*
3737 * If all of the pattern/command pairs are lumped into a single argument,
3738 * split them out again.
3739 *
3740 * TIP #280: Determine the lines the words in the list start at, based on
3741 * the same data for the list word itself. The cmdFramePtr line
3742 * information is manipulated directly.
3743 */
3744
3745 splitObjs = 0;
3746 if (objc == 1) {
3747 Tcl_Obj **listv;
3748
3749 blist = objv[0];
3750 if (TclListObjGetElements(interp, objv[0], &objc, &listv) != TCL_OK){
3751 return TCL_ERROR;
3752 }
3753
3754 /*
3755 * Ensure that the list is non-empty.
3756 */
3757
3758 if (objc < 1) {
3759 Tcl_WrongNumArgs(interp, 1, savedObjv,
3760 "?-option ...? string {?pattern body ...? ?default body?}");
3761 return TCL_ERROR;
3762 }
3763 objv = listv;
3764 splitObjs = 1;
3765 }
3766
3767 /*
3768 * Complain if there is an odd number of words in the list of patterns and
3769 * bodies.
3770 */
3771
3772 if (objc % 2) {
3773 Tcl_ResetResult(interp);
3774 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3775 "extra switch pattern with no body", -1));
3776 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SWITCH", "BADARM",
3777 (char *)NULL);
3778
3779 /*
3780 * Check if this can be due to a badly placed comment in the switch
3781 * block.
3782 *
3783 * The following is an heuristic to detect the infamous "comment in
3784 * switch" error: just check if a pattern begins with '#'.
3785 */
3786
3787 if (splitObjs) {
3788 for (i=0 ; i<objc ; i+=2) {
3789 if (TclGetString(objv[i])[0] == '#') {
3790 Tcl_AppendToObj(Tcl_GetObjResult(interp),
3791 ", this may be due to a comment incorrectly"
3792 " placed outside of a switch body - see the"
3793 " \"switch\" documentation", -1);
3794 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SWITCH",
3795 "BADARM", "COMMENT?", (char *)NULL);
3796 break;
3797 }
3798 }
3799 }
3800
3801 return TCL_ERROR;
3802 }
3803
3804 /*
3805 * Complain if the last body is a continuation. Note that this check
3806 * assumes that the list is non-empty!
3807 */
3808
3809 if (strcmp(TclGetString(objv[objc-1]), "-") == 0) {
3810 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3811 "no body specified for pattern \"%s\"",
3812 TclGetString(objv[objc-2])));
3813 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "SWITCH", "BADARM",
3814 "FALLTHROUGH", (char *)NULL);
3815 return TCL_ERROR;
3816 }
3817
3818 for (i = 0; i < objc; i += 2) {
3819 /*
3820 * See if the pattern matches the string.
3821 */
3822
3823 pattern = TclGetStringFromObj(objv[i], &patternLength);
3824
3825 if ((i == objc - 2) && (*pattern == 'd')
3826 && (strcmp(pattern, "default") == 0)) {
3827 Tcl_Obj *emptyObj = NULL;
3828
3829 /*
3830 * If either indexVarObj or matchVarObj are non-NULL, we're in
3831 * REGEXP mode but have reached the default clause anyway. TIP#75
3832 * specifies that we set the variables to empty lists (== empty
3833 * objects) in that case.
3834 */
3835
3836 if (indexVarObj != NULL) {
3837 TclNewObj(emptyObj);
3838 if (Tcl_ObjSetVar2(interp, indexVarObj, NULL, emptyObj,
3839 TCL_LEAVE_ERR_MSG) == NULL) {
3840 return TCL_ERROR;
3841 }
3842 }
3843 if (matchVarObj != NULL) {
3844 if (emptyObj == NULL) {
3845 TclNewObj(emptyObj);
3846 }
3847 if (Tcl_ObjSetVar2(interp, matchVarObj, NULL, emptyObj,
3848 TCL_LEAVE_ERR_MSG) == NULL) {
3849 return TCL_ERROR;
3850 }
3851 }
3852 goto matchFound;
3853 }
3854
3855 switch (mode) {
3856 case OPT_EXACT:
3857 if (strCmpFn(TclGetString(stringObj), pattern) == 0) {
3858 goto matchFound;
3859 }
3860 break;
3861 case OPT_GLOB:
3862 if (Tcl_StringCaseMatch(TclGetString(stringObj),pattern,noCase)) {
3863 goto matchFound;
3864 }
3865 break;
3866 case OPT_REGEXP:
3867 regExpr = Tcl_GetRegExpFromObj(interp, objv[i],
3868 TCL_REG_ADVANCED | (noCase ? TCL_REG_NOCASE : 0));
3869 if (regExpr == NULL) {
3870 return TCL_ERROR;
3871 } else {
3872 int matched = Tcl_RegExpExecObj(interp, regExpr, stringObj, 0,
3873 numMatchesSaved, 0);
3874
3875 if (matched < 0) {
3876 return TCL_ERROR;
3877 } else if (matched) {
3878 goto matchFoundRegexp;
3879 }
3880 }
3881 break;
3882 }
3883 }
3884 return TCL_OK;
3885
3886 matchFoundRegexp:
3887 /*
3888 * We are operating in REGEXP mode and we need to store information about
3889 * what we matched in some user-nominated arrays. So build the lists of
3890 * values and indices to write here. [TIP#75]
3891 */
3892
3893 if (numMatchesSaved) {
3894 Tcl_RegExpInfo info;
3895 Tcl_Obj *matchesObj, *indicesObj = NULL;
3896
3897 Tcl_RegExpGetInfo(regExpr, &info);
3898 if (matchVarObj != NULL) {
3899 TclNewObj(matchesObj);
3900 } else {
3901 matchesObj = NULL;
3902 }
3903 if (indexVarObj != NULL) {
3904 TclNewObj(indicesObj);
3905 }
3906
3907 for (j=0 ; j<=info.nsubs ; j++) {
3908 if (indexVarObj != NULL) {
3909 Tcl_Obj *rangeObjAry[2];
3910
3911 if (info.matches[j].end > 0) {
3912 rangeObjAry[0] = Tcl_NewLongObj(info.matches[j].start);
3913 rangeObjAry[1] = Tcl_NewLongObj(info.matches[j].end-1);
3914 } else {
3915 TclNewIntObj(rangeObjAry[1], -1);
3916 rangeObjAry[0] = rangeObjAry[1];
3917 }
3918
3919 /*
3920 * Never fails; the object is always clean at this point.
3921 */
3922
3923 Tcl_ListObjAppendElement(NULL, indicesObj,
3924 Tcl_NewListObj(2, rangeObjAry));
3925 }
3926
3927 if (matchVarObj != NULL) {
3928 Tcl_Obj *substringObj;
3929
3930 if (info.matches[j].end > 0) {
3931 substringObj = Tcl_GetRange(stringObj,
3932 info.matches[j].start, info.matches[j].end-1);
3933 } else {
3934 TclNewObj(substringObj);
3935 }
3936
3937 /*
3938 * Never fails; the object is always clean at this point.
3939 */
3940
3941 Tcl_ListObjAppendElement(NULL, matchesObj, substringObj);
3942 }
3943 }
3944
3945 if (indexVarObj != NULL) {
3946 if (Tcl_ObjSetVar2(interp, indexVarObj, NULL, indicesObj,
3947 TCL_LEAVE_ERR_MSG) == NULL) {
3948 /*
3949 * Careful! Check to see if we have allocated the list of
3950 * matched strings; if so (but there was an error assigning
3951 * the indices list) we have a potential memory leak because
3952 * the match list has not been written to a variable. Except
3953 * that we'll clean that up right now.
3954 */
3955
3956 if (matchesObj != NULL) {
3957 Tcl_DecrRefCount(matchesObj);
3958 }
3959 return TCL_ERROR;
3960 }
3961 }
3962 if (matchVarObj != NULL) {
3963 if (Tcl_ObjSetVar2(interp, matchVarObj, NULL, matchesObj,
3964 TCL_LEAVE_ERR_MSG) == NULL) {
3965 /*
3966 * Unlike above, if indicesObj is non-NULL at this point, it
3967 * will have been written to a variable already and will hence
3968 * not be leaked.
3969 */
3970
3971 return TCL_ERROR;
3972 }
3973 }
3974 }
3975
3976 /*
3977 * We've got a match. Find a body to execute, skipping bodies that are
3978 * "-".
3979 */
3980
3981 matchFound:
3982 ctxPtr = (CmdFrame *)TclStackAlloc(interp, sizeof(CmdFrame));
3983 *ctxPtr = *iPtr->cmdFramePtr;
3984
3985 if (splitObjs) {
3986 /*
3987 * We have to perform the GetSrc and other type dependent handling of
3988 * the frame here because we are munging with the line numbers,
3989 * something the other commands like if, etc. are not doing. Them are
3990 * fine with simply passing the CmdFrame through and having the
3991 * special handling done in 'info frame', or the bc compiler
3992 */
3993
3994 if (ctxPtr->type == TCL_LOCATION_BC) {
3995 /*
3996 * Type BC => ctxPtr->data.eval.path is not used.
3997 * ctxPtr->data.tebc.codePtr is used instead.
3998 */
3999
4000 TclGetSrcInfoForPc(ctxPtr);
4001 pc = 1;
4002
4003 /*
4004 * The line information in the cmdFrame is now a copy we do not
4005 * own.
4006 */
4007 }
4008
4009 if (ctxPtr->type == TCL_LOCATION_SOURCE && ctxPtr->line[bidx] >= 0) {
4010 int bline = ctxPtr->line[bidx];
4011
4012 ctxPtr->line = (int *)ckalloc(objc * sizeof(int));
4013 ctxPtr->nline = objc;
4014 TclListLines(blist, bline, objc, ctxPtr->line, objv);
4015 } else {
4016 /*
4017 * This is either a dynamic code word, when all elements are
4018 * relative to themselves, or something else less expected and
4019 * where we have no information. The result is the same in both
4020 * cases; tell the code to come that it doesn't know where it is,
4021 * which triggers reversion to the old behavior.
4022 */
4023
4024 int k;
4025
4026 ctxPtr->line = (int *)ckalloc(objc * sizeof(int));
4027 ctxPtr->nline = objc;
4028 for (k=0; k < objc; k++) {
4029 ctxPtr->line[k] = -1;
4030 }
4031 }
4032 }
4033
4034 for (j = i + 1; ; j += 2) {
4035 if (j >= objc) {
4036 /*
4037 * This shouldn't happen since we've checked that the last body is
4038 * not a continuation...
4039 */
4040
4041 Tcl_Panic("fall-out when searching for body to match pattern");
4042 }
4043 if (strcmp(TclGetString(objv[j]), "-") != 0) {
4044 break;
4045 }
4046 }
4047
4048 /*
4049 * TIP #280: Make invoking context available to switch branch.
4050 */
4051
4052 Tcl_NRAddCallback(interp, SwitchPostProc, INT2PTR(splitObjs), ctxPtr,
4053 INT2PTR(pc), (ClientData) pattern);
4054 return TclNREvalObjEx(interp, objv[j], 0, ctxPtr, splitObjs ? j : bidx+j);
4055 }
4056
4057 static int
4058 SwitchPostProc(
4059 ClientData data[], /* Data passed from Tcl_NRAddCallback above */
4060 Tcl_Interp *interp, /* Tcl interpreter */
4061 int result) /* Result to return*/
4062 {
4063 /* Unpack the preserved data */
4064
4065 int splitObjs = PTR2INT(data[0]);
4066 CmdFrame *ctxPtr = (CmdFrame *)data[1];
4067 int pc = PTR2INT(data[2]);
4068 const char *pattern = (const char *)data[3];
4069 int patternLength = strlen(pattern);
4070
4071 /*
4072 * Clean up TIP 280 context information
4073 */
4074
4075 if (splitObjs) {
4076 ckfree(ctxPtr->line);
4077 if (pc && (ctxPtr->type == TCL_LOCATION_SOURCE)) {
4078 /*
4079 * Death of SrcInfo reference.
4080 */
4081
4082 Tcl_DecrRefCount(ctxPtr->data.eval.path);
4083 }
4084 }
4085
4086 /*
4087 * Generate an error message if necessary.
4088 */
4089
4090 if (result == TCL_ERROR) {
4091 int limit = 50;
4092 int overflow = (patternLength > limit);
4093
4094 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
4095 "\n (\"%.*s%s\" arm line %d)",
4096 (overflow ? limit : patternLength), pattern,
4097 (overflow ? "..." : ""), Tcl_GetErrorLine(interp)));
4098 }
4099 TclStackFree(interp, ctxPtr);
4100 return result;
4101 }
4102
4103 /*
4104 *----------------------------------------------------------------------
4105 *
4106 * Tcl_ThrowObjCmd --
4107 *
4108 * This procedure is invoked to process the "throw" Tcl command. See the
4109 * user documentation for details on what it does.
4110 *
4111 * Results:
4112 * A standard Tcl result.
4113 *
4114 * Side effects:
4115 * See the user documentation.
4116 *
4117 *----------------------------------------------------------------------
4118 */
4119
4120 /* ARGSUSED */
4121 int
4122 Tcl_ThrowObjCmd(
4123 ClientData dummy, /* Not used. */
4124 Tcl_Interp *interp, /* Current interpreter. */
4125 int objc, /* Number of arguments. */
4126 Tcl_Obj *const objv[]) /* Argument objects. */
4127 {
4128 Tcl_Obj *options;
4129 int len;
4130
4131 if (objc != 3) {
4132 Tcl_WrongNumArgs(interp, 1, objv, "type message");
4133 return TCL_ERROR;
4134 }
4135
4136 /*
4137 * The type must be a list of at least length 1.
4138 */
4139
4140 if (TclListObjLength(interp, objv[1], &len) != TCL_OK) {
4141 return TCL_ERROR;
4142 } else if (len < 1) {
4143 Tcl_SetObjResult(interp, Tcl_NewStringObj(
4144 "type must be non-empty list", -1));
4145 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "THROW", "BADEXCEPTION",
4146 (char *)NULL);
4147 return TCL_ERROR;
4148 }
4149
4150 /*
4151 * Now prepare the result options dictionary. We use the list API as it is
4152 * slightly more convenient.
4153 */
4154
4155 TclNewLiteralStringObj(options, "-code error -level 0 -errorcode");
4156 Tcl_ListObjAppendElement(NULL, options, objv[1]);
4157
4158 /*
4159 * We're ready to go. Fire things into the low-level result machinery.
4160 */
4161
4162 Tcl_SetObjResult(interp, objv[2]);
4163 return Tcl_SetReturnOptions(interp, options);
4164 }
4165
4166 /*
4167 *----------------------------------------------------------------------
4168 *
4169 * Tcl_TimeObjCmd --
4170 *
4171 * This object-based procedure is invoked to process the "time" Tcl
4172 * command. See the user documentation for details on what it does.
4173 *
4174 * Results:
4175 * A standard Tcl object result.
4176 *
4177 * Side effects:
4178 * See the user documentation.
4179 *
4180 *----------------------------------------------------------------------
4181 */
4182
4183 int
4184 Tcl_TimeObjCmd(
4185 ClientData dummy, /* Not used. */
4186 Tcl_Interp *interp, /* Current interpreter. */
4187 int objc, /* Number of arguments. */
4188 Tcl_Obj *const objv[]) /* Argument objects. */
4189 {
4190 Tcl_Obj *objPtr;
4191 Tcl_Obj *objs[4];
4192 int i, result;
4193 int count;
4194 double totalMicroSec;
4195 #ifndef TCL_WIDE_CLICKS
4196 Tcl_Time start, stop;
4197 #else
4198 Tcl_WideInt start, stop;
4199 #endif
4200
4201 if (objc == 2) {
4202 count = 1;
4203 } else if (objc == 3) {
4204 result = TclGetIntFromObj(interp, objv[2], &count);
4205 if (result != TCL_OK) {
4206 return result;
4207 }
4208 } else {
4209 Tcl_WrongNumArgs(interp, 1, objv, "command ?count?");
4210 return TCL_ERROR;
4211 }
4212
4213 objPtr = objv[1];
4214 i = count;
4215 #ifndef TCL_WIDE_CLICKS
4216 Tcl_GetTime(&start);
4217 #else
4218 start = TclpGetWideClicks();
4219 #endif
4220 while (i-- > 0) {
4221 result = TclEvalObjEx(interp, objPtr, 0, NULL, 0);
4222 if (result != TCL_OK) {
4223 return result;
4224 }
4225 }
4226 #ifndef TCL_WIDE_CLICKS
4227 Tcl_GetTime(&stop);
4228 totalMicroSec = ((double) (stop.sec - start.sec)) * 1.0e6
4229 + (stop.usec - start.usec);
4230 #else
4231 stop = TclpGetWideClicks();
4232 totalMicroSec = ((double) TclpWideClicksToNanoseconds(stop - start))/1.0e3;
4233 #endif
4234
4235 if (count <= 1) {
4236 /*
4237 * Use int obj since we know time is not fractional. [Bug 1202178]
4238 */
4239
4240 objs[0] = Tcl_NewWideIntObj((count <= 0) ? 0 : (Tcl_WideInt)totalMicroSec);
4241 } else {
4242 objs[0] = Tcl_NewDoubleObj(totalMicroSec/count);
4243 }
4244
4245 /*
4246 * Construct the result as a list because many programs have always parsed
4247 * as such (extracting the first element, typically).
4248 */
4249
4250 TclNewLiteralStringObj(objs[1], "microseconds");
4251 TclNewLiteralStringObj(objs[2], "per");
4252 TclNewLiteralStringObj(objs[3], "iteration");
4253 Tcl_SetObjResult(interp, Tcl_NewListObj(4, objs));
4254
4255 return TCL_OK;
4256 }
4257
4258 /*
4259 *----------------------------------------------------------------------
4260 *
4261 * Tcl_TimeRateObjCmd --
4262 *
4263 * This object-based procedure is invoked to process the "timerate" Tcl
4264 * command.
4265 *
4266 * This is similar to command "time", except the execution limited by
4267 * given time (in milliseconds) instead of repetition count.
4268 *
4269 * Example:
4270 * timerate {after 5} 1000; # equivalent to: time {after 5} [expr 1000/5]
4271 *
4272 * Results:
4273 * A standard Tcl object result.
4274 *
4275 * Side effects:
4276 * See the user documentation.
4277 *
4278 *----------------------------------------------------------------------
4279 */
4280
4281 int
4282 Tcl_TimeRateObjCmd(
4283 ClientData dummy, /* Not used. */
4284 Tcl_Interp *interp, /* Current interpreter. */
4285 int objc, /* Number of arguments. */
4286 Tcl_Obj *const objv[]) /* Argument objects. */
4287 {
4288 static double measureOverhead = 0;
4289 /* global measure-overhead */
4290 double overhead = -1; /* given measure-overhead */
4291 Tcl_Obj *objPtr;
4292 int result, i;
4293 Tcl_Obj *calibrate = NULL, *direct = NULL;
4294 TclWideMUInt count = 0; /* Holds repetition count */
4295 TclWideMUInt lastCount = 0; /* Repetition count since last calculation. */
4296 Tcl_WideInt maxms = WIDE_MIN;
4297 /* Maximal running time (in milliseconds) */
4298 TclWideMUInt maxcnt = WIDE_MAX;
4299 /* Maximal count of iterations. */
4300 TclWideMUInt threshold = 1; /* Current threshold for check time (faster
4301 * repeat count without time check) */
4302 TclWideMUInt avgIterTm = 1; /* Average time of all processed iterations. */
4303 TclWideMUInt lastIterTm = 1;/* Average time of last block of iterations. */
4304 double estIterTm = 1.0; /* Estimated time of next iteration,
4305 * considering the growth of lastIterTm. */
4306 #ifdef TCL_WIDE_CLICKS
4307 # define TR_SCALE 10 /* Fraction is 10ns (from wide click 100ns). */
4308 #else
4309 # define TR_SCALE 100 /* Fraction is 10ns (from 1us = 1000ns). */
4310 #endif
4311 #define TR_MIN_FACTOR 2 /* Min allowed factor calculating threshold. */
4312 #define TR_MAX_FACTOR 50 /* Max allowed factor calculating threshold. */
4313 #define TR_FACT_SINGLE_ITER 25 /* This or larger factor value will force the
4314 * threshold 1, to avoid drastic growth of
4315 * execution time by quadratic O() complexity. */
4316 unsigned short factor = 16; /* Factor (2..50) limiting threshold to avoid
4317 * growth of execution time. */
4318 Tcl_WideInt start, last, middle, stop;
4319 #ifndef TCL_WIDE_CLICKS
4320 Tcl_Time now;
4321 #endif /* !TCL_WIDE_CLICKS */
4322 static const char *const options[] = {
4323 "-direct", "-overhead", "-calibrate", "--", NULL
4324 };
4325 enum options {
4326 TMRT_EV_DIRECT, TMRT_OVERHEAD, TMRT_CALIBRATE, TMRT_LAST
4327 };
4328 NRE_callback *rootPtr;
4329 ByteCode *codePtr = NULL;
4330
4331 for (i = 1; i < objc - 1; i++) {
4332 int index;
4333
4334 if (Tcl_GetIndexFromObj(NULL, objv[i], options, "option", TCL_EXACT,
4335 &index) != TCL_OK) {
4336 break;
4337 }
4338 if (index == TMRT_LAST) {
4339 i++;
4340 break;
4341 }
4342 switch (index) {
4343 case TMRT_EV_DIRECT:
4344 direct = objv[i];
4345 break;
4346 case TMRT_OVERHEAD:
4347 if (++i >= objc - 1) {
4348 goto usage;
4349 }
4350 if (Tcl_GetDoubleFromObj(interp, objv[i], &overhead) != TCL_OK) {
4351 return TCL_ERROR;
4352 }
4353 break;
4354 case TMRT_CALIBRATE:
4355 calibrate = objv[i];
4356 break;
4357 }
4358 }
4359
4360 if (i >= objc || i < objc - 3) {
4361 usage:
4362 Tcl_WrongNumArgs(interp, 1, objv,
4363 "?-direct? ?-calibrate? ?-overhead double? "
4364 "command ?time ?max-count??");
4365 return TCL_ERROR;
4366 }
4367 objPtr = objv[i++];
4368 if (i < objc) { /* max-time */
4369 result = Tcl_GetWideIntFromObj(interp, objv[i++], &maxms);
4370 if (result != TCL_OK) {
4371 return result;
4372 }
4373 if (i < objc) { /* max-count*/
4374 Tcl_WideInt v;
4375
4376 result = Tcl_GetWideIntFromObj(interp, objv[i], &v);
4377 if (result != TCL_OK) {
4378 return result;
4379 }
4380 maxcnt = (v > 0) ? v : 0;
4381 }
4382 }
4383
4384 /*
4385 * If we are doing calibration.
4386 */
4387
4388 if (calibrate) {
4389 /*
4390 * If no time specified for the calibration.
4391 */
4392
4393 if (maxms == WIDE_MIN) {
4394 Tcl_Obj *clobjv[6];
4395 Tcl_WideInt maxCalTime = 5000;
4396 double lastMeasureOverhead = measureOverhead;
4397
4398 clobjv[0] = objv[0];
4399 i = 1;
4400 if (direct) {
4401 clobjv[i++] = direct;
4402 }
4403 clobjv[i++] = objPtr;
4404
4405 /*
4406 * Reset last measurement overhead.
4407 */
4408
4409 measureOverhead = (double) 0;
4410
4411 /*
4412 * Self-call with 100 milliseconds to warm-up, before entering the
4413 * calibration cycle.
4414 */
4415
4416 TclNewLongObj(clobjv[i], 100);
4417 Tcl_IncrRefCount(clobjv[i]);
4418 result = Tcl_TimeRateObjCmd(NULL, interp, i + 1, clobjv);
4419 Tcl_DecrRefCount(clobjv[i]);
4420 if (result != TCL_OK) {
4421 return result;
4422 }
4423
4424 i--;
4425 clobjv[i++] = calibrate;
4426 clobjv[i++] = objPtr;
4427
4428 /*
4429 * Set last measurement overhead to max.
4430 */
4431
4432 measureOverhead = (double) UWIDE_MAX;
4433
4434 /*
4435 * Run the calibration cycle until it is more precise.
4436 */
4437
4438 maxms = -1000;
4439 do {
4440 lastMeasureOverhead = measureOverhead;
4441 TclNewLongObj(clobjv[i], (int) maxms);
4442 Tcl_IncrRefCount(clobjv[i]);
4443 result = Tcl_TimeRateObjCmd(NULL, interp, i + 1, clobjv);
4444 Tcl_DecrRefCount(clobjv[i]);
4445 if (result != TCL_OK) {
4446 return result;
4447 }
4448 maxCalTime += maxms;
4449
4450 /*
4451 * Increase maxms for more precise calibration.
4452 */
4453
4454 maxms -= -maxms / 4;
4455
4456 /*
4457 * As long as new value more as 0.05% better
4458 */
4459 } while ((measureOverhead >= lastMeasureOverhead
4460 || measureOverhead / lastMeasureOverhead <= 0.9995)
4461 && maxCalTime > 0);
4462
4463 return result;
4464 }
4465 if (maxms == 0) {
4466 /*
4467 * Reset last measurement overhead
4468 */
4469
4470 measureOverhead = 0;
4471 Tcl_SetObjResult(interp, Tcl_NewLongObj(0));
4472 return TCL_OK;
4473 }
4474
4475 /*
4476 * If time is negative, make current overhead more precise.
4477 */
4478
4479 if (maxms > 0) {
4480 /*
4481 * Set last measurement overhead to max.
4482 */
4483
4484 measureOverhead = (double) UWIDE_MAX;
4485 } else {
4486 maxms = -maxms;
4487 }
4488 }
4489
4490 if (maxms == WIDE_MIN) {
4491 maxms = 1000;
4492 }
4493 if (overhead == -1) {
4494 overhead = measureOverhead;
4495 }
4496
4497 /*
4498 * Ensure that resetting of result will not smudge the further
4499 * measurement.
4500 */
4501
4502 Tcl_ResetResult(interp);
4503
4504 /*
4505 * Compile object if needed.
4506 */
4507
4508 if (!direct) {
4509 if (TclInterpReady(interp) != TCL_OK) {
4510 return TCL_ERROR;
4511 }
4512 codePtr = TclCompileObj(interp, objPtr, NULL, 0);
4513 TclPreserveByteCode(codePtr);
4514 }
4515
4516 /*
4517 * Get start and stop time.
4518 */
4519
4520 #ifdef TCL_WIDE_CLICKS
4521 start = last = middle = TclpGetWideClicks();
4522
4523 /*
4524 * Time to stop execution (in wide clicks).
4525 */
4526
4527 stop = start + (maxms * 1000 / TclpWideClickInMicrosec());
4528 #else
4529 Tcl_GetTime(&now);
4530 start = now.sec;
4531 start *= 1000000;
4532 start += now.usec;
4533 last = middle = start;
4534
4535 /*
4536 * Time to stop execution (in microsecs).
4537 */
4538
4539 stop = start + maxms * 1000;
4540 #endif /* TCL_WIDE_CLICKS */
4541
4542 /*
4543 * Start measurement.
4544 */
4545
4546 if (maxcnt > 0) {
4547 while (1) {
4548 /*
4549 * Evaluate a single iteration.
4550 */
4551
4552 count++;
4553 if (!direct) { /* precompiled */
4554 rootPtr = TOP_CB(interp);
4555 /*
4556 * Use loop optimized TEBC call (TCL_EVAL_DISCARD_RESULT): it's a part of
4557 * iteration, this way evaluation will be more similar to a cycle (also
4558 * avoids extra overhead to set result to interp, etc.)
4559 */
4560 ((Interp *)interp)->evalFlags |= TCL_EVAL_DISCARD_RESULT;
4561 result = TclNRExecuteByteCode(interp, codePtr);
4562 result = TclNRRunCallbacks(interp, result, rootPtr);
4563 } else { /* eval */
4564 result = TclEvalObjEx(interp, objPtr, 0, NULL, 0);
4565 }
4566 /*
4567 * Allow break and continue from measurement cycle (used for
4568 * conditional stop and flow control of iterations).
4569 */
4570
4571 switch (result) {
4572 case TCL_OK:
4573 break;
4574 case TCL_BREAK:
4575 /*
4576 * Force stop immediately.
4577 */
4578 threshold = 1;
4579 maxcnt = 0;
4580 /* FALLTHRU */
4581 case TCL_CONTINUE:
4582 result = TCL_OK;
4583 break;
4584 default:
4585 goto done;
4586 }
4587
4588 /*
4589 * Don't check time up to threshold.
4590 */
4591
4592 if (--threshold > 0) {
4593 continue;
4594 }
4595
4596 /*
4597 * Check stop time reached, estimate new threshold.
4598 */
4599
4600 #ifdef TCL_WIDE_CLICKS
4601 middle = TclpGetWideClicks();
4602 #else
4603 Tcl_GetTime(&now);
4604 middle = now.sec;
4605 middle *= 1000000;
4606 middle += now.usec;
4607 #endif /* TCL_WIDE_CLICKS */
4608
4609 if (middle >= stop || count >= maxcnt) {
4610 break;
4611 }
4612
4613 /*
4614 * Average iteration time (scaled) in fractions of wide clicks
4615 * or microseconds.
4616 */
4617
4618 threshold = (TclWideMUInt)(middle - start) * TR_SCALE / count;
4619 if (threshold > avgIterTm) {
4620
4621 /*
4622 * Iterations seem to be longer.
4623 */
4624
4625 if (threshold > avgIterTm * 2) {
4626 factor *= 2;
4627 } else {
4628 factor++;
4629 }
4630 if (factor > TR_MAX_FACTOR) {
4631 factor = TR_MAX_FACTOR;
4632 }
4633 } else if (factor > TR_MIN_FACTOR) {
4634 /*
4635 * Iterations seem to be shorter.
4636 */
4637
4638 if (threshold < (avgIterTm / 2)) {
4639 factor /= 2;
4640 if (factor < TR_MIN_FACTOR) {
4641 factor = TR_MIN_FACTOR;
4642 }
4643 } else {
4644 factor--;
4645 }
4646 }
4647
4648 if (!threshold) {
4649 /* too short and too few iterations */
4650 threshold = 1;
4651 continue;
4652 }
4653 avgIterTm = threshold;
4654
4655 /*
4656 * Estimate last iteration time growth and time of next iteration.
4657 */
4658 lastCount = count - lastCount;
4659 if (last != start && lastCount) {
4660 TclWideMUInt lastTm;
4661
4662 lastTm = (TclWideMUInt)(middle - last) * TR_SCALE / lastCount;
4663 estIterTm = (double)lastTm / (lastIterTm ? lastIterTm : avgIterTm);
4664 lastIterTm = lastTm > avgIterTm ? lastTm : avgIterTm;
4665 } else {
4666 lastIterTm = avgIterTm;
4667 }
4668 estIterTm *= lastIterTm;
4669 last = middle; lastCount = count;
4670
4671 /*
4672 * Calculate next threshold to check.
4673 * Firstly check iteration time is not larger than remaining time,
4674 * considering last known iteration growth factor.
4675 */
4676 threshold = (TclWideMUInt)(stop - middle) * TR_SCALE;
4677 /*
4678 * Estimated count of iteration til the end of execution.
4679 * Thereby 2.5% longer execution time would be OK.
4680 */
4681 if (threshold / estIterTm < 0.975) {
4682 /* estimated time for next iteration is too large */
4683 break;
4684 }
4685 threshold /= estIterTm;
4686 /*
4687 * Don't use threshold by few iterations, because sometimes
4688 * first iteration(s) can be too fast or slow (cached, delayed
4689 * clean up, etc). Also avoid unexpected execution time growth,
4690 * so if iterations continuously grow, stay by single iteration.
4691 */
4692 if (count < 10 || factor >= TR_FACT_SINGLE_ITER) {
4693 threshold = 1;
4694 continue;
4695 }
4696 /*
4697 * Reduce it by last known factor, to avoid unexpected execution
4698 * time growth if iterations are not consistent (may be longer).
4699 */
4700 threshold = threshold / factor + 1;
4701 if (threshold > 100000) { /* fix for too large threshold */
4702 threshold = 100000;
4703 }
4704
4705 /*
4706 * Consider max-count
4707 */
4708
4709 if (threshold > maxcnt - count) {
4710 threshold = maxcnt - count;
4711 }
4712 }
4713 }
4714
4715 {
4716 Tcl_Obj *objarr[8], **objs = objarr;
4717 TclWideMUInt usec, val;
4718 int digits;
4719
4720 /*
4721 * Absolute execution time in microseconds or in wide clicks.
4722 */
4723 usec = (TclWideMUInt)(middle - start);
4724
4725 #ifdef TCL_WIDE_CLICKS
4726 /*
4727 * convert execution time (in wide clicks) to microsecs.
4728 */
4729
4730 usec *= TclpWideClickInMicrosec();
4731 #endif /* TCL_WIDE_CLICKS */
4732
4733 if (!count) { /* no iterations - avoid divide by zero */
4734 objs[0] = objs[2] = objs[4] = Tcl_NewWideIntObj(0);
4735 goto retRes;
4736 }
4737
4738 /*
4739 * If not calibrating...
4740 */
4741
4742 if (!calibrate) {
4743 /*
4744 * Minimize influence of measurement overhead.
4745 */
4746
4747 if (overhead > 0) {
4748 /*
4749 * Estimate the time of overhead (microsecs).
4750 */
4751
4752 TclWideMUInt curOverhead = overhead * count;
4753
4754 if (usec > curOverhead) {
4755 usec -= curOverhead;
4756 } else {
4757 usec = 0;
4758 }
4759 }
4760 } else {
4761 /*
4762 * Calibration: obtaining new measurement overhead.
4763 */
4764
4765 if (measureOverhead > ((double) usec) / count) {
4766 measureOverhead = ((double) usec) / count;
4767 }
4768 objs[0] = Tcl_NewDoubleObj(measureOverhead);
4769 TclNewLiteralStringObj(objs[1], "\xC2\xB5s/#-overhead"); /* mics */
4770 objs += 2;
4771 }
4772
4773 val = usec / count; /* microsecs per iteration */
4774 if (val >= 1000000) {
4775 objs[0] = Tcl_NewWideIntObj(val);
4776 } else {
4777 if (val < 10) {
4778 digits = 6;
4779 } else if (val < 100) {
4780 digits = 4;
4781 } else if (val < 1000) {
4782 digits = 3;
4783 } else if (val < 10000) {
4784 digits = 2;
4785 } else {
4786 digits = 1;
4787 }
4788 objs[0] = Tcl_ObjPrintf("%.*f", digits, ((double) usec)/count);
4789 }
4790
4791 objs[2] = Tcl_NewWideIntObj(count); /* iterations */
4792
4793 /*
4794 * Calculate speed as rate (count) per sec
4795 */
4796
4797 if (!usec) {
4798 usec++; /* Avoid divide by zero. */
4799 }
4800 if (count < (WIDE_MAX / 1000000)) {
4801 val = (count * 1000000) / usec;
4802 if (val < 100000) {
4803 if (val < 100) {
4804 digits = 3;
4805 } else if (val < 1000) {
4806 digits = 2;
4807 } else {
4808 digits = 1;
4809 }
4810 objs[4] = Tcl_ObjPrintf("%.*f",
4811 digits, ((double) (count * 1000000)) / usec);
4812 } else {
4813 objs[4] = Tcl_NewWideIntObj(val);
4814 }
4815 } else {
4816 objs[4] = Tcl_NewWideIntObj((count / usec) * 1000000);
4817 }
4818
4819 retRes:
4820 /*
4821 * Estimated net execution time (in millisecs).
4822 */
4823
4824 if (!calibrate) {
4825 if (usec >= 1) {
4826 objs[6] = Tcl_ObjPrintf("%.3f", (double)usec / 1000);
4827 } else {
4828 objs[6] = Tcl_NewWideIntObj(0);
4829 }
4830 TclNewLiteralStringObj(objs[7], "net-ms");
4831 }
4832
4833 /*
4834 * Construct the result as a list because many programs have always
4835 * parsed as such (extracting the first element, typically).
4836 */
4837
4838 TclNewLiteralStringObj(objs[1], "\xC2\xB5s/#"); /* mics/# */
4839 TclNewLiteralStringObj(objs[3], "#");
4840 TclNewLiteralStringObj(objs[5], "#/sec");
4841 Tcl_SetObjResult(interp, Tcl_NewListObj(8, objarr));
4842 }
4843
4844 done:
4845 if (codePtr != NULL) {
4846 TclReleaseByteCode(codePtr);
4847 }
4848 return result;
4849 #undef TR_SCALE
4850 #undef TR_MIN_FACTOR
4851 #undef TR_MAX_FACTOR
4852 #undef TR_FACT_SINGLE_ITER
4853 }
4854
4855 /*
4856 *----------------------------------------------------------------------
4857 *
4858 * Tcl_TryObjCmd, TclNRTryObjCmd --
4859 *
4860 * This procedure is invoked to process the "try" Tcl command. See the
4861 * user documentation (or TIP #329) for details on what it does.
4862 *
4863 * Results:
4864 * A standard Tcl object result.
4865 *
4866 * Side effects:
4867 * See the user documentation.
4868 *
4869 *----------------------------------------------------------------------
4870 */
4871
4872 int
4873 Tcl_TryObjCmd(
4874 ClientData dummy, /* Not used. */
4875 Tcl_Interp *interp, /* Current interpreter. */
4876 int objc, /* Number of arguments. */
4877 Tcl_Obj *const objv[]) /* Argument objects. */
4878 {
4879 return Tcl_NRCallObjProc(interp, TclNRTryObjCmd, dummy, objc, objv);
4880 }
4881
4882 int
4883 TclNRTryObjCmd(
4884 ClientData clientData, /* Not used. */
4885 Tcl_Interp *interp, /* Current interpreter. */
4886 int objc, /* Number of arguments. */
4887 Tcl_Obj *const objv[]) /* Argument objects. */
4888 {
4889 Tcl_Obj *bodyObj, *handlersObj, *finallyObj = NULL;
4890 int i, bodyShared, haveHandlers, dummy, code;
4891 static const char *const handlerNames[] = {
4892 "finally", "on", "trap", NULL
4893 };
4894 enum Handlers {
4895 TryFinally, TryOn, TryTrap
4896 };
4897
4898 /*
4899 * Parse the arguments. The handlers are passed to subsequent callbacks as
4900 * a Tcl_Obj list of the 5-tuples like (type, returnCode, errorCodePrefix,
4901 * bindVariables, script), and the finally script is just passed as it is.
4902 */
4903
4904 if (objc < 2) {
4905 Tcl_WrongNumArgs(interp, 1, objv,
4906 "body ?handler ...? ?finally script?");
4907 return TCL_ERROR;
4908 }
4909 bodyObj = objv[1];
4910 TclNewObj(handlersObj);
4911 bodyShared = 0;
4912 haveHandlers = 0;
4913 for (i=2 ; i<objc ; i++) {
4914 int type;
4915 Tcl_Obj *info[5];
4916
4917 if (Tcl_GetIndexFromObj(interp, objv[i], handlerNames, "handler type",
4918 0, &type) != TCL_OK) {
4919 Tcl_DecrRefCount(handlersObj);
4920 return TCL_ERROR;
4921 }
4922 switch ((enum Handlers) type) {
4923 case TryFinally: /* finally script */
4924 if (i < objc-2) {
4925 Tcl_SetObjResult(interp, Tcl_NewStringObj(
4926 "finally clause must be last", -1));
4927 Tcl_DecrRefCount(handlersObj);
4928 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "TRY", "FINALLY",
4929 "NONTERMINAL", (char *)NULL);
4930 return TCL_ERROR;
4931 } else if (i == objc-1) {
4932 Tcl_SetObjResult(interp, Tcl_NewStringObj(
4933 "wrong # args to finally clause: must be"
4934 " \"... finally script\"", -1));
4935 Tcl_DecrRefCount(handlersObj);
4936 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "TRY", "FINALLY",
4937 "ARGUMENT", (char *)NULL);
4938 return TCL_ERROR;
4939 }
4940 finallyObj = objv[++i];
4941 break;
4942
4943 case TryOn: /* on code variableList script */
4944 if (i > objc-4) {
4945 Tcl_SetObjResult(interp, Tcl_NewStringObj(
4946 "wrong # args to on clause: must be \"... on code"
4947 " variableList script\"", -1));
4948 Tcl_DecrRefCount(handlersObj);
4949 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "TRY", "ON",
4950 "ARGUMENT", (char *)NULL);
4951 return TCL_ERROR;
4952 }
4953 if (TclGetCompletionCodeFromObj(interp, objv[i+1],
4954 &code) != TCL_OK) {
4955 Tcl_DecrRefCount(handlersObj);
4956 return TCL_ERROR;
4957 }
4958 info[2] = NULL;
4959 goto commonHandler;
4960
4961 case TryTrap: /* trap pattern variableList script */
4962 if (i > objc-4) {
4963 Tcl_SetObjResult(interp, Tcl_NewStringObj(
4964 "wrong # args to trap clause: "
4965 "must be \"... trap pattern variableList script\"",
4966 -1));
4967 Tcl_DecrRefCount(handlersObj);
4968 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "TRY", "TRAP",
4969 "ARGUMENT", (char *)NULL);
4970 return TCL_ERROR;
4971 }
4972 code = 1;
4973 if (TclListObjLength(NULL, objv[i+1], &dummy) != TCL_OK) {
4974 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4975 "bad prefix '%s': must be a list",
4976 TclGetString(objv[i+1])));
4977 Tcl_DecrRefCount(handlersObj);
4978 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "TRY", "TRAP",
4979 "EXNFORMAT", (char *)NULL);
4980 return TCL_ERROR;
4981 }
4982 info[2] = objv[i+1];
4983
4984 commonHandler:
4985 if (TclListObjLength(interp, objv[i+2], &dummy) != TCL_OK) {
4986 Tcl_DecrRefCount(handlersObj);
4987 return TCL_ERROR;
4988 }
4989
4990 info[0] = objv[i]; /* type */
4991 TclNewIntObj(info[1], code); /* returnCode */
4992 if (info[2] == NULL) { /* errorCodePrefix */
4993 TclNewObj(info[2]);
4994 }
4995 info[3] = objv[i+2]; /* bindVariables */
4996 info[4] = objv[i+3]; /* script */
4997
4998 bodyShared = !strcmp(TclGetString(objv[i+3]), "-");
4999 Tcl_ListObjAppendElement(NULL, handlersObj,
5000 Tcl_NewListObj(5, info));
5001 haveHandlers = 1;
5002 i += 3;
5003 break;
5004 }
5005 }
5006 if (bodyShared) {
5007 Tcl_SetObjResult(interp, Tcl_NewStringObj(
5008 "last non-finally clause must not have a body of \"-\"", -1));
5009 Tcl_DecrRefCount(handlersObj);
5010 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "TRY", "BADFALLTHROUGH",
5011 (char *)NULL);
5012 return TCL_ERROR;
5013 }
5014 if (!haveHandlers) {
5015 Tcl_DecrRefCount(handlersObj);
5016 handlersObj = NULL;
5017 }
5018
5019 /*
5020 * Execute the body.
5021 */
5022
5023 Tcl_NRAddCallback(interp, TryPostBody, handlersObj, finallyObj,
5024 (ClientData)objv, INT2PTR(objc));
5025 return TclNREvalObjEx(interp, bodyObj, 0,
5026 ((Interp *) interp)->cmdFramePtr, 1);
5027 }
5028
5029 /*
5030 *----------------------------------------------------------------------
5031 *
5032 * During --
5033 *
5034 * This helper function patches together the updates to the interpreter's
5035 * return options that are needed when things fail during the processing
5036 * of a handler or finally script for the [try] command.
5037 *
5038 * Returns:
5039 * The new option dictionary.
5040 *
5041 *----------------------------------------------------------------------
5042 */
5043
5044 static inline Tcl_Obj *
5045 During(
5046 Tcl_Interp *interp,
5047 int resultCode, /* The result code from the just-evaluated
5048 * script. */
5049 Tcl_Obj *oldOptions, /* The old option dictionary. */
5050 Tcl_Obj *errorInfo) /* An object to append to the errorinfo and
5051 * release, or NULL if nothing is to be added.
5052 * Designed to be used with Tcl_ObjPrintf. */
5053 {
5054 Tcl_Obj *during, *options;
5055
5056 if (errorInfo != NULL) {
5057 Tcl_AppendObjToErrorInfo(interp, errorInfo);
5058 }
5059 options = Tcl_GetReturnOptions(interp, resultCode);
5060 TclNewLiteralStringObj(during, "-during");
5061 Tcl_IncrRefCount(during);
5062 Tcl_DictObjPut(interp, options, during, oldOptions);
5063 Tcl_DecrRefCount(during);
5064 Tcl_IncrRefCount(options);
5065 Tcl_DecrRefCount(oldOptions);
5066 return options;
5067 }
5068
5069 /*
5070 *----------------------------------------------------------------------
5071 *
5072 * TryPostBody --
5073 *
5074 * Callback to handle the outcome of the execution of the body of a 'try'
5075 * command.
5076 *
5077 *----------------------------------------------------------------------
5078 */
5079
5080 static int
5081 TryPostBody(
5082 ClientData data[],
5083 Tcl_Interp *interp,
5084 int result)
5085 {
5086 Tcl_Obj *resultObj, *options, *handlersObj, *finallyObj, *cmdObj, **objv;
5087 int i, dummy, code, objc;
5088 int numHandlers = 0;
5089
5090 handlersObj = (Tcl_Obj *)data[0];
5091 finallyObj = (Tcl_Obj *)data[1];
5092 objv = (Tcl_Obj **)data[2];
5093 objc = PTR2INT(data[3]);
5094
5095 cmdObj = objv[0];
5096
5097 /*
5098 * Check for limits/rewinding, which override normal trapping behaviour.
5099 */
5100
5101 if (((Interp*) interp)->execEnvPtr->rewind || Tcl_LimitExceeded(interp)) {
5102 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
5103 "\n (\"%s\" body line %d)", TclGetString(cmdObj),
5104 Tcl_GetErrorLine(interp)));
5105 if (handlersObj != NULL) {
5106 Tcl_DecrRefCount(handlersObj);
5107 }
5108 return TCL_ERROR;
5109 }
5110
5111 /*
5112 * Basic processing of the outcome of the script, including adding of
5113 * errorinfo trace.
5114 */
5115
5116 if (result == TCL_ERROR) {
5117 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
5118 "\n (\"%s\" body line %d)", TclGetString(cmdObj),
5119 Tcl_GetErrorLine(interp)));
5120 }
5121 resultObj = Tcl_GetObjResult(interp);
5122 Tcl_IncrRefCount(resultObj);
5123 options = Tcl_GetReturnOptions(interp, result);
5124 Tcl_IncrRefCount(options);
5125 Tcl_ResetResult(interp);
5126
5127 /*
5128 * Handle the results.
5129 */
5130
5131 if (handlersObj != NULL) {
5132 int found = 0;
5133 Tcl_Obj **handlers, **info;
5134
5135 TclListObjGetElements(NULL, handlersObj, &numHandlers, &handlers);
5136 for (i=0 ; i<numHandlers ; i++) {
5137 Tcl_Obj *handlerBodyObj;
5138
5139 TclListObjGetElements(NULL, handlers[i], &dummy, &info);
5140 if (!found) {
5141 Tcl_GetIntFromObj(NULL, info[1], &code);
5142 if (code != result) {
5143 continue;
5144 }
5145
5146 /*
5147 * When processing an error, we must also perform list-prefix
5148 * matching of the errorcode list. However, if this was an
5149 * 'on' handler, the list that we are matching against will be
5150 * empty.
5151 */
5152
5153 if (code == TCL_ERROR) {
5154 Tcl_Obj *errcode, **bits1, **bits2;
5155 int len1, len2, j;
5156
5157 TclDictGet(NULL, options, "-errorcode", &errcode);
5158 TclListObjGetElements(NULL, info[2], &len1, &bits1);
5159 if (TclListObjGetElements(NULL, errcode, &len2,
5160 &bits2) != TCL_OK) {
5161 continue;
5162 }
5163 if (len2 < len1) {
5164 continue;
5165 }
5166 for (j=0 ; j<len1 ; j++) {
5167 if (strcmp(TclGetString(bits1[j]),
5168 TclGetString(bits2[j])) != 0) {
5169 /*
5170 * Really want 'continue outerloop;', but C does
5171 * not give us that.
5172 */
5173
5174 goto didNotMatch;
5175 }
5176 }
5177 }
5178
5179 found = 1;
5180 }
5181
5182 /*
5183 * Now we need to scan forward over "-" bodies. Note that we've
5184 * already checked that the last body is not a "-", so this search
5185 * will terminate successfully.
5186 */
5187
5188 if (!strcmp(TclGetString(info[4]), "-")) {
5189 continue;
5190 }
5191
5192 /*
5193 * Bind the variables. We already know this is a list of variable
5194 * names, but it might be empty.
5195 */
5196
5197 Tcl_ResetResult(interp);
5198 result = TCL_ERROR;
5199 TclListObjLength(NULL, info[3], &dummy);
5200 if (dummy > 0) {
5201 Tcl_Obj *varName;
5202
5203 Tcl_ListObjIndex(NULL, info[3], 0, &varName);
5204 if (Tcl_ObjSetVar2(interp, varName, NULL, resultObj,
5205 TCL_LEAVE_ERR_MSG) == NULL) {
5206 Tcl_DecrRefCount(resultObj);
5207 goto handlerFailed;
5208 }
5209 Tcl_DecrRefCount(resultObj);
5210 if (dummy > 1) {
5211 Tcl_ListObjIndex(NULL, info[3], 1, &varName);
5212 if (Tcl_ObjSetVar2(interp, varName, NULL, options,
5213 TCL_LEAVE_ERR_MSG) == NULL) {
5214 goto handlerFailed;
5215 }
5216 }
5217 } else {
5218 /*
5219 * Dispose of the result to prevent a memleak. [Bug 2910044]
5220 */
5221
5222 Tcl_DecrRefCount(resultObj);
5223 }
5224
5225 /*
5226 * Evaluate the handler body and process the outcome. Note that we
5227 * need to keep the kind of handler for debugging purposes, and in
5228 * any case anything we want from info[] must be extracted right
5229 * now because the info[] array is about to become invalid. There
5230 * is very little refcount handling here however, since we know
5231 * that the objects that we still want to refer to now were input
5232 * arguments to [try] and so are still on the Tcl value stack.
5233 */
5234
5235 handlerBodyObj = info[4];
5236 Tcl_NRAddCallback(interp, TryPostHandler, objv, options, info[0],
5237 INT2PTR((finallyObj == NULL) ? 0 : objc - 1));
5238 Tcl_DecrRefCount(handlersObj);
5239 return TclNREvalObjEx(interp, handlerBodyObj, 0,
5240 ((Interp *) interp)->cmdFramePtr, 4*i + 5);
5241
5242 handlerFailed:
5243 resultObj = Tcl_GetObjResult(interp);
5244 Tcl_IncrRefCount(resultObj);
5245 options = During(interp, result, options, NULL);
5246 break;
5247
5248 didNotMatch:
5249 continue;
5250 }
5251
5252 /*
5253 * No handler matched; get rid of the list of handlers.
5254 */
5255
5256 Tcl_DecrRefCount(handlersObj);
5257 }
5258
5259 /*
5260 * Process the finally clause.
5261 */
5262
5263 if (finallyObj != NULL) {
5264 Tcl_NRAddCallback(interp, TryPostFinal, resultObj, options, cmdObj,
5265 NULL);
5266 return TclNREvalObjEx(interp, finallyObj, 0,
5267 ((Interp *) interp)->cmdFramePtr, objc - 1);
5268 }
5269
5270 /*
5271 * Install the correct result/options into the interpreter and clean up
5272 * any temporary storage.
5273 */
5274
5275 result = Tcl_SetReturnOptions(interp, options);
5276 Tcl_DecrRefCount(options);
5277 Tcl_SetObjResult(interp, resultObj);
5278 Tcl_DecrRefCount(resultObj);
5279 return result;
5280 }
5281
5282 /*
5283 *----------------------------------------------------------------------
5284 *
5285 * TryPostHandler --
5286 *
5287 * Callback to handle the outcome of the execution of a handler of a
5288 * 'try' command.
5289 *
5290 *----------------------------------------------------------------------
5291 */
5292
5293 static int
5294 TryPostHandler(
5295 ClientData data[],
5296 Tcl_Interp *interp,
5297 int result)
5298 {
5299 Tcl_Obj *resultObj, *cmdObj, *options, *handlerKindObj, **objv;
5300 Tcl_Obj *finallyObj;
5301 int finallyIndex;
5302
5303 objv = (Tcl_Obj **)data[0];
5304 options = (Tcl_Obj *)data[1];
5305 handlerKindObj = (Tcl_Obj *)data[2];
5306 finallyIndex = PTR2INT(data[3]);
5307
5308 cmdObj = objv[0];
5309 finallyObj = finallyIndex ? objv[finallyIndex] : 0;
5310
5311 /*
5312 * Check for limits/rewinding, which override normal trapping behaviour.
5313 */
5314
5315 if (((Interp*) interp)->execEnvPtr->rewind || Tcl_LimitExceeded(interp)) {
5316 options = During(interp, result, options, Tcl_ObjPrintf(
5317 "\n (\"%s ... %s\" handler line %d)",
5318 TclGetString(cmdObj), TclGetString(handlerKindObj),
5319 Tcl_GetErrorLine(interp)));
5320 Tcl_DecrRefCount(options);
5321 return TCL_ERROR;
5322 }
5323
5324 /*
5325 * The handler result completely substitutes for the result of the body.
5326 */
5327
5328 resultObj = Tcl_GetObjResult(interp);
5329 Tcl_IncrRefCount(resultObj);
5330 if (result == TCL_ERROR) {
5331 options = During(interp, result, options, Tcl_ObjPrintf(
5332 "\n (\"%s ... %s\" handler line %d)",
5333 TclGetString(cmdObj), TclGetString(handlerKindObj),
5334 Tcl_GetErrorLine(interp)));
5335 } else {
5336 Tcl_DecrRefCount(options);
5337 options = Tcl_GetReturnOptions(interp, result);
5338 Tcl_IncrRefCount(options);
5339 }
5340
5341 /*
5342 * Process the finally clause if it is present.
5343 */
5344
5345 if (finallyObj != NULL) {
5346 Interp *iPtr = (Interp *) interp;
5347
5348 Tcl_NRAddCallback(interp, TryPostFinal, resultObj, options, cmdObj,
5349 NULL);
5350
5351 /* The 'finally' script is always the last argument word. */
5352 return TclNREvalObjEx(interp, finallyObj, 0, iPtr->cmdFramePtr,
5353 finallyIndex);
5354 }
5355
5356 /*
5357 * Install the correct result/options into the interpreter and clean up
5358 * any temporary storage.
5359 */
5360
5361 result = Tcl_SetReturnOptions(interp, options);
5362 Tcl_DecrRefCount(options);
5363 Tcl_SetObjResult(interp, resultObj);
5364 Tcl_DecrRefCount(resultObj);
5365 return result;
5366 }
5367
5368 /*
5369 *----------------------------------------------------------------------
5370 *
5371 * TryPostFinal --
5372 *
5373 * Callback to handle the outcome of the execution of the finally script
5374 * of a 'try' command.
5375 *
5376 *----------------------------------------------------------------------
5377 */
5378
5379 static int
5380 TryPostFinal(
5381 ClientData data[],
5382 Tcl_Interp *interp,
5383 int result)
5384 {
5385 Tcl_Obj *resultObj, *options, *cmdObj;
5386
5387 resultObj = (Tcl_Obj *)data[0];
5388 options = (Tcl_Obj *)data[1];
5389 cmdObj = (Tcl_Obj *)data[2];
5390
5391 /*
5392 * If the result wasn't OK, we need to adjust the result options.
5393 */
5394
5395 if (result != TCL_OK) {
5396 Tcl_DecrRefCount(resultObj);
5397 resultObj = NULL;
5398 if (result == TCL_ERROR) {
5399 options = During(interp, result, options, Tcl_ObjPrintf(
5400 "\n (\"%s ... finally\" body line %d)",
5401 TclGetString(cmdObj), Tcl_GetErrorLine(interp)));
5402 } else {
5403 Tcl_Obj *origOptions = options;
5404
5405 options = Tcl_GetReturnOptions(interp, result);
5406 Tcl_IncrRefCount(options);
5407 Tcl_DecrRefCount(origOptions);
5408 }
5409 }
5410
5411 /*
5412 * Install the correct result/options into the interpreter and clean up
5413 * any temporary storage.
5414 */
5415
5416 result = Tcl_SetReturnOptions(interp, options);
5417 Tcl_DecrRefCount(options);
5418 if (resultObj != NULL) {
5419 Tcl_SetObjResult(interp, resultObj);
5420 Tcl_DecrRefCount(resultObj);
5421 }
5422 return result;
5423 }
5424
5425 /*
5426 *----------------------------------------------------------------------
5427 *
5428 * Tcl_WhileObjCmd --
5429 *
5430 * This procedure is invoked to process the "while" Tcl command. See the
5431 * user documentation for details on what it does.
5432 *
5433 * With the bytecode compiler, this procedure is only called when a
5434 * command name is computed at runtime, and is "while" or the name to
5435 * which "while" was renamed: e.g., "set z while; $z {$i<100} {}"
5436 *
5437 * Results:
5438 * A standard Tcl result.
5439 *
5440 * Side effects:
5441 * See the user documentation.
5442 *
5443 *----------------------------------------------------------------------
5444 */
5445
5446 int
5447 Tcl_WhileObjCmd(
5448 ClientData dummy, /* Not used. */
5449 Tcl_Interp *interp, /* Current interpreter. */
5450 int objc, /* Number of arguments. */
5451 Tcl_Obj *const objv[]) /* Argument objects. */
5452 {
5453 return Tcl_NRCallObjProc(interp, TclNRWhileObjCmd, dummy, objc, objv);
5454 }
5455
5456 int
5457 TclNRWhileObjCmd(
5458 ClientData dummy, /* Not used. */
5459 Tcl_Interp *interp, /* Current interpreter. */
5460 int objc, /* Number of arguments. */
5461 Tcl_Obj *const objv[]) /* Argument objects. */
5462 {
5463 ForIterData *iterPtr;
5464
5465 if (objc != 3) {
5466 Tcl_WrongNumArgs(interp, 1, objv, "test command");
5467 return TCL_ERROR;
5468 }
5469
5470 /*
5471 * We reuse [for]'s callback, passing a NULL for the 'next' script.
5472 */
5473
5474 TclSmallAllocEx(interp, sizeof(ForIterData), iterPtr);
5475 iterPtr->cond = objv[1];
5476 iterPtr->body = objv[2];
5477 iterPtr->next = NULL;
5478 iterPtr->msg = "\n (\"while\" body line %d)";
5479 iterPtr->word = 2;
5480
5481 TclNRAddCallback(interp, TclNRForIterCallback, iterPtr, NULL,
5482 NULL, NULL);
5483 return TCL_OK;
5484 }
5485
5486 /*
5487 *----------------------------------------------------------------------
5488 *
5489 * TclListLines --
5490 *
5491 * ???
5492 *
5493 * Results:
5494 * Filled in array of line numbers?
5495 *
5496 * Side effects:
5497 * None.
5498 *
5499 *----------------------------------------------------------------------
5500 */
5501
5502 void
5503 TclListLines(
5504 Tcl_Obj *listObj, /* Pointer to obj holding a string with list
5505 * structure. Assumed to be valid. Assumed to
5506 * contain n elements. */
5507 int line, /* Line the list as a whole starts on. */
5508 int n, /* #elements in lines */
5509 int *lines, /* Array of line numbers, to fill. */
5510 Tcl_Obj *const *elems) /* The list elems as Tcl_Obj*, in need of
5511 * derived continuation data */
5512 {
5513 const char *listStr = TclGetString(listObj);
5514 const char *listHead = listStr;
5515 int i, length = strlen(listStr);
5516 const char *element = NULL, *next = NULL;
5517 ContLineLoc *clLocPtr = TclContinuationsGet(listObj);
5518 int *clNext = (clLocPtr ? &clLocPtr->loc[0] : NULL);
5519
5520 for (i = 0; i < n; i++) {
5521 TclFindElement(NULL, listStr, length, &element, &next, NULL, NULL);
5522
5523 TclAdvanceLines(&line, listStr, element);
5524 /* Leading whitespace */
5525 TclAdvanceContinuations(&line, &clNext, element - listHead);
5526 if (elems && clNext) {
5527 TclContinuationsEnterDerived(elems[i], element-listHead, clNext);
5528 }
5529 lines[i] = line;
5530 length -= (next - listStr);
5531 TclAdvanceLines(&line, element, next);
5532 /* Element */
5533 listStr = next;
5534
5535 if (*element == 0) {
5536 /* ASSERT i == n */
5537 break;
5538 }
5539 }
5540 }
5541
5542 /*
5543 * Local Variables:
5544 * mode: c
5545 * c-basic-offset: 4
5546 * fill-column: 78
5547 * End:
5548 */