Debian Codegraph @

generic/tclCompCmdsGR.c

raw
1 /*
2 * tclCompCmdsGR.c --
3 *
4 * This file contains compilation procedures that compile various Tcl
5 * commands (beginning with the letters 'g' through 'r') into a sequence
6 * of instructions ("bytecodes").
7 *
8 * Copyright (c) 1997-1998 Sun Microsystems, Inc.
9 * Copyright (c) 2001 Kevin B. Kenny. All rights reserved.
10 * Copyright (c) 2002 ActiveState Corporation.
11 * Copyright (c) 2004-2013 Donal K. Fellows.
12 *
13 * See the file "license.terms" for information on usage and redistribution of
14 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
15 */
16
17 #include "tclInt.h"
18 #include "tclCompile.h"
19 #include <assert.h>
20
21 /*
22 * Prototypes for procedures defined later in this file:
23 */
24
25 static void CompileReturnInternal(CompileEnv *envPtr,
26 unsigned char op, int code, int level,
27 Tcl_Obj *returnOpts);
28 static int IndexTailVarIfKnown(Tcl_Interp *interp,
29 Tcl_Token *varTokenPtr, CompileEnv *envPtr);
30
31 /*
32 *----------------------------------------------------------------------
33 *
34 * TclGetIndexFromToken --
35 *
36 * Parse a token to determine if an index value is known at
37 * compile time.
38 *
39 * Returns:
40 * TCL_OK if parsing succeeded, and TCL_ERROR if it failed.
41 *
42 * Side effects:
43 * When TCL_OK is returned, the encoded index value is written
44 * to *index.
45 *
46 *----------------------------------------------------------------------
47 */
48
49 int
50 TclGetIndexFromToken(
51 Tcl_Token *tokenPtr,
52 int before,
53 int after,
54 int *indexPtr)
55 {
56 Tcl_Obj *tmpObj;
57 int result = TCL_ERROR;
58
59 TclNewObj(tmpObj);
60 if (TclWordKnownAtCompileTime(tokenPtr, tmpObj)) {
61 result = TclIndexEncode(NULL, tmpObj, before, after, indexPtr);
62 }
63 Tcl_DecrRefCount(tmpObj);
64 return result;
65 }
66
67 /*
68 *----------------------------------------------------------------------
69 *
70 * TclCompileGlobalCmd --
71 *
72 * Procedure called to compile the "global" command.
73 *
74 * Results:
75 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
76 * evaluation to runtime.
77 *
78 * Side effects:
79 * Instructions are added to envPtr to execute the "global" command at
80 * runtime.
81 *
82 *----------------------------------------------------------------------
83 */
84
85 int
86 TclCompileGlobalCmd(
87 Tcl_Interp *interp, /* Used for error reporting. */
88 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
89 * created by Tcl_ParseCommand. */
90 Command *cmdPtr, /* Points to definition of command being
91 * compiled. */
92 CompileEnv *envPtr) /* Holds resulting instructions. */
93 {
94 DefineLineInformation; /* TIP #280 */
95 Tcl_Token *varTokenPtr;
96 int localIndex, numWords, i;
97
98 /* TODO: Consider support for compiling expanded args. */
99 numWords = parsePtr->numWords;
100 if (numWords < 2) {
101 return TCL_ERROR;
102 }
103
104 /*
105 * 'global' has no effect outside of proc bodies; handle that at runtime
106 */
107
108 if (envPtr->procPtr == NULL) {
109 return TCL_ERROR;
110 }
111
112 /*
113 * Push the namespace
114 */
115
116 PushStringLiteral(envPtr, "::");
117
118 /*
119 * Loop over the variables.
120 */
121
122 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
123 for (i=1; i<numWords; varTokenPtr = TokenAfter(varTokenPtr),i++) {
124 localIndex = IndexTailVarIfKnown(interp, varTokenPtr, envPtr);
125
126 if (localIndex < 0) {
127 return TCL_ERROR;
128 }
129
130 /*
131 * TODO: Consider what value can pass through the
132 * IndexTailVarIfKnown() screen. Full CompileWord() likely does not
133 * apply here. Push known value instead.
134 */
135
136 CompileWord(envPtr, varTokenPtr, interp, i);
137 TclEmitInstInt4( INST_NSUPVAR, localIndex, envPtr);
138 }
139
140 /*
141 * Pop the namespace, and set the result to empty
142 */
143
144 TclEmitOpcode( INST_POP, envPtr);
145 PushStringLiteral(envPtr, "");
146 return TCL_OK;
147 }
148
149 /*
150 *----------------------------------------------------------------------
151 *
152 * TclCompileIfCmd --
153 *
154 * Procedure called to compile the "if" command.
155 *
156 * Results:
157 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
158 * evaluation to runtime.
159 *
160 * Side effects:
161 * Instructions are added to envPtr to execute the "if" command at
162 * runtime.
163 *
164 *----------------------------------------------------------------------
165 */
166
167 int
168 TclCompileIfCmd(
169 Tcl_Interp *interp, /* Used for error reporting. */
170 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
171 * created by Tcl_ParseCommand. */
172 Command *cmdPtr, /* Points to definition of command being
173 * compiled. */
174 CompileEnv *envPtr) /* Holds resulting instructions. */
175 {
176 DefineLineInformation; /* TIP #280 */
177 JumpFixupArray jumpFalseFixupArray;
178 /* Used to fix the ifFalse jump after each
179 * test when its target PC is determined. */
180 JumpFixupArray jumpEndFixupArray;
181 /* Used to fix the jump after each "then" body
182 * to the end of the "if" when that PC is
183 * determined. */
184 Tcl_Token *tokenPtr, *testTokenPtr;
185 int jumpIndex = 0; /* Avoid compiler warning. */
186 int numBytes, j;
187 int jumpFalseDist, numWords, wordIdx, code;
188 const char *word;
189 int realCond = 1; /* Set to 0 for static conditions:
190 * "if 0 {..}" */
191 int boolVal; /* Value of static condition. */
192 int compileScripts = 1;
193
194 /*
195 * Only compile the "if" command if all arguments are simple words, in
196 * order to insure correct substitution [Bug 219166]
197 */
198
199 tokenPtr = parsePtr->tokenPtr;
200 wordIdx = 0;
201 numWords = parsePtr->numWords;
202
203 for (wordIdx = 0; wordIdx < numWords; wordIdx++) {
204 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
205 return TCL_ERROR;
206 }
207 tokenPtr = TokenAfter(tokenPtr);
208 }
209
210 TclInitJumpFixupArray(&jumpFalseFixupArray);
211 TclInitJumpFixupArray(&jumpEndFixupArray);
212 code = TCL_OK;
213
214 /*
215 * Each iteration of this loop compiles one "if expr ?then? body" or
216 * "elseif expr ?then? body" clause.
217 */
218
219 tokenPtr = parsePtr->tokenPtr;
220 wordIdx = 0;
221 while (wordIdx < numWords) {
222 /*
223 * Stop looping if the token isn't "if" or "elseif".
224 */
225
226 word = tokenPtr[1].start;
227 numBytes = tokenPtr[1].size;
228 if ((tokenPtr == parsePtr->tokenPtr)
229 || ((numBytes == 6) && (strncmp(word, "elseif", 6) == 0))) {
230 tokenPtr = TokenAfter(tokenPtr);
231 wordIdx++;
232 } else {
233 break;
234 }
235 if (wordIdx >= numWords) {
236 code = TCL_ERROR;
237 goto done;
238 }
239
240 /*
241 * Compile the test expression then emit the conditional jump around
242 * the "then" part.
243 */
244
245 testTokenPtr = tokenPtr;
246
247 if (realCond) {
248 /*
249 * Find out if the condition is a constant.
250 */
251
252 Tcl_Obj *boolObj = Tcl_NewStringObj(testTokenPtr[1].start,
253 testTokenPtr[1].size);
254
255 Tcl_IncrRefCount(boolObj);
256 code = Tcl_GetBooleanFromObj(NULL, boolObj, &boolVal);
257 TclDecrRefCount(boolObj);
258 if (code == TCL_OK) {
259 /*
260 * A static condition.
261 */
262
263 realCond = 0;
264 if (!boolVal) {
265 compileScripts = 0;
266 }
267 } else {
268 SetLineInformation(wordIdx);
269 Tcl_ResetResult(interp);
270 TclCompileExprWords(interp, testTokenPtr, 1, envPtr);
271 if (jumpFalseFixupArray.next >= jumpFalseFixupArray.end) {
272 TclExpandJumpFixupArray(&jumpFalseFixupArray);
273 }
274 jumpIndex = jumpFalseFixupArray.next;
275 jumpFalseFixupArray.next++;
276 TclEmitForwardJump(envPtr, TCL_FALSE_JUMP,
277 jumpFalseFixupArray.fixup + jumpIndex);
278 }
279 code = TCL_OK;
280 }
281
282 /*
283 * Skip over the optional "then" before the then clause.
284 */
285
286 tokenPtr = TokenAfter(testTokenPtr);
287 wordIdx++;
288 if (wordIdx >= numWords) {
289 code = TCL_ERROR;
290 goto done;
291 }
292 if (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
293 word = tokenPtr[1].start;
294 numBytes = tokenPtr[1].size;
295 if ((numBytes == 4) && (strncmp(word, "then", 4) == 0)) {
296 tokenPtr = TokenAfter(tokenPtr);
297 wordIdx++;
298 if (wordIdx >= numWords) {
299 code = TCL_ERROR;
300 goto done;
301 }
302 }
303 }
304
305 /*
306 * Compile the "then" command body.
307 */
308
309 if (compileScripts) {
310 BODY(tokenPtr, wordIdx);
311 }
312
313 if (realCond) {
314 /*
315 * Jump to the end of the "if" command. Both jumpFalseFixupArray
316 * and jumpEndFixupArray are indexed by "jumpIndex".
317 */
318
319 if (jumpEndFixupArray.next >= jumpEndFixupArray.end) {
320 TclExpandJumpFixupArray(&jumpEndFixupArray);
321 }
322 jumpEndFixupArray.next++;
323 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP,
324 jumpEndFixupArray.fixup + jumpIndex);
325
326 /*
327 * Fix the target of the jumpFalse after the test. Generate a 4
328 * byte jump if the distance is > 120 bytes. This is conservative,
329 * and ensures that we won't have to replace this jump if we later
330 * also need to replace the proceeding jump to the end of the "if"
331 * with a 4 byte jump.
332 */
333
334 TclAdjustStackDepth(-1, envPtr);
335 if (TclFixupForwardJumpToHere(envPtr,
336 jumpFalseFixupArray.fixup + jumpIndex, 120)) {
337 /*
338 * Adjust the code offset for the proceeding jump to the end
339 * of the "if" command.
340 */
341
342 jumpEndFixupArray.fixup[jumpIndex].codeOffset += 3;
343 }
344 } else if (boolVal) {
345 /*
346 * We were processing an "if 1 {...}"; stop compiling scripts.
347 */
348
349 compileScripts = 0;
350 } else {
351 /*
352 * We were processing an "if 0 {...}"; reset so that the rest
353 * (elseif, else) is compiled correctly.
354 */
355
356 realCond = 1;
357 compileScripts = 1;
358 }
359
360 tokenPtr = TokenAfter(tokenPtr);
361 wordIdx++;
362 }
363
364 /*
365 * Check for the optional else clause. Do not compile anything if this was
366 * an "if 1 {...}" case.
367 */
368
369 if ((wordIdx < numWords) && (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD)) {
370 /*
371 * There is an else clause. Skip over the optional "else" word.
372 */
373
374 word = tokenPtr[1].start;
375 numBytes = tokenPtr[1].size;
376 if ((numBytes == 4) && (strncmp(word, "else", 4) == 0)) {
377 tokenPtr = TokenAfter(tokenPtr);
378 wordIdx++;
379 if (wordIdx >= numWords) {
380 code = TCL_ERROR;
381 goto done;
382 }
383 }
384
385 if (compileScripts) {
386 /*
387 * Compile the else command body.
388 */
389
390 BODY(tokenPtr, wordIdx);
391 }
392
393 /*
394 * Make sure there are no words after the else clause.
395 */
396
397 wordIdx++;
398 if (wordIdx < numWords) {
399 code = TCL_ERROR;
400 goto done;
401 }
402 } else {
403 /*
404 * No else clause: the "if" command's result is an empty string.
405 */
406
407 if (compileScripts) {
408 PushStringLiteral(envPtr, "");
409 }
410 }
411
412 /*
413 * Fix the unconditional jumps to the end of the "if" command.
414 */
415
416 for (j = jumpEndFixupArray.next; j > 0; j--) {
417 jumpIndex = (j - 1); /* i.e. process the closest jump first. */
418 if (TclFixupForwardJumpToHere(envPtr,
419 jumpEndFixupArray.fixup + jumpIndex, 127)) {
420 /*
421 * Adjust the immediately preceding "ifFalse" jump. We moved it's
422 * target (just after this jump) down three bytes.
423 */
424
425 unsigned char *ifFalsePc = envPtr->codeStart
426 + jumpFalseFixupArray.fixup[jumpIndex].codeOffset;
427 unsigned char opCode = *ifFalsePc;
428
429 if (opCode == INST_JUMP_FALSE1) {
430 jumpFalseDist = TclGetInt1AtPtr(ifFalsePc + 1);
431 jumpFalseDist += 3;
432 TclStoreInt1AtPtr(jumpFalseDist, (ifFalsePc + 1));
433 } else if (opCode == INST_JUMP_FALSE4) {
434 jumpFalseDist = TclGetInt4AtPtr(ifFalsePc + 1);
435 jumpFalseDist += 3;
436 TclStoreInt4AtPtr(jumpFalseDist, (ifFalsePc + 1));
437 } else {
438 Tcl_Panic("TclCompileIfCmd: unexpected opcode \"%d\" updating ifFalse jump", (int) opCode);
439 }
440 }
441 }
442
443 /*
444 * Free the jumpFixupArray array if malloc'ed storage was used.
445 */
446
447 done:
448 TclFreeJumpFixupArray(&jumpFalseFixupArray);
449 TclFreeJumpFixupArray(&jumpEndFixupArray);
450 return code;
451 }
452
453 /*
454 *----------------------------------------------------------------------
455 *
456 * TclCompileIncrCmd --
457 *
458 * Procedure called to compile the "incr" command.
459 *
460 * Results:
461 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
462 * evaluation to runtime.
463 *
464 * Side effects:
465 * Instructions are added to envPtr to execute the "incr" command at
466 * runtime.
467 *
468 *----------------------------------------------------------------------
469 */
470
471 int
472 TclCompileIncrCmd(
473 Tcl_Interp *interp, /* Used for error reporting. */
474 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
475 * created by Tcl_ParseCommand. */
476 Command *cmdPtr, /* Points to definition of command being
477 * compiled. */
478 CompileEnv *envPtr) /* Holds resulting instructions. */
479 {
480 DefineLineInformation; /* TIP #280 */
481 Tcl_Token *varTokenPtr, *incrTokenPtr;
482 int isScalar, localIndex, haveImmValue;
483 Tcl_WideInt immValue;
484
485 if ((parsePtr->numWords != 2) && (parsePtr->numWords != 3)) {
486 return TCL_ERROR;
487 }
488
489 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
490
491 PushVarNameWord(interp, varTokenPtr, envPtr, TCL_NO_LARGE_INDEX,
492 &localIndex, &isScalar, 1);
493
494 /*
495 * If an increment is given, push it, but see first if it's a small
496 * integer.
497 */
498
499 haveImmValue = 0;
500 immValue = 1;
501 if (parsePtr->numWords == 3) {
502 incrTokenPtr = TokenAfter(varTokenPtr);
503 if (incrTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
504 const char *word = incrTokenPtr[1].start;
505 int numBytes = incrTokenPtr[1].size;
506 int code;
507 Tcl_Obj *intObj = Tcl_NewStringObj(word, numBytes);
508
509 Tcl_IncrRefCount(intObj);
510 code = Tcl_GetWideIntFromObj(NULL, intObj, &immValue);
511 if ((code == TCL_OK) && (
512 #ifndef TCL_WIDE_INT_IS_LONG
513 intObj->typePtr == &tclWideIntType ||
514 #endif
515 intObj->typePtr == &tclIntType) && (-127 <= immValue) && (immValue <= 127)) {
516 haveImmValue = 1;
517 }
518 TclDecrRefCount(intObj);
519 if (!haveImmValue) {
520 PushLiteral(envPtr, word, numBytes);
521 }
522 } else {
523 SetLineInformation(2);
524 CompileTokens(envPtr, incrTokenPtr, interp);
525 }
526 } else { /* No incr amount given so use 1. */
527 haveImmValue = 1;
528 }
529
530 /*
531 * Emit the instruction to increment the variable.
532 */
533
534 if (isScalar) { /* Simple scalar variable. */
535 if (localIndex >= 0) {
536 if (haveImmValue) {
537 TclEmitInstInt1(INST_INCR_SCALAR1_IMM, localIndex, envPtr);
538 TclEmitInt1(immValue, envPtr);
539 } else {
540 TclEmitInstInt1(INST_INCR_SCALAR1, localIndex, envPtr);
541 }
542 } else {
543 if (haveImmValue) {
544 TclEmitInstInt1(INST_INCR_STK_IMM, immValue, envPtr);
545 } else {
546 TclEmitOpcode( INST_INCR_STK, envPtr);
547 }
548 }
549 } else { /* Simple array variable. */
550 if (localIndex >= 0) {
551 if (haveImmValue) {
552 TclEmitInstInt1(INST_INCR_ARRAY1_IMM, localIndex, envPtr);
553 TclEmitInt1(immValue, envPtr);
554 } else {
555 TclEmitInstInt1(INST_INCR_ARRAY1, localIndex, envPtr);
556 }
557 } else {
558 if (haveImmValue) {
559 TclEmitInstInt1(INST_INCR_ARRAY_STK_IMM, immValue, envPtr);
560 } else {
561 TclEmitOpcode( INST_INCR_ARRAY_STK, envPtr);
562 }
563 }
564 }
565
566 return TCL_OK;
567 }
568
569 /*
570 *----------------------------------------------------------------------
571 *
572 * TclCompileInfo*Cmd --
573 *
574 * Procedures called to compile "info" subcommands.
575 *
576 * Results:
577 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
578 * evaluation to runtime.
579 *
580 * Side effects:
581 * Instructions are added to envPtr to execute the "info" subcommand at
582 * runtime.
583 *
584 *----------------------------------------------------------------------
585 */
586
587 int
588 TclCompileInfoCommandsCmd(
589 Tcl_Interp *interp, /* Used for error reporting. */
590 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
591 * created by Tcl_ParseCommand. */
592 Command *cmdPtr, /* Points to definition of command being
593 * compiled. */
594 CompileEnv *envPtr)
595 {
596 DefineLineInformation; /* TIP #280 */
597 Tcl_Token *tokenPtr;
598 Tcl_Obj *objPtr;
599 const char *bytes;
600
601 /*
602 * We require one compile-time known argument for the case we can compile.
603 */
604
605 if (parsePtr->numWords == 1) {
606 return TclCompileBasic0ArgCmd(interp, parsePtr, cmdPtr, envPtr);
607 } else if (parsePtr->numWords != 2) {
608 return TCL_ERROR;
609 }
610 tokenPtr = TokenAfter(parsePtr->tokenPtr);
611 TclNewObj(objPtr);
612 Tcl_IncrRefCount(objPtr);
613 if (!TclWordKnownAtCompileTime(tokenPtr, objPtr)) {
614 goto notCompilable;
615 }
616 bytes = Tcl_GetString(objPtr);
617
618 /*
619 * We require that the argument start with "::" and not have any of "*\[?"
620 * in it. (Theoretically, we should look in only the final component, but
621 * the difference is so slight given current naming practices.)
622 */
623
624 if (bytes[0] != ':' || bytes[1] != ':' || !TclMatchIsTrivial(bytes)) {
625 goto notCompilable;
626 }
627 Tcl_DecrRefCount(objPtr);
628
629 /*
630 * Confirmed as a literal that will not frighten the horses. Compile.
631 * The result must be made into a list.
632 */
633
634 /* TODO: Just push the known value */
635 CompileWord(envPtr, tokenPtr, interp, 1);
636 TclEmitOpcode( INST_RESOLVE_COMMAND, envPtr);
637 TclEmitOpcode( INST_DUP, envPtr);
638 TclEmitOpcode( INST_STR_LEN, envPtr);
639 TclEmitInstInt1( INST_JUMP_FALSE1, 7, envPtr);
640 TclEmitInstInt4( INST_LIST, 1, envPtr);
641 return TCL_OK;
642
643 notCompilable:
644 Tcl_DecrRefCount(objPtr);
645 return TclCompileBasic1ArgCmd(interp, parsePtr, cmdPtr, envPtr);
646 }
647
648 int
649 TclCompileInfoCoroutineCmd(
650 Tcl_Interp *interp, /* Used for error reporting. */
651 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
652 * created by Tcl_ParseCommand. */
653 Command *cmdPtr, /* Points to definition of command being
654 * compiled. */
655 CompileEnv *envPtr) /* Holds resulting instructions. */
656 {
657 /*
658 * Only compile [info coroutine] without arguments.
659 */
660
661 if (parsePtr->numWords != 1) {
662 return TCL_ERROR;
663 }
664
665 /*
666 * Not much to do; we compile to a single instruction...
667 */
668
669 TclEmitOpcode( INST_COROUTINE_NAME, envPtr);
670 return TCL_OK;
671 }
672
673 int
674 TclCompileInfoExistsCmd(
675 Tcl_Interp *interp, /* Used for error reporting. */
676 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
677 * created by Tcl_ParseCommand. */
678 Command *cmdPtr, /* Points to definition of command being
679 * compiled. */
680 CompileEnv *envPtr) /* Holds resulting instructions. */
681 {
682 DefineLineInformation; /* TIP #280 */
683 Tcl_Token *tokenPtr;
684 int isScalar, localIndex;
685
686 if (parsePtr->numWords != 2) {
687 return TCL_ERROR;
688 }
689
690 /*
691 * Decide if we can use a frame slot for the var/array name or if we need
692 * to emit code to compute and push the name at runtime. We use a frame
693 * slot (entry in the array of local vars) if we are compiling a procedure
694 * body and if the name is simple text that does not include namespace
695 * qualifiers.
696 */
697
698 tokenPtr = TokenAfter(parsePtr->tokenPtr);
699 PushVarNameWord(interp, tokenPtr, envPtr, 0, &localIndex, &isScalar, 1);
700
701 /*
702 * Emit instruction to check the variable for existence.
703 */
704
705 if (isScalar) {
706 if (localIndex < 0) {
707 TclEmitOpcode( INST_EXIST_STK, envPtr);
708 } else {
709 TclEmitInstInt4( INST_EXIST_SCALAR, localIndex, envPtr);
710 }
711 } else {
712 if (localIndex < 0) {
713 TclEmitOpcode( INST_EXIST_ARRAY_STK, envPtr);
714 } else {
715 TclEmitInstInt4( INST_EXIST_ARRAY, localIndex, envPtr);
716 }
717 }
718
719 return TCL_OK;
720 }
721
722 int
723 TclCompileInfoLevelCmd(
724 Tcl_Interp *interp, /* Used for error reporting. */
725 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
726 * created by Tcl_ParseCommand. */
727 Command *cmdPtr, /* Points to definition of command being
728 * compiled. */
729 CompileEnv *envPtr) /* Holds resulting instructions. */
730 {
731 /*
732 * Only compile [info level] without arguments or with a single argument.
733 */
734
735 if (parsePtr->numWords == 1) {
736 /*
737 * Not much to do; we compile to a single instruction...
738 */
739
740 TclEmitOpcode( INST_INFO_LEVEL_NUM, envPtr);
741 } else if (parsePtr->numWords != 2) {
742 return TCL_ERROR;
743 } else {
744 DefineLineInformation; /* TIP #280 */
745
746 /*
747 * Compile the argument, then add the instruction to convert it into a
748 * list of arguments.
749 */
750
751 CompileWord(envPtr, TokenAfter(parsePtr->tokenPtr), interp, 1);
752 TclEmitOpcode( INST_INFO_LEVEL_ARGS, envPtr);
753 }
754 return TCL_OK;
755 }
756
757 int
758 TclCompileInfoObjectClassCmd(
759 Tcl_Interp *interp, /* Used for error reporting. */
760 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
761 * created by Tcl_ParseCommand. */
762 Command *cmdPtr, /* Points to definition of command being
763 * compiled. */
764 CompileEnv *envPtr)
765 {
766 DefineLineInformation; /* TIP #280 */
767 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
768
769 if (parsePtr->numWords != 2) {
770 return TCL_ERROR;
771 }
772 CompileWord(envPtr, tokenPtr, interp, 1);
773 TclEmitOpcode( INST_TCLOO_CLASS, envPtr);
774 return TCL_OK;
775 }
776
777 int
778 TclCompileInfoObjectIsACmd(
779 Tcl_Interp *interp, /* Used for error reporting. */
780 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
781 * created by Tcl_ParseCommand. */
782 Command *cmdPtr, /* Points to definition of command being
783 * compiled. */
784 CompileEnv *envPtr)
785 {
786 DefineLineInformation; /* TIP #280 */
787 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
788
789 /*
790 * We only handle [info object isa object <somevalue>]. The first three
791 * words are compressed to a single token by the ensemble compilation
792 * engine.
793 */
794
795 if (parsePtr->numWords != 3) {
796 return TCL_ERROR;
797 }
798 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD || tokenPtr[1].size < 1
799 || strncmp(tokenPtr[1].start, "object", tokenPtr[1].size)) {
800 return TCL_ERROR;
801 }
802 tokenPtr = TokenAfter(tokenPtr);
803
804 /*
805 * Issue the code.
806 */
807
808 CompileWord(envPtr, tokenPtr, interp, 2);
809 TclEmitOpcode( INST_TCLOO_IS_OBJECT, envPtr);
810 return TCL_OK;
811 }
812
813 int
814 TclCompileInfoObjectNamespaceCmd(
815 Tcl_Interp *interp, /* Used for error reporting. */
816 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
817 * created by Tcl_ParseCommand. */
818 Command *cmdPtr, /* Points to definition of command being
819 * compiled. */
820 CompileEnv *envPtr)
821 {
822 DefineLineInformation; /* TIP #280 */
823 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
824
825 if (parsePtr->numWords != 2) {
826 return TCL_ERROR;
827 }
828 CompileWord(envPtr, tokenPtr, interp, 1);
829 TclEmitOpcode( INST_TCLOO_NS, envPtr);
830 return TCL_OK;
831 }
832
833 /*
834 *----------------------------------------------------------------------
835 *
836 * TclCompileLappendCmd --
837 *
838 * Procedure called to compile the "lappend" command.
839 *
840 * Results:
841 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
842 * evaluation to runtime.
843 *
844 * Side effects:
845 * Instructions are added to envPtr to execute the "lappend" command at
846 * runtime.
847 *
848 *----------------------------------------------------------------------
849 */
850
851 int
852 TclCompileLappendCmd(
853 Tcl_Interp *interp, /* Used for error reporting. */
854 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
855 * created by Tcl_ParseCommand. */
856 Command *cmdPtr, /* Points to definition of command being
857 * compiled. */
858 CompileEnv *envPtr) /* Holds resulting instructions. */
859 {
860 DefineLineInformation; /* TIP #280 */
861 Tcl_Token *varTokenPtr, *valueTokenPtr;
862 int isScalar, localIndex, numWords, i;
863
864 /* TODO: Consider support for compiling expanded args. */
865 numWords = parsePtr->numWords;
866 if (numWords < 3) {
867 return TCL_ERROR;
868 }
869
870 if (numWords != 3 || envPtr->procPtr == NULL) {
871 goto lappendMultiple;
872 }
873
874 /*
875 * Decide if we can use a frame slot for the var/array name or if we
876 * need to emit code to compute and push the name at runtime. We use a
877 * frame slot (entry in the array of local vars) if we are compiling a
878 * procedure body and if the name is simple text that does not include
879 * namespace qualifiers.
880 */
881
882 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
883
884 PushVarNameWord(interp, varTokenPtr, envPtr, 0,
885 &localIndex, &isScalar, 1);
886
887 /*
888 * If we are doing an assignment, push the new value. In the no values
889 * case, create an empty object.
890 */
891
892 if (numWords > 2) {
893 valueTokenPtr = TokenAfter(varTokenPtr);
894
895 CompileWord(envPtr, valueTokenPtr, interp, 2);
896 }
897
898 /*
899 * Emit instructions to set/get the variable.
900 */
901
902 /*
903 * The *_STK opcodes should be refactored to make better use of existing
904 * LOAD/STORE instructions.
905 */
906
907 if (isScalar) {
908 if (localIndex < 0) {
909 TclEmitOpcode( INST_LAPPEND_STK, envPtr);
910 } else {
911 Emit14Inst( INST_LAPPEND_SCALAR, localIndex, envPtr);
912 }
913 } else {
914 if (localIndex < 0) {
915 TclEmitOpcode( INST_LAPPEND_ARRAY_STK, envPtr);
916 } else {
917 Emit14Inst( INST_LAPPEND_ARRAY, localIndex, envPtr);
918 }
919 }
920
921 return TCL_OK;
922
923 lappendMultiple:
924 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
925 PushVarNameWord(interp, varTokenPtr, envPtr, 0,
926 &localIndex, &isScalar, 1);
927 valueTokenPtr = TokenAfter(varTokenPtr);
928 for (i = 2 ; i < numWords ; i++) {
929 CompileWord(envPtr, valueTokenPtr, interp, i);
930 valueTokenPtr = TokenAfter(valueTokenPtr);
931 }
932 TclEmitInstInt4( INST_LIST, numWords - 2, envPtr);
933 if (isScalar) {
934 if (localIndex < 0) {
935 TclEmitOpcode( INST_LAPPEND_LIST_STK, envPtr);
936 } else {
937 TclEmitInstInt4(INST_LAPPEND_LIST, localIndex, envPtr);
938 }
939 } else {
940 if (localIndex < 0) {
941 TclEmitOpcode( INST_LAPPEND_LIST_ARRAY_STK, envPtr);
942 } else {
943 TclEmitInstInt4(INST_LAPPEND_LIST_ARRAY, localIndex,envPtr);
944 }
945 }
946 return TCL_OK;
947 }
948
949 /*
950 *----------------------------------------------------------------------
951 *
952 * TclCompileLassignCmd --
953 *
954 * Procedure called to compile the "lassign" command.
955 *
956 * Results:
957 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
958 * evaluation to runtime.
959 *
960 * Side effects:
961 * Instructions are added to envPtr to execute the "lassign" command at
962 * runtime.
963 *
964 *----------------------------------------------------------------------
965 */
966
967 int
968 TclCompileLassignCmd(
969 Tcl_Interp *interp, /* Used for error reporting. */
970 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
971 * created by Tcl_ParseCommand. */
972 Command *cmdPtr, /* Points to definition of command being
973 * compiled. */
974 CompileEnv *envPtr) /* Holds resulting instructions. */
975 {
976 DefineLineInformation; /* TIP #280 */
977 Tcl_Token *tokenPtr;
978 int isScalar, localIndex, numWords, idx;
979
980 numWords = parsePtr->numWords;
981
982 /*
983 * Check for command syntax error, but we'll punt that to runtime.
984 */
985
986 if (numWords < 3) {
987 return TCL_ERROR;
988 }
989
990 /*
991 * Generate code to push list being taken apart by [lassign].
992 */
993
994 tokenPtr = TokenAfter(parsePtr->tokenPtr);
995 CompileWord(envPtr, tokenPtr, interp, 1);
996
997 /*
998 * Generate code to assign values from the list to variables.
999 */
1000
1001 for (idx=0 ; idx<numWords-2 ; idx++) {
1002 tokenPtr = TokenAfter(tokenPtr);
1003
1004 /*
1005 * Generate the next variable name.
1006 */
1007
1008 PushVarNameWord(interp, tokenPtr, envPtr, 0, &localIndex,
1009 &isScalar, idx + 2);
1010
1011 /*
1012 * Emit instructions to get the idx'th item out of the list value on
1013 * the stack and assign it to the variable.
1014 */
1015
1016 if (isScalar) {
1017 if (localIndex >= 0) {
1018 TclEmitOpcode( INST_DUP, envPtr);
1019 TclEmitInstInt4(INST_LIST_INDEX_IMM, idx, envPtr);
1020 Emit14Inst( INST_STORE_SCALAR, localIndex, envPtr);
1021 TclEmitOpcode( INST_POP, envPtr);
1022 } else {
1023 TclEmitInstInt4(INST_OVER, 1, envPtr);
1024 TclEmitInstInt4(INST_LIST_INDEX_IMM, idx, envPtr);
1025 TclEmitOpcode( INST_STORE_STK, envPtr);
1026 TclEmitOpcode( INST_POP, envPtr);
1027 }
1028 } else {
1029 if (localIndex >= 0) {
1030 TclEmitInstInt4(INST_OVER, 1, envPtr);
1031 TclEmitInstInt4(INST_LIST_INDEX_IMM, idx, envPtr);
1032 Emit14Inst( INST_STORE_ARRAY, localIndex, envPtr);
1033 TclEmitOpcode( INST_POP, envPtr);
1034 } else {
1035 TclEmitInstInt4(INST_OVER, 2, envPtr);
1036 TclEmitInstInt4(INST_LIST_INDEX_IMM, idx, envPtr);
1037 TclEmitOpcode( INST_STORE_ARRAY_STK, envPtr);
1038 TclEmitOpcode( INST_POP, envPtr);
1039 }
1040 }
1041 }
1042
1043 /*
1044 * Generate code to leave the rest of the list on the stack.
1045 */
1046
1047 TclEmitInstInt4( INST_LIST_RANGE_IMM, idx, envPtr);
1048 TclEmitInt4( TCL_INDEX_END, envPtr);
1049
1050 return TCL_OK;
1051 }
1052
1053 /*
1054 *----------------------------------------------------------------------
1055 *
1056 * TclCompileLindexCmd --
1057 *
1058 * Procedure called to compile the "lindex" command.
1059 *
1060 * Results:
1061 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
1062 * evaluation to runtime.
1063 *
1064 * Side effects:
1065 * Instructions are added to envPtr to execute the "lindex" command at
1066 * runtime.
1067 *
1068 *----------------------------------------------------------------------
1069 */
1070
1071 int
1072 TclCompileLindexCmd(
1073 Tcl_Interp *interp, /* Used for error reporting. */
1074 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1075 * created by Tcl_ParseCommand. */
1076 Command *cmdPtr, /* Points to definition of command being
1077 * compiled. */
1078 CompileEnv *envPtr) /* Holds resulting instructions. */
1079 {
1080 DefineLineInformation; /* TIP #280 */
1081 Tcl_Token *idxTokenPtr, *valTokenPtr;
1082 int i, idx, numWords = parsePtr->numWords;
1083
1084 /*
1085 * Quit if not enough args.
1086 */
1087
1088 /* TODO: Consider support for compiling expanded args. */
1089 if (numWords <= 1) {
1090 return TCL_ERROR;
1091 }
1092
1093 valTokenPtr = TokenAfter(parsePtr->tokenPtr);
1094 if (numWords != 3) {
1095 goto emitComplexLindex;
1096 }
1097
1098 idxTokenPtr = TokenAfter(valTokenPtr);
1099 if (TclGetIndexFromToken(idxTokenPtr, TCL_INDEX_BEFORE, TCL_INDEX_BEFORE,
1100 &idx) == TCL_OK) {
1101 /*
1102 * The idxTokenPtr parsed as a valid index value and was
1103 * encoded as expected by INST_LIST_INDEX_IMM.
1104 *
1105 * NOTE: that we rely on indexing before a list producing the
1106 * same result as indexing after a list.
1107 */
1108
1109 CompileWord(envPtr, valTokenPtr, interp, 1);
1110 TclEmitInstInt4( INST_LIST_INDEX_IMM, idx, envPtr);
1111 return TCL_OK;
1112 }
1113
1114 /*
1115 * If the value was not known at compile time, the conversion failed or
1116 * the value was negative, we just keep on going with the more complex
1117 * compilation.
1118 */
1119
1120 /*
1121 * Push the operands onto the stack.
1122 */
1123
1124 emitComplexLindex:
1125 for (i=1 ; i<numWords ; i++) {
1126 CompileWord(envPtr, valTokenPtr, interp, i);
1127 valTokenPtr = TokenAfter(valTokenPtr);
1128 }
1129
1130 /*
1131 * Emit INST_LIST_INDEX if objc==3, or INST_LIST_INDEX_MULTI if there are
1132 * multiple index args.
1133 */
1134
1135 if (numWords == 3) {
1136 TclEmitOpcode( INST_LIST_INDEX, envPtr);
1137 } else {
1138 TclEmitInstInt4( INST_LIST_INDEX_MULTI, numWords-1, envPtr);
1139 }
1140
1141 return TCL_OK;
1142 }
1143
1144 /*
1145 *----------------------------------------------------------------------
1146 *
1147 * TclCompileListCmd --
1148 *
1149 * Procedure called to compile the "list" command.
1150 *
1151 * Results:
1152 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
1153 * evaluation to runtime.
1154 *
1155 * Side effects:
1156 * Instructions are added to envPtr to execute the "list" command at
1157 * runtime.
1158 *
1159 *----------------------------------------------------------------------
1160 */
1161
1162 int
1163 TclCompileListCmd(
1164 Tcl_Interp *interp, /* Used for error reporting. */
1165 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1166 * created by Tcl_ParseCommand. */
1167 Command *cmdPtr, /* Points to definition of command being
1168 * compiled. */
1169 CompileEnv *envPtr) /* Holds resulting instructions. */
1170 {
1171 DefineLineInformation; /* TIP #280 */
1172 Tcl_Token *valueTokenPtr;
1173 int i, numWords, concat, build;
1174 Tcl_Obj *listObj, *objPtr;
1175
1176 if (parsePtr->numWords == 1) {
1177 /*
1178 * [list] without arguments just pushes an empty object.
1179 */
1180
1181 PushStringLiteral(envPtr, "");
1182 return TCL_OK;
1183 }
1184
1185 /*
1186 * Test if all arguments are compile-time known. If they are, we can
1187 * implement with a simple push.
1188 */
1189
1190 numWords = parsePtr->numWords;
1191 valueTokenPtr = TokenAfter(parsePtr->tokenPtr);
1192 TclNewObj(listObj);
1193 for (i = 1; i < numWords && listObj != NULL; i++) {
1194 TclNewObj(objPtr);
1195 if (TclWordKnownAtCompileTime(valueTokenPtr, objPtr)) {
1196 (void) Tcl_ListObjAppendElement(NULL, listObj, objPtr);
1197 } else {
1198 Tcl_DecrRefCount(objPtr);
1199 Tcl_DecrRefCount(listObj);
1200 listObj = NULL;
1201 }
1202 valueTokenPtr = TokenAfter(valueTokenPtr);
1203 }
1204 if (listObj != NULL) {
1205 TclEmitPush(TclAddLiteralObj(envPtr, listObj, NULL), envPtr);
1206 return TCL_OK;
1207 }
1208
1209 /*
1210 * Push the all values onto the stack.
1211 */
1212
1213 numWords = parsePtr->numWords;
1214 valueTokenPtr = TokenAfter(parsePtr->tokenPtr);
1215 concat = build = 0;
1216 for (i = 1; i < numWords; i++) {
1217 if (valueTokenPtr->type == TCL_TOKEN_EXPAND_WORD && build > 0) {
1218 TclEmitInstInt4( INST_LIST, build, envPtr);
1219 if (concat) {
1220 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1221 }
1222 build = 0;
1223 concat = 1;
1224 }
1225 CompileWord(envPtr, valueTokenPtr, interp, i);
1226 if (valueTokenPtr->type == TCL_TOKEN_EXPAND_WORD) {
1227 if (concat) {
1228 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1229 } else {
1230 concat = 1;
1231 }
1232 } else {
1233 build++;
1234 }
1235 valueTokenPtr = TokenAfter(valueTokenPtr);
1236 }
1237 if (build > 0) {
1238 TclEmitInstInt4( INST_LIST, build, envPtr);
1239 if (concat) {
1240 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1241 }
1242 }
1243
1244 /*
1245 * If there was just one expanded word, we must ensure that it is a list
1246 * at this point. We use an [lrange ... 0 end] for this (instead of
1247 * [llength], as with literals) as we must drop any string representation
1248 * that might be hanging around.
1249 */
1250
1251 if (concat && numWords == 2) {
1252 TclEmitInstInt4( INST_LIST_RANGE_IMM, 0, envPtr);
1253 TclEmitInt4( TCL_INDEX_END, envPtr);
1254 }
1255 return TCL_OK;
1256 }
1257
1258 /*
1259 *----------------------------------------------------------------------
1260 *
1261 * TclCompileLlengthCmd --
1262 *
1263 * Procedure called to compile the "llength" command.
1264 *
1265 * Results:
1266 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
1267 * evaluation to runtime.
1268 *
1269 * Side effects:
1270 * Instructions are added to envPtr to execute the "llength" command at
1271 * runtime.
1272 *
1273 *----------------------------------------------------------------------
1274 */
1275
1276 int
1277 TclCompileLlengthCmd(
1278 Tcl_Interp *interp, /* Used for error reporting. */
1279 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1280 * created by Tcl_ParseCommand. */
1281 Command *cmdPtr, /* Points to definition of command being
1282 * compiled. */
1283 CompileEnv *envPtr) /* Holds resulting instructions. */
1284 {
1285 DefineLineInformation; /* TIP #280 */
1286 Tcl_Token *varTokenPtr;
1287
1288 if (parsePtr->numWords != 2) {
1289 return TCL_ERROR;
1290 }
1291 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
1292
1293 CompileWord(envPtr, varTokenPtr, interp, 1);
1294 TclEmitOpcode( INST_LIST_LENGTH, envPtr);
1295 return TCL_OK;
1296 }
1297
1298 /*
1299 *----------------------------------------------------------------------
1300 *
1301 * TclCompileLrangeCmd --
1302 *
1303 * How to compile the "lrange" command. We only bother because we needed
1304 * the opcode anyway for "lassign".
1305 *
1306 *----------------------------------------------------------------------
1307 */
1308
1309 int
1310 TclCompileLrangeCmd(
1311 Tcl_Interp *interp, /* Tcl interpreter for context. */
1312 Tcl_Parse *parsePtr, /* Points to a parse structure for the
1313 * command. */
1314 Command *cmdPtr, /* Points to definition of command being
1315 * compiled. */
1316 CompileEnv *envPtr) /* Holds the resulting instructions. */
1317 {
1318 DefineLineInformation; /* TIP #280 */
1319 Tcl_Token *tokenPtr, *listTokenPtr;
1320 int idx1, idx2;
1321
1322 if (parsePtr->numWords != 4) {
1323 return TCL_ERROR;
1324 }
1325 listTokenPtr = TokenAfter(parsePtr->tokenPtr);
1326
1327 tokenPtr = TokenAfter(listTokenPtr);
1328 if (TclGetIndexFromToken(tokenPtr, TCL_INDEX_START, TCL_INDEX_AFTER,
1329 &idx1) != TCL_OK) {
1330 return TCL_ERROR;
1331 }
1332 /*
1333 * Token was an index value, and we treat all "first" indices
1334 * before the list same as the start of the list.
1335 */
1336
1337 tokenPtr = TokenAfter(tokenPtr);
1338 if (TclGetIndexFromToken(tokenPtr, TCL_INDEX_BEFORE, TCL_INDEX_END,
1339 &idx2) != TCL_OK) {
1340 return TCL_ERROR;
1341 }
1342 /*
1343 * Token was an index value, and we treat all "last" indices
1344 * after the list same as the end of the list.
1345 */
1346
1347 /*
1348 * Issue instructions. It's not safe to skip doing the LIST_RANGE, as
1349 * we've not proved that the 'list' argument is really a list. Not that it
1350 * is worth trying to do that given current knowledge.
1351 */
1352
1353 CompileWord(envPtr, listTokenPtr, interp, 1);
1354 TclEmitInstInt4( INST_LIST_RANGE_IMM, idx1, envPtr);
1355 TclEmitInt4( idx2, envPtr);
1356 return TCL_OK;
1357 }
1358
1359 /*
1360 *----------------------------------------------------------------------
1361 *
1362 * TclCompileLinsertCmd --
1363 *
1364 * How to compile the "linsert" command. We only bother with the case
1365 * where the index is constant.
1366 *
1367 *----------------------------------------------------------------------
1368 */
1369
1370 int
1371 TclCompileLinsertCmd(
1372 Tcl_Interp *interp, /* Tcl interpreter for context. */
1373 Tcl_Parse *parsePtr, /* Points to a parse structure for the
1374 * command. */
1375 Command *cmdPtr, /* Points to definition of command being
1376 * compiled. */
1377 CompileEnv *envPtr) /* Holds the resulting instructions. */
1378 {
1379 DefineLineInformation; /* TIP #280 */
1380 Tcl_Token *tokenPtr, *listTokenPtr;
1381 int idx, i;
1382
1383 if (parsePtr->numWords < 3) {
1384 return TCL_ERROR;
1385 }
1386 listTokenPtr = TokenAfter(parsePtr->tokenPtr);
1387
1388 /*
1389 * Parse the index. Will only compile if it is constant and not an
1390 * _integer_ less than zero (since we reserve negative indices here for
1391 * end-relative indexing) or an end-based index greater than 'end' itself.
1392 */
1393
1394 tokenPtr = TokenAfter(listTokenPtr);
1395
1396 /*
1397 * NOTE: This command treats all inserts at indices before the list
1398 * the same as inserts at the start of the list, and all inserts
1399 * after the list the same as inserts at the end of the list. We
1400 * make that transformation here so we can use the optimized bytecode
1401 * as much as possible.
1402 */
1403 if (TclGetIndexFromToken(tokenPtr, TCL_INDEX_START, TCL_INDEX_END,
1404 &idx) != TCL_OK) {
1405 return TCL_ERROR;
1406 }
1407
1408 /*
1409 * There are four main cases. If there are no values to insert, this is
1410 * just a confirm-listiness check. If the index is '0', this is a prepend.
1411 * If the index is 'end' (== TCL_INDEX_END), this is an append. Otherwise,
1412 * this is a splice (== split, insert values as list, concat-3).
1413 */
1414
1415 CompileWord(envPtr, listTokenPtr, interp, 1);
1416 if (parsePtr->numWords == 3) {
1417 TclEmitInstInt4( INST_LIST_RANGE_IMM, 0, envPtr);
1418 TclEmitInt4( TCL_INDEX_END, envPtr);
1419 return TCL_OK;
1420 }
1421
1422 for (i=3 ; i<parsePtr->numWords ; i++) {
1423 tokenPtr = TokenAfter(tokenPtr);
1424 CompileWord(envPtr, tokenPtr, interp, i);
1425 }
1426 TclEmitInstInt4( INST_LIST, i-3, envPtr);
1427
1428 if (idx == TCL_INDEX_START) {
1429 TclEmitInstInt4( INST_REVERSE, 2, envPtr);
1430 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1431 } else if (idx == TCL_INDEX_END) {
1432 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1433 } else {
1434 /*
1435 * Here we handle two ranges for idx. First when idx > 0, we
1436 * want the first half of the split to end at index idx-1 and
1437 * the second half to start at index idx.
1438 * Second when idx < TCL_INDEX_END, indicating "end-N" indexing,
1439 * we want the first half of the split to end at index end-N and
1440 * the second half to start at index end-N+1. We accomplish this
1441 * with a preadjustment of the end-N value.
1442 * The root of this is that the commands [lrange] and [linsert]
1443 * differ in their interpretation of the "end" index.
1444 */
1445
1446 if (idx < TCL_INDEX_END) {
1447 idx++;
1448 }
1449 TclEmitInstInt4( INST_OVER, 1, envPtr);
1450 TclEmitInstInt4( INST_LIST_RANGE_IMM, 0, envPtr);
1451 TclEmitInt4( idx-1, envPtr);
1452 TclEmitInstInt4( INST_REVERSE, 3, envPtr);
1453 TclEmitInstInt4( INST_LIST_RANGE_IMM, idx, envPtr);
1454 TclEmitInt4( TCL_INDEX_END, envPtr);
1455 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1456 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1457 }
1458
1459 return TCL_OK;
1460 }
1461
1462 /*
1463 *----------------------------------------------------------------------
1464 *
1465 * TclCompileLreplaceCmd --
1466 *
1467 * How to compile the "lreplace" command. We only bother with the case
1468 * where the indices are constant.
1469 *
1470 *----------------------------------------------------------------------
1471 */
1472
1473 int
1474 TclCompileLreplaceCmd(
1475 Tcl_Interp *interp, /* Tcl interpreter for context. */
1476 Tcl_Parse *parsePtr, /* Points to a parse structure for the
1477 * command. */
1478 Command *cmdPtr, /* Points to definition of command being
1479 * compiled. */
1480 CompileEnv *envPtr) /* Holds the resulting instructions. */
1481 {
1482 DefineLineInformation; /* TIP #280 */
1483 Tcl_Token *tokenPtr, *listTokenPtr;
1484 int idx1, idx2, i;
1485 int emptyPrefix=1, suffixStart = 0;
1486
1487 if (parsePtr->numWords < 4) {
1488 return TCL_ERROR;
1489 }
1490 listTokenPtr = TokenAfter(parsePtr->tokenPtr);
1491
1492 tokenPtr = TokenAfter(listTokenPtr);
1493 if (TclGetIndexFromToken(tokenPtr, TCL_INDEX_START, TCL_INDEX_AFTER,
1494 &idx1) != TCL_OK) {
1495 return TCL_ERROR;
1496 }
1497
1498 tokenPtr = TokenAfter(tokenPtr);
1499 if (TclGetIndexFromToken(tokenPtr, TCL_INDEX_BEFORE, TCL_INDEX_END,
1500 &idx2) != TCL_OK) {
1501 return TCL_ERROR;
1502 }
1503
1504 /*
1505 * General structure of the [lreplace] result is
1506 * prefix replacement suffix
1507 * In a few cases we can predict various parts will be empty and
1508 * take advantage.
1509 *
1510 * The proper suffix begins with the greater of indices idx1 or
1511 * idx2 + 1. If we cannot tell at compile time which is greater,
1512 * we must defer to direct evaluation.
1513 */
1514
1515 if (idx1 == TCL_INDEX_AFTER) {
1516 suffixStart = idx1;
1517 } else if (idx2 == TCL_INDEX_BEFORE) {
1518 suffixStart = idx1;
1519 } else if (idx2 == TCL_INDEX_END) {
1520 suffixStart = TCL_INDEX_AFTER;
1521 } else if (((idx2 < TCL_INDEX_END) && (idx1 <= TCL_INDEX_END))
1522 || ((idx2 >= TCL_INDEX_START) && (idx1 >= TCL_INDEX_START))) {
1523 suffixStart = (idx1 > idx2 + 1) ? idx1 : idx2 + 1;
1524 } else {
1525 return TCL_ERROR;
1526 }
1527
1528 /* All paths start with computing/pushing the original value. */
1529 CompileWord(envPtr, listTokenPtr, interp, 1);
1530
1531 /*
1532 * Push all the replacement values next so any errors raised in
1533 * creating them get raised first.
1534 */
1535 if (parsePtr->numWords > 4) {
1536 /* Push the replacement arguments */
1537 tokenPtr = TokenAfter(tokenPtr);
1538 for (i=4 ; i<parsePtr->numWords ; i++) {
1539 CompileWord(envPtr, tokenPtr, interp, i);
1540 tokenPtr = TokenAfter(tokenPtr);
1541 }
1542
1543 /* Make a list of them... */
1544 TclEmitInstInt4( INST_LIST, i - 4, envPtr);
1545
1546 emptyPrefix = 0;
1547 }
1548
1549 if ((idx1 == suffixStart) && (parsePtr->numWords == 4)) {
1550 /*
1551 * This is a "no-op". Example: [lreplace {a b c} 2 0]
1552 * We still do a list operation to get list-verification
1553 * and canonicalization side effects.
1554 */
1555 TclEmitInstInt4( INST_LIST_RANGE_IMM, 0, envPtr);
1556 TclEmitInt4( TCL_INDEX_END, envPtr);
1557 return TCL_OK;
1558 }
1559
1560 if (idx1 != TCL_INDEX_START) {
1561 /* Prefix may not be empty; generate bytecode to push it */
1562 if (emptyPrefix) {
1563 TclEmitOpcode( INST_DUP, envPtr);
1564 } else {
1565 TclEmitInstInt4( INST_OVER, 1, envPtr);
1566 }
1567 TclEmitInstInt4( INST_LIST_RANGE_IMM, 0, envPtr);
1568 TclEmitInt4( idx1 - 1, envPtr);
1569 if (!emptyPrefix) {
1570 TclEmitInstInt4( INST_REVERSE, 2, envPtr);
1571 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1572 }
1573 emptyPrefix = 0;
1574 }
1575
1576 if (!emptyPrefix) {
1577 TclEmitInstInt4( INST_REVERSE, 2, envPtr);
1578 }
1579
1580 if (suffixStart == TCL_INDEX_AFTER) {
1581 TclEmitOpcode( INST_POP, envPtr);
1582 if (emptyPrefix) {
1583 PushStringLiteral(envPtr, "");
1584 }
1585 } else {
1586 /* Suffix may not be empty; generate bytecode to push it */
1587 TclEmitInstInt4( INST_LIST_RANGE_IMM, suffixStart, envPtr);
1588 TclEmitInt4( TCL_INDEX_END, envPtr);
1589 if (!emptyPrefix) {
1590 TclEmitOpcode( INST_LIST_CONCAT, envPtr);
1591 }
1592 }
1593
1594 return TCL_OK;
1595 }
1596
1597 /*
1598 *----------------------------------------------------------------------
1599 *
1600 * TclCompileLsetCmd --
1601 *
1602 * Procedure called to compile the "lset" command.
1603 *
1604 * Results:
1605 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
1606 * evaluation to runtime.
1607 *
1608 * Side effects:
1609 * Instructions are added to envPtr to execute the "lset" command at
1610 * runtime.
1611 *
1612 * The general template for execution of the "lset" command is:
1613 * (1) Instructions to push the variable name, unless the variable is
1614 * local to the stack frame.
1615 * (2) If the variable is an array element, instructions to push the
1616 * array element name.
1617 * (3) Instructions to push each of zero or more "index" arguments to the
1618 * stack, followed with the "newValue" element.
1619 * (4) Instructions to duplicate the variable name and/or array element
1620 * name onto the top of the stack, if either was pushed at steps (1)
1621 * and (2).
1622 * (5) The appropriate INST_LOAD_* instruction to place the original
1623 * value of the list variable at top of stack.
1624 * (6) At this point, the stack contains:
1625 * varName? arrayElementName? index1 index2 ... newValue oldList
1626 * The compiler emits one of INST_LSET_FLAT or INST_LSET_LIST
1627 * according as whether there is exactly one index element (LIST) or
1628 * either zero or else two or more (FLAT). This instruction removes
1629 * everything from the stack except for the two names and pushes the
1630 * new value of the variable.
1631 * (7) Finally, INST_STORE_* stores the new value in the variable and
1632 * cleans up the stack.
1633 *
1634 *----------------------------------------------------------------------
1635 */
1636
1637 int
1638 TclCompileLsetCmd(
1639 Tcl_Interp *interp, /* Tcl interpreter for error reporting. */
1640 Tcl_Parse *parsePtr, /* Points to a parse structure for the
1641 * command. */
1642 Command *cmdPtr, /* Points to definition of command being
1643 * compiled. */
1644 CompileEnv *envPtr) /* Holds the resulting instructions. */
1645 {
1646 DefineLineInformation; /* TIP #280 */
1647 int tempDepth; /* Depth used for emitting one part of the
1648 * code burst. */
1649 Tcl_Token *varTokenPtr; /* Pointer to the Tcl_Token representing the
1650 * parse of the variable name. */
1651 int localIndex; /* Index of var in local var table. */
1652 int isScalar; /* Flag == 1 if scalar, 0 if array. */
1653 int i;
1654
1655 /*
1656 * Check argument count.
1657 */
1658
1659 /* TODO: Consider support for compiling expanded args. */
1660 if (parsePtr->numWords < 3) {
1661 /*
1662 * Fail at run time, not in compilation.
1663 */
1664
1665 return TCL_ERROR;
1666 }
1667
1668 /*
1669 * Decide if we can use a frame slot for the var/array name or if we need
1670 * to emit code to compute and push the name at runtime. We use a frame
1671 * slot (entry in the array of local vars) if we are compiling a procedure
1672 * body and if the name is simple text that does not include namespace
1673 * qualifiers.
1674 */
1675
1676 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
1677 PushVarNameWord(interp, varTokenPtr, envPtr, 0,
1678 &localIndex, &isScalar, 1);
1679
1680 /*
1681 * Push the "index" args and the new element value.
1682 */
1683
1684 for (i=2 ; i<parsePtr->numWords ; ++i) {
1685 varTokenPtr = TokenAfter(varTokenPtr);
1686 CompileWord(envPtr, varTokenPtr, interp, i);
1687 }
1688
1689 /*
1690 * Duplicate the variable name if it's been pushed.
1691 */
1692
1693 if (localIndex < 0) {
1694 if (isScalar) {
1695 tempDepth = parsePtr->numWords - 2;
1696 } else {
1697 tempDepth = parsePtr->numWords - 1;
1698 }
1699 TclEmitInstInt4( INST_OVER, tempDepth, envPtr);
1700 }
1701
1702 /*
1703 * Duplicate an array index if one's been pushed.
1704 */
1705
1706 if (!isScalar) {
1707 if (localIndex < 0) {
1708 tempDepth = parsePtr->numWords - 1;
1709 } else {
1710 tempDepth = parsePtr->numWords - 2;
1711 }
1712 TclEmitInstInt4( INST_OVER, tempDepth, envPtr);
1713 }
1714
1715 /*
1716 * Emit code to load the variable's value.
1717 */
1718
1719 if (isScalar) {
1720 if (localIndex < 0) {
1721 TclEmitOpcode( INST_LOAD_STK, envPtr);
1722 } else {
1723 Emit14Inst( INST_LOAD_SCALAR, localIndex, envPtr);
1724 }
1725 } else {
1726 if (localIndex < 0) {
1727 TclEmitOpcode( INST_LOAD_ARRAY_STK, envPtr);
1728 } else {
1729 Emit14Inst( INST_LOAD_ARRAY, localIndex, envPtr);
1730 }
1731 }
1732
1733 /*
1734 * Emit the correct variety of 'lset' instruction.
1735 */
1736
1737 if (parsePtr->numWords == 4) {
1738 TclEmitOpcode( INST_LSET_LIST, envPtr);
1739 } else {
1740 TclEmitInstInt4( INST_LSET_FLAT, parsePtr->numWords-1, envPtr);
1741 }
1742
1743 /*
1744 * Emit code to put the value back in the variable.
1745 */
1746
1747 if (isScalar) {
1748 if (localIndex < 0) {
1749 TclEmitOpcode( INST_STORE_STK, envPtr);
1750 } else {
1751 Emit14Inst( INST_STORE_SCALAR, localIndex, envPtr);
1752 }
1753 } else {
1754 if (localIndex < 0) {
1755 TclEmitOpcode( INST_STORE_ARRAY_STK, envPtr);
1756 } else {
1757 Emit14Inst( INST_STORE_ARRAY, localIndex, envPtr);
1758 }
1759 }
1760
1761 return TCL_OK;
1762 }
1763
1764 /*
1765 *----------------------------------------------------------------------
1766 *
1767 * TclCompileNamespace*Cmd --
1768 *
1769 * Procedures called to compile the "namespace" command; currently, only
1770 * the subcommands "namespace current" and "namespace upvar" are compiled
1771 * to bytecodes, and the latter only inside a procedure(-like) context.
1772 *
1773 * Results:
1774 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
1775 * evaluation to runtime.
1776 *
1777 * Side effects:
1778 * Instructions are added to envPtr to execute the "namespace upvar"
1779 * command at runtime.
1780 *
1781 *----------------------------------------------------------------------
1782 */
1783
1784 int
1785 TclCompileNamespaceCurrentCmd(
1786 Tcl_Interp *interp, /* Used for error reporting. */
1787 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1788 * created by Tcl_ParseCommand. */
1789 Command *cmdPtr, /* Points to definition of command being
1790 * compiled. */
1791 CompileEnv *envPtr) /* Holds resulting instructions. */
1792 {
1793 /*
1794 * Only compile [namespace current] without arguments.
1795 */
1796
1797 if (parsePtr->numWords != 1) {
1798 return TCL_ERROR;
1799 }
1800
1801 /*
1802 * Not much to do; we compile to a single instruction...
1803 */
1804
1805 TclEmitOpcode( INST_NS_CURRENT, envPtr);
1806 return TCL_OK;
1807 }
1808
1809 int
1810 TclCompileNamespaceCodeCmd(
1811 Tcl_Interp *interp, /* Used for error reporting. */
1812 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1813 * created by Tcl_ParseCommand. */
1814 Command *cmdPtr, /* Points to definition of command being
1815 * compiled. */
1816 CompileEnv *envPtr) /* Holds resulting instructions. */
1817 {
1818 DefineLineInformation; /* TIP #280 */
1819 Tcl_Token *tokenPtr;
1820
1821 if (parsePtr->numWords != 2) {
1822 return TCL_ERROR;
1823 }
1824 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1825
1826 /*
1827 * The specification of [namespace code] is rather shocking, in that it is
1828 * supposed to check if the argument is itself the result of [namespace
1829 * code] and not apply itself in that case. Which is excessively cautious,
1830 * but what the test suite checks for.
1831 */
1832
1833 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD || (tokenPtr[1].size > 20
1834 && strncmp(tokenPtr[1].start, "::namespace inscope ", 20) == 0)) {
1835 /*
1836 * Technically, we could just pass a literal '::namespace inscope '
1837 * term through, but that's something which really shouldn't be
1838 * occurring as something that the user writes so we'll just punt it.
1839 */
1840
1841 return TCL_ERROR;
1842 }
1843
1844 /*
1845 * Now we can compile using the same strategy as [namespace code]'s normal
1846 * implementation does internally. Note that we can't bind the namespace
1847 * name directly here, because TclOO plays complex games with namespaces;
1848 * the value needs to be determined at runtime for safety.
1849 */
1850
1851 PushStringLiteral(envPtr, "::namespace");
1852 PushStringLiteral(envPtr, "inscope");
1853 TclEmitOpcode( INST_NS_CURRENT, envPtr);
1854 CompileWord(envPtr, tokenPtr, interp, 1);
1855 TclEmitInstInt4( INST_LIST, 4, envPtr);
1856 return TCL_OK;
1857 }
1858
1859 int
1860 TclCompileNamespaceOriginCmd(
1861 Tcl_Interp *interp, /* Used for error reporting. */
1862 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1863 * created by Tcl_ParseCommand. */
1864 Command *cmdPtr, /* Points to definition of command being
1865 * compiled. */
1866 CompileEnv *envPtr) /* Holds resulting instructions. */
1867 {
1868 DefineLineInformation; /* TIP #280 */
1869 Tcl_Token *tokenPtr;
1870
1871 if (parsePtr->numWords != 2) {
1872 return TCL_ERROR;
1873 }
1874 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1875
1876 CompileWord(envPtr, tokenPtr, interp, 1);
1877 TclEmitOpcode( INST_ORIGIN_COMMAND, envPtr);
1878 return TCL_OK;
1879 }
1880
1881 int
1882 TclCompileNamespaceQualifiersCmd(
1883 Tcl_Interp *interp, /* Used for error reporting. */
1884 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1885 * created by Tcl_ParseCommand. */
1886 Command *cmdPtr, /* Points to definition of command being
1887 * compiled. */
1888 CompileEnv *envPtr) /* Holds resulting instructions. */
1889 {
1890 DefineLineInformation; /* TIP #280 */
1891 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
1892 int off;
1893
1894 if (parsePtr->numWords != 2) {
1895 return TCL_ERROR;
1896 }
1897
1898 CompileWord(envPtr, tokenPtr, interp, 1);
1899 PushStringLiteral(envPtr, "0");
1900 PushStringLiteral(envPtr, "::");
1901 TclEmitInstInt4( INST_OVER, 2, envPtr);
1902 TclEmitOpcode( INST_STR_FIND_LAST, envPtr);
1903 off = CurrentOffset(envPtr);
1904 PushStringLiteral(envPtr, "1");
1905 TclEmitOpcode( INST_SUB, envPtr);
1906 TclEmitInstInt4( INST_OVER, 2, envPtr);
1907 TclEmitInstInt4( INST_OVER, 1, envPtr);
1908 TclEmitOpcode( INST_STR_INDEX, envPtr);
1909 PushStringLiteral(envPtr, ":");
1910 TclEmitOpcode( INST_STR_EQ, envPtr);
1911 off = off - CurrentOffset(envPtr);
1912 TclEmitInstInt1( INST_JUMP_TRUE1, off, envPtr);
1913 TclEmitOpcode( INST_STR_RANGE, envPtr);
1914 return TCL_OK;
1915 }
1916
1917 int
1918 TclCompileNamespaceTailCmd(
1919 Tcl_Interp *interp, /* Used for error reporting. */
1920 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1921 * created by Tcl_ParseCommand. */
1922 Command *cmdPtr, /* Points to definition of command being
1923 * compiled. */
1924 CompileEnv *envPtr) /* Holds resulting instructions. */
1925 {
1926 DefineLineInformation; /* TIP #280 */
1927 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
1928 JumpFixup jumpFixup;
1929
1930 if (parsePtr->numWords != 2) {
1931 return TCL_ERROR;
1932 }
1933
1934 /*
1935 * Take care; only add 2 to found index if the string was actually found.
1936 */
1937
1938 CompileWord(envPtr, tokenPtr, interp, 1);
1939 PushStringLiteral(envPtr, "::");
1940 TclEmitInstInt4( INST_OVER, 1, envPtr);
1941 TclEmitOpcode( INST_STR_FIND_LAST, envPtr);
1942 TclEmitOpcode( INST_DUP, envPtr);
1943 PushStringLiteral(envPtr, "0");
1944 TclEmitOpcode( INST_GE, envPtr);
1945 TclEmitForwardJump(envPtr, TCL_FALSE_JUMP, &jumpFixup);
1946 PushStringLiteral(envPtr, "2");
1947 TclEmitOpcode( INST_ADD, envPtr);
1948 TclFixupForwardJumpToHere(envPtr, &jumpFixup, 127);
1949 PushStringLiteral(envPtr, "end");
1950 TclEmitOpcode( INST_STR_RANGE, envPtr);
1951 return TCL_OK;
1952 }
1953
1954 int
1955 TclCompileNamespaceUpvarCmd(
1956 Tcl_Interp *interp, /* Used for error reporting. */
1957 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1958 * created by Tcl_ParseCommand. */
1959 Command *cmdPtr, /* Points to definition of command being
1960 * compiled. */
1961 CompileEnv *envPtr) /* Holds resulting instructions. */
1962 {
1963 DefineLineInformation; /* TIP #280 */
1964 Tcl_Token *tokenPtr, *otherTokenPtr, *localTokenPtr;
1965 int localIndex, numWords, i;
1966
1967 if (envPtr->procPtr == NULL) {
1968 return TCL_ERROR;
1969 }
1970
1971 /*
1972 * Only compile [namespace upvar ...]: needs an even number of args, >=4
1973 */
1974
1975 numWords = parsePtr->numWords;
1976 if ((numWords % 2) || (numWords < 4)) {
1977 return TCL_ERROR;
1978 }
1979
1980 /*
1981 * Push the namespace
1982 */
1983
1984 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1985 CompileWord(envPtr, tokenPtr, interp, 1);
1986
1987 /*
1988 * Loop over the (otherVar, thisVar) pairs. If any of the thisVar is not a
1989 * local variable, return an error so that the non-compiled command will
1990 * be called at runtime.
1991 */
1992
1993 localTokenPtr = tokenPtr;
1994 for (i=2; i<numWords; i+=2) {
1995 otherTokenPtr = TokenAfter(localTokenPtr);
1996 localTokenPtr = TokenAfter(otherTokenPtr);
1997
1998 CompileWord(envPtr, otherTokenPtr, interp, i);
1999 localIndex = LocalScalarFromToken(localTokenPtr, envPtr);
2000 if (localIndex < 0) {
2001 return TCL_ERROR;
2002 }
2003 TclEmitInstInt4( INST_NSUPVAR, localIndex, envPtr);
2004 }
2005
2006 /*
2007 * Pop the namespace, and set the result to empty
2008 */
2009
2010 TclEmitOpcode( INST_POP, envPtr);
2011 PushStringLiteral(envPtr, "");
2012 return TCL_OK;
2013 }
2014
2015 int
2016 TclCompileNamespaceWhichCmd(
2017 Tcl_Interp *interp, /* Used for error reporting. */
2018 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2019 * created by Tcl_ParseCommand. */
2020 Command *cmdPtr, /* Points to definition of command being
2021 * compiled. */
2022 CompileEnv *envPtr) /* Holds resulting instructions. */
2023 {
2024 DefineLineInformation; /* TIP #280 */
2025 Tcl_Token *tokenPtr, *opt;
2026 int idx;
2027
2028 if (parsePtr->numWords < 2 || parsePtr->numWords > 3) {
2029 return TCL_ERROR;
2030 }
2031 tokenPtr = TokenAfter(parsePtr->tokenPtr);
2032 idx = 1;
2033
2034 /*
2035 * If there's an option, check that it's "-command". We don't handle
2036 * "-variable" (currently) and anything else is an error.
2037 */
2038
2039 if (parsePtr->numWords == 3) {
2040 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2041 return TCL_ERROR;
2042 }
2043 opt = tokenPtr + 1;
2044 if (opt->size < 2 || opt->size > 8
2045 || strncmp(opt->start, "-command", opt->size) != 0) {
2046 return TCL_ERROR;
2047 }
2048 tokenPtr = TokenAfter(tokenPtr);
2049 idx++;
2050 }
2051
2052 /*
2053 * Issue the bytecode.
2054 */
2055
2056 CompileWord(envPtr, tokenPtr, interp, idx);
2057 TclEmitOpcode( INST_RESOLVE_COMMAND, envPtr);
2058 return TCL_OK;
2059 }
2060
2061 /*
2062 *----------------------------------------------------------------------
2063 *
2064 * TclCompileRegexpCmd --
2065 *
2066 * Procedure called to compile the "regexp" command.
2067 *
2068 * Results:
2069 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2070 * evaluation to runtime.
2071 *
2072 * Side effects:
2073 * Instructions are added to envPtr to execute the "regexp" command at
2074 * runtime.
2075 *
2076 *----------------------------------------------------------------------
2077 */
2078
2079 int
2080 TclCompileRegexpCmd(
2081 Tcl_Interp *interp, /* Tcl interpreter for error reporting. */
2082 Tcl_Parse *parsePtr, /* Points to a parse structure for the
2083 * command. */
2084 Command *cmdPtr, /* Points to definition of command being
2085 * compiled. */
2086 CompileEnv *envPtr) /* Holds the resulting instructions. */
2087 {
2088 DefineLineInformation; /* TIP #280 */
2089 Tcl_Token *varTokenPtr; /* Pointer to the Tcl_Token representing the
2090 * parse of the RE or string. */
2091 int len;
2092 int i, nocase, exact, sawLast, simple;
2093 const char *str;
2094
2095 /*
2096 * We are only interested in compiling simple regexp cases. Currently
2097 * supported compile cases are:
2098 * regexp ?-nocase? ?--? staticString $var
2099 * regexp ?-nocase? ?--? {^staticString$} $var
2100 */
2101
2102 if (parsePtr->numWords < 3) {
2103 return TCL_ERROR;
2104 }
2105
2106 simple = 0;
2107 nocase = 0;
2108 sawLast = 0;
2109 varTokenPtr = parsePtr->tokenPtr;
2110
2111 /*
2112 * We only look for -nocase and -- as options. Everything else gets pushed
2113 * to runtime execution. This is different than regexp's runtime option
2114 * handling, but satisfies our stricter needs.
2115 */
2116
2117 for (i = 1; i < parsePtr->numWords - 2; i++) {
2118 varTokenPtr = TokenAfter(varTokenPtr);
2119 if (varTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2120 /*
2121 * Not a simple string, so punt to runtime.
2122 */
2123
2124 return TCL_ERROR;
2125 }
2126 str = varTokenPtr[1].start;
2127 len = varTokenPtr[1].size;
2128 if ((len == 2) && (str[0] == '-') && (str[1] == '-')) {
2129 sawLast++;
2130 i++;
2131 break;
2132 } else if ((len > 1) && (strncmp(str, "-nocase", len) == 0)) {
2133 nocase = 1;
2134 } else {
2135 /*
2136 * Not an option we recognize.
2137 */
2138
2139 return TCL_ERROR;
2140 }
2141 }
2142
2143 if ((parsePtr->numWords - i) != 2) {
2144 /*
2145 * We don't support capturing to variables.
2146 */
2147
2148 return TCL_ERROR;
2149 }
2150
2151 /*
2152 * Get the regexp string. If it is not a simple string or can't be
2153 * converted to a glob pattern, push the word for the INST_REGEXP.
2154 * Keep changes here in sync with TclCompileSwitchCmd Switch_Regexp.
2155 */
2156
2157 varTokenPtr = TokenAfter(varTokenPtr);
2158
2159 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2160 Tcl_DString ds;
2161
2162 str = varTokenPtr[1].start;
2163 len = varTokenPtr[1].size;
2164
2165 /*
2166 * If it has a '-', it could be an incorrectly formed regexp command.
2167 */
2168
2169 if ((*str == '-') && !sawLast) {
2170 return TCL_ERROR;
2171 }
2172
2173 /*
2174 * Note: do not optimize for len == 0, as error should be generated
2175 * at runtime if operand is not a resolvable variable.
2176 * Bug https://core.tcl-lang.org/tcl/info/cb03e57a7b24d22c
2177 */
2178
2179 /*
2180 * Attempt to convert pattern to glob. If successful, push the
2181 * converted pattern as a literal.
2182 */
2183
2184 if (TclReToGlob(NULL, varTokenPtr[1].start, len, &ds, &exact, NULL)
2185 == TCL_OK) {
2186 simple = 1;
2187 PushLiteral(envPtr, Tcl_DStringValue(&ds),Tcl_DStringLength(&ds));
2188 Tcl_DStringFree(&ds);
2189 }
2190 }
2191
2192 if (!simple) {
2193 CompileWord(envPtr, varTokenPtr, interp, parsePtr->numWords - 2);
2194 }
2195
2196 /*
2197 * Push the string arg.
2198 */
2199
2200 varTokenPtr = TokenAfter(varTokenPtr);
2201 CompileWord(envPtr, varTokenPtr, interp, parsePtr->numWords - 1);
2202
2203 if (simple) {
2204 if (exact && !nocase) {
2205 TclEmitOpcode( INST_STR_EQ, envPtr);
2206 } else {
2207 TclEmitInstInt1( INST_STR_MATCH, nocase, envPtr);
2208 }
2209 } else {
2210 /*
2211 * Pass correct RE compile flags. We use only Int1 (8-bit), but
2212 * that handles all the flags we want to pass.
2213 * Don't use TCL_REG_NOSUB as we may have backrefs.
2214 */
2215
2216 int cflags = TCL_REG_ADVANCED | (nocase ? TCL_REG_NOCASE : 0);
2217
2218 TclEmitInstInt1( INST_REGEXP, cflags, envPtr);
2219 }
2220
2221 return TCL_OK;
2222 }
2223
2224 /*
2225 *----------------------------------------------------------------------
2226 *
2227 * TclCompileRegsubCmd --
2228 *
2229 * Procedure called to compile the "regsub" command.
2230 *
2231 * Results:
2232 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2233 * evaluation to runtime.
2234 *
2235 * Side effects:
2236 * Instructions are added to envPtr to execute the "regsub" command at
2237 * runtime.
2238 *
2239 *----------------------------------------------------------------------
2240 */
2241
2242 int
2243 TclCompileRegsubCmd(
2244 Tcl_Interp *interp, /* Tcl interpreter for error reporting. */
2245 Tcl_Parse *parsePtr, /* Points to a parse structure for the
2246 * command. */
2247 Command *cmdPtr, /* Points to definition of command being
2248 * compiled. */
2249 CompileEnv *envPtr) /* Holds the resulting instructions. */
2250 {
2251 /*
2252 * We only compile the case with [regsub -all] where the pattern is both
2253 * known at compile time and simple (i.e., no RE metacharacters). That is,
2254 * the pattern must be translatable into a glob like "*foo*" with no other
2255 * glob metacharacters inside it; there must be some "foo" in there too.
2256 * The substitution string must also be known at compile time and free of
2257 * metacharacters ("\digit" and "&"). Finally, there must not be a
2258 * variable mentioned in the [regsub] to write the result back to (because
2259 * we can't get the count of substitutions that would be the result in
2260 * that case). The key is that these are the conditions under which a
2261 * [string map] could be used instead, in particular a [string map] of the
2262 * form we can compile to bytecode.
2263 *
2264 * In short, we look for:
2265 *
2266 * regsub -all [--] simpleRE string simpleReplacement
2267 *
2268 * The only optional part is the "--", and no other options are handled.
2269 */
2270
2271 DefineLineInformation; /* TIP #280 */
2272 Tcl_Token *tokenPtr, *stringTokenPtr;
2273 Tcl_Obj *patternObj = NULL, *replacementObj = NULL;
2274 Tcl_DString pattern;
2275 const char *bytes;
2276 int exact, quantified, result = TCL_ERROR;
2277 int len;
2278
2279 if (parsePtr->numWords < 5 || parsePtr->numWords > 6) {
2280 return TCL_ERROR;
2281 }
2282
2283 /*
2284 * Parse the "-all", which must be the first argument (other options not
2285 * supported, non-"-all" substitution we can't compile).
2286 */
2287
2288 tokenPtr = TokenAfter(parsePtr->tokenPtr);
2289 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD || tokenPtr[1].size != 4
2290 || strncmp(tokenPtr[1].start, "-all", 4)) {
2291 return TCL_ERROR;
2292 }
2293
2294 /*
2295 * Get the pattern into patternObj, checking for "--" in the process.
2296 */
2297
2298 Tcl_DStringInit(&pattern);
2299 tokenPtr = TokenAfter(tokenPtr);
2300 TclNewObj(patternObj);
2301 if (!TclWordKnownAtCompileTime(tokenPtr, patternObj)) {
2302 goto done;
2303 }
2304 if (Tcl_GetString(patternObj)[0] == '-') {
2305 if (strcmp(Tcl_GetString(patternObj), "--") != 0
2306 || parsePtr->numWords == 5) {
2307 goto done;
2308 }
2309 tokenPtr = TokenAfter(tokenPtr);
2310 Tcl_DecrRefCount(patternObj);
2311 TclNewObj(patternObj);
2312 if (!TclWordKnownAtCompileTime(tokenPtr, patternObj)) {
2313 goto done;
2314 }
2315 } else if (parsePtr->numWords == 6) {
2316 goto done;
2317 }
2318
2319 /*
2320 * Identify the code which produces the string to apply the substitution
2321 * to (stringTokenPtr), and the replacement string (into replacementObj).
2322 */
2323
2324 stringTokenPtr = TokenAfter(tokenPtr);
2325 tokenPtr = TokenAfter(stringTokenPtr);
2326 TclNewObj(replacementObj);
2327 if (!TclWordKnownAtCompileTime(tokenPtr, replacementObj)) {
2328 goto done;
2329 }
2330
2331 /*
2332 * Next, higher-level checks. Is the RE a very simple glob? Is the
2333 * replacement "simple"?
2334 */
2335
2336 bytes = Tcl_GetStringFromObj(patternObj, &len);
2337 if (TclReToGlob(NULL, bytes, len, &pattern, &exact, &quantified)
2338 != TCL_OK || exact || quantified) {
2339 goto done;
2340 }
2341 bytes = Tcl_DStringValue(&pattern);
2342 if (*bytes++ != '*') {
2343 goto done;
2344 }
2345 while (1) {
2346 switch (*bytes) {
2347 case '*':
2348 if (bytes[1] == '\0') {
2349 /*
2350 * OK, we've proved there are no metacharacters except for the
2351 * '*' at each end.
2352 */
2353
2354 len = Tcl_DStringLength(&pattern) - 2;
2355 if (len > 0) {
2356 goto isSimpleGlob;
2357 }
2358
2359 /*
2360 * The pattern is "**"! I believe that should be impossible,
2361 * but we definitely can't handle that at all.
2362 */
2363 }
2364 case '\0': case '?': case '[': case '\\':
2365 goto done;
2366 }
2367 bytes++;
2368 }
2369 isSimpleGlob:
2370 for (bytes = Tcl_GetString(replacementObj); *bytes; bytes++) {
2371 switch (*bytes) {
2372 case '\\': case '&':
2373 goto done;
2374 }
2375 }
2376
2377 /*
2378 * Proved the simplicity constraints! Time to issue the code.
2379 */
2380
2381 result = TCL_OK;
2382 bytes = Tcl_DStringValue(&pattern) + 1;
2383 PushLiteral(envPtr, bytes, len);
2384 bytes = Tcl_GetStringFromObj(replacementObj, &len);
2385 PushLiteral(envPtr, bytes, len);
2386 CompileWord(envPtr, stringTokenPtr, interp, parsePtr->numWords - 2);
2387 TclEmitOpcode( INST_STR_MAP, envPtr);
2388
2389 done:
2390 Tcl_DStringFree(&pattern);
2391 if (patternObj) {
2392 Tcl_DecrRefCount(patternObj);
2393 }
2394 if (replacementObj) {
2395 Tcl_DecrRefCount(replacementObj);
2396 }
2397 return result;
2398 }
2399
2400 /*
2401 *----------------------------------------------------------------------
2402 *
2403 * TclCompileReturnCmd --
2404 *
2405 * Procedure called to compile the "return" command.
2406 *
2407 * Results:
2408 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2409 * evaluation to runtime.
2410 *
2411 * Side effects:
2412 * Instructions are added to envPtr to execute the "return" command at
2413 * runtime.
2414 *
2415 *----------------------------------------------------------------------
2416 */
2417
2418 int
2419 TclCompileReturnCmd(
2420 Tcl_Interp *interp, /* Used for error reporting. */
2421 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2422 * created by Tcl_ParseCommand. */
2423 Command *cmdPtr, /* Points to definition of command being
2424 * compiled. */
2425 CompileEnv *envPtr) /* Holds resulting instructions. */
2426 {
2427 DefineLineInformation; /* TIP #280 */
2428 /*
2429 * General syntax: [return ?-option value ...? ?result?]
2430 * An even number of words means an explicit result argument is present.
2431 */
2432 int level, code, status = TCL_OK;
2433 int size;
2434 int numWords = parsePtr->numWords;
2435 int explicitResult = (0 == (numWords % 2));
2436 int objc, numOptionWords = numWords - 1 - explicitResult;
2437 Tcl_Obj *returnOpts, **objv;
2438 Tcl_Token *wordTokenPtr = TokenAfter(parsePtr->tokenPtr);
2439
2440 /*
2441 * Check for special case which can always be compiled:
2442 * return -options <opts> <msg>
2443 * Unlike the normal [return] compilation, this version does everything at
2444 * runtime so it can handle arbitrary words and not just literals. Note
2445 * that if INST_RETURN_STK wasn't already needed for something else
2446 * ('finally' clause processing) this piece of code would not be present.
2447 */
2448
2449 if ((numWords == 4) && (wordTokenPtr->type == TCL_TOKEN_SIMPLE_WORD)
2450 && (wordTokenPtr[1].size == 8)
2451 && (strncmp(wordTokenPtr[1].start, "-options", 8) == 0)) {
2452 Tcl_Token *optsTokenPtr = TokenAfter(wordTokenPtr);
2453 Tcl_Token *msgTokenPtr = TokenAfter(optsTokenPtr);
2454
2455 CompileWord(envPtr, optsTokenPtr, interp, 2);
2456 CompileWord(envPtr, msgTokenPtr, interp, 3);
2457 TclEmitInvoke(envPtr, INST_RETURN_STK);
2458 return TCL_OK;
2459 }
2460
2461 /*
2462 * Allocate some working space.
2463 */
2464
2465 objv = (Tcl_Obj **)TclStackAlloc(interp, numOptionWords * sizeof(Tcl_Obj *));
2466
2467 /*
2468 * Scan through the return options. If any are unknown at compile time,
2469 * there is no value in bytecompiling. Save the option values known in an
2470 * objv array for merging into a return options dictionary.
2471 *
2472 * TODO: There is potential for improvement if all option keys are known
2473 * at compile time and all option values relating to '-code' and '-level'
2474 * are known at compile time.
2475 */
2476
2477 for (objc = 0; objc < numOptionWords; objc++) {
2478 TclNewObj(objv[objc]);
2479 Tcl_IncrRefCount(objv[objc]);
2480 if (!TclWordKnownAtCompileTime(wordTokenPtr, objv[objc])) {
2481 /*
2482 * Non-literal, so punt to run-time assembly of the dictionary.
2483 */
2484
2485 for (; objc>=0 ; objc--) {
2486 TclDecrRefCount(objv[objc]);
2487 }
2488 TclStackFree(interp, objv);
2489 goto issueRuntimeReturn;
2490 }
2491 wordTokenPtr = TokenAfter(wordTokenPtr);
2492 }
2493 status = TclMergeReturnOptions(interp, objc, objv,
2494 &returnOpts, &code, &level);
2495 while (--objc >= 0) {
2496 TclDecrRefCount(objv[objc]);
2497 }
2498 TclStackFree(interp, objv);
2499 if (TCL_ERROR == status) {
2500 /*
2501 * Something was bogus in the return options. Clear the error message,
2502 * and report back to the compiler that this must be interpreted at
2503 * runtime.
2504 */
2505
2506 Tcl_ResetResult(interp);
2507 return TCL_ERROR;
2508 }
2509
2510 /*
2511 * All options are known at compile time, so we're going to bytecompile.
2512 * Emit instructions to push the result on the stack.
2513 */
2514
2515 if (explicitResult) {
2516 CompileWord(envPtr, wordTokenPtr, interp, numWords - 1);
2517 } else {
2518 /*
2519 * No explict result argument, so default result is empty string.
2520 */
2521
2522 PushStringLiteral(envPtr, "");
2523 }
2524
2525 /*
2526 * Check for optimization: When [return] is in a proc, and there's no
2527 * enclosing [catch], and there are no return options, then the INST_DONE
2528 * instruction is equivalent, and may be more efficient.
2529 */
2530
2531 if (numOptionWords == 0 && envPtr->procPtr != NULL) {
2532 /*
2533 * We have default return options and we're in a proc ...
2534 */
2535
2536 int index = envPtr->exceptArrayNext - 1;
2537 int enclosingCatch = 0;
2538
2539 while (index >= 0) {
2540 ExceptionRange range = envPtr->exceptArrayPtr[index];
2541
2542 if ((range.type == CATCH_EXCEPTION_RANGE)
2543 && (range.catchOffset == -1)) {
2544 enclosingCatch = 1;
2545 break;
2546 }
2547 index--;
2548 }
2549 if (!enclosingCatch) {
2550 /*
2551 * ... and there is no enclosing catch. Issue the maximally
2552 * efficient exit instruction.
2553 */
2554
2555 Tcl_DecrRefCount(returnOpts);
2556 TclEmitOpcode(INST_DONE, envPtr);
2557 TclAdjustStackDepth(1, envPtr);
2558 return TCL_OK;
2559 }
2560 }
2561
2562 /* Optimize [return -level 0 $x]. */
2563 Tcl_DictObjSize(NULL, returnOpts, &size);
2564 if (size == 0 && level == 0 && code == TCL_OK) {
2565 Tcl_DecrRefCount(returnOpts);
2566 return TCL_OK;
2567 }
2568
2569 /*
2570 * Could not use the optimization, so we push the return options dict, and
2571 * emit the INST_RETURN_IMM instruction with code and level as operands.
2572 */
2573
2574 CompileReturnInternal(envPtr, INST_RETURN_IMM, code, level, returnOpts);
2575 return TCL_OK;
2576
2577 issueRuntimeReturn:
2578 /*
2579 * Assemble the option dictionary (as a list as that's good enough).
2580 */
2581
2582 wordTokenPtr = TokenAfter(parsePtr->tokenPtr);
2583 for (objc=1 ; objc<=numOptionWords ; objc++) {
2584 CompileWord(envPtr, wordTokenPtr, interp, objc);
2585 wordTokenPtr = TokenAfter(wordTokenPtr);
2586 }
2587 TclEmitInstInt4(INST_LIST, numOptionWords, envPtr);
2588
2589 /*
2590 * Push the result.
2591 */
2592
2593 if (explicitResult) {
2594 CompileWord(envPtr, wordTokenPtr, interp, numWords - 1);
2595 } else {
2596 PushStringLiteral(envPtr, "");
2597 }
2598
2599 /*
2600 * Issue the RETURN itself.
2601 */
2602
2603 TclEmitInvoke(envPtr, INST_RETURN_STK);
2604 return TCL_OK;
2605 }
2606
2607 static void
2608 CompileReturnInternal(
2609 CompileEnv *envPtr,
2610 unsigned char op,
2611 int code,
2612 int level,
2613 Tcl_Obj *returnOpts)
2614 {
2615 if (level == 0 && (code == TCL_BREAK || code == TCL_CONTINUE)) {
2616 ExceptionRange *rangePtr;
2617 ExceptionAux *exceptAux;
2618
2619 rangePtr = TclGetInnermostExceptionRange(envPtr, code, &exceptAux);
2620 if (rangePtr && rangePtr->type == LOOP_EXCEPTION_RANGE) {
2621 TclCleanupStackForBreakContinue(envPtr, exceptAux);
2622 if (code == TCL_BREAK) {
2623 TclAddLoopBreakFixup(envPtr, exceptAux);
2624 } else {
2625 TclAddLoopContinueFixup(envPtr, exceptAux);
2626 }
2627 Tcl_DecrRefCount(returnOpts);
2628 return;
2629 }
2630 }
2631
2632 TclEmitPush(TclAddLiteralObj(envPtr, returnOpts, NULL), envPtr);
2633 TclEmitInstInt4(op, code, envPtr);
2634 TclEmitInt4(level, envPtr);
2635 }
2636
2637 void
2638 TclCompileSyntaxError(
2639 Tcl_Interp *interp,
2640 CompileEnv *envPtr)
2641 {
2642 Tcl_Obj *msg = Tcl_GetObjResult(interp);
2643 int numBytes;
2644 const char *bytes = TclGetStringFromObj(msg, &numBytes);
2645
2646 TclErrorStackResetIf(interp, bytes, numBytes);
2647 TclEmitPush(TclRegisterNewLiteral(envPtr, bytes, numBytes), envPtr);
2648 CompileReturnInternal(envPtr, INST_SYNTAX, TCL_ERROR, 0,
2649 TclNoErrorStack(interp, Tcl_GetReturnOptions(interp, TCL_ERROR)));
2650 Tcl_ResetResult(interp);
2651 }
2652
2653 /*
2654 *----------------------------------------------------------------------
2655 *
2656 * TclCompileUpvarCmd --
2657 *
2658 * Procedure called to compile the "upvar" command.
2659 *
2660 * Results:
2661 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2662 * evaluation to runtime.
2663 *
2664 * Side effects:
2665 * Instructions are added to envPtr to execute the "upvar" command at
2666 * runtime.
2667 *
2668 *----------------------------------------------------------------------
2669 */
2670
2671 int
2672 TclCompileUpvarCmd(
2673 Tcl_Interp *interp, /* Used for error reporting. */
2674 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2675 * created by Tcl_ParseCommand. */
2676 Command *cmdPtr, /* Points to definition of command being
2677 * compiled. */
2678 CompileEnv *envPtr) /* Holds resulting instructions. */
2679 {
2680 DefineLineInformation; /* TIP #280 */
2681 Tcl_Token *tokenPtr, *otherTokenPtr, *localTokenPtr;
2682 int localIndex, numWords, i;
2683 Tcl_Obj *objPtr;
2684
2685 if (envPtr->procPtr == NULL) {
2686 return TCL_ERROR;
2687 }
2688
2689 numWords = parsePtr->numWords;
2690 if (numWords < 3) {
2691 return TCL_ERROR;
2692 }
2693
2694 /*
2695 * Push the frame index if it is known at compile time
2696 */
2697
2698 TclNewObj(objPtr);
2699 tokenPtr = TokenAfter(parsePtr->tokenPtr);
2700 if (TclWordKnownAtCompileTime(tokenPtr, objPtr)) {
2701 CallFrame *framePtr;
2702 const Tcl_ObjType *newTypePtr, *typePtr = objPtr->typePtr;
2703
2704 /*
2705 * Attempt to convert to a level reference. Note that TclObjGetFrame
2706 * only changes the obj type when a conversion was successful.
2707 */
2708
2709 TclObjGetFrame(interp, objPtr, &framePtr);
2710 newTypePtr = objPtr->typePtr;
2711 Tcl_DecrRefCount(objPtr);
2712
2713 if (newTypePtr != typePtr) {
2714 if (numWords%2) {
2715 return TCL_ERROR;
2716 }
2717 /* TODO: Push the known value instead? */
2718 CompileWord(envPtr, tokenPtr, interp, 1);
2719 otherTokenPtr = TokenAfter(tokenPtr);
2720 i = 2;
2721 } else {
2722 if (!(numWords%2)) {
2723 return TCL_ERROR;
2724 }
2725 PushStringLiteral(envPtr, "1");
2726 otherTokenPtr = tokenPtr;
2727 i = 1;
2728 }
2729 } else {
2730 Tcl_DecrRefCount(objPtr);
2731 return TCL_ERROR;
2732 }
2733
2734 /*
2735 * Loop over the (otherVar, thisVar) pairs. If any of the thisVar is not a
2736 * local variable, return an error so that the non-compiled command will
2737 * be called at runtime.
2738 */
2739
2740 for (; i<numWords; i+=2, otherTokenPtr = TokenAfter(localTokenPtr)) {
2741 localTokenPtr = TokenAfter(otherTokenPtr);
2742
2743 CompileWord(envPtr, otherTokenPtr, interp, i);
2744 localIndex = LocalScalarFromToken(localTokenPtr, envPtr);
2745 if (localIndex < 0) {
2746 return TCL_ERROR;
2747 }
2748 TclEmitInstInt4( INST_UPVAR, localIndex, envPtr);
2749 }
2750
2751 /*
2752 * Pop the frame index, and set the result to empty
2753 */
2754
2755 TclEmitOpcode( INST_POP, envPtr);
2756 PushStringLiteral(envPtr, "");
2757 return TCL_OK;
2758 }
2759
2760 /*
2761 *----------------------------------------------------------------------
2762 *
2763 * TclCompileVariableCmd --
2764 *
2765 * Procedure called to compile the "variable" command.
2766 *
2767 * Results:
2768 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2769 * evaluation to runtime.
2770 *
2771 * Side effects:
2772 * Instructions are added to envPtr to execute the "variable" command at
2773 * runtime.
2774 *
2775 *----------------------------------------------------------------------
2776 */
2777
2778 int
2779 TclCompileVariableCmd(
2780 Tcl_Interp *interp, /* Used for error reporting. */
2781 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2782 * created by Tcl_ParseCommand. */
2783 Command *cmdPtr, /* Points to definition of command being
2784 * compiled. */
2785 CompileEnv *envPtr) /* Holds resulting instructions. */
2786 {
2787 DefineLineInformation; /* TIP #280 */
2788 Tcl_Token *varTokenPtr, *valueTokenPtr;
2789 int localIndex, numWords, i;
2790
2791 numWords = parsePtr->numWords;
2792 if (numWords < 2) {
2793 return TCL_ERROR;
2794 }
2795
2796 /*
2797 * Bail out if not compiling a proc body
2798 */
2799
2800 if (envPtr->procPtr == NULL) {
2801 return TCL_ERROR;
2802 }
2803
2804 /*
2805 * Loop over the (var, value) pairs.
2806 */
2807
2808 valueTokenPtr = parsePtr->tokenPtr;
2809 for (i=1; i<numWords; i+=2) {
2810 varTokenPtr = TokenAfter(valueTokenPtr);
2811 valueTokenPtr = TokenAfter(varTokenPtr);
2812
2813 localIndex = IndexTailVarIfKnown(interp, varTokenPtr, envPtr);
2814
2815 if (localIndex < 0) {
2816 return TCL_ERROR;
2817 }
2818
2819 /* TODO: Consider what value can pass through the
2820 * IndexTailVarIfKnown() screen. Full CompileWord()
2821 * likely does not apply here. Push known value instead. */
2822 CompileWord(envPtr, varTokenPtr, interp, i);
2823 TclEmitInstInt4( INST_VARIABLE, localIndex, envPtr);
2824
2825 if (i + 1 < numWords) {
2826 /*
2827 * A value has been given: set the variable, pop the value
2828 */
2829
2830 CompileWord(envPtr, valueTokenPtr, interp, i + 1);
2831 Emit14Inst( INST_STORE_SCALAR, localIndex, envPtr);
2832 TclEmitOpcode( INST_POP, envPtr);
2833 }
2834 }
2835
2836 /*
2837 * Set the result to empty
2838 */
2839
2840 PushStringLiteral(envPtr, "");
2841 return TCL_OK;
2842 }
2843
2844 /*
2845 *----------------------------------------------------------------------
2846 *
2847 * IndexTailVarIfKnown --
2848 *
2849 * Procedure used in compiling [global] and [variable] commands. It
2850 * inspects the variable name described by varTokenPtr and, if the tail
2851 * is known at compile time, defines a corresponding local variable.
2852 *
2853 * Results:
2854 * Returns the variable's index in the table of compiled locals if the
2855 * tail is known at compile time, or -1 otherwise.
2856 *
2857 * Side effects:
2858 * None.
2859 *
2860 *----------------------------------------------------------------------
2861 */
2862
2863 static int
2864 IndexTailVarIfKnown(
2865 Tcl_Interp *interp,
2866 Tcl_Token *varTokenPtr, /* Token representing the variable name */
2867 CompileEnv *envPtr) /* Holds resulting instructions. */
2868 {
2869 Tcl_Obj *tailPtr;
2870 const char *tailName, *p;
2871 int n = varTokenPtr->numComponents;
2872 int len;
2873 Tcl_Token *lastTokenPtr;
2874 int full, localIndex;
2875
2876 /*
2877 * Determine if the tail is (a) known at compile time, and (b) not an
2878 * array element. Should any of these fail, return an error so that the
2879 * non-compiled command will be called at runtime.
2880 *
2881 * In order for the tail to be known at compile time, the last token in
2882 * the word has to be constant and contain "::" if it is not the only one.
2883 */
2884
2885 if (!EnvHasLVT(envPtr)) {
2886 return -1;
2887 }
2888
2889 TclNewObj(tailPtr);
2890 if (TclWordKnownAtCompileTime(varTokenPtr, tailPtr)) {
2891 full = 1;
2892 lastTokenPtr = varTokenPtr;
2893 } else {
2894 full = 0;
2895 lastTokenPtr = varTokenPtr + n;
2896
2897 if (lastTokenPtr->type != TCL_TOKEN_TEXT) {
2898 Tcl_DecrRefCount(tailPtr);
2899 return -1;
2900 }
2901 Tcl_SetStringObj(tailPtr, lastTokenPtr->start, lastTokenPtr->size);
2902 }
2903
2904 tailName = TclGetStringFromObj(tailPtr, &len);
2905
2906 if (len) {
2907 if (*(tailName + len - 1) == ')') {
2908 /*
2909 * Possible array: bail out
2910 */
2911
2912 Tcl_DecrRefCount(tailPtr);
2913 return -1;
2914 }
2915
2916 /*
2917 * Get the tail: immediately after the last '::'
2918 */
2919
2920 for (p = tailName + len -1; p > tailName; p--) {
2921 if ((*p == ':') && (*(p - 1) == ':')) {
2922 p++;
2923 break;
2924 }
2925 }
2926 if (!full && (p == tailName)) {
2927 /*
2928 * No :: in the last component.
2929 */
2930
2931 Tcl_DecrRefCount(tailPtr);
2932 return -1;
2933 }
2934 len -= p - tailName;
2935 tailName = p;
2936 }
2937
2938 localIndex = TclFindCompiledLocal(tailName, len, 1, envPtr);
2939 Tcl_DecrRefCount(tailPtr);
2940 return localIndex;
2941 }
2942
2943 /*
2944 * ----------------------------------------------------------------------
2945 *
2946 * TclCompileObjectNextCmd, TclCompileObjectSelfCmd --
2947 *
2948 * Compilations of the TclOO utility commands [next] and [self].
2949 *
2950 * ----------------------------------------------------------------------
2951 */
2952
2953 int
2954 TclCompileObjectNextCmd(
2955 Tcl_Interp *interp, /* Used for error reporting. */
2956 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2957 * created by Tcl_ParseCommand. */
2958 Command *cmdPtr, /* Points to definition of command being
2959 * compiled. */
2960 CompileEnv *envPtr) /* Holds resulting instructions. */
2961 {
2962 DefineLineInformation; /* TIP #280 */
2963 Tcl_Token *tokenPtr = parsePtr->tokenPtr;
2964 int i;
2965
2966 if (parsePtr->numWords > 255) {
2967 return TCL_ERROR;
2968 }
2969
2970 for (i=0 ; i<parsePtr->numWords ; i++) {
2971 CompileWord(envPtr, tokenPtr, interp, i);
2972 tokenPtr = TokenAfter(tokenPtr);
2973 }
2974 TclEmitInstInt1( INST_TCLOO_NEXT, i, envPtr);
2975 return TCL_OK;
2976 }
2977
2978 int
2979 TclCompileObjectNextToCmd(
2980 Tcl_Interp *interp, /* Used for error reporting. */
2981 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2982 * created by Tcl_ParseCommand. */
2983 Command *cmdPtr, /* Points to definition of command being
2984 * compiled. */
2985 CompileEnv *envPtr) /* Holds resulting instructions. */
2986 {
2987 DefineLineInformation; /* TIP #280 */
2988 Tcl_Token *tokenPtr = parsePtr->tokenPtr;
2989 int i;
2990
2991 if (parsePtr->numWords < 2 || parsePtr->numWords > 255) {
2992 return TCL_ERROR;
2993 }
2994
2995 for (i=0 ; i<parsePtr->numWords ; i++) {
2996 CompileWord(envPtr, tokenPtr, interp, i);
2997 tokenPtr = TokenAfter(tokenPtr);
2998 }
2999 TclEmitInstInt1( INST_TCLOO_NEXT_CLASS, i, envPtr);
3000 return TCL_OK;
3001 }
3002
3003 int
3004 TclCompileObjectSelfCmd(
3005 Tcl_Interp *interp, /* Used for error reporting. */
3006 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3007 * created by Tcl_ParseCommand. */
3008 Command *cmdPtr, /* Points to definition of command being
3009 * compiled. */
3010 CompileEnv *envPtr) /* Holds resulting instructions. */
3011 {
3012 /*
3013 * We only handle [self] and [self object] (which is the same operation).
3014 * These are the only very common operations on [self] for which
3015 * bytecoding is at all reasonable.
3016 */
3017
3018 if (parsePtr->numWords == 1) {
3019 goto compileSelfObject;
3020 } else if (parsePtr->numWords == 2) {
3021 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr), *subcmd;
3022
3023 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD || tokenPtr[1].size==0) {
3024 return TCL_ERROR;
3025 }
3026
3027 subcmd = tokenPtr + 1;
3028 if (strncmp(subcmd->start, "object", subcmd->size) == 0) {
3029 goto compileSelfObject;
3030 } else if (strncmp(subcmd->start, "namespace", subcmd->size) == 0) {
3031 goto compileSelfNamespace;
3032 }
3033 }
3034
3035 /*
3036 * Can't compile; handle with runtime call.
3037 */
3038
3039 return TCL_ERROR;
3040
3041 compileSelfObject:
3042
3043 /*
3044 * This delegates the entire problem to a single opcode.
3045 */
3046
3047 TclEmitOpcode( INST_TCLOO_SELF, envPtr);
3048 return TCL_OK;
3049
3050 compileSelfNamespace:
3051
3052 /*
3053 * This is formally only correct with TclOO methods as they are currently
3054 * implemented; it assumes that the current namespace is invariably when a
3055 * TclOO context is present is the object's namespace, and that's
3056 * technically only something that's a matter of current policy. But it
3057 * avoids creating another opcode, so that's all good!
3058 */
3059
3060 TclEmitOpcode( INST_TCLOO_SELF, envPtr);
3061 TclEmitOpcode( INST_POP, envPtr);
3062 TclEmitOpcode( INST_NS_CURRENT, envPtr);
3063 return TCL_OK;
3064 }
3065
3066 /*
3067 * Local Variables:
3068 * mode: c
3069 * c-basic-offset: 4
3070 * fill-column: 78
3071 * End:
3072 */