Debian Codegraph @

generic/tclCompCmdsSZ.c

raw
1 /*
2 * tclCompCmdsSZ.c --
3 *
4 * This file contains compilation procedures that compile various Tcl
5 * commands (beginning with the letters 's' through 'z', except for
6 * [upvar] and [variable]) into a sequence of instructions ("bytecodes").
7 * Also includes the operator command compilers.
8 *
9 * Copyright (c) 1997-1998 Sun Microsystems, Inc.
10 * Copyright (c) 2001 Kevin B. Kenny. All rights reserved.
11 * Copyright (c) 2002 ActiveState Corporation.
12 * Copyright (c) 2004-2010 Donal K. Fellows.
13 *
14 * See the file "license.terms" for information on usage and redistribution of
15 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
16 */
17
18 #include "tclInt.h"
19 #include "tclCompile.h"
20 #include "tclStringTrim.h"
21
22 /*
23 * Prototypes for procedures defined later in this file:
24 */
25
26 static AuxDataDupProc DupJumptableInfo;
27 static AuxDataFreeProc FreeJumptableInfo;
28 static AuxDataPrintProc PrintJumptableInfo;
29 static AuxDataPrintProc DisassembleJumptableInfo;
30 static int CompileAssociativeBinaryOpCmd(Tcl_Interp *interp,
31 Tcl_Parse *parsePtr, const char *identity,
32 int instruction, CompileEnv *envPtr);
33 static int CompileComparisonOpCmd(Tcl_Interp *interp,
34 Tcl_Parse *parsePtr, int instruction,
35 CompileEnv *envPtr);
36 static int CompileStrictlyBinaryOpCmd(Tcl_Interp *interp,
37 Tcl_Parse *parsePtr, int instruction,
38 CompileEnv *envPtr);
39 static int CompileUnaryOpCmd(Tcl_Interp *interp,
40 Tcl_Parse *parsePtr, int instruction,
41 CompileEnv *envPtr);
42 static void IssueSwitchChainedTests(Tcl_Interp *interp,
43 CompileEnv *envPtr, int mode, int noCase,
44 int numWords, Tcl_Token **bodyToken,
45 int *bodyLines, int **bodyNext);
46 static void IssueSwitchJumpTable(Tcl_Interp *interp,
47 CompileEnv *envPtr, int numWords,
48 Tcl_Token **bodyToken, int *bodyLines,
49 int **bodyContLines);
50 static int IssueTryClausesInstructions(Tcl_Interp *interp,
51 CompileEnv *envPtr, Tcl_Token *bodyToken,
52 int numHandlers, int *matchCodes,
53 Tcl_Obj **matchClauses, int *resultVarIndices,
54 int *optionVarIndices, Tcl_Token **handlerTokens);
55 static int IssueTryClausesFinallyInstructions(Tcl_Interp *interp,
56 CompileEnv *envPtr, Tcl_Token *bodyToken,
57 int numHandlers, int *matchCodes,
58 Tcl_Obj **matchClauses, int *resultVarIndices,
59 int *optionVarIndices, Tcl_Token **handlerTokens,
60 Tcl_Token *finallyToken);
61 static int IssueTryFinallyInstructions(Tcl_Interp *interp,
62 CompileEnv *envPtr, Tcl_Token *bodyToken,
63 Tcl_Token *finallyToken);
64
65 /*
66 * The structures below define the AuxData types defined in this file.
67 */
68
69 const AuxDataType tclJumptableInfoType = {
70 "JumptableInfo", /* name */
71 DupJumptableInfo, /* dupProc */
72 FreeJumptableInfo, /* freeProc */
73 PrintJumptableInfo, /* printProc */
74 DisassembleJumptableInfo /* disassembleProc */
75 };
76
77 /*
78 * Shorthand macros for instruction issuing.
79 */
80
81 #define OP(name) TclEmitOpcode(INST_##name, envPtr)
82 #define OP1(name,val) TclEmitInstInt1(INST_##name,(val),envPtr)
83 #define OP4(name,val) TclEmitInstInt4(INST_##name,(val),envPtr)
84 #define OP14(name,val1,val2) \
85 TclEmitInstInt1(INST_##name,(val1),envPtr);TclEmitInt4((val2),envPtr)
86 #define OP44(name,val1,val2) \
87 TclEmitInstInt4(INST_##name,(val1),envPtr);TclEmitInt4((val2),envPtr)
88 #define PUSH(str) \
89 PushStringLiteral(envPtr, str)
90 #define JUMP4(name,var) \
91 (var) = CurrentOffset(envPtr);TclEmitInstInt4(INST_##name##4,0,envPtr)
92 #define FIXJUMP4(var) \
93 TclStoreInt4AtPtr(CurrentOffset(envPtr)-(var),envPtr->codeStart+(var)+1)
94 #define JUMP1(name,var) \
95 (var) = CurrentOffset(envPtr);TclEmitInstInt1(INST_##name##1,0,envPtr)
96 #define FIXJUMP1(var) \
97 TclStoreInt1AtPtr(CurrentOffset(envPtr)-(var),envPtr->codeStart+(var)+1)
98 #define LOAD(idx) \
99 if ((idx)<256) {OP1(LOAD_SCALAR1,(idx));} else {OP4(LOAD_SCALAR4,(idx));}
100 #define STORE(idx) \
101 if ((idx)<256) {OP1(STORE_SCALAR1,(idx));} else {OP4(STORE_SCALAR4,(idx));}
102 #define INVOKE(name) \
103 TclEmitInvoke(envPtr,INST_##name)
104
105
106 /*
107 *----------------------------------------------------------------------
108 *
109 * TclCompileSetCmd --
110 *
111 * Procedure called to compile the "set" command.
112 *
113 * Results:
114 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
115 * evaluation to runtime.
116 *
117 * Side effects:
118 * Instructions are added to envPtr to execute the "set" command at
119 * runtime.
120 *
121 *----------------------------------------------------------------------
122 */
123
124 int
125 TclCompileSetCmd(
126 Tcl_Interp *interp, /* Used for error reporting. */
127 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
128 * created by Tcl_ParseCommand. */
129 Command *cmdPtr, /* Points to definition of command being
130 * compiled. */
131 CompileEnv *envPtr) /* Holds resulting instructions. */
132 {
133 DefineLineInformation; /* TIP #280 */
134 Tcl_Token *varTokenPtr, *valueTokenPtr;
135 int isAssignment, isScalar, localIndex, numWords;
136
137 numWords = parsePtr->numWords;
138 if ((numWords != 2) && (numWords != 3)) {
139 return TCL_ERROR;
140 }
141 isAssignment = (numWords == 3);
142
143 /*
144 * Decide if we can use a frame slot for the var/array name or if we need
145 * to emit code to compute and push the name at runtime. We use a frame
146 * slot (entry in the array of local vars) if we are compiling a procedure
147 * body and if the name is simple text that does not include namespace
148 * qualifiers.
149 */
150
151 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
152 PushVarNameWord(interp, varTokenPtr, envPtr, 0,
153 &localIndex, &isScalar, 1);
154
155 /*
156 * If we are doing an assignment, push the new value.
157 */
158
159 if (isAssignment) {
160 valueTokenPtr = TokenAfter(varTokenPtr);
161 CompileWord(envPtr, valueTokenPtr, interp, 2);
162 }
163
164 /*
165 * Emit instructions to set/get the variable.
166 */
167
168 if (isScalar) {
169 if (localIndex < 0) {
170 TclEmitOpcode((isAssignment?
171 INST_STORE_STK : INST_LOAD_STK), envPtr);
172 } else if (localIndex <= 255) {
173 TclEmitInstInt1((isAssignment?
174 INST_STORE_SCALAR1 : INST_LOAD_SCALAR1),
175 localIndex, envPtr);
176 } else {
177 TclEmitInstInt4((isAssignment?
178 INST_STORE_SCALAR4 : INST_LOAD_SCALAR4),
179 localIndex, envPtr);
180 }
181 } else {
182 if (localIndex < 0) {
183 TclEmitOpcode((isAssignment?
184 INST_STORE_ARRAY_STK : INST_LOAD_ARRAY_STK), envPtr);
185 } else if (localIndex <= 255) {
186 TclEmitInstInt1((isAssignment?
187 INST_STORE_ARRAY1 : INST_LOAD_ARRAY1),
188 localIndex, envPtr);
189 } else {
190 TclEmitInstInt4((isAssignment?
191 INST_STORE_ARRAY4 : INST_LOAD_ARRAY4),
192 localIndex, envPtr);
193 }
194 }
195
196 return TCL_OK;
197 }
198
199 /*
200 *----------------------------------------------------------------------
201 *
202 * TclCompileString*Cmd --
203 *
204 * Procedures called to compile various subcommands of the "string"
205 * command.
206 *
207 * Results:
208 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
209 * evaluation to runtime.
210 *
211 * Side effects:
212 * Instructions are added to envPtr to execute the "string" command at
213 * runtime.
214 *
215 *----------------------------------------------------------------------
216 */
217
218 int
219 TclCompileStringCatCmd(
220 Tcl_Interp *interp, /* Used for error reporting. */
221 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
222 * created by Tcl_ParseCommand. */
223 Command *cmdPtr, /* Points to definition of command being
224 * compiled. */
225 CompileEnv *envPtr) /* Holds resulting instructions. */
226 {
227 DefineLineInformation; /* TIP #280 */
228 int i, numWords = parsePtr->numWords, numArgs;
229 Tcl_Token *wordTokenPtr;
230 Tcl_Obj *obj, *folded;
231
232 /* Trivial case, no arg */
233
234 if (numWords<2) {
235 PushStringLiteral(envPtr, "");
236 return TCL_OK;
237 }
238
239 /* General case: issue CONCAT1's (by chunks of 254 if needed), folding
240 contiguous constants along the way */
241
242 numArgs = 0;
243 folded = NULL;
244 wordTokenPtr = TokenAfter(parsePtr->tokenPtr);
245 for (i = 1; i < numWords; i++) {
246 TclNewObj(obj);
247 if (TclWordKnownAtCompileTime(wordTokenPtr, obj)) {
248 if (folded) {
249 Tcl_AppendObjToObj(folded, obj);
250 Tcl_DecrRefCount(obj);
251 } else {
252 folded = obj;
253 }
254 } else {
255 Tcl_DecrRefCount(obj);
256 if (folded) {
257 int len;
258 const char *bytes = Tcl_GetStringFromObj(folded, &len);
259
260 PushLiteral(envPtr, bytes, len);
261 Tcl_DecrRefCount(folded);
262 folded = NULL;
263 numArgs ++;
264 }
265 CompileWord(envPtr, wordTokenPtr, interp, i);
266 numArgs ++;
267 if (numArgs >= 254) { /* 254 to take care of the possible +1 of "folded" above */
268 TclEmitInstInt1(INST_STR_CONCAT1, numArgs, envPtr);
269 numArgs = 1; /* concat pushes 1 obj, the result */
270 }
271 }
272 wordTokenPtr = TokenAfter(wordTokenPtr);
273 }
274 if (folded) {
275 int len;
276 const char *bytes = Tcl_GetStringFromObj(folded, &len);
277
278 PushLiteral(envPtr, bytes, len);
279 Tcl_DecrRefCount(folded);
280 folded = NULL;
281 numArgs ++;
282 }
283 if (numArgs > 1) {
284 TclEmitInstInt1(INST_STR_CONCAT1, numArgs, envPtr);
285 }
286
287 return TCL_OK;
288 }
289
290 int
291 TclCompileStringCmpCmd(
292 Tcl_Interp *interp, /* Used for error reporting. */
293 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
294 * created by Tcl_ParseCommand. */
295 Command *cmdPtr, /* Points to definition of command being
296 * compiled. */
297 CompileEnv *envPtr) /* Holds resulting instructions. */
298 {
299 DefineLineInformation; /* TIP #280 */
300 Tcl_Token *tokenPtr;
301
302 /*
303 * We don't support any flags; the bytecode isn't that sophisticated.
304 */
305
306 if (parsePtr->numWords != 3) {
307 return TCL_ERROR;
308 }
309
310 /*
311 * Push the two operands onto the stack and then the test.
312 */
313
314 tokenPtr = TokenAfter(parsePtr->tokenPtr);
315 CompileWord(envPtr, tokenPtr, interp, 1);
316 tokenPtr = TokenAfter(tokenPtr);
317 CompileWord(envPtr, tokenPtr, interp, 2);
318 TclEmitOpcode(INST_STR_CMP, envPtr);
319 return TCL_OK;
320 }
321
322 int
323 TclCompileStringEqualCmd(
324 Tcl_Interp *interp, /* Used for error reporting. */
325 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
326 * created by Tcl_ParseCommand. */
327 Command *cmdPtr, /* Points to definition of command being
328 * compiled. */
329 CompileEnv *envPtr) /* Holds resulting instructions. */
330 {
331 DefineLineInformation; /* TIP #280 */
332 Tcl_Token *tokenPtr;
333
334 /*
335 * We don't support any flags; the bytecode isn't that sophisticated.
336 */
337
338 if (parsePtr->numWords != 3) {
339 return TCL_ERROR;
340 }
341
342 /*
343 * Push the two operands onto the stack and then the test.
344 */
345
346 tokenPtr = TokenAfter(parsePtr->tokenPtr);
347 CompileWord(envPtr, tokenPtr, interp, 1);
348 tokenPtr = TokenAfter(tokenPtr);
349 CompileWord(envPtr, tokenPtr, interp, 2);
350 TclEmitOpcode(INST_STR_EQ, envPtr);
351 return TCL_OK;
352 }
353
354 int
355 TclCompileStringFirstCmd(
356 Tcl_Interp *interp, /* Used for error reporting. */
357 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
358 * created by Tcl_ParseCommand. */
359 Command *cmdPtr, /* Points to definition of command being
360 * compiled. */
361 CompileEnv *envPtr) /* Holds resulting instructions. */
362 {
363 DefineLineInformation; /* TIP #280 */
364 Tcl_Token *tokenPtr;
365
366 /*
367 * We don't support any flags; the bytecode isn't that sophisticated.
368 */
369
370 if (parsePtr->numWords != 3) {
371 return TCL_ERROR;
372 }
373
374 /*
375 * Push the two operands onto the stack and then the test.
376 */
377
378 tokenPtr = TokenAfter(parsePtr->tokenPtr);
379 CompileWord(envPtr, tokenPtr, interp, 1);
380 tokenPtr = TokenAfter(tokenPtr);
381 CompileWord(envPtr, tokenPtr, interp, 2);
382 OP(STR_FIND);
383 return TCL_OK;
384 }
385
386 int
387 TclCompileStringLastCmd(
388 Tcl_Interp *interp, /* Used for error reporting. */
389 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
390 * created by Tcl_ParseCommand. */
391 Command *cmdPtr, /* Points to definition of command being
392 * compiled. */
393 CompileEnv *envPtr) /* Holds resulting instructions. */
394 {
395 DefineLineInformation; /* TIP #280 */
396 Tcl_Token *tokenPtr;
397
398 /*
399 * We don't support any flags; the bytecode isn't that sophisticated.
400 */
401
402 if (parsePtr->numWords != 3) {
403 return TCL_ERROR;
404 }
405
406 /*
407 * Push the two operands onto the stack and then the test.
408 */
409
410 tokenPtr = TokenAfter(parsePtr->tokenPtr);
411 CompileWord(envPtr, tokenPtr, interp, 1);
412 tokenPtr = TokenAfter(tokenPtr);
413 CompileWord(envPtr, tokenPtr, interp, 2);
414 OP(STR_FIND_LAST);
415 return TCL_OK;
416 }
417
418 int
419 TclCompileStringIndexCmd(
420 Tcl_Interp *interp, /* Used for error reporting. */
421 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
422 * created by Tcl_ParseCommand. */
423 Command *cmdPtr, /* Points to definition of command being
424 * compiled. */
425 CompileEnv *envPtr) /* Holds resulting instructions. */
426 {
427 DefineLineInformation; /* TIP #280 */
428 Tcl_Token *tokenPtr;
429
430 if (parsePtr->numWords != 3) {
431 return TCL_ERROR;
432 }
433
434 /*
435 * Push the two operands onto the stack and then the index operation.
436 */
437
438 tokenPtr = TokenAfter(parsePtr->tokenPtr);
439 CompileWord(envPtr, tokenPtr, interp, 1);
440 tokenPtr = TokenAfter(tokenPtr);
441 CompileWord(envPtr, tokenPtr, interp, 2);
442 TclEmitOpcode(INST_STR_INDEX, envPtr);
443 return TCL_OK;
444 }
445
446 int
447 TclCompileStringIsCmd(
448 Tcl_Interp *interp, /* Used for error reporting. */
449 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
450 * created by Tcl_ParseCommand. */
451 Command *cmdPtr, /* Points to definition of command being
452 * compiled. */
453 CompileEnv *envPtr) /* Holds resulting instructions. */
454 {
455 DefineLineInformation; /* TIP #280 */
456 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
457 static const char *const isClasses[] = {
458 "alnum", "alpha", "ascii", "control",
459 "boolean", "digit", "double", "entier",
460 "false", "graph", "integer", "list",
461 "lower", "print", "punct", "space",
462 "true", "upper", "wideinteger", "wordchar",
463 "xdigit", NULL
464 };
465 enum isClassesEnum {
466 STR_IS_ALNUM, STR_IS_ALPHA, STR_IS_ASCII, STR_IS_CONTROL,
467 STR_IS_BOOL, STR_IS_DIGIT, STR_IS_DOUBLE, STR_IS_ENTIER,
468 STR_IS_FALSE, STR_IS_GRAPH, STR_IS_INT, STR_IS_LIST,
469 STR_IS_LOWER, STR_IS_PRINT, STR_IS_PUNCT, STR_IS_SPACE,
470 STR_IS_TRUE, STR_IS_UPPER, STR_IS_WIDE, STR_IS_WORD,
471 STR_IS_XDIGIT
472 };
473 int t, range, allowEmpty = 0, end;
474 InstStringClassType strClassType;
475 Tcl_Obj *isClass;
476
477 if (parsePtr->numWords < 3 || parsePtr->numWords > 6) {
478 return TCL_ERROR;
479 }
480 TclNewObj(isClass);
481 if (!TclWordKnownAtCompileTime(tokenPtr, isClass)) {
482 Tcl_DecrRefCount(isClass);
483 return TCL_ERROR;
484 } else if (Tcl_GetIndexFromObj(interp, isClass, isClasses, "class", 0,
485 &t) != TCL_OK) {
486 Tcl_DecrRefCount(isClass);
487 TclCompileSyntaxError(interp, envPtr);
488 return TCL_OK;
489 }
490 Tcl_DecrRefCount(isClass);
491
492 #define GotLiteral(tokenPtr, word) \
493 ((tokenPtr)->type == TCL_TOKEN_SIMPLE_WORD && \
494 (tokenPtr)[1].size > 1 && \
495 (tokenPtr)[1].start[0] == word[0] && \
496 strncmp((tokenPtr)[1].start, (word), (tokenPtr)[1].size) == 0)
497
498 /*
499 * Cannot handle the -failindex option at all, and that's the only legal
500 * way to have more than 4 arguments.
501 */
502
503 if (parsePtr->numWords != 3 && parsePtr->numWords != 4) {
504 return TCL_ERROR;
505 }
506
507 tokenPtr = TokenAfter(tokenPtr);
508 if (parsePtr->numWords == 3) {
509 allowEmpty = 1;
510 } else {
511 if (!GotLiteral(tokenPtr, "-strict")) {
512 return TCL_ERROR;
513 }
514 tokenPtr = TokenAfter(tokenPtr);
515 }
516 #undef GotLiteral
517
518 /*
519 * Compile the code. There are several main classes of check here.
520 * 1. Character classes
521 * 2. Booleans
522 * 3. Integers
523 * 4. Floats
524 * 5. Lists
525 */
526
527 CompileWord(envPtr, tokenPtr, interp, parsePtr->numWords-1);
528
529 switch ((enum isClassesEnum) t) {
530 case STR_IS_ALNUM:
531 strClassType = STR_CLASS_ALNUM;
532 goto compileStrClass;
533 case STR_IS_ALPHA:
534 strClassType = STR_CLASS_ALPHA;
535 goto compileStrClass;
536 case STR_IS_ASCII:
537 strClassType = STR_CLASS_ASCII;
538 goto compileStrClass;
539 case STR_IS_CONTROL:
540 strClassType = STR_CLASS_CONTROL;
541 goto compileStrClass;
542 case STR_IS_DIGIT:
543 strClassType = STR_CLASS_DIGIT;
544 goto compileStrClass;
545 case STR_IS_GRAPH:
546 strClassType = STR_CLASS_GRAPH;
547 goto compileStrClass;
548 case STR_IS_LOWER:
549 strClassType = STR_CLASS_LOWER;
550 goto compileStrClass;
551 case STR_IS_PRINT:
552 strClassType = STR_CLASS_PRINT;
553 goto compileStrClass;
554 case STR_IS_PUNCT:
555 strClassType = STR_CLASS_PUNCT;
556 goto compileStrClass;
557 case STR_IS_SPACE:
558 strClassType = STR_CLASS_SPACE;
559 goto compileStrClass;
560 case STR_IS_UPPER:
561 strClassType = STR_CLASS_UPPER;
562 goto compileStrClass;
563 case STR_IS_WORD:
564 strClassType = STR_CLASS_WORD;
565 goto compileStrClass;
566 case STR_IS_XDIGIT:
567 strClassType = STR_CLASS_XDIGIT;
568 compileStrClass:
569 if (allowEmpty) {
570 OP1( STR_CLASS, strClassType);
571 } else {
572 int over, over2;
573
574 OP( DUP);
575 OP1( STR_CLASS, strClassType);
576 JUMP1( JUMP_TRUE, over);
577 OP( POP);
578 PUSH( "0");
579 JUMP1( JUMP, over2);
580 FIXJUMP1(over);
581 PUSH( "");
582 OP( STR_NEQ);
583 FIXJUMP1(over2);
584 }
585 return TCL_OK;
586
587 case STR_IS_BOOL:
588 case STR_IS_FALSE:
589 case STR_IS_TRUE:
590 OP( TRY_CVT_TO_BOOLEAN);
591 switch (t) {
592 int over, over2;
593
594 case STR_IS_BOOL:
595 if (allowEmpty) {
596 JUMP1( JUMP_TRUE, over);
597 PUSH( "");
598 OP( STR_EQ);
599 JUMP1( JUMP, over2);
600 FIXJUMP1(over);
601 OP( POP);
602 PUSH( "1");
603 FIXJUMP1(over2);
604 } else {
605 OP4( REVERSE, 2);
606 OP( POP);
607 }
608 return TCL_OK;
609 case STR_IS_TRUE:
610 JUMP1( JUMP_TRUE, over);
611 if (allowEmpty) {
612 PUSH( "");
613 OP( STR_EQ);
614 } else {
615 OP( POP);
616 PUSH( "0");
617 }
618 FIXJUMP1( over);
619 OP( LNOT);
620 OP( LNOT);
621 return TCL_OK;
622 case STR_IS_FALSE:
623 JUMP1( JUMP_TRUE, over);
624 if (allowEmpty) {
625 PUSH( "");
626 OP( STR_NEQ);
627 } else {
628 OP( POP);
629 PUSH( "1");
630 }
631 FIXJUMP1( over);
632 OP( LNOT);
633 return TCL_OK;
634 }
635 break;
636
637 case STR_IS_DOUBLE: {
638 int satisfied, isEmpty;
639
640 if (allowEmpty) {
641 OP( DUP);
642 PUSH( "");
643 OP( STR_EQ);
644 JUMP1( JUMP_TRUE, isEmpty);
645 OP( NUM_TYPE);
646 JUMP1( JUMP_TRUE, satisfied);
647 PUSH( "0");
648 JUMP1( JUMP, end);
649 FIXJUMP1( isEmpty);
650 OP( POP);
651 FIXJUMP1( satisfied);
652 } else {
653 OP( NUM_TYPE);
654 JUMP1( JUMP_TRUE, satisfied);
655 PUSH( "0");
656 JUMP1( JUMP, end);
657 TclAdjustStackDepth(-1, envPtr);
658 FIXJUMP1( satisfied);
659 }
660 PUSH( "1");
661 FIXJUMP1( end);
662 return TCL_OK;
663 }
664
665 case STR_IS_INT:
666 case STR_IS_WIDE:
667 case STR_IS_ENTIER:
668 if (allowEmpty) {
669 int testNumType;
670
671 OP( DUP);
672 OP( NUM_TYPE);
673 OP( DUP);
674 JUMP1( JUMP_TRUE, testNumType);
675 OP( POP);
676 PUSH( "");
677 OP( STR_EQ);
678 JUMP1( JUMP, end);
679 TclAdjustStackDepth(1, envPtr);
680 FIXJUMP1( testNumType);
681 OP4( REVERSE, 2);
682 OP( POP);
683 } else {
684 OP( NUM_TYPE);
685 OP( DUP);
686 JUMP1( JUMP_FALSE, end);
687 }
688
689 switch (t) {
690 case STR_IS_WIDE:
691 PUSH( "2");
692 OP( LE);
693 break;
694 case STR_IS_INT:
695 PUSH( "1");
696 OP( EQ);
697 break;
698 case STR_IS_ENTIER:
699 PUSH( "3");
700 OP( LE);
701 break;
702 }
703 FIXJUMP1( end);
704 return TCL_OK;
705
706 case STR_IS_LIST:
707 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
708 OP4( BEGIN_CATCH4, range);
709 ExceptionRangeStarts(envPtr, range);
710 OP( DUP);
711 OP( LIST_LENGTH);
712 OP( POP);
713 ExceptionRangeEnds(envPtr, range);
714 ExceptionRangeTarget(envPtr, range, catchOffset);
715 OP( POP);
716 OP( PUSH_RETURN_CODE);
717 OP( END_CATCH);
718 OP( LNOT);
719 return TCL_OK;
720 }
721
722 return TclCompileBasicMin0ArgCmd(interp, parsePtr, cmdPtr, envPtr);
723 }
724
725 int
726 TclCompileStringMatchCmd(
727 Tcl_Interp *interp, /* Used for error reporting. */
728 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
729 * created by Tcl_ParseCommand. */
730 Command *cmdPtr, /* Points to definition of command being
731 * compiled. */
732 CompileEnv *envPtr) /* Holds resulting instructions. */
733 {
734 DefineLineInformation; /* TIP #280 */
735 Tcl_Token *tokenPtr;
736 int i, length, exactMatch = 0, nocase = 0;
737 const char *str;
738
739 if (parsePtr->numWords < 3 || parsePtr->numWords > 4) {
740 return TCL_ERROR;
741 }
742 tokenPtr = TokenAfter(parsePtr->tokenPtr);
743
744 /*
745 * Check if we have a -nocase flag.
746 */
747
748 if (parsePtr->numWords == 4) {
749 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
750 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
751 }
752 str = tokenPtr[1].start;
753 length = tokenPtr[1].size;
754 if ((length <= 1) || strncmp(str, "-nocase", length)) {
755 /*
756 * Fail at run time, not in compilation.
757 */
758
759 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
760 }
761 nocase = 1;
762 tokenPtr = TokenAfter(tokenPtr);
763 }
764
765 /*
766 * Push the strings to match against each other.
767 */
768
769 for (i = 0; i < 2; i++) {
770 if (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
771 str = tokenPtr[1].start;
772 length = tokenPtr[1].size;
773 if (!nocase && (i == 0)) {
774 /*
775 * Trivial matches can be done by 'string equal'. If -nocase
776 * was specified, we can't do this because INST_STR_EQ has no
777 * support for nocase.
778 */
779
780 Tcl_Obj *copy = Tcl_NewStringObj(str, length);
781
782 Tcl_IncrRefCount(copy);
783 exactMatch = TclMatchIsTrivial(TclGetString(copy));
784 TclDecrRefCount(copy);
785 }
786 PushLiteral(envPtr, str, length);
787 } else {
788 SetLineInformation(i+1+nocase);
789 CompileTokens(envPtr, tokenPtr, interp);
790 }
791 tokenPtr = TokenAfter(tokenPtr);
792 }
793
794 /*
795 * Push the matcher.
796 */
797
798 if (exactMatch) {
799 TclEmitOpcode(INST_STR_EQ, envPtr);
800 } else {
801 TclEmitInstInt1(INST_STR_MATCH, nocase, envPtr);
802 }
803 return TCL_OK;
804 }
805
806 int
807 TclCompileStringLenCmd(
808 Tcl_Interp *interp, /* Used for error reporting. */
809 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
810 * created by Tcl_ParseCommand. */
811 Command *cmdPtr, /* Points to definition of command being
812 * compiled. */
813 CompileEnv *envPtr) /* Holds resulting instructions. */
814 {
815 DefineLineInformation; /* TIP #280 */
816 Tcl_Token *tokenPtr;
817 Tcl_Obj *objPtr;
818
819 if (parsePtr->numWords != 2) {
820 return TCL_ERROR;
821 }
822
823 tokenPtr = TokenAfter(parsePtr->tokenPtr);
824 TclNewObj(objPtr);
825 if (TclWordKnownAtCompileTime(tokenPtr, objPtr)) {
826 /*
827 * Here someone is asking for the length of a static string (or
828 * something with backslashes). Just push the actual character (not
829 * byte) length.
830 */
831
832 char buf[TCL_INTEGER_SPACE];
833 int len = Tcl_GetCharLength(objPtr);
834
835 len = snprintf(buf, sizeof(buf), "%d", len);
836 PushLiteral(envPtr, buf, len);
837 } else {
838 SetLineInformation(1);
839 CompileTokens(envPtr, tokenPtr, interp);
840 TclEmitOpcode(INST_STR_LEN, envPtr);
841 }
842 TclDecrRefCount(objPtr);
843 return TCL_OK;
844 }
845
846 int
847 TclCompileStringMapCmd(
848 Tcl_Interp *interp, /* Used for error reporting. */
849 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
850 * created by Tcl_ParseCommand. */
851 Command *cmdPtr, /* Points to definition of command being
852 * compiled. */
853 CompileEnv *envPtr) /* Holds resulting instructions. */
854 {
855 DefineLineInformation; /* TIP #280 */
856 Tcl_Token *mapTokenPtr, *stringTokenPtr;
857 Tcl_Obj *mapObj, **objv;
858 const char *bytes;
859 int len;
860
861 /*
862 * We only handle the case:
863 *
864 * string map {foo bar} $thing
865 *
866 * That is, a literal two-element list (doesn't need to be brace-quoted,
867 * but does need to be compile-time knowable) and any old argument (the
868 * thing to map).
869 */
870
871 if (parsePtr->numWords != 3) {
872 return TCL_ERROR;
873 }
874 mapTokenPtr = TokenAfter(parsePtr->tokenPtr);
875 stringTokenPtr = TokenAfter(mapTokenPtr);
876 TclNewObj(mapObj);
877 Tcl_IncrRefCount(mapObj);
878 if (!TclWordKnownAtCompileTime(mapTokenPtr, mapObj)) {
879 Tcl_DecrRefCount(mapObj);
880 return TclCompileBasic2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
881 } else if (TclListObjGetElements(NULL, mapObj, &len, &objv) != TCL_OK) {
882 Tcl_DecrRefCount(mapObj);
883 return TclCompileBasic2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
884 } else if (len != 2) {
885 Tcl_DecrRefCount(mapObj);
886 return TclCompileBasic2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
887 }
888
889 /*
890 * Now issue the opcodes. Note that in the case that we know that the
891 * first word is an empty word, we don't issue the map at all. That is the
892 * correct semantics for mapping.
893 */
894
895 bytes = Tcl_GetStringFromObj(objv[0], &len);
896 if (len == 0) {
897 CompileWord(envPtr, stringTokenPtr, interp, 2);
898 } else {
899 PushLiteral(envPtr, bytes, len);
900 bytes = Tcl_GetStringFromObj(objv[1], &len);
901 PushLiteral(envPtr, bytes, len);
902 CompileWord(envPtr, stringTokenPtr, interp, 2);
903 OP(STR_MAP);
904 }
905 Tcl_DecrRefCount(mapObj);
906 return TCL_OK;
907 }
908
909 int
910 TclCompileStringRangeCmd(
911 Tcl_Interp *interp, /* Used for error reporting. */
912 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
913 * created by Tcl_ParseCommand. */
914 Command *cmdPtr, /* Points to definition of command being
915 * compiled. */
916 CompileEnv *envPtr) /* Holds resulting instructions. */
917 {
918 DefineLineInformation; /* TIP #280 */
919 Tcl_Token *stringTokenPtr, *fromTokenPtr, *toTokenPtr;
920 int idx1, idx2;
921
922 if (parsePtr->numWords != 4) {
923 return TCL_ERROR;
924 }
925 stringTokenPtr = TokenAfter(parsePtr->tokenPtr);
926 fromTokenPtr = TokenAfter(stringTokenPtr);
927 toTokenPtr = TokenAfter(fromTokenPtr);
928
929 /* Every path must push the string argument */
930 CompileWord(envPtr, stringTokenPtr, interp, 1);
931
932 /*
933 * Parse the two indices.
934 */
935
936 if (TclGetIndexFromToken(fromTokenPtr, TCL_INDEX_START, TCL_INDEX_AFTER,
937 &idx1) != TCL_OK) {
938 goto nonConstantIndices;
939 }
940 /*
941 * Token parsed as an index expression. We treat all indices before
942 * the string the same as the start of the string.
943 */
944
945 if (idx1 == TCL_INDEX_AFTER) {
946 /* [string range $s end+1 $last] must be empty string */
947 OP( POP);
948 PUSH( "");
949 return TCL_OK;
950 }
951
952 if (TclGetIndexFromToken(toTokenPtr, TCL_INDEX_BEFORE, TCL_INDEX_END,
953 &idx2) != TCL_OK) {
954 goto nonConstantIndices;
955 }
956 /*
957 * Token parsed as an index expression. We treat all indices after
958 * the string the same as the end of the string.
959 */
960 if (idx2 == TCL_INDEX_BEFORE) {
961 /* [string range $s $first -1] must be empty string */
962 OP( POP);
963 PUSH( "");
964 return TCL_OK;
965 }
966
967 /*
968 * Push the operand onto the stack and then the substring operation.
969 */
970
971 OP44( STR_RANGE_IMM, idx1, idx2);
972 return TCL_OK;
973
974 /*
975 * Push the operands onto the stack and then the substring operation.
976 */
977
978 nonConstantIndices:
979 CompileWord(envPtr, fromTokenPtr, interp, 2);
980 CompileWord(envPtr, toTokenPtr, interp, 3);
981 OP( STR_RANGE);
982 return TCL_OK;
983 }
984
985 int
986 TclCompileStringReplaceCmd(
987 Tcl_Interp *interp, /* Tcl interpreter for context. */
988 Tcl_Parse *parsePtr, /* Points to a parse structure for the
989 * command. */
990 Command *cmdPtr, /* Points to definition of command being
991 * compiled. */
992 CompileEnv *envPtr) /* Holds the resulting instructions. */
993 {
994 DefineLineInformation; /* TIP #280 */
995 Tcl_Token *tokenPtr, *valueTokenPtr;
996 int first, last;
997
998 if (parsePtr->numWords < 4 || parsePtr->numWords > 5) {
999 return TCL_ERROR;
1000 }
1001
1002 /* Bytecode to compute/push string argument being replaced */
1003 valueTokenPtr = TokenAfter(parsePtr->tokenPtr);
1004 CompileWord(envPtr, valueTokenPtr, interp, 1);
1005
1006 /*
1007 * Check for first index known and useful at compile time.
1008 */
1009 tokenPtr = TokenAfter(valueTokenPtr);
1010 if (TclGetIndexFromToken(tokenPtr, TCL_INDEX_BEFORE, TCL_INDEX_AFTER,
1011 &first) != TCL_OK) {
1012 goto genericReplace;
1013 }
1014
1015 /*
1016 * Check for last index known and useful at compile time.
1017 */
1018 tokenPtr = TokenAfter(tokenPtr);
1019 if (TclGetIndexFromToken(tokenPtr, TCL_INDEX_BEFORE, TCL_INDEX_AFTER,
1020 &last) != TCL_OK) {
1021 goto genericReplace;
1022 }
1023
1024 /*
1025 * [string replace] is an odd bird. For many arguments it is
1026 * a conventional substring replacer. However it also goes out
1027 * of its way to become a no-op for many cases where it would be
1028 * replacing an empty substring. Precisely, it is a no-op when
1029 *
1030 * (last < first) OR
1031 * (last < 0) OR
1032 * (end < first)
1033 *
1034 * For some compile-time values we can detect these cases, and
1035 * compile direct to bytecode implementing the no-op.
1036 */
1037
1038 if ((last == TCL_INDEX_BEFORE) /* Know (last < 0) */
1039 || (first == TCL_INDEX_AFTER) /* Know (first > end) */
1040
1041 /*
1042 * Tricky to determine when runtime (last < first) can be
1043 * certainly known based on the encoded values. Consider the
1044 * cases...
1045 *
1046 * (first <= TCL_INDEX_END) &&
1047 * (last == TCL_INDEX_AFTER) => cannot tell REJECT
1048 * (last <= TCL_INDEX END) && (last < first) => ACCEPT
1049 * else => cannot tell REJECT
1050 */
1051 || ((first <= TCL_INDEX_END) && (last <= TCL_INDEX_END)
1052 && (last < first)) /* Know (last < first) */
1053 /*
1054 * (first == TCL_INDEX_BEFORE) &&
1055 * (last == TCL_INDEX_AFTER) => (first < last) REJECT
1056 * (last <= TCL_INDEX_END) => cannot tell REJECT
1057 * else => (first < last) REJECT
1058 *
1059 * else [[first >= TCL_INDEX_START]] &&
1060 * (last == TCL_INDEX_AFTER) => cannot tell REJECT
1061 * (last <= TCL_INDEX_END) => cannot tell REJECT
1062 * else [[last >= TCL_INDEX START]] && (last < first) => ACCEPT
1063 */
1064 || ((first >= TCL_INDEX_START) && (last >= TCL_INDEX_START)
1065 && (last < first))) { /* Know (last < first) */
1066 if (parsePtr->numWords == 5) {
1067 tokenPtr = TokenAfter(tokenPtr);
1068 CompileWord(envPtr, tokenPtr, interp, 4);
1069 OP( POP); /* Pop newString */
1070 }
1071 /* Original string argument now on TOS as result */
1072 return TCL_OK;
1073 }
1074
1075 if (parsePtr->numWords == 5) {
1076 /*
1077 * When we have a string replacement, we have to take care about
1078 * not replacing empty substrings that [string replace] promises
1079 * not to replace
1080 *
1081 * The remaining index values might be suitable for conventional
1082 * string replacement, but only if they cannot possibly meet the
1083 * conditions described above at runtime. If there's a chance they
1084 * might, we would have to emit bytecode to check and at that point
1085 * we're paying more in bytecode execution time than would make
1086 * things worthwhile. Trouble is we are very limited in
1087 * how much we can detect that at compile time. After decoding,
1088 * we need, first:
1089 *
1090 * (first <= end)
1091 *
1092 * The encoded indices (first <= TCL_INDEX END) and
1093 * (first == TCL_INDEX_BEFORE) always meets this condition, but
1094 * any other encoded first index has some list for which it fails.
1095 *
1096 * We also need, second:
1097 *
1098 * (last >= 0)
1099 *
1100 * The encoded indices (last >= TCL_INDEX_START) and
1101 * (last == TCL_INDEX_AFTER) always meet this condition but any
1102 * other encoded last index has some list for which it fails.
1103 *
1104 * Finally we need, third:
1105 *
1106 * (first <= last)
1107 *
1108 * Considered in combination with the constraints we already have,
1109 * we see that we can proceed when (first == TCL_INDEX_BEFORE)
1110 * or (last == TCL_INDEX_AFTER). These also permit simplification
1111 * of the prefix|replace|suffix construction. The other constraints,
1112 * though, interfere with getting a guarantee that first <= last.
1113 */
1114
1115 if ((first == TCL_INDEX_BEFORE) && (last >= TCL_INDEX_START)) {
1116 /* empty prefix */
1117 tokenPtr = TokenAfter(tokenPtr);
1118 CompileWord(envPtr, tokenPtr, interp, 4);
1119 OP4( REVERSE, 2);
1120 if (last == TCL_INDEX_AFTER) {
1121 OP( POP); /* Pop original */
1122 } else {
1123 OP44( STR_RANGE_IMM, last + 1, TCL_INDEX_END);
1124 OP1( STR_CONCAT1, 2);
1125 }
1126 return TCL_OK;
1127 }
1128
1129 if ((last == TCL_INDEX_AFTER) && (first <= TCL_INDEX_END)) {
1130 OP44( STR_RANGE_IMM, 0, first-1);
1131 tokenPtr = TokenAfter(tokenPtr);
1132 CompileWord(envPtr, tokenPtr, interp, 4);
1133 OP1( STR_CONCAT1, 2);
1134 return TCL_OK;
1135 }
1136
1137 /* FLOW THROUGH TO genericReplace */
1138
1139 } else {
1140 /*
1141 * When we have no replacement string to worry about, we may
1142 * have more luck, because the forbidden empty string replacements
1143 * are harmless when they are replaced by another empty string.
1144 */
1145
1146 if ((first == TCL_INDEX_BEFORE) || (first == TCL_INDEX_START)) {
1147 /* empty prefix - build suffix only */
1148
1149 if ((last == TCL_INDEX_END) || (last == TCL_INDEX_AFTER)) {
1150 /* empty suffix too => empty result */
1151 OP( POP); /* Pop original */
1152 PUSH ( "");
1153 return TCL_OK;
1154 }
1155 OP44( STR_RANGE_IMM, last + 1, TCL_INDEX_END);
1156 return TCL_OK;
1157 } else {
1158 if ((last == TCL_INDEX_END) || (last == TCL_INDEX_AFTER)) {
1159 /* empty suffix - build prefix only */
1160 OP44( STR_RANGE_IMM, 0, first-1);
1161 return TCL_OK;
1162 }
1163 OP( DUP);
1164 OP44( STR_RANGE_IMM, 0, first-1);
1165 OP4( REVERSE, 2);
1166 OP44( STR_RANGE_IMM, last + 1, TCL_INDEX_END);
1167 OP1( STR_CONCAT1, 2);
1168 return TCL_OK;
1169 }
1170 }
1171
1172 genericReplace:
1173 tokenPtr = TokenAfter(valueTokenPtr);
1174 CompileWord(envPtr, tokenPtr, interp, 2);
1175 tokenPtr = TokenAfter(tokenPtr);
1176 CompileWord(envPtr, tokenPtr, interp, 3);
1177 if (parsePtr->numWords == 5) {
1178 tokenPtr = TokenAfter(tokenPtr);
1179 CompileWord(envPtr, tokenPtr, interp, 4);
1180 } else {
1181 PUSH( "");
1182 }
1183 OP( STR_REPLACE);
1184 return TCL_OK;
1185 }
1186
1187 int
1188 TclCompileStringTrimLCmd(
1189 Tcl_Interp *interp, /* Used for error reporting. */
1190 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1191 * created by Tcl_ParseCommand. */
1192 Command *cmdPtr, /* Points to definition of command being
1193 * compiled. */
1194 CompileEnv *envPtr) /* Holds resulting instructions. */
1195 {
1196 DefineLineInformation; /* TIP #280 */
1197 Tcl_Token *tokenPtr;
1198
1199 if (parsePtr->numWords != 2 && parsePtr->numWords != 3) {
1200 return TCL_ERROR;
1201 }
1202
1203 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1204 CompileWord(envPtr, tokenPtr, interp, 1);
1205 if (parsePtr->numWords == 3) {
1206 tokenPtr = TokenAfter(tokenPtr);
1207 CompileWord(envPtr, tokenPtr, interp, 2);
1208 } else {
1209 PushLiteral(envPtr, tclDefaultTrimSet, strlen(tclDefaultTrimSet));
1210 }
1211 OP( STR_TRIM_LEFT);
1212 return TCL_OK;
1213 }
1214
1215 int
1216 TclCompileStringTrimRCmd(
1217 Tcl_Interp *interp, /* Used for error reporting. */
1218 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1219 * created by Tcl_ParseCommand. */
1220 Command *cmdPtr, /* Points to definition of command being
1221 * compiled. */
1222 CompileEnv *envPtr) /* Holds resulting instructions. */
1223 {
1224 DefineLineInformation; /* TIP #280 */
1225 Tcl_Token *tokenPtr;
1226
1227 if (parsePtr->numWords != 2 && parsePtr->numWords != 3) {
1228 return TCL_ERROR;
1229 }
1230
1231 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1232 CompileWord(envPtr, tokenPtr, interp, 1);
1233 if (parsePtr->numWords == 3) {
1234 tokenPtr = TokenAfter(tokenPtr);
1235 CompileWord(envPtr, tokenPtr, interp, 2);
1236 } else {
1237 PushLiteral(envPtr, tclDefaultTrimSet, strlen(tclDefaultTrimSet));
1238 }
1239 OP( STR_TRIM_RIGHT);
1240 return TCL_OK;
1241 }
1242
1243 int
1244 TclCompileStringTrimCmd(
1245 Tcl_Interp *interp, /* Used for error reporting. */
1246 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1247 * created by Tcl_ParseCommand. */
1248 Command *cmdPtr, /* Points to definition of command being
1249 * compiled. */
1250 CompileEnv *envPtr) /* Holds resulting instructions. */
1251 {
1252 DefineLineInformation; /* TIP #280 */
1253 Tcl_Token *tokenPtr;
1254
1255 if (parsePtr->numWords != 2 && parsePtr->numWords != 3) {
1256 return TCL_ERROR;
1257 }
1258
1259 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1260 CompileWord(envPtr, tokenPtr, interp, 1);
1261 if (parsePtr->numWords == 3) {
1262 tokenPtr = TokenAfter(tokenPtr);
1263 CompileWord(envPtr, tokenPtr, interp, 2);
1264 } else {
1265 PushLiteral(envPtr, tclDefaultTrimSet, strlen(tclDefaultTrimSet));
1266 }
1267 OP( STR_TRIM);
1268 return TCL_OK;
1269 }
1270
1271 int
1272 TclCompileStringToUpperCmd(
1273 Tcl_Interp *interp, /* Used for error reporting. */
1274 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1275 * created by Tcl_ParseCommand. */
1276 Command *cmdPtr, /* Points to definition of command being
1277 * compiled. */
1278 CompileEnv *envPtr) /* Holds resulting instructions. */
1279 {
1280 DefineLineInformation; /* TIP #280 */
1281 Tcl_Token *tokenPtr;
1282
1283 if (parsePtr->numWords != 2) {
1284 return TclCompileBasic1To3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1285 }
1286
1287 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1288 CompileWord(envPtr, tokenPtr, interp, 1);
1289 OP( STR_UPPER);
1290 return TCL_OK;
1291 }
1292
1293 int
1294 TclCompileStringToLowerCmd(
1295 Tcl_Interp *interp, /* Used for error reporting. */
1296 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1297 * created by Tcl_ParseCommand. */
1298 Command *cmdPtr, /* Points to definition of command being
1299 * compiled. */
1300 CompileEnv *envPtr) /* Holds resulting instructions. */
1301 {
1302 DefineLineInformation; /* TIP #280 */
1303 Tcl_Token *tokenPtr;
1304
1305 if (parsePtr->numWords != 2) {
1306 return TclCompileBasic1To3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1307 }
1308
1309 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1310 CompileWord(envPtr, tokenPtr, interp, 1);
1311 OP( STR_LOWER);
1312 return TCL_OK;
1313 }
1314
1315 int
1316 TclCompileStringToTitleCmd(
1317 Tcl_Interp *interp, /* Used for error reporting. */
1318 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1319 * created by Tcl_ParseCommand. */
1320 Command *cmdPtr, /* Points to definition of command being
1321 * compiled. */
1322 CompileEnv *envPtr) /* Holds resulting instructions. */
1323 {
1324 DefineLineInformation; /* TIP #280 */
1325 Tcl_Token *tokenPtr;
1326
1327 if (parsePtr->numWords != 2) {
1328 return TclCompileBasic1To3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1329 }
1330
1331 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1332 CompileWord(envPtr, tokenPtr, interp, 1);
1333 OP( STR_TITLE);
1334 return TCL_OK;
1335 }
1336
1337 /*
1338 * Support definitions for the [string is] compilation.
1339 */
1340
1341 static int
1342 UniCharIsAscii(
1343 int character)
1344 {
1345 return (character >= 0) && (character < 0x80);
1346 }
1347
1348 static int
1349 UniCharIsHexDigit(
1350 int character)
1351 {
1352 return (character >= 0) && (character < 0x80) && isxdigit(UCHAR(character));
1353 }
1354
1355 StringClassDesc const tclStringClassTable[] = {
1356 {"alnum", Tcl_UniCharIsAlnum},
1357 {"alpha", Tcl_UniCharIsAlpha},
1358 {"ascii", UniCharIsAscii},
1359 {"control", Tcl_UniCharIsControl},
1360 {"digit", Tcl_UniCharIsDigit},
1361 {"graph", Tcl_UniCharIsGraph},
1362 {"lower", Tcl_UniCharIsLower},
1363 {"print", Tcl_UniCharIsPrint},
1364 {"punct", Tcl_UniCharIsPunct},
1365 {"space", Tcl_UniCharIsSpace},
1366 {"upper", Tcl_UniCharIsUpper},
1367 {"word", Tcl_UniCharIsWordChar},
1368 {"xdigit", UniCharIsHexDigit},
1369 {NULL, NULL}
1370 };
1371
1372 /*
1373 *----------------------------------------------------------------------
1374 *
1375 * TclCompileSubstCmd --
1376 *
1377 * Procedure called to compile the "subst" command.
1378 *
1379 * Results:
1380 * Returns TCL_OK for successful compile, or TCL_ERROR to defer
1381 * evaluation to runtime (either when it is too complex to get the
1382 * semantics right, or when we know for sure that it is an error but need
1383 * the error to happen at the right time).
1384 *
1385 * Side effects:
1386 * Instructions are added to envPtr to execute the "subst" command at
1387 * runtime.
1388 *
1389 *----------------------------------------------------------------------
1390 */
1391
1392 int
1393 TclCompileSubstCmd(
1394 Tcl_Interp *interp, /* Used for error reporting. */
1395 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1396 * created by Tcl_ParseCommand. */
1397 Command *cmdPtr, /* Points to definition of command being
1398 * compiled. */
1399 CompileEnv *envPtr) /* Holds resulting instructions. */
1400 {
1401 DefineLineInformation; /* TIP #280 */
1402 int numArgs = parsePtr->numWords - 1;
1403 int numOpts = numArgs - 1;
1404 int objc, flags = TCL_SUBST_ALL;
1405 Tcl_Obj **objv/*, *toSubst = NULL*/;
1406 Tcl_Token *wordTokenPtr = TokenAfter(parsePtr->tokenPtr);
1407 int code = TCL_ERROR;
1408
1409 if (numArgs == 0) {
1410 return TCL_ERROR;
1411 }
1412
1413 objv = (Tcl_Obj **)TclStackAlloc(interp, /*numArgs*/ numOpts * sizeof(Tcl_Obj *));
1414
1415 for (objc = 0; objc < /*numArgs*/ numOpts; objc++) {
1416 TclNewObj(objv[objc]);
1417 Tcl_IncrRefCount(objv[objc]);
1418 if (!TclWordKnownAtCompileTime(wordTokenPtr, objv[objc])) {
1419 objc++;
1420 goto cleanup;
1421 }
1422 wordTokenPtr = TokenAfter(wordTokenPtr);
1423 }
1424
1425 /*
1426 if (TclSubstOptions(NULL, numOpts, objv, &flags) == TCL_OK) {
1427 toSubst = objv[numOpts];
1428 Tcl_IncrRefCount(toSubst);
1429 }
1430 */
1431
1432 /* TODO: Figure out expansion to cover WordKnownAtCompileTime
1433 * The difficulty is that WKACT makes a copy, and if TclSubstParse
1434 * below parses the copy of the original source string, some deep
1435 * parts of the compile machinery get upset. They want all pointers
1436 * stored in Tcl_Tokens to point back to the same original string.
1437 */
1438 if (wordTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
1439 code = TclSubstOptions(NULL, numOpts, objv, &flags);
1440 }
1441
1442 cleanup:
1443 while (--objc >= 0) {
1444 TclDecrRefCount(objv[objc]);
1445 }
1446 TclStackFree(interp, objv);
1447 if (/*toSubst == NULL*/ code != TCL_OK) {
1448 return TCL_ERROR;
1449 }
1450
1451 SetLineInformation(numArgs);
1452 TclSubstCompile(interp, wordTokenPtr[1].start, wordTokenPtr[1].size,
1453 flags, mapPtr->loc[eclIndex].line[numArgs], envPtr);
1454
1455 /* TclDecrRefCount(toSubst);*/
1456 return TCL_OK;
1457 }
1458
1459 void
1460 TclSubstCompile(
1461 Tcl_Interp *interp,
1462 const char *bytes,
1463 int numBytes,
1464 int flags,
1465 int line,
1466 CompileEnv *envPtr)
1467 {
1468 Tcl_Token *endTokenPtr, *tokenPtr;
1469 int breakOffset = 0, count = 0, bline = line;
1470 Tcl_Parse parse;
1471 Tcl_InterpState state = NULL;
1472
1473 TclSubstParse(interp, bytes, numBytes, flags, &parse, &state);
1474 if (state != NULL) {
1475 Tcl_ResetResult(interp);
1476 }
1477
1478 /*
1479 * Tricky point! If the first token does not result in a *guaranteed* push
1480 * of a Tcl_Obj on the stack, we must push an empty object. Otherwise it
1481 * is possible to get to an INST_STR_CONCAT1 or INST_DONE without enough
1482 * values on the stack, resulting in a crash. Thanks to Joe Mistachkin for
1483 * identifying a script that could trigger this case.
1484 */
1485
1486 tokenPtr = parse.tokenPtr;
1487 if (tokenPtr->type != TCL_TOKEN_TEXT && tokenPtr->type != TCL_TOKEN_BS) {
1488 PUSH("");
1489 count++;
1490 }
1491
1492 for (endTokenPtr = tokenPtr + parse.numTokens;
1493 tokenPtr < endTokenPtr; tokenPtr = TokenAfter(tokenPtr)) {
1494 int length, literal, catchRange, breakJump;
1495 char buf[TCL_UTF_MAX] = "";
1496 JumpFixup startFixup, okFixup, returnFixup, breakFixup;
1497 JumpFixup continueFixup, otherFixup, endFixup;
1498
1499 switch (tokenPtr->type) {
1500 case TCL_TOKEN_TEXT:
1501 literal = TclRegisterNewLiteral(envPtr,
1502 tokenPtr->start, tokenPtr->size);
1503 TclEmitPush(literal, envPtr);
1504 TclAdvanceLines(&bline, tokenPtr->start,
1505 tokenPtr->start + tokenPtr->size);
1506 count++;
1507 continue;
1508 case TCL_TOKEN_BS:
1509 length = TclParseBackslash(tokenPtr->start, tokenPtr->size,
1510 NULL, buf);
1511 literal = TclRegisterNewLiteral(envPtr, buf, length);
1512 TclEmitPush(literal, envPtr);
1513 count++;
1514 continue;
1515 case TCL_TOKEN_VARIABLE:
1516 /*
1517 * Check for simple variable access; see if we can only generate
1518 * TCL_OK or TCL_ERROR from the substituted variable read; if so,
1519 * there is no need to generate elaborate exception-management
1520 * code. Note that the first component of TCL_TOKEN_VARIABLE is
1521 * always TCL_TOKEN_TEXT...
1522 */
1523
1524 if (tokenPtr->numComponents > 1) {
1525 int i, foundCommand = 0;
1526
1527 for (i=2 ; i<=tokenPtr->numComponents ; i++) {
1528 if (tokenPtr[i].type == TCL_TOKEN_COMMAND) {
1529 foundCommand = 1;
1530 break;
1531 }
1532 }
1533 if (foundCommand) {
1534 break;
1535 }
1536 }
1537
1538 envPtr->line = bline;
1539 TclCompileVarSubst(interp, tokenPtr, envPtr);
1540 bline = envPtr->line;
1541 count++;
1542 continue;
1543 }
1544
1545 while (count > 255) {
1546 OP1( STR_CONCAT1, 255);
1547 count -= 254;
1548 }
1549 if (count > 1) {
1550 OP1( STR_CONCAT1, count);
1551 count = 1;
1552 }
1553
1554 if (breakOffset == 0) {
1555 /* Jump to the start (jump over the jump to end) */
1556 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &startFixup);
1557
1558 /* Jump to the end (all BREAKs land here) */
1559 breakOffset = CurrentOffset(envPtr);
1560 TclEmitInstInt4(INST_JUMP4, 0, envPtr);
1561
1562 /* Start */
1563 if (TclFixupForwardJumpToHere(envPtr, &startFixup, 127)) {
1564 Tcl_Panic("TclCompileSubstCmd: bad start jump distance %d",
1565 (int) (CurrentOffset(envPtr) - startFixup.codeOffset));
1566 }
1567 }
1568
1569 envPtr->line = bline;
1570 catchRange = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
1571 OP4( BEGIN_CATCH4, catchRange);
1572 ExceptionRangeStarts(envPtr, catchRange);
1573
1574 switch (tokenPtr->type) {
1575 case TCL_TOKEN_COMMAND:
1576 TclCompileScript(interp, tokenPtr->start+1, tokenPtr->size-2,
1577 envPtr);
1578 count++;
1579 break;
1580 case TCL_TOKEN_VARIABLE:
1581 TclCompileVarSubst(interp, tokenPtr, envPtr);
1582 count++;
1583 break;
1584 default:
1585 Tcl_Panic("unexpected token type in TclCompileSubstCmd: %d",
1586 tokenPtr->type);
1587 }
1588
1589 ExceptionRangeEnds(envPtr, catchRange);
1590
1591 /* Substitution produced TCL_OK */
1592 OP( END_CATCH);
1593 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &okFixup);
1594 TclAdjustStackDepth(-1, envPtr);
1595
1596 /* Exceptional return codes processed here */
1597 ExceptionRangeTarget(envPtr, catchRange, catchOffset);
1598 OP( PUSH_RETURN_OPTIONS);
1599 OP( PUSH_RESULT);
1600 OP( PUSH_RETURN_CODE);
1601 OP( END_CATCH);
1602 OP( RETURN_CODE_BRANCH);
1603
1604 /* ERROR -> reraise it; NB: can't require BREAK/CONTINUE handling */
1605 OP( RETURN_STK);
1606 OP( NOP);
1607
1608 /* RETURN */
1609 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &returnFixup);
1610
1611 /* BREAK */
1612 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &breakFixup);
1613
1614 /* CONTINUE */
1615 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &continueFixup);
1616
1617 /* OTHER */
1618 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &otherFixup);
1619
1620 TclAdjustStackDepth(1, envPtr);
1621 /* BREAK destination */
1622 if (TclFixupForwardJumpToHere(envPtr, &breakFixup, 127)) {
1623 Tcl_Panic("TclCompileSubstCmd: bad break jump distance %d",
1624 (int) (CurrentOffset(envPtr) - breakFixup.codeOffset));
1625 }
1626 OP( POP);
1627 OP( POP);
1628
1629 breakJump = CurrentOffset(envPtr) - breakOffset;
1630 if (breakJump > 127) {
1631 OP4(JUMP4, -breakJump);
1632 } else {
1633 OP1(JUMP1, -breakJump);
1634 }
1635
1636 TclAdjustStackDepth(2, envPtr);
1637 /* CONTINUE destination */
1638 if (TclFixupForwardJumpToHere(envPtr, &continueFixup, 127)) {
1639 Tcl_Panic("TclCompileSubstCmd: bad continue jump distance %d",
1640 (int) (CurrentOffset(envPtr) - continueFixup.codeOffset));
1641 }
1642 OP( POP);
1643 OP( POP);
1644 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &endFixup);
1645
1646 TclAdjustStackDepth(2, envPtr);
1647 /* RETURN + other destination */
1648 if (TclFixupForwardJumpToHere(envPtr, &returnFixup, 127)) {
1649 Tcl_Panic("TclCompileSubstCmd: bad return jump distance %d",
1650 (int) (CurrentOffset(envPtr) - returnFixup.codeOffset));
1651 }
1652 if (TclFixupForwardJumpToHere(envPtr, &otherFixup, 127)) {
1653 Tcl_Panic("TclCompileSubstCmd: bad other jump distance %d",
1654 (int) (CurrentOffset(envPtr) - otherFixup.codeOffset));
1655 }
1656
1657 /*
1658 * Pull the result to top of stack, discard options dict.
1659 */
1660
1661 OP4( REVERSE, 2);
1662 OP( POP);
1663
1664 /* OK destination */
1665 if (TclFixupForwardJumpToHere(envPtr, &okFixup, 127)) {
1666 Tcl_Panic("TclCompileSubstCmd: bad ok jump distance %d",
1667 (int) (CurrentOffset(envPtr) - okFixup.codeOffset));
1668 }
1669 if (count > 1) {
1670 OP1(STR_CONCAT1, count);
1671 count = 1;
1672 }
1673
1674 /* CONTINUE jump to here */
1675 if (TclFixupForwardJumpToHere(envPtr, &endFixup, 127)) {
1676 Tcl_Panic("TclCompileSubstCmd: bad end jump distance %d",
1677 (int) (CurrentOffset(envPtr) - endFixup.codeOffset));
1678 }
1679 bline = envPtr->line;
1680 }
1681
1682 while (count > 255) {
1683 OP1( STR_CONCAT1, 255);
1684 count -= 254;
1685 }
1686 if (count > 1) {
1687 OP1( STR_CONCAT1, count);
1688 }
1689
1690 Tcl_FreeParse(&parse);
1691
1692 if (state != NULL) {
1693 Tcl_RestoreInterpState(interp, state);
1694 TclCompileSyntaxError(interp, envPtr);
1695 TclAdjustStackDepth(-1, envPtr);
1696 }
1697
1698 /* Final target of the multi-jump from all BREAKs */
1699 if (breakOffset > 0) {
1700 TclUpdateInstInt4AtPc(INST_JUMP4, CurrentOffset(envPtr) - breakOffset,
1701 envPtr->codeStart + breakOffset);
1702 }
1703 }
1704
1705 /*
1706 *----------------------------------------------------------------------
1707 *
1708 * TclCompileSwitchCmd --
1709 *
1710 * Procedure called to compile the "switch" command.
1711 *
1712 * Results:
1713 * Returns TCL_OK for successful compile, or TCL_ERROR to defer
1714 * evaluation to runtime (either when it is too complex to get the
1715 * semantics right, or when we know for sure that it is an error but need
1716 * the error to happen at the right time).
1717 *
1718 * Side effects:
1719 * Instructions are added to envPtr to execute the "switch" command at
1720 * runtime.
1721 *
1722 *----------------------------------------------------------------------
1723 */
1724
1725 int
1726 TclCompileSwitchCmd(
1727 Tcl_Interp *interp, /* Used for error reporting. */
1728 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1729 * created by Tcl_ParseCommand. */
1730 Command *cmdPtr, /* Points to definition of command being
1731 * compiled. */
1732 CompileEnv *envPtr) /* Holds resulting instructions. */
1733 {
1734 DefineLineInformation; /* TIP #280 */
1735 Tcl_Token *tokenPtr; /* Pointer to tokens in command. */
1736 int numWords; /* Number of words in command. */
1737
1738 Tcl_Token *valueTokenPtr; /* Token for the value to switch on. */
1739 enum {Switch_Exact, Switch_Glob, Switch_Regexp} mode;
1740 /* What kind of switch are we doing? */
1741
1742 Tcl_Token *bodyTokenArray; /* Array of real pattern list items. */
1743 Tcl_Token **bodyToken; /* Array of pointers to pattern list items. */
1744 int *bodyLines; /* Array of line numbers for body list
1745 * items. */
1746 int **bodyContLines; /* Array of continuation line info. */
1747 int noCase; /* Has the -nocase flag been given? */
1748 int foundMode = 0; /* Have we seen a mode flag yet? */
1749 int i, valueIndex;
1750 int result = TCL_ERROR;
1751 int *clNext = envPtr->clNext;
1752
1753 /*
1754 * Only handle the following versions:
1755 * switch ?--? word {pattern body ...}
1756 * switch -exact ?--? word {pattern body ...}
1757 * switch -glob ?--? word {pattern body ...}
1758 * switch -regexp ?--? word {pattern body ...}
1759 * switch -- word simpleWordPattern simpleWordBody ...
1760 * switch -exact -- word simpleWordPattern simpleWordBody ...
1761 * switch -glob -- word simpleWordPattern simpleWordBody ...
1762 * switch -regexp -- word simpleWordPattern simpleWordBody ...
1763 * When the mode is -glob, can also handle a -nocase flag.
1764 *
1765 * First off, we don't care how the command's word was generated; we're
1766 * compiling it anyway! So skip it...
1767 */
1768
1769 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1770 valueIndex = 1;
1771 numWords = parsePtr->numWords-1;
1772
1773 /*
1774 * Check for options.
1775 */
1776
1777 noCase = 0;
1778 mode = Switch_Exact;
1779 if (numWords == 2) {
1780 /*
1781 * There's just the switch value and the bodies list. In that case, we
1782 * can skip all option parsing and move on to consider switch values
1783 * and the body list.
1784 */
1785
1786 goto finishedOptionParse;
1787 }
1788
1789 /*
1790 * There must be at least one option, --, because without that there is no
1791 * way to statically avoid the problems you get from strings-to-be-matched
1792 * that start with a - (the interpreted code falls apart if it encounters
1793 * them, so we punt if we *might* encounter them as that is the easiest
1794 * way of emulating the behaviour).
1795 */
1796
1797 for (; numWords>=3 ; tokenPtr=TokenAfter(tokenPtr),numWords--) {
1798 unsigned size = tokenPtr[1].size;
1799 const char *chrs = tokenPtr[1].start;
1800
1801 /*
1802 * We only process literal options, and we assume that -e, -g and -n
1803 * are unique prefixes of -exact, -glob and -nocase respectively (true
1804 * at time of writing). Note that -exact and -glob may only be given
1805 * at most once or we bail out (error case).
1806 */
1807
1808 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD || size < 2) {
1809 return TCL_ERROR;
1810 }
1811
1812 if ((size <= 6) && !memcmp(chrs, "-exact", size)) {
1813 if (foundMode) {
1814 return TCL_ERROR;
1815 }
1816 mode = Switch_Exact;
1817 foundMode = 1;
1818 valueIndex++;
1819 continue;
1820 } else if ((size <= 5) && !memcmp(chrs, "-glob", size)) {
1821 if (foundMode) {
1822 return TCL_ERROR;
1823 }
1824 mode = Switch_Glob;
1825 foundMode = 1;
1826 valueIndex++;
1827 continue;
1828 } else if ((size <= 7) && !memcmp(chrs, "-regexp", size)) {
1829 if (foundMode) {
1830 return TCL_ERROR;
1831 }
1832 mode = Switch_Regexp;
1833 foundMode = 1;
1834 valueIndex++;
1835 continue;
1836 } else if ((size <= 7) && !memcmp(chrs, "-nocase", size)) {
1837 noCase = 1;
1838 valueIndex++;
1839 continue;
1840 } else if ((size == 2) && !memcmp(chrs, "--", 2)) {
1841 valueIndex++;
1842 break;
1843 }
1844
1845 /*
1846 * The switch command has many flags we cannot compile at all (e.g.
1847 * all the RE-related ones) which we must have encountered. Either
1848 * that or we have run off the end. The action here is the same: punt
1849 * to interpreted version.
1850 */
1851
1852 return TCL_ERROR;
1853 }
1854 if (numWords < 3) {
1855 return TCL_ERROR;
1856 }
1857 tokenPtr = TokenAfter(tokenPtr);
1858 numWords--;
1859 if (noCase && (mode == Switch_Exact)) {
1860 /*
1861 * Can't compile this case; no opcode for case-insensitive equality!
1862 */
1863
1864 return TCL_ERROR;
1865 }
1866
1867 /*
1868 * The value to test against is going to always get pushed on the stack.
1869 * But not yet; we need to verify that the rest of the command is
1870 * compilable too.
1871 */
1872
1873 finishedOptionParse:
1874 valueTokenPtr = tokenPtr;
1875 /* For valueIndex, see previous loop. */
1876 tokenPtr = TokenAfter(tokenPtr);
1877 numWords--;
1878
1879 /*
1880 * Build an array of tokens for the matcher terms and script bodies. Note
1881 * that in the case of the quoted bodies, this is tricky as we cannot use
1882 * copies of the string from the input token for the generated tokens (it
1883 * causes a crash during exception handling). When multiple tokens are
1884 * available at this point, this is pretty easy.
1885 */
1886
1887 if (numWords == 1) {
1888 const char *bytes;
1889 int maxLen, numBytes;
1890 int bline; /* TIP #280: line of the pattern/action list,
1891 * and start of list for when tracking the
1892 * location. This list comes immediately after
1893 * the value we switch on. */
1894
1895 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
1896 return TCL_ERROR;
1897 }
1898 bytes = tokenPtr[1].start;
1899 numBytes = tokenPtr[1].size;
1900
1901 /* Allocate enough space to work in. */
1902 maxLen = TclMaxListLength(bytes, numBytes, NULL);
1903 if (maxLen < 2) {
1904 return TCL_ERROR;
1905 }
1906 bodyTokenArray = (Tcl_Token *)ckalloc(sizeof(Tcl_Token) * maxLen);
1907 bodyToken = (Tcl_Token **)ckalloc(sizeof(Tcl_Token *) * maxLen);
1908 bodyLines = (int *)ckalloc(sizeof(int) * maxLen);
1909 bodyContLines = (int **)ckalloc(sizeof(int*) * maxLen);
1910
1911 bline = mapPtr->loc[eclIndex].line[valueIndex+1];
1912 numWords = 0;
1913
1914 while (numBytes > 0) {
1915 const char *prevBytes = bytes;
1916 int literal;
1917
1918 if (TCL_OK != TclFindElement(NULL, bytes, numBytes,
1919 &(bodyTokenArray[numWords].start), &bytes,
1920 &(bodyTokenArray[numWords].size), &literal) || !literal) {
1921 goto abort;
1922 }
1923
1924 bodyTokenArray[numWords].type = TCL_TOKEN_TEXT;
1925 bodyTokenArray[numWords].numComponents = 0;
1926 bodyToken[numWords] = bodyTokenArray + numWords;
1927
1928 /*
1929 * TIP #280: Now determine the line the list element starts on
1930 * (there is no need to do it earlier, due to the possibility of
1931 * aborting, see above).
1932 */
1933
1934 TclAdvanceLines(&bline, prevBytes, bodyTokenArray[numWords].start);
1935 TclAdvanceContinuations(&bline, &clNext,
1936 bodyTokenArray[numWords].start - envPtr->source);
1937 bodyLines[numWords] = bline;
1938 bodyContLines[numWords] = clNext;
1939 TclAdvanceLines(&bline, bodyTokenArray[numWords].start, bytes);
1940 TclAdvanceContinuations(&bline, &clNext, bytes - envPtr->source);
1941
1942 numBytes -= (bytes - prevBytes);
1943 numWords++;
1944 }
1945 if (numWords % 2) {
1946 abort:
1947 ckfree((char *) bodyToken);
1948 ckfree((char *) bodyTokenArray);
1949 ckfree((char *) bodyLines);
1950 ckfree((char *) bodyContLines);
1951 return TCL_ERROR;
1952 }
1953 } else if (numWords % 2 || numWords == 0) {
1954 /*
1955 * Odd number of words (>1) available, or no words at all available.
1956 * Both are error cases, so punt and let the interpreted-version
1957 * generate the error message. Note that the second case probably
1958 * should get caught earlier, but it's easy to check here again anyway
1959 * because it'd cause a nasty crash otherwise.
1960 */
1961
1962 return TCL_ERROR;
1963 } else {
1964 /*
1965 * Multi-word definition of patterns & actions.
1966 */
1967
1968 bodyToken = (Tcl_Token **)ckalloc(sizeof(Tcl_Token *) * numWords);
1969 bodyLines = (int *)ckalloc(sizeof(int) * numWords);
1970 bodyContLines = (int **)ckalloc(sizeof(int*) * numWords);
1971 bodyTokenArray = NULL;
1972 for (i=0 ; i<numWords ; i++) {
1973 /*
1974 * We only handle the very simplest case. Anything more complex is
1975 * a good reason to go to the interpreted case anyway due to
1976 * traces, etc.
1977 */
1978
1979 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
1980 goto freeTemporaries;
1981 }
1982 bodyToken[i] = tokenPtr+1;
1983
1984 /*
1985 * TIP #280: Copy line information from regular cmd info.
1986 */
1987
1988 bodyLines[i] = mapPtr->loc[eclIndex].line[valueIndex+1+i];
1989 bodyContLines[i] = mapPtr->loc[eclIndex].next[valueIndex+1+i];
1990 tokenPtr = TokenAfter(tokenPtr);
1991 }
1992 }
1993
1994 /*
1995 * Fall back to interpreted if the last body is a continuation (it's
1996 * illegal, but this makes the error happen at the right time).
1997 */
1998
1999 if (bodyToken[numWords-1]->size == 1 &&
2000 bodyToken[numWords-1]->start[0] == '-') {
2001 goto freeTemporaries;
2002 }
2003
2004 /*
2005 * Now we commit to generating code; the parsing stage per se is done.
2006 * Check if we can generate a jump table, since if so that's faster than
2007 * doing an explicit compare with each body. Note that we're definitely
2008 * over-conservative with determining whether we can do the jump table,
2009 * but it handles the most common case well enough.
2010 */
2011
2012 /* Both methods push the value to match against onto the stack. */
2013 CompileWord(envPtr, valueTokenPtr, interp, valueIndex);
2014
2015 if (mode == Switch_Exact) {
2016 IssueSwitchJumpTable(interp, envPtr, numWords, bodyToken,
2017 bodyLines, bodyContLines);
2018 } else {
2019 IssueSwitchChainedTests(interp, envPtr, mode, noCase,
2020 numWords, bodyToken, bodyLines, bodyContLines);
2021 }
2022 result = TCL_OK;
2023
2024 /*
2025 * Clean up all our temporary space and return.
2026 */
2027
2028 freeTemporaries:
2029 ckfree(bodyToken);
2030 ckfree(bodyLines);
2031 ckfree(bodyContLines);
2032 if (bodyTokenArray != NULL) {
2033 ckfree(bodyTokenArray);
2034 }
2035 return result;
2036 }
2037
2038 /*
2039 *----------------------------------------------------------------------
2040 *
2041 * IssueSwitchChainedTests --
2042 *
2043 * Generate instructions for a [switch] command that is to be compiled
2044 * into a sequence of tests. This is the generic handle-everything mode
2045 * that inherently has performance that is (on average) linear in the
2046 * number of tests. It is the only mode that can handle -glob and -regexp
2047 * matches, or anything that is case-insensitive. It does not handle the
2048 * wild-and-wooly end of regexp matching (i.e., capture of match results)
2049 * so that's when we spill to the interpreted version.
2050 *
2051 *----------------------------------------------------------------------
2052 */
2053
2054 static void
2055 IssueSwitchChainedTests(
2056 Tcl_Interp *interp, /* Context for compiling script bodies. */
2057 CompileEnv *envPtr, /* Holds resulting instructions. */
2058 int mode, /* Exact, Glob or Regexp */
2059 int noCase, /* Case-insensitivity flag. */
2060 int numBodyTokens, /* Number of tokens describing things the
2061 * switch can match against and bodies to
2062 * execute when the match succeeds. */
2063 Tcl_Token **bodyToken, /* Array of pointers to pattern list items. */
2064 int *bodyLines, /* Array of line numbers for body list
2065 * items. */
2066 int **bodyContLines) /* Array of continuation line info. */
2067 {
2068 enum {Switch_Exact, Switch_Glob, Switch_Regexp};
2069 int foundDefault; /* Flag to indicate whether a "default" clause
2070 * is present. */
2071 JumpFixup *fixupArray; /* Array of forward-jump fixup records. */
2072 unsigned int *fixupTargetArray; /* Array of places for fixups to point at. */
2073 int fixupCount; /* Number of places to fix up. */
2074 int contFixIndex; /* Where the first of the jumps due to a group
2075 * of continuation bodies starts, or -1 if
2076 * there aren't any. */
2077 int contFixCount; /* Number of continuation bodies pointing to
2078 * the current (or next) real body. */
2079 int nextArmFixupIndex;
2080 int simple, exact; /* For extracting the type of regexp. */
2081 int i;
2082
2083 /*
2084 * Generate a test for each arm.
2085 */
2086
2087 contFixIndex = -1;
2088 contFixCount = 0;
2089 fixupArray = (JumpFixup *)TclStackAlloc(interp, sizeof(JumpFixup) * numBodyTokens);
2090 fixupTargetArray = (unsigned int *)TclStackAlloc(interp, sizeof(int) * numBodyTokens);
2091 memset(fixupTargetArray, 0, numBodyTokens * sizeof(int));
2092 fixupCount = 0;
2093 foundDefault = 0;
2094 for (i=0 ; i<numBodyTokens ; i+=2) {
2095 nextArmFixupIndex = -1;
2096 if (i!=numBodyTokens-2 || bodyToken[numBodyTokens-2]->size != 7 ||
2097 memcmp(bodyToken[numBodyTokens-2]->start, "default", 7)) {
2098 /*
2099 * Generate the test for the arm.
2100 */
2101
2102 switch (mode) {
2103 case Switch_Exact:
2104 OP( DUP);
2105 TclCompileTokens(interp, bodyToken[i], 1, envPtr);
2106 OP( STR_EQ);
2107 break;
2108 case Switch_Glob:
2109 TclCompileTokens(interp, bodyToken[i], 1, envPtr);
2110 OP4( OVER, 1);
2111 OP1( STR_MATCH, noCase);
2112 break;
2113 case Switch_Regexp:
2114 simple = exact = 0;
2115
2116 /*
2117 * Keep in sync with TclCompileRegexpCmd.
2118 */
2119
2120 if (bodyToken[i]->type == TCL_TOKEN_TEXT) {
2121 Tcl_DString ds;
2122
2123 if (bodyToken[i]->size == 0) {
2124 /*
2125 * The semantics of regexps are that they always match
2126 * when the RE == "".
2127 */
2128
2129 PUSH("1");
2130 break;
2131 }
2132
2133 /*
2134 * Attempt to convert pattern to glob. If successful, push
2135 * the converted pattern.
2136 */
2137
2138 if (TclReToGlob(NULL, bodyToken[i]->start,
2139 bodyToken[i]->size, &ds, &exact, NULL) == TCL_OK){
2140 simple = 1;
2141 PushLiteral(envPtr, Tcl_DStringValue(&ds),
2142 Tcl_DStringLength(&ds));
2143 Tcl_DStringFree(&ds);
2144 }
2145 }
2146 if (!simple) {
2147 TclCompileTokens(interp, bodyToken[i], 1, envPtr);
2148 }
2149
2150 OP4( OVER, 1);
2151 if (!simple) {
2152 /*
2153 * Pass correct RE compile flags. We use only Int1
2154 * (8-bit), but that handles all the flags we want to
2155 * pass. Don't use TCL_REG_NOSUB as we may have backrefs
2156 * or capture vars.
2157 */
2158
2159 int cflags = TCL_REG_ADVANCED
2160 | (noCase ? TCL_REG_NOCASE : 0);
2161
2162 OP1(REGEXP, cflags);
2163 } else if (exact && !noCase) {
2164 OP( STR_EQ);
2165 } else {
2166 OP1(STR_MATCH, noCase);
2167 }
2168 break;
2169 default:
2170 Tcl_Panic("unknown switch mode: %d", mode);
2171 }
2172
2173 /*
2174 * In a fall-through case, we will jump on _true_ to the place
2175 * where the body starts (generated later, with guarantee of this
2176 * ensured earlier; the final body is never a fall-through).
2177 */
2178
2179 if (bodyToken[i+1]->size==1 && bodyToken[i+1]->start[0]=='-') {
2180 if (contFixIndex == -1) {
2181 contFixIndex = fixupCount;
2182 contFixCount = 0;
2183 }
2184 TclEmitForwardJump(envPtr, TCL_TRUE_JUMP,
2185 &fixupArray[contFixIndex+contFixCount]);
2186 fixupCount++;
2187 contFixCount++;
2188 continue;
2189 }
2190
2191 TclEmitForwardJump(envPtr, TCL_FALSE_JUMP,
2192 &fixupArray[fixupCount]);
2193 nextArmFixupIndex = fixupCount;
2194 fixupCount++;
2195 } else {
2196 /*
2197 * Got a default clause; set a flag to inhibit the generation of
2198 * the jump after the body and the cleanup of the intermediate
2199 * value that we are switching against.
2200 *
2201 * Note that default clauses (which are always terminal clauses)
2202 * cannot be fall-through clauses as well, since the last clause
2203 * is never a fall-through clause (which we have already
2204 * verified).
2205 */
2206
2207 foundDefault = 1;
2208 }
2209
2210 /*
2211 * Generate the body for the arm. This is guaranteed not to be a
2212 * fall-through case, but it might have preceding fall-through cases,
2213 * so we must process those first.
2214 */
2215
2216 if (contFixIndex != -1) {
2217 int j;
2218
2219 for (j=0 ; j<contFixCount ; j++) {
2220 fixupTargetArray[contFixIndex+j] = CurrentOffset(envPtr);
2221 }
2222 contFixIndex = -1;
2223 }
2224
2225 /*
2226 * Now do the actual compilation. Note that we do not use BODY()
2227 * because we may have synthesized the tokens in a non-standard
2228 * pattern.
2229 */
2230
2231 OP( POP);
2232 envPtr->line = bodyLines[i+1]; /* TIP #280 */
2233 envPtr->clNext = bodyContLines[i+1]; /* TIP #280 */
2234 TclCompileCmdWord(interp, bodyToken[i+1], 1, envPtr);
2235
2236 if (!foundDefault) {
2237 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP,
2238 &fixupArray[fixupCount]);
2239 fixupCount++;
2240 fixupTargetArray[nextArmFixupIndex] = CurrentOffset(envPtr);
2241 }
2242 }
2243
2244 /*
2245 * Discard the value we are matching against unless we've had a default
2246 * clause (in which case it will already be gone due to the code at the
2247 * start of processing an arm, guaranteed) and make the result of the
2248 * command an empty string.
2249 */
2250
2251 if (!foundDefault) {
2252 OP( POP);
2253 PUSH("");
2254 }
2255
2256 /*
2257 * Do jump fixups for arms that were executed. First, fill in the jumps of
2258 * all jumps that don't point elsewhere to point to here.
2259 */
2260
2261 for (i=0 ; i<fixupCount ; i++) {
2262 if (fixupTargetArray[i] == 0) {
2263 fixupTargetArray[i] = envPtr->codeNext-envPtr->codeStart;
2264 }
2265 }
2266
2267 /*
2268 * Now scan backwards over all the jumps (all of which are forward jumps)
2269 * doing each one. When we do one and there is a size changes, we must
2270 * scan back over all the previous ones and see if they need adjusting
2271 * before proceeding with further jump fixups (the interleaved nature of
2272 * all the jumps makes this impossible to do without nested loops).
2273 */
2274
2275 for (i=fixupCount-1 ; i>=0 ; i--) {
2276 if (TclFixupForwardJump(envPtr, &fixupArray[i],
2277 fixupTargetArray[i] - fixupArray[i].codeOffset, 127)) {
2278 int j;
2279
2280 for (j=i-1 ; j>=0 ; j--) {
2281 if (fixupTargetArray[j] > fixupArray[i].codeOffset) {
2282 fixupTargetArray[j] += 3;
2283 }
2284 }
2285 }
2286 }
2287 TclStackFree(interp, fixupTargetArray);
2288 TclStackFree(interp, fixupArray);
2289 }
2290
2291 /*
2292 *----------------------------------------------------------------------
2293 *
2294 * IssueSwitchJumpTable --
2295 *
2296 * Generate instructions for a [switch] command that is to be compiled
2297 * into a jump table. This only handles the case where case-sensitive,
2298 * exact matching is used, but this is actually the most common case in
2299 * real code.
2300 *
2301 *----------------------------------------------------------------------
2302 */
2303
2304 static void
2305 IssueSwitchJumpTable(
2306 Tcl_Interp *interp, /* Context for compiling script bodies. */
2307 CompileEnv *envPtr, /* Holds resulting instructions. */
2308 int numBodyTokens, /* Number of tokens describing things the
2309 * switch can match against and bodies to
2310 * execute when the match succeeds. */
2311 Tcl_Token **bodyToken, /* Array of pointers to pattern list items. */
2312 int *bodyLines, /* Array of line numbers for body list
2313 * items. */
2314 int **bodyContLines) /* Array of continuation line info. */
2315 {
2316 JumptableInfo *jtPtr;
2317 int infoIndex, isNew, *finalFixups, numRealBodies = 0, jumpLocation;
2318 int mustGenerate, foundDefault, jumpToDefault, i;
2319 Tcl_DString buffer;
2320 Tcl_HashEntry *hPtr;
2321
2322 /*
2323 * Compile the switch by using a jump table, which is basically a
2324 * hashtable that maps from literal values to match against to the offset
2325 * (relative to the INST_JUMP_TABLE instruction) to jump to. The jump
2326 * table itself is independent of any invocation of the bytecode, and as
2327 * such is stored in an auxData block.
2328 *
2329 * Start by allocating the jump table itself, plus some workspace.
2330 */
2331
2332 jtPtr = (JumptableInfo *)ckalloc(sizeof(JumptableInfo));
2333 Tcl_InitHashTable(&jtPtr->hashTable, TCL_STRING_KEYS);
2334 infoIndex = TclCreateAuxData(jtPtr, &tclJumptableInfoType, envPtr);
2335 finalFixups = (int *)TclStackAlloc(interp, sizeof(int) * (numBodyTokens/2));
2336 foundDefault = 0;
2337 mustGenerate = 1;
2338
2339 /*
2340 * Next, issue the instruction to do the jump, together with what we want
2341 * to do if things do not work out (jump to either the default clause or
2342 * the "default" default, which just sets the result to empty). Note that
2343 * we will come back and rewrite the jump's offset parameter when we know
2344 * what it should be, and that all jumps we issue are of the wide kind
2345 * because that makes the code much easier to debug!
2346 */
2347
2348 jumpLocation = CurrentOffset(envPtr);
2349 OP4( JUMP_TABLE, infoIndex);
2350 jumpToDefault = CurrentOffset(envPtr);
2351 OP4( JUMP4, 0);
2352
2353 for (i=0 ; i<numBodyTokens ; i+=2) {
2354 /*
2355 * For each arm, we must first work out what to do with the match
2356 * term.
2357 */
2358
2359 if (i!=numBodyTokens-2 || bodyToken[numBodyTokens-2]->size != 7 ||
2360 memcmp(bodyToken[numBodyTokens-2]->start, "default", 7)) {
2361 /*
2362 * This is not a default clause, so insert the current location as
2363 * a target in the jump table (assuming it isn't already there,
2364 * which would indicate that this clause is probably masked by an
2365 * earlier one). Note that we use a Tcl_DString here simply
2366 * because the hash API does not let us specify the string length.
2367 */
2368
2369 Tcl_DStringInit(&buffer);
2370 TclDStringAppendToken(&buffer, bodyToken[i]);
2371 hPtr = Tcl_CreateHashEntry(&jtPtr->hashTable,
2372 Tcl_DStringValue(&buffer), &isNew);
2373 if (isNew) {
2374 /*
2375 * First time we've encountered this match clause, so it must
2376 * point to here.
2377 */
2378
2379 Tcl_SetHashValue(hPtr, INT2PTR(CurrentOffset(envPtr) - jumpLocation));
2380 }
2381 Tcl_DStringFree(&buffer);
2382 } else {
2383 /*
2384 * This is a default clause, so patch up the fallthrough from the
2385 * INST_JUMP_TABLE instruction to here.
2386 */
2387
2388 foundDefault = 1;
2389 isNew = 1;
2390 TclStoreInt4AtPtr(CurrentOffset(envPtr)-jumpToDefault,
2391 envPtr->codeStart+jumpToDefault+1);
2392 }
2393
2394 /*
2395 * Now, for each arm we must deal with the body of the clause.
2396 *
2397 * If this is a continuation body (never true of a final clause,
2398 * whether default or not) we're done because the next jump target
2399 * will also point here, so we advance to the next clause.
2400 */
2401
2402 if (bodyToken[i+1]->size == 1 && bodyToken[i+1]->start[0] == '-') {
2403 mustGenerate = 1;
2404 continue;
2405 }
2406
2407 /*
2408 * Also skip this arm if its only match clause is masked. (We could
2409 * probably be more aggressive about this, but that would be much more
2410 * difficult to get right.)
2411 */
2412
2413 if (!isNew && !mustGenerate) {
2414 continue;
2415 }
2416 mustGenerate = 0;
2417
2418 /*
2419 * Compile the body of the arm.
2420 */
2421
2422 envPtr->line = bodyLines[i+1]; /* TIP #280 */
2423 envPtr->clNext = bodyContLines[i+1]; /* TIP #280 */
2424 TclCompileCmdWord(interp, bodyToken[i+1], 1, envPtr);
2425
2426 /*
2427 * Compile a jump in to the end of the command if this body is
2428 * anything other than a user-supplied default arm (to either skip
2429 * over the remaining bodies or the code that generates an empty
2430 * result).
2431 */
2432
2433 if (i+2 < numBodyTokens || !foundDefault) {
2434 finalFixups[numRealBodies++] = CurrentOffset(envPtr);
2435
2436 /*
2437 * Easier by far to issue this jump as a fixed-width jump, since
2438 * otherwise we'd need to do a lot more (and more awkward)
2439 * rewriting when we fixed this all up.
2440 */
2441
2442 OP4( JUMP4, 0);
2443 TclAdjustStackDepth(-1, envPtr);
2444 }
2445 }
2446
2447 /*
2448 * We're at the end. If we've not already done so through the processing
2449 * of a user-supplied default clause, add in a "default" default clause
2450 * now.
2451 */
2452
2453 if (!foundDefault) {
2454 TclStoreInt4AtPtr(CurrentOffset(envPtr)-jumpToDefault,
2455 envPtr->codeStart+jumpToDefault+1);
2456 PUSH("");
2457 }
2458
2459 /*
2460 * No more instructions to be issued; everything that needs to jump to the
2461 * end of the command is fixed up at this point.
2462 */
2463
2464 for (i=0 ; i<numRealBodies ; i++) {
2465 TclStoreInt4AtPtr(CurrentOffset(envPtr)-finalFixups[i],
2466 envPtr->codeStart+finalFixups[i]+1);
2467 }
2468
2469 /*
2470 * Clean up all our temporary space and return.
2471 */
2472
2473 TclStackFree(interp, finalFixups);
2474 }
2475
2476 /*
2477 *----------------------------------------------------------------------
2478 *
2479 * DupJumptableInfo, FreeJumptableInfo --
2480 *
2481 * Functions to duplicate, release and print a jump-table created for use
2482 * with the INST_JUMP_TABLE instruction.
2483 *
2484 * Results:
2485 * DupJumptableInfo: a copy of the jump-table
2486 * FreeJumptableInfo: none
2487 * PrintJumptableInfo: none
2488 * DisassembleJumptableInfo: none
2489 *
2490 * Side effects:
2491 * DupJumptableInfo: allocates memory
2492 * FreeJumptableInfo: releases memory
2493 * PrintJumptableInfo: none
2494 * DisassembleJumptableInfo: none
2495 *
2496 *----------------------------------------------------------------------
2497 */
2498
2499 static ClientData
2500 DupJumptableInfo(
2501 ClientData clientData)
2502 {
2503 JumptableInfo *jtPtr = (JumptableInfo *)clientData;
2504 JumptableInfo *newJtPtr = (JumptableInfo *)ckalloc(sizeof(JumptableInfo));
2505 Tcl_HashEntry *hPtr, *newHPtr;
2506 Tcl_HashSearch search;
2507 int isNew;
2508
2509 Tcl_InitHashTable(&newJtPtr->hashTable, TCL_STRING_KEYS);
2510 hPtr = Tcl_FirstHashEntry(&jtPtr->hashTable, &search);
2511 while (hPtr != NULL) {
2512 newHPtr = Tcl_CreateHashEntry(&newJtPtr->hashTable,
2513 Tcl_GetHashKey(&jtPtr->hashTable, hPtr), &isNew);
2514 Tcl_SetHashValue(newHPtr, Tcl_GetHashValue(hPtr));
2515 }
2516 return newJtPtr;
2517 }
2518
2519 static void
2520 FreeJumptableInfo(
2521 ClientData clientData)
2522 {
2523 JumptableInfo *jtPtr = (JumptableInfo *)clientData;
2524
2525 Tcl_DeleteHashTable(&jtPtr->hashTable);
2526 ckfree(jtPtr);
2527 }
2528
2529 static void
2530 PrintJumptableInfo(
2531 ClientData clientData,
2532 Tcl_Obj *appendObj,
2533 ByteCode *codePtr,
2534 unsigned int pcOffset)
2535 {
2536 JumptableInfo *jtPtr = (JumptableInfo *)clientData;
2537 Tcl_HashEntry *hPtr;
2538 Tcl_HashSearch search;
2539 const char *keyPtr;
2540 int offset, i = 0;
2541
2542 hPtr = Tcl_FirstHashEntry(&jtPtr->hashTable, &search);
2543 for (; hPtr ; hPtr = Tcl_NextHashEntry(&search)) {
2544 keyPtr = (const char *)Tcl_GetHashKey(&jtPtr->hashTable, hPtr);
2545 offset = PTR2INT(Tcl_GetHashValue(hPtr));
2546
2547 if (i++) {
2548 Tcl_AppendToObj(appendObj, ", ", -1);
2549 if (i%4==0) {
2550 Tcl_AppendToObj(appendObj, "\n\t\t", -1);
2551 }
2552 }
2553 Tcl_AppendPrintfToObj(appendObj, "\"%s\"->pc %d",
2554 keyPtr, pcOffset + offset);
2555 }
2556 }
2557
2558 static void
2559 DisassembleJumptableInfo(
2560 ClientData clientData,
2561 Tcl_Obj *dictObj,
2562 ByteCode *codePtr,
2563 unsigned int pcOffset)
2564 {
2565 JumptableInfo *jtPtr = (JumptableInfo *)clientData;
2566 Tcl_Obj *mapping;
2567 Tcl_HashEntry *hPtr;
2568 Tcl_HashSearch search;
2569 const char *keyPtr;
2570 int offset;
2571
2572 TclNewObj(mapping);
2573 hPtr = Tcl_FirstHashEntry(&jtPtr->hashTable, &search);
2574 for (; hPtr ; hPtr = Tcl_NextHashEntry(&search)) {
2575 keyPtr = (const char *)Tcl_GetHashKey(&jtPtr->hashTable, hPtr);
2576 offset = PTR2INT(Tcl_GetHashValue(hPtr));
2577 TclDictPut(NULL, mapping, keyPtr, Tcl_NewIntObj(offset));
2578 }
2579 TclDictPut(NULL, dictObj, "mapping", mapping);
2580 }
2581
2582 /*
2583 *----------------------------------------------------------------------
2584 *
2585 * TclCompileTailcallCmd --
2586 *
2587 * Procedure called to compile the "tailcall" command.
2588 *
2589 * Results:
2590 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2591 * evaluation to runtime.
2592 *
2593 * Side effects:
2594 * Instructions are added to envPtr to execute the "tailcall" command at
2595 * runtime.
2596 *
2597 *----------------------------------------------------------------------
2598 */
2599
2600 int
2601 TclCompileTailcallCmd(
2602 Tcl_Interp *interp, /* Used for error reporting. */
2603 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2604 * created by Tcl_ParseCommand. */
2605 Command *cmdPtr, /* Points to definition of command being
2606 * compiled. */
2607 CompileEnv *envPtr) /* Holds resulting instructions. */
2608 {
2609 DefineLineInformation; /* TIP #280 */
2610 Tcl_Token *tokenPtr = parsePtr->tokenPtr;
2611 int i;
2612
2613 if (parsePtr->numWords < 2 || parsePtr->numWords >= 256
2614 || envPtr->procPtr == NULL) {
2615 return TCL_ERROR;
2616 }
2617
2618 /* make room for the nsObjPtr */
2619 /* TODO: Doesn't this have to be a known value? */
2620 CompileWord(envPtr, tokenPtr, interp, 0);
2621 for (i=1 ; i<parsePtr->numWords ; i++) {
2622 tokenPtr = TokenAfter(tokenPtr);
2623 CompileWord(envPtr, tokenPtr, interp, i);
2624 }
2625 TclEmitInstInt1( INST_TAILCALL, parsePtr->numWords, envPtr);
2626 return TCL_OK;
2627 }
2628
2629 /*
2630 *----------------------------------------------------------------------
2631 *
2632 * TclCompileThrowCmd --
2633 *
2634 * Procedure called to compile the "throw" command.
2635 *
2636 * Results:
2637 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2638 * evaluation to runtime.
2639 *
2640 * Side effects:
2641 * Instructions are added to envPtr to execute the "throw" command at
2642 * runtime.
2643 *
2644 *----------------------------------------------------------------------
2645 */
2646
2647 int
2648 TclCompileThrowCmd(
2649 Tcl_Interp *interp, /* Used for error reporting. */
2650 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2651 * created by Tcl_ParseCommand. */
2652 Command *cmdPtr, /* Points to definition of command being
2653 * compiled. */
2654 CompileEnv *envPtr) /* Holds resulting instructions. */
2655 {
2656 DefineLineInformation; /* TIP #280 */
2657 int numWords = parsePtr->numWords;
2658 Tcl_Token *codeToken, *msgToken;
2659 Tcl_Obj *objPtr;
2660 int codeKnown, codeIsList, codeIsValid, len;
2661
2662 if (numWords != 3) {
2663 return TCL_ERROR;
2664 }
2665 codeToken = TokenAfter(parsePtr->tokenPtr);
2666 msgToken = TokenAfter(codeToken);
2667
2668 TclNewObj(objPtr);
2669 Tcl_IncrRefCount(objPtr);
2670
2671 codeKnown = TclWordKnownAtCompileTime(codeToken, objPtr);
2672
2673 /*
2674 * First we must emit the code to substitute the arguments. This
2675 * must come first in case substitution raises errors.
2676 */
2677 if (!codeKnown) {
2678 CompileWord(envPtr, codeToken, interp, 1);
2679 PUSH( "-errorcode");
2680 }
2681 CompileWord(envPtr, msgToken, interp, 2);
2682
2683 codeIsList = codeKnown && (TCL_OK ==
2684 TclListObjLength(interp, objPtr, &len));
2685 codeIsValid = codeIsList && (len != 0);
2686
2687 if (codeIsValid) {
2688 Tcl_Obj *errPtr, *dictPtr;
2689
2690 TclNewLiteralStringObj(errPtr, "-errorcode");
2691 TclNewObj(dictPtr);
2692 Tcl_DictObjPut(NULL, dictPtr, errPtr, objPtr);
2693 TclEmitPush(TclAddLiteralObj(envPtr, dictPtr, NULL), envPtr);
2694 }
2695 TclDecrRefCount(objPtr);
2696
2697 /*
2698 * Simpler bytecodes when we detect invalid arguments at compile time.
2699 */
2700 if (codeKnown && !codeIsValid) {
2701 OP( POP);
2702 if (codeIsList) {
2703 /* Must be an empty list */
2704 goto issueErrorForEmptyCode;
2705 }
2706 TclCompileSyntaxError(interp, envPtr);
2707 return TCL_OK;
2708 }
2709
2710 if (!codeKnown) {
2711 /*
2712 * Argument validity checking has to be done by bytecode at
2713 * run time.
2714 */
2715 OP4( REVERSE, 3);
2716 OP( DUP);
2717 OP( LIST_LENGTH);
2718 OP1( JUMP_FALSE1, 16);
2719 OP4( LIST, 2);
2720 OP44( RETURN_IMM, TCL_ERROR, 0);
2721 TclAdjustStackDepth(2, envPtr);
2722 OP( POP);
2723 OP( POP);
2724 OP( POP);
2725 issueErrorForEmptyCode:
2726 PUSH( "type must be non-empty list");
2727 PUSH( "-errorcode {TCL OPERATION THROW BADEXCEPTION}");
2728 }
2729 OP44( RETURN_IMM, TCL_ERROR, 0);
2730 return TCL_OK;
2731 }
2732
2733 /*
2734 *----------------------------------------------------------------------
2735 *
2736 * TclCompileTryCmd --
2737 *
2738 * Procedure called to compile the "try" command.
2739 *
2740 * Results:
2741 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2742 * evaluation to runtime.
2743 *
2744 * Side effects:
2745 * Instructions are added to envPtr to execute the "try" command at
2746 * runtime.
2747 *
2748 *----------------------------------------------------------------------
2749 */
2750
2751 int
2752 TclCompileTryCmd(
2753 Tcl_Interp *interp, /* Used for error reporting. */
2754 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2755 * created by Tcl_ParseCommand. */
2756 Command *cmdPtr, /* Points to definition of command being
2757 * compiled. */
2758 CompileEnv *envPtr) /* Holds resulting instructions. */
2759 {
2760 int numWords = parsePtr->numWords, numHandlers, result = TCL_ERROR;
2761 Tcl_Token *bodyToken, *finallyToken, *tokenPtr;
2762 Tcl_Token **handlerTokens = NULL;
2763 Tcl_Obj **matchClauses = NULL;
2764 int *matchCodes=NULL, *resultVarIndices=NULL, *optionVarIndices=NULL;
2765 int i;
2766
2767 if (numWords < 2) {
2768 return TCL_ERROR;
2769 }
2770
2771 bodyToken = TokenAfter(parsePtr->tokenPtr);
2772
2773 if (numWords == 2) {
2774 /*
2775 * No handlers or finally; do nothing beyond evaluating the body.
2776 */
2777
2778 DefineLineInformation; /* TIP #280 */
2779 BODY(bodyToken, 1);
2780 return TCL_OK;
2781 }
2782
2783 numWords -= 2;
2784 tokenPtr = TokenAfter(bodyToken);
2785
2786 /*
2787 * Extract information about what handlers there are.
2788 */
2789
2790 numHandlers = numWords >> 2;
2791 numWords -= numHandlers * 4;
2792 if (numHandlers > 0) {
2793 handlerTokens = (Tcl_Token**)TclStackAlloc(interp, sizeof(Tcl_Token*)*numHandlers);
2794 matchClauses = (Tcl_Obj **)TclStackAlloc(interp, sizeof(Tcl_Obj *) * numHandlers);
2795 memset(matchClauses, 0, sizeof(Tcl_Obj *) * numHandlers);
2796 matchCodes = (int *)TclStackAlloc(interp, sizeof(int) * numHandlers);
2797 resultVarIndices = (int *)TclStackAlloc(interp, sizeof(int) * numHandlers);
2798 optionVarIndices = (int *)TclStackAlloc(interp, sizeof(int) * numHandlers);
2799
2800 for (i=0 ; i<numHandlers ; i++) {
2801 Tcl_Obj *tmpObj, **objv;
2802 int objc;
2803
2804 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2805 goto failedToCompile;
2806 }
2807 if (tokenPtr[1].size == 4
2808 && !strncmp(tokenPtr[1].start, "trap", 4)) {
2809 /*
2810 * Parse the list of errorCode words to match against.
2811 */
2812
2813 matchCodes[i] = TCL_ERROR;
2814 tokenPtr = TokenAfter(tokenPtr);
2815 TclNewObj(tmpObj);
2816 Tcl_IncrRefCount(tmpObj);
2817 if (!TclWordKnownAtCompileTime(tokenPtr, tmpObj)
2818 || TclListObjLength(NULL, tmpObj, &objc) != TCL_OK
2819 || (objc == 0)) {
2820 TclDecrRefCount(tmpObj);
2821 goto failedToCompile;
2822 }
2823 Tcl_ListObjReplace(NULL, tmpObj, 0, 0, 0, NULL);
2824 matchClauses[i] = tmpObj;
2825 } else if (tokenPtr[1].size == 2
2826 && !strncmp(tokenPtr[1].start, "on", 2)) {
2827 int code;
2828
2829 /*
2830 * Parse the result code to look for.
2831 */
2832
2833 tokenPtr = TokenAfter(tokenPtr);
2834 TclNewObj(tmpObj);
2835 Tcl_IncrRefCount(tmpObj);
2836 if (!TclWordKnownAtCompileTime(tokenPtr, tmpObj)) {
2837 TclDecrRefCount(tmpObj);
2838 goto failedToCompile;
2839 }
2840 if (TCL_ERROR == TclGetCompletionCodeFromObj(NULL, tmpObj, &code)) {
2841 TclDecrRefCount(tmpObj);
2842 goto failedToCompile;
2843 }
2844 matchCodes[i] = code;
2845 TclDecrRefCount(tmpObj);
2846 } else {
2847 goto failedToCompile;
2848 }
2849
2850 /*
2851 * Parse the variable binding.
2852 */
2853
2854 tokenPtr = TokenAfter(tokenPtr);
2855 TclNewObj(tmpObj);
2856 Tcl_IncrRefCount(tmpObj);
2857 if (!TclWordKnownAtCompileTime(tokenPtr, tmpObj)) {
2858 TclDecrRefCount(tmpObj);
2859 goto failedToCompile;
2860 }
2861 if (TclListObjGetElements(NULL, tmpObj, &objc, &objv) != TCL_OK
2862 || (objc > 2)) {
2863 TclDecrRefCount(tmpObj);
2864 goto failedToCompile;
2865 }
2866 if (objc > 0) {
2867 int len;
2868 const char *varname = Tcl_GetStringFromObj(objv[0], &len);
2869
2870 resultVarIndices[i] = LocalScalar(varname, len, envPtr);
2871 if (resultVarIndices[i] < 0) {
2872 TclDecrRefCount(tmpObj);
2873 goto failedToCompile;
2874 }
2875 } else {
2876 resultVarIndices[i] = -1;
2877 }
2878 if (objc == 2) {
2879 int len;
2880 const char *varname = Tcl_GetStringFromObj(objv[1], &len);
2881
2882 optionVarIndices[i] = LocalScalar(varname, len, envPtr);
2883 if (optionVarIndices[i] < 0) {
2884 TclDecrRefCount(tmpObj);
2885 goto failedToCompile;
2886 }
2887 } else {
2888 optionVarIndices[i] = -1;
2889 }
2890 TclDecrRefCount(tmpObj);
2891
2892 /*
2893 * Extract the body for this handler.
2894 */
2895
2896 tokenPtr = TokenAfter(tokenPtr);
2897 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2898 goto failedToCompile;
2899 }
2900 if (tokenPtr[1].size == 1 && tokenPtr[1].start[0] == '-') {
2901 handlerTokens[i] = NULL;
2902 } else {
2903 handlerTokens[i] = tokenPtr;
2904 }
2905
2906 tokenPtr = TokenAfter(tokenPtr);
2907 }
2908
2909 if (handlerTokens[numHandlers-1] == NULL) {
2910 goto failedToCompile;
2911 }
2912 }
2913
2914 /*
2915 * Parse the finally clause
2916 */
2917
2918 if (numWords == 0) {
2919 finallyToken = NULL;
2920 } else if (numWords == 2) {
2921 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD || tokenPtr[1].size != 7
2922 || strncmp(tokenPtr[1].start, "finally", 7)) {
2923 goto failedToCompile;
2924 }
2925 finallyToken = TokenAfter(tokenPtr);
2926 if (finallyToken->type != TCL_TOKEN_SIMPLE_WORD) {
2927 goto failedToCompile;
2928 }
2929 } else {
2930 goto failedToCompile;
2931 }
2932
2933 /*
2934 * Issue the bytecode.
2935 */
2936
2937 if (!finallyToken) {
2938 result = IssueTryClausesInstructions(interp, envPtr, bodyToken,
2939 numHandlers, matchCodes, matchClauses, resultVarIndices,
2940 optionVarIndices, handlerTokens);
2941 } else if (numHandlers == 0) {
2942 result = IssueTryFinallyInstructions(interp, envPtr, bodyToken,
2943 finallyToken);
2944 } else {
2945 result = IssueTryClausesFinallyInstructions(interp, envPtr, bodyToken,
2946 numHandlers, matchCodes, matchClauses, resultVarIndices,
2947 optionVarIndices, handlerTokens, finallyToken);
2948 }
2949
2950 /*
2951 * Delete any temporary state and finish off.
2952 */
2953
2954 failedToCompile:
2955 if (numHandlers > 0) {
2956 for (i=0 ; i<numHandlers ; i++) {
2957 if (matchClauses[i]) {
2958 TclDecrRefCount(matchClauses[i]);
2959 }
2960 }
2961 TclStackFree(interp, optionVarIndices);
2962 TclStackFree(interp, resultVarIndices);
2963 TclStackFree(interp, matchCodes);
2964 TclStackFree(interp, matchClauses);
2965 TclStackFree(interp, handlerTokens);
2966 }
2967 return result;
2968 }
2969
2970 /*
2971 *----------------------------------------------------------------------
2972 *
2973 * IssueTryClausesInstructions, IssueTryClausesFinallyInstructions,
2974 * IssueTryFinallyInstructions --
2975 *
2976 * The code generators for [try]. Split from the parsing engine for
2977 * reasons of developer sanity, and also split between no-finally,
2978 * just-finally and with-finally cases because so many of the details of
2979 * generation vary between the three.
2980 *
2981 * The macros below make the instruction issuing easier to follow.
2982 *
2983 *----------------------------------------------------------------------
2984 */
2985
2986 static int
2987 IssueTryClausesInstructions(
2988 Tcl_Interp *interp,
2989 CompileEnv *envPtr,
2990 Tcl_Token *bodyToken,
2991 int numHandlers,
2992 int *matchCodes,
2993 Tcl_Obj **matchClauses,
2994 int *resultVars,
2995 int *optionVars,
2996 Tcl_Token **handlerTokens)
2997 {
2998 DefineLineInformation; /* TIP #280 */
2999 int range, resultVar, optionsVar;
3000 int i, j, len, forwardsNeedFixing = 0, trapZero = 0, afterBody = 0;
3001 int *addrsToFix, *forwardsToFix, notCodeJumpSource, notECJumpSource;
3002 int *noError;
3003 char buf[TCL_INTEGER_SPACE];
3004
3005 resultVar = AnonymousLocal(envPtr);
3006 optionsVar = AnonymousLocal(envPtr);
3007 if (resultVar < 0 || optionsVar < 0) {
3008 return TCL_ERROR;
3009 }
3010
3011 /*
3012 * Check if we're supposed to trap a normal TCL_OK completion of the body.
3013 * If not, we can handle that case much more efficiently.
3014 */
3015
3016 for (i=0 ; i<numHandlers ; i++) {
3017 if (matchCodes[i] == 0) {
3018 trapZero = 1;
3019 break;
3020 }
3021 }
3022
3023 /*
3024 * Compile the body, trapping any error in it so that we can trap on it
3025 * and/or run a finally clause. Note that there must be at least one
3026 * on/trap clause; when none is present, this whole function is not called
3027 * (and it's never called when there's a finally clause).
3028 */
3029
3030 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
3031 OP4( BEGIN_CATCH4, range);
3032 ExceptionRangeStarts(envPtr, range);
3033 BODY( bodyToken, 1);
3034 ExceptionRangeEnds(envPtr, range);
3035 if (!trapZero) {
3036 OP( END_CATCH);
3037 JUMP4( JUMP, afterBody);
3038 TclAdjustStackDepth(-1, envPtr);
3039 } else {
3040 PUSH( "0");
3041 OP4( REVERSE, 2);
3042 OP1( JUMP1, 4);
3043 TclAdjustStackDepth(-2, envPtr);
3044 }
3045 ExceptionRangeTarget(envPtr, range, catchOffset);
3046 OP( PUSH_RETURN_CODE);
3047 OP( PUSH_RESULT);
3048 OP( PUSH_RETURN_OPTIONS);
3049 OP( END_CATCH);
3050 STORE( optionsVar);
3051 OP( POP);
3052 STORE( resultVar);
3053 OP( POP);
3054
3055 /*
3056 * Now we handle all the registered 'on' and 'trap' handlers in order.
3057 * For us to be here, there must be at least one handler.
3058 *
3059 * Slight overallocation, but reduces size of this function.
3060 */
3061
3062 addrsToFix = (int *)TclStackAlloc(interp, sizeof(int)*numHandlers);
3063 forwardsToFix = (int *)TclStackAlloc(interp, sizeof(int)*numHandlers);
3064 noError = (int *)TclStackAlloc(interp, sizeof(int)*numHandlers);
3065
3066 for (i=0 ; i<numHandlers ; i++) {
3067 noError[i] = -1;
3068 snprintf(buf, sizeof(buf), "%d", matchCodes[i]);
3069 OP( DUP);
3070 PushLiteral(envPtr, buf, strlen(buf));
3071 OP( EQ);
3072 JUMP4( JUMP_FALSE, notCodeJumpSource);
3073 if (matchClauses[i]) {
3074 const char *p;
3075 TclListObjLength(NULL, matchClauses[i], &len);
3076
3077 /*
3078 * Match the errorcode according to try/trap rules.
3079 */
3080
3081 LOAD( optionsVar);
3082 PUSH( "-errorcode");
3083 OP4( DICT_GET, 1);
3084 TclAdjustStackDepth(-1, envPtr);
3085 OP44( LIST_RANGE_IMM, 0, len-1);
3086 p = Tcl_GetStringFromObj(matchClauses[i], &len);
3087 PushLiteral(envPtr, p, len);
3088 OP( STR_EQ);
3089 JUMP4( JUMP_FALSE, notECJumpSource);
3090 } else {
3091 notECJumpSource = -1;
3092 }
3093 OP( POP);
3094
3095 /*
3096 * There is no finally clause, so we can avoid wrapping a catch
3097 * context around the handler. That simplifies what instructions need
3098 * to be issued a lot since we can let errors just fall through.
3099 */
3100
3101 if (resultVars[i] >= 0) {
3102 LOAD( resultVar);
3103 STORE( resultVars[i]);
3104 OP( POP);
3105 if (optionVars[i] >= 0) {
3106 LOAD( optionsVar);
3107 STORE( optionVars[i]);
3108 OP( POP);
3109 }
3110 }
3111 if (!handlerTokens[i]) {
3112 forwardsNeedFixing = 1;
3113 JUMP4( JUMP, forwardsToFix[i]);
3114 TclAdjustStackDepth(1, envPtr);
3115 } else {
3116 int dontChangeOptions;
3117
3118 forwardsToFix[i] = -1;
3119 if (forwardsNeedFixing) {
3120 forwardsNeedFixing = 0;
3121 for (j=0 ; j<i ; j++) {
3122 if (forwardsToFix[j] == -1) {
3123 continue;
3124 }
3125 FIXJUMP4(forwardsToFix[j]);
3126 forwardsToFix[j] = -1;
3127 }
3128 }
3129 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
3130 OP4( BEGIN_CATCH4, range);
3131 ExceptionRangeStarts(envPtr, range);
3132 BODY( handlerTokens[i], 5+i*4);
3133 ExceptionRangeEnds(envPtr, range);
3134 OP( END_CATCH);
3135 JUMP4( JUMP, noError[i]);
3136 ExceptionRangeTarget(envPtr, range, catchOffset);
3137 TclAdjustStackDepth(-1, envPtr);
3138 OP( PUSH_RESULT);
3139 OP( PUSH_RETURN_OPTIONS);
3140 OP( PUSH_RETURN_CODE);
3141 OP( END_CATCH);
3142 PUSH( "1");
3143 OP( EQ);
3144 JUMP1( JUMP_FALSE, dontChangeOptions);
3145 LOAD( optionsVar);
3146 OP4( REVERSE, 2);
3147 STORE( optionsVar);
3148 OP( POP);
3149 PUSH( "-during");
3150 OP4( REVERSE, 2);
3151 OP44( DICT_SET, 1, optionsVar);
3152 TclAdjustStackDepth(-1, envPtr);
3153 FIXJUMP1( dontChangeOptions);
3154 OP4( REVERSE, 2);
3155 INVOKE( RETURN_STK);
3156 }
3157
3158 JUMP4( JUMP, addrsToFix[i]);
3159 if (matchClauses[i]) {
3160 FIXJUMP4( notECJumpSource);
3161 }
3162 FIXJUMP4( notCodeJumpSource);
3163 }
3164
3165 /*
3166 * Drop the result code since it didn't match any clause, and reissue the
3167 * exception. Note also that INST_RETURN_STK can proceed to the next
3168 * instruction.
3169 */
3170
3171 OP( POP);
3172 LOAD( optionsVar);
3173 LOAD( resultVar);
3174 INVOKE( RETURN_STK);
3175
3176 /*
3177 * Fix all the jumps from taken clauses to here (which is the end of the
3178 * [try]).
3179 */
3180
3181 if (!trapZero) {
3182 FIXJUMP4(afterBody);
3183 }
3184 for (i=0 ; i<numHandlers ; i++) {
3185 FIXJUMP4(addrsToFix[i]);
3186 if (noError[i] != -1) {
3187 FIXJUMP4(noError[i]);
3188 }
3189 }
3190 TclStackFree(interp, noError);
3191 TclStackFree(interp, forwardsToFix);
3192 TclStackFree(interp, addrsToFix);
3193 return TCL_OK;
3194 }
3195
3196 static int
3197 IssueTryClausesFinallyInstructions(
3198 Tcl_Interp *interp,
3199 CompileEnv *envPtr,
3200 Tcl_Token *bodyToken,
3201 int numHandlers,
3202 int *matchCodes,
3203 Tcl_Obj **matchClauses,
3204 int *resultVars,
3205 int *optionVars,
3206 Tcl_Token **handlerTokens,
3207 Tcl_Token *finallyToken) /* Not NULL */
3208 {
3209 DefineLineInformation; /* TIP #280 */
3210 int range, resultVar, optionsVar, i, j, len, forwardsNeedFixing = 0;
3211 int trapZero = 0, afterBody = 0, finalOK, finalError, noFinalError;
3212 int *addrsToFix, *forwardsToFix, notCodeJumpSource, notECJumpSource;
3213 char buf[TCL_INTEGER_SPACE];
3214
3215 resultVar = AnonymousLocal(envPtr);
3216 optionsVar = AnonymousLocal(envPtr);
3217 if (resultVar < 0 || optionsVar < 0) {
3218 return TCL_ERROR;
3219 }
3220
3221 /*
3222 * Check if we're supposed to trap a normal TCL_OK completion of the body.
3223 * If not, we can handle that case much more efficiently.
3224 */
3225
3226 for (i=0 ; i<numHandlers ; i++) {
3227 if (matchCodes[i] == 0) {
3228 trapZero = 1;
3229 break;
3230 }
3231 }
3232
3233 /*
3234 * Compile the body, trapping any error in it so that we can trap on it
3235 * (if any trap matches) and run a finally clause.
3236 */
3237
3238 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
3239 OP4( BEGIN_CATCH4, range);
3240 ExceptionRangeStarts(envPtr, range);
3241 BODY( bodyToken, 1);
3242 ExceptionRangeEnds(envPtr, range);
3243 if (!trapZero) {
3244 OP( END_CATCH);
3245 STORE( resultVar);
3246 OP( POP);
3247 PUSH( "-level 0 -code 0");
3248 STORE( optionsVar);
3249 OP( POP);
3250 JUMP4( JUMP, afterBody);
3251 } else {
3252 PUSH( "0");
3253 OP4( REVERSE, 2);
3254 OP1( JUMP1, 4);
3255 TclAdjustStackDepth(-2, envPtr);
3256 }
3257 ExceptionRangeTarget(envPtr, range, catchOffset);
3258 OP( PUSH_RETURN_CODE);
3259 OP( PUSH_RESULT);
3260 OP( PUSH_RETURN_OPTIONS);
3261 OP( END_CATCH);
3262 STORE( optionsVar);
3263 OP( POP);
3264 STORE( resultVar);
3265 OP( POP);
3266
3267 /*
3268 * Now we handle all the registered 'on' and 'trap' handlers in order.
3269 *
3270 * Slight overallocation, but reduces size of this function.
3271 */
3272
3273 addrsToFix = (int *)TclStackAlloc(interp, sizeof(int)*numHandlers);
3274 forwardsToFix = (int *)TclStackAlloc(interp, sizeof(int)*numHandlers);
3275
3276 for (i=0 ; i<numHandlers ; i++) {
3277 int noTrapError, trapError;
3278 const char *p;
3279
3280 snprintf(buf, sizeof(buf), "%d", matchCodes[i]);
3281 OP( DUP);
3282 PushLiteral(envPtr, buf, strlen(buf));
3283 OP( EQ);
3284 JUMP4( JUMP_FALSE, notCodeJumpSource);
3285 if (matchClauses[i]) {
3286 TclListObjLength(NULL, matchClauses[i], &len);
3287
3288 /*
3289 * Match the errorcode according to try/trap rules.
3290 */
3291
3292 LOAD( optionsVar);
3293 PUSH( "-errorcode");
3294 OP4( DICT_GET, 1);
3295 TclAdjustStackDepth(-1, envPtr);
3296 OP44( LIST_RANGE_IMM, 0, len-1);
3297 p = Tcl_GetStringFromObj(matchClauses[i], &len);
3298 PushLiteral(envPtr, p, len);
3299 OP( STR_EQ);
3300 JUMP4( JUMP_FALSE, notECJumpSource);
3301 } else {
3302 notECJumpSource = -1;
3303 }
3304 OP( POP);
3305
3306 /*
3307 * There is a finally clause, so we need a fairly complex sequence of
3308 * instructions to deal with an on/trap handler because we must call
3309 * the finally handler *and* we need to substitute the result from a
3310 * failed trap for the result from the main script.
3311 */
3312
3313 if (resultVars[i] >= 0 || handlerTokens[i]) {
3314 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
3315 OP4( BEGIN_CATCH4, range);
3316 ExceptionRangeStarts(envPtr, range);
3317 }
3318 if (resultVars[i] >= 0) {
3319 LOAD( resultVar);
3320 STORE( resultVars[i]);
3321 OP( POP);
3322 if (optionVars[i] >= 0) {
3323 LOAD( optionsVar);
3324 STORE( optionVars[i]);
3325 OP( POP);
3326 }
3327
3328 if (!handlerTokens[i]) {
3329 /*
3330 * No handler. Will not be the last handler (that is a
3331 * condition that is checked by the caller). Chain to the next
3332 * one.
3333 */
3334
3335 ExceptionRangeEnds(envPtr, range);
3336 OP( END_CATCH);
3337 forwardsNeedFixing = 1;
3338 JUMP4( JUMP, forwardsToFix[i]);
3339 goto finishTrapCatchHandling;
3340 }
3341 } else if (!handlerTokens[i]) {
3342 /*
3343 * No handler. Will not be the last handler (that condition is
3344 * checked by the caller). Chain to the next one.
3345 */
3346
3347 forwardsNeedFixing = 1;
3348 JUMP4( JUMP, forwardsToFix[i]);
3349 goto endOfThisArm;
3350 }
3351
3352 /*
3353 * Got a handler. Make sure that any pending patch-up actions from
3354 * previous unprocessed handlers are dealt with now that we know where
3355 * they are to jump to.
3356 */
3357
3358 if (forwardsNeedFixing) {
3359 forwardsNeedFixing = 0;
3360 OP1( JUMP1, 7);
3361 for (j=0 ; j<i ; j++) {
3362 if (forwardsToFix[j] == -1) {
3363 continue;
3364 }
3365 FIXJUMP4( forwardsToFix[j]);
3366 forwardsToFix[j] = -1;
3367 }
3368 OP4( BEGIN_CATCH4, range);
3369 }
3370 BODY( handlerTokens[i], 5+i*4);
3371 ExceptionRangeEnds(envPtr, range);
3372 PUSH( "0");
3373 OP( PUSH_RETURN_OPTIONS);
3374 OP4( REVERSE, 3);
3375 OP1( JUMP1, 5);
3376 TclAdjustStackDepth(-3, envPtr);
3377 forwardsToFix[i] = -1;
3378
3379 /*
3380 * Error in handler or setting of variables; replace the stored
3381 * exception with the new one. Note that we only push this if we have
3382 * either a body or some variable setting here. Otherwise this code is
3383 * unreachable.
3384 */
3385
3386 finishTrapCatchHandling:
3387 ExceptionRangeTarget(envPtr, range, catchOffset);
3388 OP( PUSH_RETURN_OPTIONS);
3389 OP( PUSH_RETURN_CODE);
3390 OP( PUSH_RESULT);
3391 OP( END_CATCH);
3392 STORE( resultVar);
3393 OP( POP);
3394 PUSH( "1");
3395 OP( EQ);
3396 JUMP1( JUMP_FALSE, noTrapError);
3397 LOAD( optionsVar);
3398 PUSH( "-during");
3399 OP4( REVERSE, 3);
3400 STORE( optionsVar);
3401 OP( POP);
3402 OP44( DICT_SET, 1, optionsVar);
3403 TclAdjustStackDepth(-1, envPtr);
3404 JUMP1( JUMP, trapError);
3405 FIXJUMP1( noTrapError);
3406 STORE( optionsVar);
3407 FIXJUMP1( trapError);
3408 /* Skip POP at end; can clean up with subsequent POP */
3409 if (i+1 < numHandlers) {
3410 OP( POP);
3411 }
3412
3413 endOfThisArm:
3414 if (i+1 < numHandlers) {
3415 JUMP4( JUMP, addrsToFix[i]);
3416 TclAdjustStackDepth(1, envPtr);
3417 }
3418 if (matchClauses[i]) {
3419 FIXJUMP4( notECJumpSource);
3420 }
3421 FIXJUMP4( notCodeJumpSource);
3422 }
3423
3424 /*
3425 * Drop the result code, and fix all the jumps from taken clauses - which
3426 * drop the result code as their first action - to point straight after
3427 * (i.e., to the start of the finally clause).
3428 */
3429
3430 OP( POP);
3431 for (i=0 ; i<numHandlers-1 ; i++) {
3432 FIXJUMP4( addrsToFix[i]);
3433 }
3434 TclStackFree(interp, forwardsToFix);
3435 TclStackFree(interp, addrsToFix);
3436
3437 /*
3438 * Process the finally clause (at last!) Note that we do not wrap this in
3439 * error handlers because we would just rethrow immediately anyway. Then
3440 * (on normal success) we reissue the exception. Note also that
3441 * INST_RETURN_STK can proceed to the next instruction; that'll be the
3442 * next command (or some inter-command manipulation).
3443 */
3444
3445 if (!trapZero) {
3446 FIXJUMP4( afterBody);
3447 }
3448 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
3449 OP4( BEGIN_CATCH4, range);
3450 ExceptionRangeStarts(envPtr, range);
3451 BODY( finallyToken, 3 + 4*numHandlers);
3452 ExceptionRangeEnds(envPtr, range);
3453 OP( END_CATCH);
3454 OP( POP);
3455 JUMP1( JUMP, finalOK);
3456 ExceptionRangeTarget(envPtr, range, catchOffset);
3457 OP( PUSH_RESULT);
3458 OP( PUSH_RETURN_OPTIONS);
3459 OP( PUSH_RETURN_CODE);
3460 OP( END_CATCH);
3461 PUSH( "1");
3462 OP( EQ);
3463 JUMP1( JUMP_FALSE, noFinalError);
3464 LOAD( optionsVar);
3465 PUSH( "-during");
3466 OP4( REVERSE, 3);
3467 STORE( optionsVar);
3468 OP( POP);
3469 OP44( DICT_SET, 1, optionsVar);
3470 TclAdjustStackDepth(-1, envPtr);
3471 OP( POP);
3472 JUMP1( JUMP, finalError);
3473 TclAdjustStackDepth(1, envPtr);
3474 FIXJUMP1( noFinalError);
3475 STORE( optionsVar);
3476 OP( POP);
3477 FIXJUMP1( finalError);
3478 STORE( resultVar);
3479 OP( POP);
3480 FIXJUMP1( finalOK);
3481 LOAD( optionsVar);
3482 LOAD( resultVar);
3483 INVOKE( RETURN_STK);
3484
3485 return TCL_OK;
3486 }
3487
3488 static int
3489 IssueTryFinallyInstructions(
3490 Tcl_Interp *interp,
3491 CompileEnv *envPtr,
3492 Tcl_Token *bodyToken,
3493 Tcl_Token *finallyToken)
3494 {
3495 DefineLineInformation; /* TIP #280 */
3496 int range, jumpOK, jumpSplice;
3497
3498 /*
3499 * Note that this one is simple enough that we can issue it without
3500 * needing a local variable table, making it a universal compilation.
3501 */
3502
3503 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
3504 OP4( BEGIN_CATCH4, range);
3505 ExceptionRangeStarts(envPtr, range);
3506 BODY( bodyToken, 1);
3507 ExceptionRangeEnds(envPtr, range);
3508 OP1( JUMP1, 3);
3509 TclAdjustStackDepth(-1, envPtr);
3510 ExceptionRangeTarget(envPtr, range, catchOffset);
3511 OP( PUSH_RESULT);
3512 OP( PUSH_RETURN_OPTIONS);
3513 OP( END_CATCH);
3514
3515 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
3516 OP4( BEGIN_CATCH4, range);
3517 ExceptionRangeStarts(envPtr, range);
3518 BODY( finallyToken, 3);
3519 ExceptionRangeEnds(envPtr, range);
3520 OP( END_CATCH);
3521 OP( POP);
3522 JUMP1( JUMP, jumpOK);
3523 ExceptionRangeTarget(envPtr, range, catchOffset);
3524 OP( PUSH_RESULT);
3525 OP( PUSH_RETURN_OPTIONS);
3526 OP( PUSH_RETURN_CODE);
3527 OP( END_CATCH);
3528 PUSH( "1");
3529 OP( EQ);
3530 JUMP1( JUMP_FALSE, jumpSplice);
3531 PUSH( "-during");
3532 OP4( OVER, 3);
3533 OP4( LIST, 2);
3534 OP( LIST_CONCAT);
3535 FIXJUMP1( jumpSplice);
3536 OP4( REVERSE, 4);
3537 OP( POP);
3538 OP( POP);
3539 OP1( JUMP1, 7);
3540 FIXJUMP1( jumpOK);
3541 OP4( REVERSE, 2);
3542 INVOKE( RETURN_STK);
3543 return TCL_OK;
3544 }
3545
3546 /*
3547 *----------------------------------------------------------------------
3548 *
3549 * TclCompileUnsetCmd --
3550 *
3551 * Procedure called to compile the "unset" command.
3552 *
3553 * Results:
3554 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
3555 * evaluation to runtime.
3556 *
3557 * Side effects:
3558 * Instructions are added to envPtr to execute the "unset" command at
3559 * runtime.
3560 *
3561 *----------------------------------------------------------------------
3562 */
3563
3564 int
3565 TclCompileUnsetCmd(
3566 Tcl_Interp *interp, /* Used for error reporting. */
3567 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3568 * created by Tcl_ParseCommand. */
3569 Command *cmdPtr, /* Points to definition of command being
3570 * compiled. */
3571 CompileEnv *envPtr) /* Holds resulting instructions. */
3572 {
3573 DefineLineInformation; /* TIP #280 */
3574 Tcl_Token *varTokenPtr;
3575 int isScalar, localIndex, flags = 1, i, varCount = 0, haveFlags = 0;
3576
3577 /* TODO: Consider support for compiling expanded args. */
3578
3579 /*
3580 * Verify that all words - except the first non-option one - are known at
3581 * compile time so that we can handle them without needing to do a nasty
3582 * push/rotate. [Bug 3970f54c4e]
3583 */
3584
3585 for (i=1,varTokenPtr=parsePtr->tokenPtr ; i<parsePtr->numWords ; i++) {
3586 Tcl_Obj *leadingWord;
3587
3588 TclNewObj(leadingWord);
3589 varTokenPtr = TokenAfter(varTokenPtr);
3590 if (!TclWordKnownAtCompileTime(varTokenPtr, leadingWord)) {
3591 TclDecrRefCount(leadingWord);
3592
3593 /*
3594 * We can tolerate non-trivial substitutions in the first variable
3595 * to be unset. If a '--' or '-nocomplain' was present, anything
3596 * goes in that one place! (All subsequent variable names must be
3597 * constants since we don't want to have to push them all first.)
3598 */
3599
3600 if (varCount == 0) {
3601 if (haveFlags) {
3602 continue;
3603 }
3604
3605 /*
3606 * In fact, we're OK as long as we're the first argument *and*
3607 * we provably don't start with a '-'. If that is true, then
3608 * even if everything else is varying, we still can't be a
3609 * flag. Otherwise we'll spill to runtime to place a limit on
3610 * the trickiness.
3611 */
3612
3613 if (varTokenPtr->type == TCL_TOKEN_WORD
3614 && varTokenPtr[1].type == TCL_TOKEN_TEXT
3615 && varTokenPtr[1].size > 0
3616 && varTokenPtr[1].start[0] != '-') {
3617 continue;
3618 }
3619 }
3620 return TCL_ERROR;
3621 }
3622 if (varCount == 0) {
3623 const char *bytes;
3624 int len;
3625
3626 bytes = Tcl_GetStringFromObj(leadingWord, &len);
3627 if (i == 1 && len == 11 && !strncmp("-nocomplain", bytes, 11)) {
3628 flags = 0;
3629 haveFlags++;
3630 } else if (i == (2 - flags) && len == 2 && !strncmp("--", bytes, 2)) {
3631 haveFlags++;
3632 } else {
3633 varCount++;
3634 }
3635 } else {
3636 varCount++;
3637 }
3638 TclDecrRefCount(leadingWord);
3639 }
3640
3641 /*
3642 * Issue instructions to unset each of the named variables.
3643 */
3644
3645 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
3646 for (i=0; i<haveFlags;i++) {
3647 varTokenPtr = TokenAfter(varTokenPtr);
3648 }
3649 for (i=1+haveFlags ; i<parsePtr->numWords ; i++) {
3650 /*
3651 * Decide if we can use a frame slot for the var/array name or if we
3652 * need to emit code to compute and push the name at runtime. We use a
3653 * frame slot (entry in the array of local vars) if we are compiling a
3654 * procedure body and if the name is simple text that does not include
3655 * namespace qualifiers.
3656 */
3657
3658 PushVarNameWord(interp, varTokenPtr, envPtr, 0,
3659 &localIndex, &isScalar, i);
3660
3661 /*
3662 * Emit instructions to unset the variable.
3663 */
3664
3665 if (isScalar) {
3666 if (localIndex < 0) {
3667 OP1( UNSET_STK, flags);
3668 } else {
3669 OP14( UNSET_SCALAR, flags, localIndex);
3670 }
3671 } else {
3672 if (localIndex < 0) {
3673 OP1( UNSET_ARRAY_STK, flags);
3674 } else {
3675 OP14( UNSET_ARRAY, flags, localIndex);
3676 }
3677 }
3678
3679 varTokenPtr = TokenAfter(varTokenPtr);
3680 }
3681 PUSH("");
3682 return TCL_OK;
3683 }
3684
3685 /*
3686 *----------------------------------------------------------------------
3687 *
3688 * TclCompileWhileCmd --
3689 *
3690 * Procedure called to compile the "while" command.
3691 *
3692 * Results:
3693 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
3694 * evaluation to runtime.
3695 *
3696 * Side effects:
3697 * Instructions are added to envPtr to execute the "while" command at
3698 * runtime.
3699 *
3700 *----------------------------------------------------------------------
3701 */
3702
3703 int
3704 TclCompileWhileCmd(
3705 Tcl_Interp *interp, /* Used for error reporting. */
3706 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3707 * created by Tcl_ParseCommand. */
3708 Command *cmdPtr, /* Points to definition of command being
3709 * compiled. */
3710 CompileEnv *envPtr) /* Holds resulting instructions. */
3711 {
3712 DefineLineInformation; /* TIP #280 */
3713 Tcl_Token *testTokenPtr, *bodyTokenPtr;
3714 JumpFixup jumpEvalCondFixup;
3715 int testCodeOffset, bodyCodeOffset, jumpDist, range, code, boolVal;
3716 int loopMayEnd = 1; /* This is set to 0 if it is recognized as an
3717 * infinite loop. */
3718 Tcl_Obj *boolObj;
3719
3720 if (parsePtr->numWords != 3) {
3721 return TCL_ERROR;
3722 }
3723
3724 /*
3725 * If the test expression requires substitutions, don't compile the while
3726 * command inline. E.g., the expression might cause the loop to never
3727 * execute or execute forever, as in "while "$x < 5" {}".
3728 *
3729 * Bail out also if the body expression requires substitutions in order to
3730 * insure correct behaviour [Bug 219166]
3731 */
3732
3733 testTokenPtr = TokenAfter(parsePtr->tokenPtr);
3734 bodyTokenPtr = TokenAfter(testTokenPtr);
3735
3736 if ((testTokenPtr->type != TCL_TOKEN_SIMPLE_WORD)
3737 || (bodyTokenPtr->type != TCL_TOKEN_SIMPLE_WORD)) {
3738 return TCL_ERROR;
3739 }
3740
3741 /*
3742 * Find out if the condition is a constant.
3743 */
3744
3745 boolObj = Tcl_NewStringObj(testTokenPtr[1].start, testTokenPtr[1].size);
3746 Tcl_IncrRefCount(boolObj);
3747 code = Tcl_GetBooleanFromObj(NULL, boolObj, &boolVal);
3748 TclDecrRefCount(boolObj);
3749 if (code == TCL_OK) {
3750 if (boolVal) {
3751 /*
3752 * It is an infinite loop; flag it so that we generate a more
3753 * efficient body.
3754 */
3755
3756 loopMayEnd = 0;
3757 } else {
3758 /*
3759 * This is an empty loop: "while 0 {...}" or such. Compile no
3760 * bytecodes.
3761 */
3762
3763 goto pushResult;
3764 }
3765 }
3766
3767 /*
3768 * Create a ExceptionRange record for the loop body. This is used to
3769 * implement break and continue.
3770 */
3771
3772 range = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
3773
3774 /*
3775 * Jump to the evaluation of the condition. This code uses the "loop
3776 * rotation" optimisation (which eliminates one branch from the loop).
3777 * "while cond body" produces then:
3778 * goto A
3779 * B: body : bodyCodeOffset
3780 * A: cond -> result : testCodeOffset, continueOffset
3781 * if (result) goto B
3782 *
3783 * The infinite loop "while 1 body" produces:
3784 * B: body : all three offsets here
3785 * goto B
3786 */
3787
3788 if (loopMayEnd) {
3789 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP,
3790 &jumpEvalCondFixup);
3791 testCodeOffset = 0; /* Avoid compiler warning. */
3792 } else {
3793 /*
3794 * Make sure that the first command in the body is preceded by an
3795 * INST_START_CMD, and hence counted properly. [Bug 1752146]
3796 */
3797
3798 envPtr->atCmdStart &= ~1;
3799 testCodeOffset = CurrentOffset(envPtr);
3800 }
3801
3802 /*
3803 * Compile the loop body.
3804 */
3805
3806 bodyCodeOffset = ExceptionRangeStarts(envPtr, range);
3807 if (!loopMayEnd) {
3808 envPtr->exceptArrayPtr[range].continueOffset = testCodeOffset;
3809 envPtr->exceptArrayPtr[range].codeOffset = bodyCodeOffset;
3810 }
3811 BODY(bodyTokenPtr, 2);
3812 ExceptionRangeEnds(envPtr, range);
3813 OP( POP);
3814
3815 /*
3816 * Compile the test expression then emit the conditional jump that
3817 * terminates the while. We already know it's a simple word.
3818 */
3819
3820 if (loopMayEnd) {
3821 testCodeOffset = CurrentOffset(envPtr);
3822 jumpDist = testCodeOffset - jumpEvalCondFixup.codeOffset;
3823 if (TclFixupForwardJump(envPtr, &jumpEvalCondFixup, jumpDist, 127)) {
3824 bodyCodeOffset += 3;
3825 testCodeOffset += 3;
3826 }
3827 SetLineInformation(1);
3828 TclCompileExprWords(interp, testTokenPtr, 1, envPtr);
3829
3830 jumpDist = CurrentOffset(envPtr) - bodyCodeOffset;
3831 if (jumpDist > 127) {
3832 TclEmitInstInt4(INST_JUMP_TRUE4, -jumpDist, envPtr);
3833 } else {
3834 TclEmitInstInt1(INST_JUMP_TRUE1, -jumpDist, envPtr);
3835 }
3836 } else {
3837 jumpDist = CurrentOffset(envPtr) - bodyCodeOffset;
3838 if (jumpDist > 127) {
3839 TclEmitInstInt4(INST_JUMP4, -jumpDist, envPtr);
3840 } else {
3841 TclEmitInstInt1(INST_JUMP1, -jumpDist, envPtr);
3842 }
3843 }
3844
3845 /*
3846 * Set the loop's body, continue and break offsets.
3847 */
3848
3849 envPtr->exceptArrayPtr[range].continueOffset = testCodeOffset;
3850 envPtr->exceptArrayPtr[range].codeOffset = bodyCodeOffset;
3851 ExceptionRangeTarget(envPtr, range, breakOffset);
3852 TclFinalizeLoopExceptionRange(envPtr, range);
3853
3854 /*
3855 * The while command's result is an empty string.
3856 */
3857
3858 pushResult:
3859 PUSH("");
3860 return TCL_OK;
3861 }
3862
3863 /*
3864 *----------------------------------------------------------------------
3865 *
3866 * TclCompileYieldCmd --
3867 *
3868 * Procedure called to compile the "yield" command.
3869 *
3870 * Results:
3871 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
3872 * evaluation to runtime.
3873 *
3874 * Side effects:
3875 * Instructions are added to envPtr to execute the "yield" command at
3876 * runtime.
3877 *
3878 *----------------------------------------------------------------------
3879 */
3880
3881 int
3882 TclCompileYieldCmd(
3883 Tcl_Interp *interp, /* Used for error reporting. */
3884 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3885 * created by Tcl_ParseCommand. */
3886 Command *cmdPtr, /* Points to definition of command being
3887 * compiled. */
3888 CompileEnv *envPtr) /* Holds resulting instructions. */
3889 {
3890 if (parsePtr->numWords < 1 || parsePtr->numWords > 2) {
3891 return TCL_ERROR;
3892 }
3893
3894 if (parsePtr->numWords == 1) {
3895 PUSH("");
3896 } else {
3897 DefineLineInformation; /* TIP #280 */
3898 Tcl_Token *valueTokenPtr = TokenAfter(parsePtr->tokenPtr);
3899
3900 CompileWord(envPtr, valueTokenPtr, interp, 1);
3901 }
3902 OP( YIELD);
3903 return TCL_OK;
3904 }
3905
3906 /*
3907 *----------------------------------------------------------------------
3908 *
3909 * TclCompileYieldToCmd --
3910 *
3911 * Procedure called to compile the "yieldto" command.
3912 *
3913 * Results:
3914 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
3915 * evaluation to runtime.
3916 *
3917 * Side effects:
3918 * Instructions are added to envPtr to execute the "yieldto" command at
3919 * runtime.
3920 *
3921 *----------------------------------------------------------------------
3922 */
3923
3924 int
3925 TclCompileYieldToCmd(
3926 Tcl_Interp *interp, /* Used for error reporting. */
3927 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3928 * created by Tcl_ParseCommand. */
3929 Command *cmdPtr, /* Points to definition of command being
3930 * compiled. */
3931 CompileEnv *envPtr) /* Holds resulting instructions. */
3932 {
3933 DefineLineInformation; /* TIP #280 */
3934 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
3935 int i;
3936
3937 if (parsePtr->numWords < 2) {
3938 return TCL_ERROR;
3939 }
3940
3941 OP( NS_CURRENT);
3942 for (i = 1 ; i < parsePtr->numWords ; i++) {
3943 CompileWord(envPtr, tokenPtr, interp, i);
3944 tokenPtr = TokenAfter(tokenPtr);
3945 }
3946 OP4( LIST, i);
3947 OP( YIELD_TO_INVOKE);
3948 return TCL_OK;
3949 }
3950
3951 /*
3952 *----------------------------------------------------------------------
3953 *
3954 * CompileUnaryOpCmd --
3955 *
3956 * Utility routine to compile the unary operator commands.
3957 *
3958 * Results:
3959 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
3960 * evaluation to runtime.
3961 *
3962 * Side effects:
3963 * Instructions are added to envPtr to execute the compiled command at
3964 * runtime.
3965 *
3966 *----------------------------------------------------------------------
3967 */
3968
3969 static int
3970 CompileUnaryOpCmd(
3971 Tcl_Interp *interp,
3972 Tcl_Parse *parsePtr,
3973 int instruction,
3974 CompileEnv *envPtr)
3975 {
3976 DefineLineInformation; /* TIP #280 */
3977 Tcl_Token *tokenPtr;
3978
3979 if (parsePtr->numWords != 2) {
3980 return TCL_ERROR;
3981 }
3982 tokenPtr = TokenAfter(parsePtr->tokenPtr);
3983 CompileWord(envPtr, tokenPtr, interp, 1);
3984 TclEmitOpcode(instruction, envPtr);
3985 return TCL_OK;
3986 }
3987
3988 /*
3989 *----------------------------------------------------------------------
3990 *
3991 * CompileAssociativeBinaryOpCmd --
3992 *
3993 * Utility routine to compile the binary operator commands that accept an
3994 * arbitrary number of arguments, and that are associative operations.
3995 * Because of the associativity, we may combine operations from right to
3996 * left, saving us any effort of re-ordering the arguments on the stack
3997 * after substitutions are completed.
3998 *
3999 * Results:
4000 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
4001 * evaluation to runtime.
4002 *
4003 * Side effects:
4004 * Instructions are added to envPtr to execute the compiled command at
4005 * runtime.
4006 *
4007 *----------------------------------------------------------------------
4008 */
4009
4010 static int
4011 CompileAssociativeBinaryOpCmd(
4012 Tcl_Interp *interp,
4013 Tcl_Parse *parsePtr,
4014 const char *identity,
4015 int instruction,
4016 CompileEnv *envPtr)
4017 {
4018 DefineLineInformation; /* TIP #280 */
4019 Tcl_Token *tokenPtr = parsePtr->tokenPtr;
4020 int words;
4021
4022 /* TODO: Consider support for compiling expanded args. */
4023 for (words=1 ; words<parsePtr->numWords ; words++) {
4024 tokenPtr = TokenAfter(tokenPtr);
4025 CompileWord(envPtr, tokenPtr, interp, words);
4026 }
4027 if (parsePtr->numWords <= 2) {
4028 PushLiteral(envPtr, identity, -1);
4029 words++;
4030 }
4031 if (words > 3) {
4032 /*
4033 * Reverse order of arguments to get precise agreement with [expr] in
4034 * calculations, including roundoff errors.
4035 */
4036
4037 OP4( REVERSE, words-1);
4038 }
4039 while (--words > 1) {
4040 TclEmitOpcode(instruction, envPtr);
4041 }
4042 return TCL_OK;
4043 }
4044
4045 /*
4046 *----------------------------------------------------------------------
4047 *
4048 * CompileStrictlyBinaryOpCmd --
4049 *
4050 * Utility routine to compile the binary operator commands, that strictly
4051 * accept exactly two arguments.
4052 *
4053 * Results:
4054 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
4055 * evaluation to runtime.
4056 *
4057 * Side effects:
4058 * Instructions are added to envPtr to execute the compiled command at
4059 * runtime.
4060 *
4061 *----------------------------------------------------------------------
4062 */
4063
4064 static int
4065 CompileStrictlyBinaryOpCmd(
4066 Tcl_Interp *interp,
4067 Tcl_Parse *parsePtr,
4068 int instruction,
4069 CompileEnv *envPtr)
4070 {
4071 if (parsePtr->numWords != 3) {
4072 return TCL_ERROR;
4073 }
4074 return CompileAssociativeBinaryOpCmd(interp, parsePtr,
4075 NULL, instruction, envPtr);
4076 }
4077
4078 /*
4079 *----------------------------------------------------------------------
4080 *
4081 * CompileComparisonOpCmd --
4082 *
4083 * Utility routine to compile the n-ary comparison operator commands.
4084 *
4085 * Results:
4086 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
4087 * evaluation to runtime.
4088 *
4089 * Side effects:
4090 * Instructions are added to envPtr to execute the compiled command at
4091 * runtime.
4092 *
4093 *----------------------------------------------------------------------
4094 */
4095
4096 static int
4097 CompileComparisonOpCmd(
4098 Tcl_Interp *interp,
4099 Tcl_Parse *parsePtr,
4100 int instruction,
4101 CompileEnv *envPtr)
4102 {
4103 DefineLineInformation; /* TIP #280 */
4104 Tcl_Token *tokenPtr;
4105
4106 /* TODO: Consider support for compiling expanded args. */
4107 if (parsePtr->numWords < 3) {
4108 PUSH("1");
4109 } else if (parsePtr->numWords == 3) {
4110 tokenPtr = TokenAfter(parsePtr->tokenPtr);
4111 CompileWord(envPtr, tokenPtr, interp, 1);
4112 tokenPtr = TokenAfter(tokenPtr);
4113 CompileWord(envPtr, tokenPtr, interp, 2);
4114 TclEmitOpcode(instruction, envPtr);
4115 } else if (envPtr->procPtr == NULL) {
4116 /*
4117 * No local variable space!
4118 */
4119
4120 return TCL_ERROR;
4121 } else {
4122 int tmpIndex = AnonymousLocal(envPtr);
4123 int words;
4124
4125 tokenPtr = TokenAfter(parsePtr->tokenPtr);
4126 CompileWord(envPtr, tokenPtr, interp, 1);
4127 tokenPtr = TokenAfter(tokenPtr);
4128 CompileWord(envPtr, tokenPtr, interp, 2);
4129 STORE(tmpIndex);
4130 TclEmitOpcode(instruction, envPtr);
4131 for (words=3 ; words<parsePtr->numWords ;) {
4132 LOAD(tmpIndex);
4133 tokenPtr = TokenAfter(tokenPtr);
4134 CompileWord(envPtr, tokenPtr, interp, words);
4135 if (++words < parsePtr->numWords) {
4136 STORE(tmpIndex);
4137 }
4138 TclEmitOpcode(instruction, envPtr);
4139 }
4140 for (; words>3 ; words--) {
4141 OP( BITAND);
4142 }
4143
4144 /*
4145 * Drop the value from the temp variable; retaining that reference
4146 * might be expensive elsewhere.
4147 */
4148
4149 OP14( UNSET_SCALAR, 0, tmpIndex);
4150 }
4151 return TCL_OK;
4152 }
4153
4154 /*
4155 *----------------------------------------------------------------------
4156 *
4157 * TclCompile*OpCmd --
4158 *
4159 * Procedures called to compile the corresponding "::tcl::mathop::*"
4160 * commands. These are all wrappers around the utility operator command
4161 * compiler functions, except for the compilers for subtraction and
4162 * division, which are special.
4163 *
4164 * Results:
4165 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
4166 * evaluation to runtime.
4167 *
4168 * Side effects:
4169 * Instructions are added to envPtr to execute the compiled command at
4170 * runtime.
4171 *
4172 *----------------------------------------------------------------------
4173 */
4174
4175 int
4176 TclCompileInvertOpCmd(
4177 Tcl_Interp *interp,
4178 Tcl_Parse *parsePtr,
4179 Command *cmdPtr, /* Points to definition of command being
4180 * compiled. */
4181 CompileEnv *envPtr)
4182 {
4183 return CompileUnaryOpCmd(interp, parsePtr, INST_BITNOT, envPtr);
4184 }
4185
4186 int
4187 TclCompileNotOpCmd(
4188 Tcl_Interp *interp,
4189 Tcl_Parse *parsePtr,
4190 Command *cmdPtr, /* Points to definition of command being
4191 * compiled. */
4192 CompileEnv *envPtr)
4193 {
4194 return CompileUnaryOpCmd(interp, parsePtr, INST_LNOT, envPtr);
4195 }
4196
4197 int
4198 TclCompileAddOpCmd(
4199 Tcl_Interp *interp,
4200 Tcl_Parse *parsePtr,
4201 Command *cmdPtr, /* Points to definition of command being
4202 * compiled. */
4203 CompileEnv *envPtr)
4204 {
4205 return CompileAssociativeBinaryOpCmd(interp, parsePtr, "0", INST_ADD,
4206 envPtr);
4207 }
4208
4209 int
4210 TclCompileMulOpCmd(
4211 Tcl_Interp *interp,
4212 Tcl_Parse *parsePtr,
4213 Command *cmdPtr, /* Points to definition of command being
4214 * compiled. */
4215 CompileEnv *envPtr)
4216 {
4217 return CompileAssociativeBinaryOpCmd(interp, parsePtr, "1", INST_MULT,
4218 envPtr);
4219 }
4220
4221 int
4222 TclCompileAndOpCmd(
4223 Tcl_Interp *interp,
4224 Tcl_Parse *parsePtr,
4225 Command *cmdPtr, /* Points to definition of command being
4226 * compiled. */
4227 CompileEnv *envPtr)
4228 {
4229 return CompileAssociativeBinaryOpCmd(interp, parsePtr, "-1", INST_BITAND,
4230 envPtr);
4231 }
4232
4233 int
4234 TclCompileOrOpCmd(
4235 Tcl_Interp *interp,
4236 Tcl_Parse *parsePtr,
4237 Command *cmdPtr, /* Points to definition of command being
4238 * compiled. */
4239 CompileEnv *envPtr)
4240 {
4241 return CompileAssociativeBinaryOpCmd(interp, parsePtr, "0", INST_BITOR,
4242 envPtr);
4243 }
4244
4245 int
4246 TclCompileXorOpCmd(
4247 Tcl_Interp *interp,
4248 Tcl_Parse *parsePtr,
4249 Command *cmdPtr, /* Points to definition of command being
4250 * compiled. */
4251 CompileEnv *envPtr)
4252 {
4253 return CompileAssociativeBinaryOpCmd(interp, parsePtr, "0", INST_BITXOR,
4254 envPtr);
4255 }
4256
4257 int
4258 TclCompilePowOpCmd(
4259 Tcl_Interp *interp,
4260 Tcl_Parse *parsePtr,
4261 Command *cmdPtr, /* Points to definition of command being
4262 * compiled. */
4263 CompileEnv *envPtr)
4264 {
4265 DefineLineInformation; /* TIP #280 */
4266 Tcl_Token *tokenPtr = parsePtr->tokenPtr;
4267 int words;
4268
4269 /*
4270 * This one has its own implementation because the ** operator is the only
4271 * one with right associativity.
4272 */
4273
4274 for (words=1 ; words<parsePtr->numWords ; words++) {
4275 tokenPtr = TokenAfter(tokenPtr);
4276 CompileWord(envPtr, tokenPtr, interp, words);
4277 }
4278 if (parsePtr->numWords <= 2) {
4279 PUSH("1");
4280 words++;
4281 }
4282 while (--words > 1) {
4283 TclEmitOpcode(INST_EXPON, envPtr);
4284 }
4285 return TCL_OK;
4286 }
4287
4288 int
4289 TclCompileLshiftOpCmd(
4290 Tcl_Interp *interp,
4291 Tcl_Parse *parsePtr,
4292 Command *cmdPtr, /* Points to definition of command being
4293 * compiled. */
4294 CompileEnv *envPtr)
4295 {
4296 return CompileStrictlyBinaryOpCmd(interp, parsePtr, INST_LSHIFT, envPtr);
4297 }
4298
4299 int
4300 TclCompileRshiftOpCmd(
4301 Tcl_Interp *interp,
4302 Tcl_Parse *parsePtr,
4303 Command *cmdPtr, /* Points to definition of command being
4304 * compiled. */
4305 CompileEnv *envPtr)
4306 {
4307 return CompileStrictlyBinaryOpCmd(interp, parsePtr, INST_RSHIFT, envPtr);
4308 }
4309
4310 int
4311 TclCompileModOpCmd(
4312 Tcl_Interp *interp,
4313 Tcl_Parse *parsePtr,
4314 Command *cmdPtr, /* Points to definition of command being
4315 * compiled. */
4316 CompileEnv *envPtr)
4317 {
4318 return CompileStrictlyBinaryOpCmd(interp, parsePtr, INST_MOD, envPtr);
4319 }
4320
4321 int
4322 TclCompileNeqOpCmd(
4323 Tcl_Interp *interp,
4324 Tcl_Parse *parsePtr,
4325 Command *cmdPtr, /* Points to definition of command being
4326 * compiled. */
4327 CompileEnv *envPtr)
4328 {
4329 return CompileStrictlyBinaryOpCmd(interp, parsePtr, INST_NEQ, envPtr);
4330 }
4331
4332 int
4333 TclCompileStrneqOpCmd(
4334 Tcl_Interp *interp,
4335 Tcl_Parse *parsePtr,
4336 Command *cmdPtr, /* Points to definition of command being
4337 * compiled. */
4338 CompileEnv *envPtr)
4339 {
4340 return CompileStrictlyBinaryOpCmd(interp, parsePtr, INST_STR_NEQ, envPtr);
4341 }
4342
4343 int
4344 TclCompileInOpCmd(
4345 Tcl_Interp *interp,
4346 Tcl_Parse *parsePtr,
4347 Command *cmdPtr, /* Points to definition of command being
4348 * compiled. */
4349 CompileEnv *envPtr)
4350 {
4351 return CompileStrictlyBinaryOpCmd(interp, parsePtr, INST_LIST_IN, envPtr);
4352 }
4353
4354 int
4355 TclCompileNiOpCmd(
4356 Tcl_Interp *interp,
4357 Tcl_Parse *parsePtr,
4358 Command *cmdPtr, /* Points to definition of command being
4359 * compiled. */
4360 CompileEnv *envPtr)
4361 {
4362 return CompileStrictlyBinaryOpCmd(interp, parsePtr, INST_LIST_NOT_IN,
4363 envPtr);
4364 }
4365
4366 int
4367 TclCompileLessOpCmd(
4368 Tcl_Interp *interp,
4369 Tcl_Parse *parsePtr,
4370 Command *cmdPtr, /* Points to definition of command being
4371 * compiled. */
4372 CompileEnv *envPtr)
4373 {
4374 return CompileComparisonOpCmd(interp, parsePtr, INST_LT, envPtr);
4375 }
4376
4377 int
4378 TclCompileLeqOpCmd(
4379 Tcl_Interp *interp,
4380 Tcl_Parse *parsePtr,
4381 Command *cmdPtr, /* Points to definition of command being
4382 * compiled. */
4383 CompileEnv *envPtr)
4384 {
4385 return CompileComparisonOpCmd(interp, parsePtr, INST_LE, envPtr);
4386 }
4387
4388 int
4389 TclCompileGreaterOpCmd(
4390 Tcl_Interp *interp,
4391 Tcl_Parse *parsePtr,
4392 Command *cmdPtr, /* Points to definition of command being
4393 * compiled. */
4394 CompileEnv *envPtr)
4395 {
4396 return CompileComparisonOpCmd(interp, parsePtr, INST_GT, envPtr);
4397 }
4398
4399 int
4400 TclCompileGeqOpCmd(
4401 Tcl_Interp *interp,
4402 Tcl_Parse *parsePtr,
4403 Command *cmdPtr, /* Points to definition of command being
4404 * compiled. */
4405 CompileEnv *envPtr)
4406 {
4407 return CompileComparisonOpCmd(interp, parsePtr, INST_GE, envPtr);
4408 }
4409
4410 int
4411 TclCompileEqOpCmd(
4412 Tcl_Interp *interp,
4413 Tcl_Parse *parsePtr,
4414 Command *cmdPtr, /* Points to definition of command being
4415 * compiled. */
4416 CompileEnv *envPtr)
4417 {
4418 return CompileComparisonOpCmd(interp, parsePtr, INST_EQ, envPtr);
4419 }
4420
4421 int
4422 TclCompileStreqOpCmd(
4423 Tcl_Interp *interp,
4424 Tcl_Parse *parsePtr,
4425 Command *cmdPtr, /* Points to definition of command being
4426 * compiled. */
4427 CompileEnv *envPtr)
4428 {
4429 return CompileComparisonOpCmd(interp, parsePtr, INST_STR_EQ, envPtr);
4430 }
4431
4432 int
4433 TclCompileMinusOpCmd(
4434 Tcl_Interp *interp,
4435 Tcl_Parse *parsePtr,
4436 Command *cmdPtr, /* Points to definition of command being
4437 * compiled. */
4438 CompileEnv *envPtr)
4439 {
4440 DefineLineInformation; /* TIP #280 */
4441 Tcl_Token *tokenPtr = parsePtr->tokenPtr;
4442 int words;
4443
4444 /* TODO: Consider support for compiling expanded args. */
4445 if (parsePtr->numWords == 1) {
4446 /*
4447 * Fallback to direct eval to report syntax error.
4448 */
4449
4450 return TCL_ERROR;
4451 }
4452 for (words=1 ; words<parsePtr->numWords ; words++) {
4453 tokenPtr = TokenAfter(tokenPtr);
4454 CompileWord(envPtr, tokenPtr, interp, words);
4455 }
4456 if (words == 2) {
4457 TclEmitOpcode(INST_UMINUS, envPtr);
4458 return TCL_OK;
4459 }
4460 if (words == 3) {
4461 TclEmitOpcode(INST_SUB, envPtr);
4462 return TCL_OK;
4463 }
4464
4465 /*
4466 * Reverse order of arguments to get precise agreement with [expr] in
4467 * calculations, including roundoff errors.
4468 */
4469
4470 TclEmitInstInt4(INST_REVERSE, words-1, envPtr);
4471 while (--words > 1) {
4472 TclEmitInstInt4(INST_REVERSE, 2, envPtr);
4473 TclEmitOpcode(INST_SUB, envPtr);
4474 }
4475 return TCL_OK;
4476 }
4477
4478 int
4479 TclCompileDivOpCmd(
4480 Tcl_Interp *interp,
4481 Tcl_Parse *parsePtr,
4482 Command *cmdPtr, /* Points to definition of command being
4483 * compiled. */
4484 CompileEnv *envPtr)
4485 {
4486 DefineLineInformation; /* TIP #280 */
4487 Tcl_Token *tokenPtr = parsePtr->tokenPtr;
4488 int words;
4489
4490 /* TODO: Consider support for compiling expanded args. */
4491 if (parsePtr->numWords == 1) {
4492 /*
4493 * Fallback to direct eval to report syntax error.
4494 */
4495
4496 return TCL_ERROR;
4497 }
4498 if (parsePtr->numWords == 2) {
4499 PUSH("1.0");
4500 }
4501 for (words=1 ; words<parsePtr->numWords ; words++) {
4502 tokenPtr = TokenAfter(tokenPtr);
4503 CompileWord(envPtr, tokenPtr, interp, words);
4504 }
4505 if (words <= 3) {
4506 TclEmitOpcode(INST_DIV, envPtr);
4507 return TCL_OK;
4508 }
4509
4510 /*
4511 * Reverse order of arguments to get precise agreement with [expr] in
4512 * calculations, including roundoff errors.
4513 */
4514
4515 TclEmitInstInt4(INST_REVERSE, words-1, envPtr);
4516 while (--words > 1) {
4517 TclEmitInstInt4(INST_REVERSE, 2, envPtr);
4518 TclEmitOpcode(INST_DIV, envPtr);
4519 }
4520 return TCL_OK;
4521 }
4522
4523 /*
4524 * Local Variables:
4525 * mode: c
4526 * c-basic-offset: 4
4527 * fill-column: 78
4528 * End:
4529 */