Debian Codegraph @

pTk/mTk/tclGeneric/tclCompCmds.c

raw symbols SCIP
1 /*
2 * tclCompCmds.c --
3 *
4 * This file contains compilation procedures that compile various
5 * Tcl commands into a sequence of instructions ("bytecodes").
6 *
7 * Copyright (c) 1997-1998 Sun Microsystems, Inc.
8 * Copyright (c) 2001 by Kevin B. Kenny. All rights reserved.
9 * Copyright (c) 2002 ActiveState Corporation.
10 *
11 * See the file "license.terms" for information on usage and redistribution
12 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 *
14 * RCS: @(#) $Id: tclCompCmds.c,v 1.39.2.2 2003/07/15 20:51:49 dgp Exp $
15 */
16
17 #include "tclInt.h"
18 #include "tclCompile.h"
19
20 /*
21 * Prototypes for procedures defined later in this file:
22 */
23
24 static ClientData DupForeachInfo _ANSI_ARGS_((ClientData clientData));
25 static void FreeForeachInfo _ANSI_ARGS_((ClientData clientData));
26 static int TclPushVarName _ANSI_ARGS_((Tcl_Interp *interp,
27 Tcl_Token *varTokenPtr, CompileEnv *envPtr, int flags,
28 int *localIndexPtr, int *simpleVarNamePtr, int *isScalarPtr));
29
30 /*
31 * Flags bits used by TclPushVarName.
32 */
33
34 #define TCL_CREATE_VAR 1 /* Create a compiled local if none is found */
35 #define TCL_NO_LARGE_INDEX 2 /* Do not return localIndex value > 255 */
36
37 /*
38 * The structures below define the AuxData types defined in this file.
39 */
40
41 AuxDataType tclForeachInfoType = {
42 "ForeachInfo", /* name */
43 DupForeachInfo, /* dupProc */
44 FreeForeachInfo /* freeProc */
45 };
46
47 /*
48 *----------------------------------------------------------------------
49 *
50 * TclCompileAppendCmd --
51 *
52 * Procedure called to compile the "append" command.
53 *
54 * Results:
55 * The return value is a standard Tcl result, which is normally TCL_OK
56 * unless there was an error while parsing string. If an error occurs
57 * then the interpreter's result contains a standard error message. If
58 * complation fails because the command requires a second level of
59 * substitutions, TCL_OUT_LINE_COMPILE is returned indicating that the
60 * command should be compiled "out of line" by emitting code to
61 * invoke its command procedure (Tcl_AppendObjCmd) at runtime.
62 *
63 * Side effects:
64 * Instructions are added to envPtr to execute the "append" command
65 * at runtime.
66 *
67 *----------------------------------------------------------------------
68 */
69
70 int
71 TclCompileAppendCmd(interp, parsePtr, envPtr)
72 Tcl_Interp *interp; /* Used for error reporting. */
73 Tcl_Parse *parsePtr; /* Points to a parse structure for the
74 * command created by Tcl_ParseCommand. */
75 CompileEnv *envPtr; /* Holds resulting instructions. */
76 {
77 Tcl_Token *varTokenPtr, *valueTokenPtr;
78 int simpleVarName, isScalar, localIndex, numWords;
79 int code = TCL_OK;
80
81 numWords = parsePtr->numWords;
82 if (numWords == 1) {
83 Tcl_ResetResult(interp);
84 Tcl_AppendToObj(Tcl_GetObjResult(interp),
85 "wrong # args: should be \"append varName ?value value ...?\"",
86 -1);
87 return TCL_ERROR;
88 } else if (numWords == 2) {
89 /*
90 * append varName === set varName
91 */
92 return TclCompileSetCmd(interp, parsePtr, envPtr);
93 } else if (numWords > 3) {
94 /*
95 * APPEND instructions currently only handle one value
96 */
97 return TCL_OUT_LINE_COMPILE;
98 }
99
100 /*
101 * Decide if we can use a frame slot for the var/array name or if we
102 * need to emit code to compute and push the name at runtime. We use a
103 * frame slot (entry in the array of local vars) if we are compiling a
104 * procedure body and if the name is simple text that does not include
105 * namespace qualifiers.
106 */
107
108 varTokenPtr = parsePtr->tokenPtr
109 + (parsePtr->tokenPtr->numComponents + 1);
110
111 code = TclPushVarName(interp, varTokenPtr, envPtr, TCL_CREATE_VAR,
112 &localIndex, &simpleVarName, &isScalar);
113 if (code != TCL_OK) {
114 goto done;
115 }
116
117 /*
118 * We are doing an assignment, otherwise TclCompileSetCmd was called,
119 * so push the new value. This will need to be extended to push a
120 * value for each argument.
121 */
122
123 if (numWords > 2) {
124 valueTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
125 if (valueTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
126 TclEmitPush(TclRegisterNewLiteral(envPtr,
127 valueTokenPtr[1].start, valueTokenPtr[1].size), envPtr);
128 } else {
129 code = TclCompileTokens(interp, valueTokenPtr+1,
130 valueTokenPtr->numComponents, envPtr);
131 if (code != TCL_OK) {
132 goto done;
133 }
134 }
135 }
136
137 /*
138 * Emit instructions to set/get the variable.
139 */
140
141 if (simpleVarName) {
142 if (isScalar) {
143 if (localIndex >= 0) {
144 if (localIndex <= 255) {
145 TclEmitInstInt1(INST_APPEND_SCALAR1, localIndex, envPtr);
146 } else {
147 TclEmitInstInt4(INST_APPEND_SCALAR4, localIndex, envPtr);
148 }
149 } else {
150 TclEmitOpcode(INST_APPEND_STK, envPtr);
151 }
152 } else {
153 if (localIndex >= 0) {
154 if (localIndex <= 255) {
155 TclEmitInstInt1(INST_APPEND_ARRAY1, localIndex, envPtr);
156 } else {
157 TclEmitInstInt4(INST_APPEND_ARRAY4, localIndex, envPtr);
158 }
159 } else {
160 TclEmitOpcode(INST_APPEND_ARRAY_STK, envPtr);
161 }
162 }
163 } else {
164 TclEmitOpcode(INST_APPEND_STK, envPtr);
165 }
166
167 done:
168 return code;
169 }
170
171 /*
172 *----------------------------------------------------------------------
173 *
174 * TclCompileBreakCmd --
175 *
176 * Procedure called to compile the "break" command.
177 *
178 * Results:
179 * The return value is a standard Tcl result, which is TCL_OK unless
180 * there was an error during compilation. If an error occurs then
181 * the interpreter's result contains a standard error message.
182 *
183 * Side effects:
184 * Instructions are added to envPtr to execute the "break" command
185 * at runtime.
186 *
187 *----------------------------------------------------------------------
188 */
189
190 int
191 TclCompileBreakCmd(interp, parsePtr, envPtr)
192 Tcl_Interp *interp; /* Used for error reporting. */
193 Tcl_Parse *parsePtr; /* Points to a parse structure for the
194 * command created by Tcl_ParseCommand. */
195 CompileEnv *envPtr; /* Holds resulting instructions. */
196 {
197 if (parsePtr->numWords != 1) {
198 Tcl_ResetResult(interp);
199 Tcl_AppendToObj(Tcl_GetObjResult(interp),
200 "wrong # args: should be \"break\"", -1);
201 return TCL_ERROR;
202 }
203
204 /*
205 * Emit a break instruction.
206 */
207
208 TclEmitOpcode(INST_BREAK, envPtr);
209 return TCL_OK;
210 }
211
212 /*
213 *----------------------------------------------------------------------
214 *
215 * TclCompileCatchCmd --
216 *
217 * Procedure called to compile the "catch" command.
218 *
219 * Results:
220 * The return value is a standard Tcl result, which is TCL_OK if
221 * compilation was successful. If an error occurs then the
222 * interpreter's result contains a standard error message and TCL_ERROR
223 * is returned. If the command is too complex for TclCompileCatchCmd,
224 * TCL_OUT_LINE_COMPILE is returned indicating that the catch command
225 * should be compiled "out of line" by emitting code to invoke its
226 * command procedure at runtime.
227 *
228 * Side effects:
229 * Instructions are added to envPtr to execute the "catch" command
230 * at runtime.
231 *
232 *----------------------------------------------------------------------
233 */
234
235 int
236 TclCompileCatchCmd(interp, parsePtr, envPtr)
237 Tcl_Interp *interp; /* Used for error reporting. */
238 Tcl_Parse *parsePtr; /* Points to a parse structure for the
239 * command created by Tcl_ParseCommand. */
240 CompileEnv *envPtr; /* Holds resulting instructions. */
241 {
242 JumpFixup jumpFixup;
243 Tcl_Token *cmdTokenPtr, *nameTokenPtr;
244 CONST char *name;
245 int localIndex, nameChars, range, startOffset, jumpDist;
246 int code;
247 int savedStackDepth = envPtr->currStackDepth;
248
249 if ((parsePtr->numWords != 2) && (parsePtr->numWords != 3)) {
250 Tcl_ResetResult(interp);
251 Tcl_AppendToObj(Tcl_GetObjResult(interp),
252 "wrong # args: should be \"catch command ?varName?\"", -1);
253 return TCL_ERROR;
254 }
255
256 /*
257 * If a variable was specified and the catch command is at global level
258 * (not in a procedure), don't compile it inline: the payoff is
259 * too small.
260 */
261
262 if ((parsePtr->numWords == 3) && (envPtr->procPtr == NULL)) {
263 return TCL_OUT_LINE_COMPILE;
264 }
265
266 /*
267 * Make sure the variable name, if any, has no substitutions and just
268 * refers to a local scaler.
269 */
270
271 localIndex = -1;
272 cmdTokenPtr = parsePtr->tokenPtr
273 + (parsePtr->tokenPtr->numComponents + 1);
274 if (parsePtr->numWords == 3) {
275 nameTokenPtr = cmdTokenPtr + (cmdTokenPtr->numComponents + 1);
276 if (nameTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
277 name = nameTokenPtr[1].start;
278 nameChars = nameTokenPtr[1].size;
279 if (!TclIsLocalScalar(name, nameChars)) {
280 return TCL_OUT_LINE_COMPILE;
281 }
282 localIndex = TclFindCompiledLocal(nameTokenPtr[1].start,
283 nameTokenPtr[1].size, /*create*/ 1,
284 /*flags*/ VAR_SCALAR, envPtr->procPtr);
285 } else {
286 return TCL_OUT_LINE_COMPILE;
287 }
288 }
289
290 /*
291 * We will compile the catch command. Emit a beginCatch instruction at
292 * the start of the catch body: the subcommand it controls.
293 */
294
295 envPtr->exceptDepth++;
296 envPtr->maxExceptDepth =
297 TclMax(envPtr->exceptDepth, envPtr->maxExceptDepth);
298 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
299 TclEmitInstInt4(INST_BEGIN_CATCH4, range, envPtr);
300
301 /*
302 * If the body is a simple word, compile the instructions to
303 * eval it. Otherwise, compile instructions to substitute its
304 * text without catching, a catch instruction that resets the
305 * stack to what it was before substituting the body, and then
306 * an instruction to eval the body. Care has to be taken to
307 * register the correct startOffset for the catch range so that
308 * errors in the substitution are not catched [Bug 219184]
309 */
310
311 if (cmdTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
312 startOffset = (envPtr->codeNext - envPtr->codeStart);
313 code = TclCompileCmdWord(interp, cmdTokenPtr+1, 1, envPtr);
314 } else {
315 code = TclCompileTokens(interp, cmdTokenPtr+1,
316 cmdTokenPtr->numComponents, envPtr);
317 startOffset = (envPtr->codeNext - envPtr->codeStart);
318 TclEmitOpcode(INST_EVAL_STK, envPtr);
319 }
320 envPtr->exceptArrayPtr[range].codeOffset = startOffset;
321
322 if (code != TCL_OK) {
323 code = TCL_OUT_LINE_COMPILE;
324 goto done;
325 }
326 envPtr->exceptArrayPtr[range].numCodeBytes =
327 (envPtr->codeNext - envPtr->codeStart) - startOffset;
328
329 /*
330 * The "no errors" epilogue code: store the body's result into the
331 * variable (if any), push "0" (TCL_OK) as the catch's "no error"
332 * result, and jump around the "error case" code.
333 */
334
335 if (localIndex != -1) {
336 if (localIndex <= 255) {
337 TclEmitInstInt1(INST_STORE_SCALAR1, localIndex, envPtr);
338 } else {
339 TclEmitInstInt4(INST_STORE_SCALAR4, localIndex, envPtr);
340 }
341 }
342 TclEmitOpcode(INST_POP, envPtr);
343 TclEmitPush(TclRegisterNewLiteral(envPtr, "0", 1), envPtr);
344 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpFixup);
345
346 /*
347 * The "error case" code: store the body's result into the variable (if
348 * any), then push the error result code. The initial PC offset here is
349 * the catch's error target.
350 */
351
352 envPtr->currStackDepth = savedStackDepth;
353 envPtr->exceptArrayPtr[range].catchOffset =
354 (envPtr->codeNext - envPtr->codeStart);
355 if (localIndex != -1) {
356 TclEmitOpcode(INST_PUSH_RESULT, envPtr);
357 if (localIndex <= 255) {
358 TclEmitInstInt1(INST_STORE_SCALAR1, localIndex, envPtr);
359 } else {
360 TclEmitInstInt4(INST_STORE_SCALAR4, localIndex, envPtr);
361 }
362 TclEmitOpcode(INST_POP, envPtr);
363 }
364 TclEmitOpcode(INST_PUSH_RETURN_CODE, envPtr);
365
366
367 /*
368 * Update the target of the jump after the "no errors" code, then emit
369 * an endCatch instruction at the end of the catch command.
370 */
371
372 jumpDist = (envPtr->codeNext - envPtr->codeStart)
373 - jumpFixup.codeOffset;
374 if (TclFixupForwardJump(envPtr, &jumpFixup, jumpDist, 127)) {
375 panic("TclCompileCatchCmd: bad jump distance %d\n", jumpDist);
376 }
377 TclEmitOpcode(INST_END_CATCH, envPtr);
378
379 done:
380 envPtr->currStackDepth = savedStackDepth + 1;
381 envPtr->exceptDepth--;
382 return code;
383 }
384
385 /*
386 *----------------------------------------------------------------------
387 *
388 * TclCompileContinueCmd --
389 *
390 * Procedure called to compile the "continue" command.
391 *
392 * Results:
393 * The return value is a standard Tcl result, which is TCL_OK unless
394 * there was an error while parsing string. If an error occurs then
395 * the interpreter's result contains a standard error message.
396 *
397 * Side effects:
398 * Instructions are added to envPtr to execute the "continue" command
399 * at runtime.
400 *
401 *----------------------------------------------------------------------
402 */
403
404 int
405 TclCompileContinueCmd(interp, parsePtr, envPtr)
406 Tcl_Interp *interp; /* Used for error reporting. */
407 Tcl_Parse *parsePtr; /* Points to a parse structure for the
408 * command created by Tcl_ParseCommand. */
409 CompileEnv *envPtr; /* Holds resulting instructions. */
410 {
411 /*
412 * There should be no argument after the "continue".
413 */
414
415 if (parsePtr->numWords != 1) {
416 Tcl_ResetResult(interp);
417 Tcl_AppendToObj(Tcl_GetObjResult(interp),
418 "wrong # args: should be \"continue\"", -1);
419 return TCL_ERROR;
420 }
421
422 /*
423 * Emit a continue instruction.
424 */
425
426 TclEmitOpcode(INST_CONTINUE, envPtr);
427 return TCL_OK;
428 }
429
430 /*
431 *----------------------------------------------------------------------
432 *
433 * TclCompileExprCmd --
434 *
435 * Procedure called to compile the "expr" command.
436 *
437 * Results:
438 * The return value is a standard Tcl result, which is TCL_OK
439 * unless there was an error while parsing string. If an error occurs
440 * then the interpreter's result contains a standard error message.
441 *
442 * Side effects:
443 * Instructions are added to envPtr to execute the "expr" command
444 * at runtime.
445 *
446 *----------------------------------------------------------------------
447 */
448
449 int
450 TclCompileExprCmd(interp, parsePtr, envPtr)
451 Tcl_Interp *interp; /* Used for error reporting. */
452 Tcl_Parse *parsePtr; /* Points to a parse structure for the
453 * command created by Tcl_ParseCommand. */
454 CompileEnv *envPtr; /* Holds resulting instructions. */
455 {
456 Tcl_Token *firstWordPtr;
457
458 if (parsePtr->numWords == 1) {
459 Tcl_ResetResult(interp);
460 Tcl_AppendToObj(Tcl_GetObjResult(interp),
461 "wrong # args: should be \"expr arg ?arg ...?\"", -1);
462 return TCL_ERROR;
463 }
464
465 firstWordPtr = parsePtr->tokenPtr
466 + (parsePtr->tokenPtr->numComponents + 1);
467 return TclCompileExprWords(interp, firstWordPtr, (parsePtr->numWords-1),
468 envPtr);
469 }
470
471 /*
472 *----------------------------------------------------------------------
473 *
474 * TclCompileForCmd --
475 *
476 * Procedure called to compile the "for" command.
477 *
478 * Results:
479 * The return value is a standard Tcl result, which is TCL_OK unless
480 * there was an error while parsing string. If an error occurs then
481 * the interpreter's result contains a standard error message.
482 *
483 * Side effects:
484 * Instructions are added to envPtr to execute the "for" command
485 * at runtime.
486 *
487 *----------------------------------------------------------------------
488 */
489 int
490 TclCompileForCmd(interp, parsePtr, envPtr)
491 Tcl_Interp *interp; /* Used for error reporting. */
492 Tcl_Parse *parsePtr; /* Points to a parse structure for the
493 * command created by Tcl_ParseCommand. */
494 CompileEnv *envPtr; /* Holds resulting instructions. */
495 {
496 Tcl_Token *startTokenPtr, *testTokenPtr, *nextTokenPtr, *bodyTokenPtr;
497 JumpFixup jumpEvalCondFixup;
498 int testCodeOffset, bodyCodeOffset, nextCodeOffset, jumpDist;
499 int bodyRange, nextRange, code;
500 char buffer[32 + TCL_INTEGER_SPACE];
501 int savedStackDepth = envPtr->currStackDepth;
502
503 if (parsePtr->numWords != 5) {
504 Tcl_ResetResult(interp);
505 Tcl_AppendToObj(Tcl_GetObjResult(interp),
506 "wrong # args: should be \"for start test next command\"", -1);
507 return TCL_ERROR;
508 }
509
510 /*
511 * If the test expression requires substitutions, don't compile the for
512 * command inline. E.g., the expression might cause the loop to never
513 * execute or execute forever, as in "for {} "$x > 5" {incr x} {}".
514 */
515
516 startTokenPtr = parsePtr->tokenPtr
517 + (parsePtr->tokenPtr->numComponents + 1);
518 testTokenPtr = startTokenPtr + (startTokenPtr->numComponents + 1);
519 if (testTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
520 return TCL_OUT_LINE_COMPILE;
521 }
522
523 /*
524 * Bail out also if the body or the next expression require substitutions
525 * in order to insure correct behaviour [Bug 219166]
526 */
527
528 nextTokenPtr = testTokenPtr + (testTokenPtr->numComponents + 1);
529 bodyTokenPtr = nextTokenPtr + (nextTokenPtr->numComponents + 1);
530 if ((nextTokenPtr->type != TCL_TOKEN_SIMPLE_WORD)
531 || (bodyTokenPtr->type != TCL_TOKEN_SIMPLE_WORD)) {
532 return TCL_OUT_LINE_COMPILE;
533 }
534
535 /*
536 * Create ExceptionRange records for the body and the "next" command.
537 * The "next" command's ExceptionRange supports break but not continue
538 * (and has a -1 continueOffset).
539 */
540
541 envPtr->exceptDepth++;
542 envPtr->maxExceptDepth =
543 TclMax(envPtr->exceptDepth, envPtr->maxExceptDepth);
544 bodyRange = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
545 nextRange = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
546
547 /*
548 * Inline compile the initial command.
549 */
550
551 code = TclCompileCmdWord(interp, startTokenPtr+1,
552 startTokenPtr->numComponents, envPtr);
553 if (code != TCL_OK) {
554 if (code == TCL_ERROR) {
555 Tcl_AddObjErrorInfo(interp,
556 "\n (\"for\" initial command)", -1);
557 }
558 goto done;
559 }
560 TclEmitOpcode(INST_POP, envPtr);
561
562 /*
563 * Jump to the evaluation of the condition. This code uses the "loop
564 * rotation" optimisation (which eliminates one branch from the loop).
565 * "for start cond next body" produces then:
566 * start
567 * goto A
568 * B: body : bodyCodeOffset
569 * next : nextCodeOffset, continueOffset
570 * A: cond -> result : testCodeOffset
571 * if (result) goto B
572 */
573
574 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpEvalCondFixup);
575
576 /*
577 * Compile the loop body.
578 */
579
580 bodyCodeOffset = (envPtr->codeNext - envPtr->codeStart);
581
582 code = TclCompileCmdWord(interp, bodyTokenPtr+1,
583 bodyTokenPtr->numComponents, envPtr);
584 envPtr->currStackDepth = savedStackDepth + 1;
585 if (code != TCL_OK) {
586 if (code == TCL_ERROR) {
587 sprintf(buffer, "\n (\"for\" body line %d)",
588 interp->errorLine);
589 Tcl_AddObjErrorInfo(interp, buffer, -1);
590 }
591 goto done;
592 }
593 envPtr->exceptArrayPtr[bodyRange].numCodeBytes =
594 (envPtr->codeNext - envPtr->codeStart) - bodyCodeOffset;
595 TclEmitOpcode(INST_POP, envPtr);
596
597
598 /*
599 * Compile the "next" subcommand.
600 */
601
602 nextCodeOffset = (envPtr->codeNext - envPtr->codeStart);
603
604 envPtr->currStackDepth = savedStackDepth;
605 code = TclCompileCmdWord(interp, nextTokenPtr+1,
606 nextTokenPtr->numComponents, envPtr);
607 envPtr->currStackDepth = savedStackDepth + 1;
608 if (code != TCL_OK) {
609 if (code == TCL_ERROR) {
610 Tcl_AddObjErrorInfo(interp,
611 "\n (\"for\" loop-end command)", -1);
612 }
613 goto done;
614 }
615 envPtr->exceptArrayPtr[nextRange].numCodeBytes =
616 (envPtr->codeNext - envPtr->codeStart)
617 - nextCodeOffset;
618 TclEmitOpcode(INST_POP, envPtr);
619 envPtr->currStackDepth = savedStackDepth;
620
621 /*
622 * Compile the test expression then emit the conditional jump that
623 * terminates the for.
624 */
625
626 testCodeOffset = (envPtr->codeNext - envPtr->codeStart);
627
628 jumpDist = testCodeOffset - jumpEvalCondFixup.codeOffset;
629 if (TclFixupForwardJump(envPtr, &jumpEvalCondFixup, jumpDist, 127)) {
630 bodyCodeOffset += 3;
631 nextCodeOffset += 3;
632 testCodeOffset += 3;
633 }
634
635 envPtr->currStackDepth = savedStackDepth;
636 code = TclCompileExprWords(interp, testTokenPtr, 1, envPtr);
637 if (code != TCL_OK) {
638 if (code == TCL_ERROR) {
639 Tcl_AddObjErrorInfo(interp,
640 "\n (\"for\" test expression)", -1);
641 }
642 goto done;
643 }
644 envPtr->currStackDepth = savedStackDepth + 1;
645
646 jumpDist = (envPtr->codeNext - envPtr->codeStart) - bodyCodeOffset;
647 if (jumpDist > 127) {
648 TclEmitInstInt4(INST_JUMP_TRUE4, -jumpDist, envPtr);
649 } else {
650 TclEmitInstInt1(INST_JUMP_TRUE1, -jumpDist, envPtr);
651 }
652
653 /*
654 * Set the loop's offsets and break target.
655 */
656
657 envPtr->exceptArrayPtr[bodyRange].codeOffset = bodyCodeOffset;
658 envPtr->exceptArrayPtr[bodyRange].continueOffset = nextCodeOffset;
659
660 envPtr->exceptArrayPtr[nextRange].codeOffset = nextCodeOffset;
661
662 envPtr->exceptArrayPtr[bodyRange].breakOffset =
663 envPtr->exceptArrayPtr[nextRange].breakOffset =
664 (envPtr->codeNext - envPtr->codeStart);
665
666 /*
667 * The for command's result is an empty string.
668 */
669
670 envPtr->currStackDepth = savedStackDepth;
671 TclEmitPush(TclRegisterNewLiteral(envPtr, "", 0), envPtr);
672 code = TCL_OK;
673
674 done:
675 envPtr->exceptDepth--;
676 return code;
677 }
678
679 /*
680 *----------------------------------------------------------------------
681 *
682 * TclCompileForeachCmd --
683 *
684 * Procedure called to compile the "foreach" command.
685 *
686 * Results:
687 * The return value is a standard Tcl result, which is TCL_OK if
688 * compilation was successful. If an error occurs then the
689 * interpreter's result contains a standard error message and TCL_ERROR
690 * is returned. If the command is too complex for TclCompileForeachCmd,
691 * TCL_OUT_LINE_COMPILE is returned indicating that the foreach command
692 * should be compiled "out of line" by emitting code to invoke its
693 * command procedure at runtime.
694 *
695 * Side effects:
696 * Instructions are added to envPtr to execute the "foreach" command
697 * at runtime.
698 *
699 n*----------------------------------------------------------------------
700 */
701
702 int
703 TclCompileForeachCmd(interp, parsePtr, envPtr)
704 Tcl_Interp *interp; /* Used for error reporting. */
705 Tcl_Parse *parsePtr; /* Points to a parse structure for the
706 * command created by Tcl_ParseCommand. */
707 CompileEnv *envPtr; /* Holds resulting instructions. */
708 {
709 Proc *procPtr = envPtr->procPtr;
710 ForeachInfo *infoPtr; /* Points to the structure describing this
711 * foreach command. Stored in a AuxData
712 * record in the ByteCode. */
713 int firstValueTemp; /* Index of the first temp var in the frame
714 * used to point to a value list. */
715 int loopCtTemp; /* Index of temp var holding the loop's
716 * iteration count. */
717 Tcl_Token *tokenPtr, *bodyTokenPtr;
718 unsigned char *jumpPc;
719 JumpFixup jumpFalseFixup;
720 int jumpDist, jumpBackDist, jumpBackOffset, infoIndex, range;
721 int numWords, numLists, numVars, loopIndex, tempVar, i, j, code;
722 char buffer[32 + TCL_INTEGER_SPACE];
723 int savedStackDepth = envPtr->currStackDepth;
724
725 /*
726 * We parse the variable list argument words and create two arrays:
727 * varcList[i] is number of variables in i-th var list
728 * varvList[i] points to array of var names in i-th var list
729 */
730
731 #define STATIC_VAR_LIST_SIZE 5
732 int varcListStaticSpace[STATIC_VAR_LIST_SIZE];
733 CONST char **varvListStaticSpace[STATIC_VAR_LIST_SIZE];
734 int *varcList = varcListStaticSpace;
735 CONST char ***varvList = varvListStaticSpace;
736
737 /*
738 * If the foreach command isn't in a procedure, don't compile it inline:
739 * the payoff is too small.
740 */
741
742 if (procPtr == NULL) {
743 return TCL_OUT_LINE_COMPILE;
744 }
745
746 numWords = parsePtr->numWords;
747 if ((numWords < 4) || (numWords%2 != 0)) {
748 Tcl_ResetResult(interp);
749 Tcl_AppendToObj(Tcl_GetObjResult(interp),
750 "wrong # args: should be \"foreach varList list ?varList list ...? command\"", -1);
751 return TCL_ERROR;
752 }
753
754 /*
755 * Bail out if the body requires substitutions
756 * in order to insure correct behaviour [Bug 219166]
757 */
758 for (i = 0, tokenPtr = parsePtr->tokenPtr;
759 i < numWords-1;
760 i++, tokenPtr += (tokenPtr->numComponents + 1)) {
761 }
762 bodyTokenPtr = tokenPtr;
763 if (bodyTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
764 return TCL_OUT_LINE_COMPILE;
765 }
766
767 /*
768 * Allocate storage for the varcList and varvList arrays if necessary.
769 */
770
771 numLists = (numWords - 2)/2;
772 if (numLists > STATIC_VAR_LIST_SIZE) {
773 varcList = (int *) ckalloc(numLists * sizeof(int));
774 varvList = (CONST char ***) ckalloc(numLists * sizeof(CONST char **));
775 }
776 for (loopIndex = 0; loopIndex < numLists; loopIndex++) {
777 varcList[loopIndex] = 0;
778 varvList[loopIndex] = NULL;
779 }
780
781 /*
782 * Set the exception stack depth.
783 */
784
785 envPtr->exceptDepth++;
786 envPtr->maxExceptDepth =
787 TclMax(envPtr->exceptDepth, envPtr->maxExceptDepth);
788
789 /*
790 * Break up each var list and set the varcList and varvList arrays.
791 * Don't compile the foreach inline if any var name needs substitutions
792 * or isn't a scalar, or if any var list needs substitutions.
793 */
794
795 loopIndex = 0;
796 for (i = 0, tokenPtr = parsePtr->tokenPtr;
797 i < numWords-1;
798 i++, tokenPtr += (tokenPtr->numComponents + 1)) {
799 if (i%2 == 1) {
800 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
801 code = TCL_OUT_LINE_COMPILE;
802 goto done;
803 } else {
804 /* Lots of copying going on here. Need a ListObj wizard
805 * to show a better way. */
806
807 Tcl_DString varList;
808
809 Tcl_DStringInit(&varList);
810 Tcl_DStringAppend(&varList, tokenPtr[1].start,
811 tokenPtr[1].size);
812 code = Tcl_SplitList(interp, Tcl_DStringValue(&varList),
813 &varcList[loopIndex], &varvList[loopIndex]);
814 Tcl_DStringFree(&varList);
815 if (code != TCL_OK) {
816 goto done;
817 }
818 numVars = varcList[loopIndex];
819 for (j = 0; j < numVars; j++) {
820 CONST char *varName = varvList[loopIndex][j];
821 if (!TclIsLocalScalar(varName, (int) strlen(varName))) {
822 code = TCL_OUT_LINE_COMPILE;
823 goto done;
824 }
825 }
826 }
827 loopIndex++;
828 }
829 }
830
831 /*
832 * We will compile the foreach command.
833 * Reserve (numLists + 1) temporary variables:
834 * - numLists temps to hold each value list
835 * - 1 temp for the loop counter (index of next element in each list)
836 * At this time we don't try to reuse temporaries; if there are two
837 * nonoverlapping foreach loops, they don't share any temps.
838 */
839
840 firstValueTemp = -1;
841 for (loopIndex = 0; loopIndex < numLists; loopIndex++) {
842 tempVar = TclFindCompiledLocal(NULL, /*nameChars*/ 0,
843 /*create*/ 1, /*flags*/ VAR_SCALAR, procPtr);
844 if (loopIndex == 0) {
845 firstValueTemp = tempVar;
846 }
847 }
848 loopCtTemp = TclFindCompiledLocal(NULL, /*nameChars*/ 0,
849 /*create*/ 1, /*flags*/ VAR_SCALAR, procPtr);
850
851 /*
852 * Create and initialize the ForeachInfo and ForeachVarList data
853 * structures describing this command. Then create a AuxData record
854 * pointing to the ForeachInfo structure.
855 */
856
857 infoPtr = (ForeachInfo *) ckalloc((unsigned)
858 (sizeof(ForeachInfo) + (numLists * sizeof(ForeachVarList *))));
859 infoPtr->numLists = numLists;
860 infoPtr->firstValueTemp = firstValueTemp;
861 infoPtr->loopCtTemp = loopCtTemp;
862 for (loopIndex = 0; loopIndex < numLists; loopIndex++) {
863 ForeachVarList *varListPtr;
864 numVars = varcList[loopIndex];
865 varListPtr = (ForeachVarList *) ckalloc((unsigned)
866 sizeof(ForeachVarList) + (numVars * sizeof(int)));
867 varListPtr->numVars = numVars;
868 for (j = 0; j < numVars; j++) {
869 CONST char *varName = varvList[loopIndex][j];
870 int nameChars = strlen(varName);
871 varListPtr->varIndexes[j] = TclFindCompiledLocal(varName,
872 nameChars, /*create*/ 1, /*flags*/ VAR_SCALAR, procPtr);
873 }
874 infoPtr->varLists[loopIndex] = varListPtr;
875 }
876 infoIndex = TclCreateAuxData((ClientData) infoPtr, &tclForeachInfoType, envPtr);
877
878 /*
879 * Evaluate then store each value list in the associated temporary.
880 */
881
882 range = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
883
884 loopIndex = 0;
885 for (i = 0, tokenPtr = parsePtr->tokenPtr;
886 i < numWords-1;
887 i++, tokenPtr += (tokenPtr->numComponents + 1)) {
888 if ((i%2 == 0) && (i > 0)) {
889 code = TclCompileTokens(interp, tokenPtr+1,
890 tokenPtr->numComponents, envPtr);
891 if (code != TCL_OK) {
892 goto done;
893 }
894
895 tempVar = (firstValueTemp + loopIndex);
896 if (tempVar <= 255) {
897 TclEmitInstInt1(INST_STORE_SCALAR1, tempVar, envPtr);
898 } else {
899 TclEmitInstInt4(INST_STORE_SCALAR4, tempVar, envPtr);
900 }
901 TclEmitOpcode(INST_POP, envPtr);
902 loopIndex++;
903 }
904 }
905
906 /*
907 * Initialize the temporary var that holds the count of loop iterations.
908 */
909
910 TclEmitInstInt4(INST_FOREACH_START4, infoIndex, envPtr);
911
912 /*
913 * Top of loop code: assign each loop variable and check whether
914 * to terminate the loop.
915 */
916
917 envPtr->exceptArrayPtr[range].continueOffset =
918 (envPtr->codeNext - envPtr->codeStart);
919 TclEmitInstInt4(INST_FOREACH_STEP4, infoIndex, envPtr);
920 TclEmitForwardJump(envPtr, TCL_FALSE_JUMP, &jumpFalseFixup);
921
922 /*
923 * Inline compile the loop body.
924 */
925
926 envPtr->exceptArrayPtr[range].codeOffset =
927 (envPtr->codeNext - envPtr->codeStart);
928 code = TclCompileCmdWord(interp, bodyTokenPtr+1,
929 bodyTokenPtr->numComponents, envPtr);
930 envPtr->currStackDepth = savedStackDepth + 1;
931 if (code != TCL_OK) {
932 if (code == TCL_ERROR) {
933 sprintf(buffer, "\n (\"foreach\" body line %d)",
934 interp->errorLine);
935 Tcl_AddObjErrorInfo(interp, buffer, -1);
936 }
937 goto done;
938 }
939 envPtr->exceptArrayPtr[range].numCodeBytes =
940 (envPtr->codeNext - envPtr->codeStart)
941 - envPtr->exceptArrayPtr[range].codeOffset;
942 TclEmitOpcode(INST_POP, envPtr);
943
944 /*
945 * Jump back to the test at the top of the loop. Generate a 4 byte jump
946 * if the distance to the test is > 120 bytes. This is conservative and
947 * ensures that we won't have to replace this jump if we later need to
948 * replace the ifFalse jump with a 4 byte jump.
949 */
950
951 jumpBackOffset = (envPtr->codeNext - envPtr->codeStart);
952 jumpBackDist =
953 (jumpBackOffset - envPtr->exceptArrayPtr[range].continueOffset);
954 if (jumpBackDist > 120) {
955 TclEmitInstInt4(INST_JUMP4, -jumpBackDist, envPtr);
956 } else {
957 TclEmitInstInt1(INST_JUMP1, -jumpBackDist, envPtr);
958 }
959
960 /*
961 * Fix the target of the jump after the foreach_step test.
962 */
963
964 jumpDist = (envPtr->codeNext - envPtr->codeStart)
965 - jumpFalseFixup.codeOffset;
966 if (TclFixupForwardJump(envPtr, &jumpFalseFixup, jumpDist, 127)) {
967 /*
968 * Update the loop body's starting PC offset since it moved down.
969 */
970
971 envPtr->exceptArrayPtr[range].codeOffset += 3;
972
973 /*
974 * Update the jump back to the test at the top of the loop since it
975 * also moved down 3 bytes.
976 */
977
978 jumpBackOffset += 3;
979 jumpPc = (envPtr->codeStart + jumpBackOffset);
980 jumpBackDist += 3;
981 if (jumpBackDist > 120) {
982 TclUpdateInstInt4AtPc(INST_JUMP4, -jumpBackDist, jumpPc);
983 } else {
984 TclUpdateInstInt1AtPc(INST_JUMP1, -jumpBackDist, jumpPc);
985 }
986 }
987
988 /*
989 * Set the loop's break target.
990 */
991
992 envPtr->exceptArrayPtr[range].breakOffset =
993 (envPtr->codeNext - envPtr->codeStart);
994
995 /*
996 * The foreach command's result is an empty string.
997 */
998
999 envPtr->currStackDepth = savedStackDepth;
1000 TclEmitPush(TclRegisterNewLiteral(envPtr, "", 0), envPtr);
1001 envPtr->currStackDepth = savedStackDepth + 1;
1002
1003 done:
1004 for (loopIndex = 0; loopIndex < numLists; loopIndex++) {
1005 if (varvList[loopIndex] != (CONST char **) NULL) {
1006 ckfree((char *) varvList[loopIndex]);
1007 }
1008 }
1009 if (varcList != varcListStaticSpace) {
1010 ckfree((char *) varcList);
1011 ckfree((char *) varvList);
1012 }
1013 envPtr->exceptDepth--;
1014 return code;
1015 }
1016
1017 /*
1018 *----------------------------------------------------------------------
1019 *
1020 * DupForeachInfo --
1021 *
1022 * This procedure duplicates a ForeachInfo structure created as
1023 * auxiliary data during the compilation of a foreach command.
1024 *
1025 * Results:
1026 * A pointer to a newly allocated copy of the existing ForeachInfo
1027 * structure is returned.
1028 *
1029 * Side effects:
1030 * Storage for the copied ForeachInfo record is allocated. If the
1031 * original ForeachInfo structure pointed to any ForeachVarList
1032 * records, these structures are also copied and pointers to them
1033 * are stored in the new ForeachInfo record.
1034 *
1035 *----------------------------------------------------------------------
1036 */
1037
1038 static ClientData
1039 DupForeachInfo(clientData)
1040 ClientData clientData; /* The foreach command's compilation
1041 * auxiliary data to duplicate. */
1042 {
1043 register ForeachInfo *srcPtr = (ForeachInfo *) clientData;
1044 ForeachInfo *dupPtr;
1045 register ForeachVarList *srcListPtr, *dupListPtr;
1046 int numLists = srcPtr->numLists;
1047 int numVars, i, j;
1048
1049 dupPtr = (ForeachInfo *) ckalloc((unsigned)
1050 (sizeof(ForeachInfo) + (numLists * sizeof(ForeachVarList *))));
1051 dupPtr->numLists = numLists;
1052 dupPtr->firstValueTemp = srcPtr->firstValueTemp;
1053 dupPtr->loopCtTemp = srcPtr->loopCtTemp;
1054
1055 for (i = 0; i < numLists; i++) {
1056 srcListPtr = srcPtr->varLists[i];
1057 numVars = srcListPtr->numVars;
1058 dupListPtr = (ForeachVarList *) ckalloc((unsigned)
1059 sizeof(ForeachVarList) + numVars*sizeof(int));
1060 dupListPtr->numVars = numVars;
1061 for (j = 0; j < numVars; j++) {
1062 dupListPtr->varIndexes[j] = srcListPtr->varIndexes[j];
1063 }
1064 dupPtr->varLists[i] = dupListPtr;
1065 }
1066 return (ClientData) dupPtr;
1067 }
1068
1069 /*
1070 *----------------------------------------------------------------------
1071 *
1072 * FreeForeachInfo --
1073 *
1074 * Procedure to free a ForeachInfo structure created as auxiliary data
1075 * during the compilation of a foreach command.
1076 *
1077 * Results:
1078 * None.
1079 *
1080 * Side effects:
1081 * Storage for the ForeachInfo structure pointed to by the ClientData
1082 * argument is freed as is any ForeachVarList record pointed to by the
1083 * ForeachInfo structure.
1084 *
1085 *----------------------------------------------------------------------
1086 */
1087
1088 static void
1089 FreeForeachInfo(clientData)
1090 ClientData clientData; /* The foreach command's compilation
1091 * auxiliary data to free. */
1092 {
1093 register ForeachInfo *infoPtr = (ForeachInfo *) clientData;
1094 register ForeachVarList *listPtr;
1095 int numLists = infoPtr->numLists;
1096 register int i;
1097
1098 for (i = 0; i < numLists; i++) {
1099 listPtr = infoPtr->varLists[i];
1100 ckfree((char *) listPtr);
1101 }
1102 ckfree((char *) infoPtr);
1103 }
1104
1105 /*
1106 *----------------------------------------------------------------------
1107 *
1108 * TclCompileIfCmd --
1109 *
1110 * Procedure called to compile the "if" command.
1111 *
1112 * Results:
1113 * The return value is a standard Tcl result, which is TCL_OK if
1114 * compilation was successful. If an error occurs then the
1115 * interpreter's result contains a standard error message and TCL_ERROR
1116 * is returned. If the command is too complex for TclCompileIfCmd,
1117 * TCL_OUT_LINE_COMPILE is returned indicating that the if command
1118 * should be compiled "out of line" by emitting code to invoke its
1119 * command procedure at runtime.
1120 *
1121 * Side effects:
1122 * Instructions are added to envPtr to execute the "if" command
1123 * at runtime.
1124 *
1125 *----------------------------------------------------------------------
1126 */
1127 int
1128 TclCompileIfCmd(interp, parsePtr, envPtr)
1129 Tcl_Interp *interp; /* Used for error reporting. */
1130 Tcl_Parse *parsePtr; /* Points to a parse structure for the
1131 * command created by Tcl_ParseCommand. */
1132 CompileEnv *envPtr; /* Holds resulting instructions. */
1133 {
1134 JumpFixupArray jumpFalseFixupArray;
1135 /* Used to fix the ifFalse jump after each
1136 * test when its target PC is determined. */
1137 JumpFixupArray jumpEndFixupArray;
1138 /* Used to fix the jump after each "then"
1139 * body to the end of the "if" when that PC
1140 * is determined. */
1141 Tcl_Token *tokenPtr, *testTokenPtr;
1142 int jumpDist, jumpFalseDist;
1143 int jumpIndex = 0; /* avoid compiler warning. */
1144 int numWords, wordIdx, numBytes, j, code;
1145 CONST char *word;
1146 char buffer[100];
1147 int savedStackDepth = envPtr->currStackDepth;
1148 /* Saved stack depth at the start of the first
1149 * test; the envPtr current depth is restored
1150 * to this value at the start of each test. */
1151 int realCond = 1; /* set to 0 for static conditions: "if 0 {..}" */
1152 int boolVal; /* value of static condition */
1153 int compileScripts = 1;
1154
1155 /*
1156 * Only compile the "if" command if all arguments are simple
1157 * words, in order to insure correct substitution [Bug 219166]
1158 */
1159
1160 tokenPtr = parsePtr->tokenPtr;
1161 wordIdx = 0;
1162 numWords = parsePtr->numWords;
1163
1164 for (wordIdx = 0; wordIdx < numWords; wordIdx++) {
1165 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
1166 return TCL_OUT_LINE_COMPILE;
1167 }
1168 tokenPtr += 2;
1169 }
1170
1171
1172 TclInitJumpFixupArray(&jumpFalseFixupArray);
1173 TclInitJumpFixupArray(&jumpEndFixupArray);
1174 code = TCL_OK;
1175
1176 /*
1177 * Each iteration of this loop compiles one "if expr ?then? body"
1178 * or "elseif expr ?then? body" clause.
1179 */
1180
1181 tokenPtr = parsePtr->tokenPtr;
1182 wordIdx = 0;
1183 while (wordIdx < numWords) {
1184 /*
1185 * Stop looping if the token isn't "if" or "elseif".
1186 */
1187
1188 word = tokenPtr[1].start;
1189 numBytes = tokenPtr[1].size;
1190 if ((tokenPtr == parsePtr->tokenPtr)
1191 || ((numBytes == 6) && (strncmp(word, "elseif", 6) == 0))) {
1192 tokenPtr += (tokenPtr->numComponents + 1);
1193 wordIdx++;
1194 } else {
1195 break;
1196 }
1197 if (wordIdx >= numWords) {
1198 sprintf(buffer,
1199 "wrong # args: no expression after \"%.*s\" argument",
1200 (numBytes > 50 ? 50 : numBytes), word);
1201 Tcl_ResetResult(interp);
1202 Tcl_AppendToObj(Tcl_GetObjResult(interp), buffer, -1);
1203 code = TCL_ERROR;
1204 goto done;
1205 }
1206
1207 /*
1208 * Compile the test expression then emit the conditional jump
1209 * around the "then" part.
1210 */
1211
1212 envPtr->currStackDepth = savedStackDepth;
1213 testTokenPtr = tokenPtr;
1214
1215
1216 if (realCond) {
1217 /*
1218 * Find out if the condition is a constant.
1219 */
1220
1221 Tcl_Obj *boolObj = Tcl_NewStringObj(testTokenPtr[1].start,
1222 testTokenPtr[1].size);
1223 Tcl_IncrRefCount(boolObj);
1224 code = Tcl_GetBooleanFromObj(NULL, boolObj, &boolVal);
1225 Tcl_DecrRefCount(boolObj);
1226 if (code == TCL_OK) {
1227 /*
1228 * A static condition
1229 */
1230 realCond = 0;
1231 if (!boolVal) {
1232 compileScripts = 0;
1233 }
1234 } else {
1235 Tcl_ResetResult(interp);
1236 code = TclCompileExprWords(interp, testTokenPtr, 1, envPtr);
1237 if (code != TCL_OK) {
1238 if (code == TCL_ERROR) {
1239 Tcl_AddObjErrorInfo(interp,
1240 "\n (\"if\" test expression)", -1);
1241 }
1242 goto done;
1243 }
1244 if (jumpFalseFixupArray.next >= jumpFalseFixupArray.end) {
1245 TclExpandJumpFixupArray(&jumpFalseFixupArray);
1246 }
1247 jumpIndex = jumpFalseFixupArray.next;
1248 jumpFalseFixupArray.next++;
1249 TclEmitForwardJump(envPtr, TCL_FALSE_JUMP,
1250 &(jumpFalseFixupArray.fixup[jumpIndex]));
1251 }
1252 }
1253
1254
1255 /*
1256 * Skip over the optional "then" before the then clause.
1257 */
1258
1259 tokenPtr = testTokenPtr + (testTokenPtr->numComponents + 1);
1260 wordIdx++;
1261 if (wordIdx >= numWords) {
1262 sprintf(buffer,
1263 "wrong # args: no script following \"%.*s\" argument",
1264 (testTokenPtr->size > 50 ? 50 : testTokenPtr->size),
1265 testTokenPtr->start);
1266 Tcl_ResetResult(interp);
1267 Tcl_AppendToObj(Tcl_GetObjResult(interp), buffer, -1);
1268 code = TCL_ERROR;
1269 goto done;
1270 }
1271 if (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
1272 word = tokenPtr[1].start;
1273 numBytes = tokenPtr[1].size;
1274 if ((numBytes == 4) && (strncmp(word, "then", 4) == 0)) {
1275 tokenPtr += (tokenPtr->numComponents + 1);
1276 wordIdx++;
1277 if (wordIdx >= numWords) {
1278 Tcl_ResetResult(interp);
1279 Tcl_AppendToObj(Tcl_GetObjResult(interp),
1280 "wrong # args: no script following \"then\" argument", -1);
1281 code = TCL_ERROR;
1282 goto done;
1283 }
1284 }
1285 }
1286
1287 /*
1288 * Compile the "then" command body.
1289 */
1290
1291 if (compileScripts) {
1292 envPtr->currStackDepth = savedStackDepth;
1293 code = TclCompileCmdWord(interp, tokenPtr+1,
1294 tokenPtr->numComponents, envPtr);
1295 if (code != TCL_OK) {
1296 if (code == TCL_ERROR) {
1297 sprintf(buffer, "\n (\"if\" then script line %d)",
1298 interp->errorLine);
1299 Tcl_AddObjErrorInfo(interp, buffer, -1);
1300 }
1301 goto done;
1302 }
1303 }
1304
1305 if (realCond) {
1306 /*
1307 * Jump to the end of the "if" command. Both jumpFalseFixupArray and
1308 * jumpEndFixupArray are indexed by "jumpIndex".
1309 */
1310
1311 if (jumpEndFixupArray.next >= jumpEndFixupArray.end) {
1312 TclExpandJumpFixupArray(&jumpEndFixupArray);
1313 }
1314 jumpEndFixupArray.next++;
1315 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP,
1316 &(jumpEndFixupArray.fixup[jumpIndex]));
1317
1318 /*
1319 * Fix the target of the jumpFalse after the test. Generate a 4 byte
1320 * jump if the distance is > 120 bytes. This is conservative, and
1321 * ensures that we won't have to replace this jump if we later also
1322 * need to replace the proceeding jump to the end of the "if" with a
1323 * 4 byte jump.
1324 */
1325
1326 jumpDist = (envPtr->codeNext - envPtr->codeStart)
1327 - jumpFalseFixupArray.fixup[jumpIndex].codeOffset;
1328 if (TclFixupForwardJump(envPtr,
1329 &(jumpFalseFixupArray.fixup[jumpIndex]), jumpDist, 120)) {
1330 /*
1331 * Adjust the code offset for the proceeding jump to the end
1332 * of the "if" command.
1333 */
1334
1335 jumpEndFixupArray.fixup[jumpIndex].codeOffset += 3;
1336 }
1337 } else if (boolVal) {
1338 /*
1339 *We were processing an "if 1 {...}"; stop compiling
1340 * scripts
1341 */
1342
1343 compileScripts = 0;
1344 } else {
1345 /*
1346 *We were processing an "if 0 {...}"; reset so that
1347 * the rest (elseif, else) is compiled correctly
1348 */
1349
1350 realCond = 1;
1351 compileScripts = 1;
1352 }
1353
1354 tokenPtr += (tokenPtr->numComponents + 1);
1355 wordIdx++;
1356 }
1357
1358 /*
1359 * Restore the current stack depth in the environment; the
1360 * "else" clause (or its default) will add 1 to this.
1361 */
1362
1363 envPtr->currStackDepth = savedStackDepth;
1364
1365 /*
1366 * Check for the optional else clause. Do not compile
1367 * anything if this was an "if 1 {...}" case.
1368 */
1369
1370 if ((wordIdx < numWords)
1371 && (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD)) {
1372 /*
1373 * There is an else clause. Skip over the optional "else" word.
1374 */
1375
1376 word = tokenPtr[1].start;
1377 numBytes = tokenPtr[1].size;
1378 if ((numBytes == 4) && (strncmp(word, "else", 4) == 0)) {
1379 tokenPtr += (tokenPtr->numComponents + 1);
1380 wordIdx++;
1381 if (wordIdx >= numWords) {
1382 Tcl_ResetResult(interp);
1383 Tcl_AppendToObj(Tcl_GetObjResult(interp),
1384 "wrong # args: no script following \"else\" argument", -1);
1385 code = TCL_ERROR;
1386 goto done;
1387 }
1388 }
1389
1390 if (compileScripts) {
1391 /*
1392 * Compile the else command body.
1393 */
1394
1395 code = TclCompileCmdWord(interp, tokenPtr+1,
1396 tokenPtr->numComponents, envPtr);
1397 if (code != TCL_OK) {
1398 if (code == TCL_ERROR) {
1399 sprintf(buffer, "\n (\"if\" else script line %d)",
1400 interp->errorLine);
1401 Tcl_AddObjErrorInfo(interp, buffer, -1);
1402 }
1403 goto done;
1404 }
1405 }
1406
1407 /*
1408 * Make sure there are no words after the else clause.
1409 */
1410
1411 wordIdx++;
1412 if (wordIdx < numWords) {
1413 Tcl_ResetResult(interp);
1414 Tcl_AppendToObj(Tcl_GetObjResult(interp),
1415 "wrong # args: extra words after \"else\" clause in \"if\" command", -1);
1416 code = TCL_ERROR;
1417 goto done;
1418 }
1419 } else {
1420 /*
1421 * No else clause: the "if" command's result is an empty string.
1422 */
1423
1424 if (compileScripts) {
1425 TclEmitPush(TclRegisterNewLiteral(envPtr, "", 0), envPtr);
1426 }
1427 }
1428
1429 /*
1430 * Fix the unconditional jumps to the end of the "if" command.
1431 */
1432
1433 for (j = jumpEndFixupArray.next; j > 0; j--) {
1434 jumpIndex = (j - 1); /* i.e. process the closest jump first */
1435 jumpDist = (envPtr->codeNext - envPtr->codeStart)
1436 - jumpEndFixupArray.fixup[jumpIndex].codeOffset;
1437 if (TclFixupForwardJump(envPtr,
1438 &(jumpEndFixupArray.fixup[jumpIndex]), jumpDist, 127)) {
1439 /*
1440 * Adjust the immediately preceeding "ifFalse" jump. We moved
1441 * it's target (just after this jump) down three bytes.
1442 */
1443
1444 unsigned char *ifFalsePc = envPtr->codeStart
1445 + jumpFalseFixupArray.fixup[jumpIndex].codeOffset;
1446 unsigned char opCode = *ifFalsePc;
1447 if (opCode == INST_JUMP_FALSE1) {
1448 jumpFalseDist = TclGetInt1AtPtr(ifFalsePc + 1);
1449 jumpFalseDist += 3;
1450 TclStoreInt1AtPtr(jumpFalseDist, (ifFalsePc + 1));
1451 } else if (opCode == INST_JUMP_FALSE4) {
1452 jumpFalseDist = TclGetInt4AtPtr(ifFalsePc + 1);
1453 jumpFalseDist += 3;
1454 TclStoreInt4AtPtr(jumpFalseDist, (ifFalsePc + 1));
1455 } else {
1456 panic("TclCompileIfCmd: unexpected opcode updating ifFalse jump");
1457 }
1458 }
1459 }
1460
1461 /*
1462 * Free the jumpFixupArray array if malloc'ed storage was used.
1463 */
1464
1465 done:
1466 envPtr->currStackDepth = savedStackDepth + 1;
1467 TclFreeJumpFixupArray(&jumpFalseFixupArray);
1468 TclFreeJumpFixupArray(&jumpEndFixupArray);
1469 return code;
1470 }
1471
1472 /*
1473 *----------------------------------------------------------------------
1474 *
1475 * TclCompileIncrCmd --
1476 *
1477 * Procedure called to compile the "incr" command.
1478 *
1479 * Results:
1480 * The return value is a standard Tcl result, which is TCL_OK if
1481 * compilation was successful. If an error occurs then the
1482 * interpreter's result contains a standard error message and TCL_ERROR
1483 * is returned. If the command is too complex for TclCompileIncrCmd,
1484 * TCL_OUT_LINE_COMPILE is returned indicating that the incr command
1485 * should be compiled "out of line" by emitting code to invoke its
1486 * command procedure at runtime.
1487 *
1488 * Side effects:
1489 * Instructions are added to envPtr to execute the "incr" command
1490 * at runtime.
1491 *
1492 *----------------------------------------------------------------------
1493 */
1494
1495 int
1496 TclCompileIncrCmd(interp, parsePtr, envPtr)
1497 Tcl_Interp *interp; /* Used for error reporting. */
1498 Tcl_Parse *parsePtr; /* Points to a parse structure for the
1499 * command created by Tcl_ParseCommand. */
1500 CompileEnv *envPtr; /* Holds resulting instructions. */
1501 {
1502 Tcl_Token *varTokenPtr, *incrTokenPtr;
1503 int simpleVarName, isScalar, localIndex, haveImmValue, immValue;
1504 int code = TCL_OK;
1505
1506 if ((parsePtr->numWords != 2) && (parsePtr->numWords != 3)) {
1507 Tcl_ResetResult(interp);
1508 Tcl_AppendToObj(Tcl_GetObjResult(interp),
1509 "wrong # args: should be \"incr varName ?increment?\"", -1);
1510 return TCL_ERROR;
1511 }
1512
1513 varTokenPtr = parsePtr->tokenPtr
1514 + (parsePtr->tokenPtr->numComponents + 1);
1515
1516 code = TclPushVarName(interp, varTokenPtr, envPtr,
1517 (TCL_NO_LARGE_INDEX | TCL_CREATE_VAR),
1518 &localIndex, &simpleVarName, &isScalar);
1519 if (code != TCL_OK) {
1520 goto done;
1521 }
1522
1523 /*
1524 * If an increment is given, push it, but see first if it's a small
1525 * integer.
1526 */
1527
1528 haveImmValue = 0;
1529 immValue = 0;
1530 if (parsePtr->numWords == 3) {
1531 incrTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
1532 if (incrTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
1533 CONST char *word = incrTokenPtr[1].start;
1534 int numBytes = incrTokenPtr[1].size;
1535 int validLength = TclParseInteger(word, numBytes);
1536 long n;
1537
1538 /*
1539 * Note there is a danger that modifying the string could have
1540 * undesirable side effects. In this case, TclLooksLikeInt and
1541 * TclGetLong do not have any dependencies on shared strings so we
1542 * should be safe.
1543 */
1544
1545 if (validLength == numBytes) {
1546 int code;
1547 Tcl_Obj *longObj = Tcl_NewStringObj(word, numBytes);
1548 Tcl_IncrRefCount(longObj);
1549 code = Tcl_GetLongFromObj(NULL, longObj, &n);
1550 Tcl_DecrRefCount(longObj);
1551 if ((code == TCL_OK) && (-127 <= n) && (n <= 127)) {
1552 haveImmValue = 1;
1553 immValue = n;
1554 }
1555 }
1556 if (!haveImmValue) {
1557 TclEmitPush(
1558 TclRegisterNewLiteral(envPtr, word, numBytes), envPtr);
1559 }
1560 } else {
1561 code = TclCompileTokens(interp, incrTokenPtr+1,
1562 incrTokenPtr->numComponents, envPtr);
1563 if (code != TCL_OK) {
1564 goto done;
1565 }
1566 }
1567 } else { /* no incr amount given so use 1 */
1568 haveImmValue = 1;
1569 immValue = 1;
1570 }
1571
1572 /*
1573 * Emit the instruction to increment the variable.
1574 */
1575
1576 if (simpleVarName) {
1577 if (isScalar) {
1578 if (localIndex >= 0) {
1579 if (haveImmValue) {
1580 TclEmitInstInt1(INST_INCR_SCALAR1_IMM, localIndex, envPtr);
1581 TclEmitInt1(immValue, envPtr);
1582 } else {
1583 TclEmitInstInt1(INST_INCR_SCALAR1, localIndex, envPtr);
1584 }
1585 } else {
1586 if (haveImmValue) {
1587 TclEmitInstInt1(INST_INCR_SCALAR_STK_IMM, immValue, envPtr);
1588 } else {
1589 TclEmitOpcode(INST_INCR_SCALAR_STK, envPtr);
1590 }
1591 }
1592 } else {
1593 if (localIndex >= 0) {
1594 if (haveImmValue) {
1595 TclEmitInstInt1(INST_INCR_ARRAY1_IMM, localIndex, envPtr);
1596 TclEmitInt1(immValue, envPtr);
1597 } else {
1598 TclEmitInstInt1(INST_INCR_ARRAY1, localIndex, envPtr);
1599 }
1600 } else {
1601 if (haveImmValue) {
1602 TclEmitInstInt1(INST_INCR_ARRAY_STK_IMM, immValue, envPtr);
1603 } else {
1604 TclEmitOpcode(INST_INCR_ARRAY_STK, envPtr);
1605 }
1606 }
1607 }
1608 } else { /* non-simple variable name */
1609 if (haveImmValue) {
1610 TclEmitInstInt1(INST_INCR_STK_IMM, immValue, envPtr);
1611 } else {
1612 TclEmitOpcode(INST_INCR_STK, envPtr);
1613 }
1614 }
1615
1616 done:
1617 return code;
1618 }
1619
1620 /*
1621 *----------------------------------------------------------------------
1622 *
1623 * TclCompileLappendCmd --
1624 *
1625 * Procedure called to compile the "lappend" command.
1626 *
1627 * Results:
1628 * The return value is a standard Tcl result, which is normally TCL_OK
1629 * unless there was an error while parsing string. If an error occurs
1630 * then the interpreter's result contains a standard error message. If
1631 * complation fails because the command requires a second level of
1632 * substitutions, TCL_OUT_LINE_COMPILE is returned indicating that the
1633 * command should be compiled "out of line" by emitting code to
1634 * invoke its command procedure (Tcl_LappendObjCmd) at runtime.
1635 *
1636 * Side effects:
1637 * Instructions are added to envPtr to execute the "lappend" command
1638 * at runtime.
1639 *
1640 *----------------------------------------------------------------------
1641 */
1642
1643 int
1644 TclCompileLappendCmd(interp, parsePtr, envPtr)
1645 Tcl_Interp *interp; /* Used for error reporting. */
1646 Tcl_Parse *parsePtr; /* Points to a parse structure for the
1647 * command created by Tcl_ParseCommand. */
1648 CompileEnv *envPtr; /* Holds resulting instructions. */
1649 {
1650 Tcl_Token *varTokenPtr, *valueTokenPtr;
1651 int simpleVarName, isScalar, localIndex, numWords;
1652 int code = TCL_OK;
1653
1654 /*
1655 * If we're not in a procedure, don't compile.
1656 */
1657 if (envPtr->procPtr == NULL) {
1658 return TCL_OUT_LINE_COMPILE;
1659 }
1660
1661 numWords = parsePtr->numWords;
1662 if (numWords == 1) {
1663 Tcl_ResetResult(interp);
1664 Tcl_AppendToObj(Tcl_GetObjResult(interp),
1665 "wrong # args: should be \"lappend varName ?value value ...?\"", -1);
1666 return TCL_ERROR;
1667 }
1668 if (numWords != 3) {
1669 /*
1670 * LAPPEND instructions currently only handle one value appends
1671 */
1672 return TCL_OUT_LINE_COMPILE;
1673 }
1674
1675 /*
1676 * Decide if we can use a frame slot for the var/array name or if we
1677 * need to emit code to compute and push the name at runtime. We use a
1678 * frame slot (entry in the array of local vars) if we are compiling a
1679 * procedure body and if the name is simple text that does not include
1680 * namespace qualifiers.
1681 */
1682
1683 varTokenPtr = parsePtr->tokenPtr
1684 + (parsePtr->tokenPtr->numComponents + 1);
1685
1686 code = TclPushVarName(interp, varTokenPtr, envPtr, TCL_CREATE_VAR,
1687 &localIndex, &simpleVarName, &isScalar);
1688 if (code != TCL_OK) {
1689 goto done;
1690 }
1691
1692 /*
1693 * If we are doing an assignment, push the new value.
1694 * In the no values case, create an empty object.
1695 */
1696
1697 if (numWords > 2) {
1698 valueTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
1699 if (valueTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
1700 TclEmitPush(TclRegisterNewLiteral(envPtr,
1701 valueTokenPtr[1].start, valueTokenPtr[1].size), envPtr);
1702 } else {
1703 code = TclCompileTokens(interp, valueTokenPtr+1,
1704 valueTokenPtr->numComponents, envPtr);
1705 if (code != TCL_OK) {
1706 goto done;
1707 }
1708 }
1709 }
1710
1711 /*
1712 * Emit instructions to set/get the variable.
1713 */
1714
1715 /*
1716 * The *_STK opcodes should be refactored to make better use of existing
1717 * LOAD/STORE instructions.
1718 */
1719 if (simpleVarName) {
1720 if (isScalar) {
1721 if (localIndex >= 0) {
1722 if (localIndex <= 255) {
1723 TclEmitInstInt1(INST_LAPPEND_SCALAR1, localIndex, envPtr);
1724 } else {
1725 TclEmitInstInt4(INST_LAPPEND_SCALAR4, localIndex, envPtr);
1726 }
1727 } else {
1728 TclEmitOpcode(INST_LAPPEND_STK, envPtr);
1729 }
1730 } else {
1731 if (localIndex >= 0) {
1732 if (localIndex <= 255) {
1733 TclEmitInstInt1(INST_LAPPEND_ARRAY1, localIndex, envPtr);
1734 } else {
1735 TclEmitInstInt4(INST_LAPPEND_ARRAY4, localIndex, envPtr);
1736 }
1737 } else {
1738 TclEmitOpcode(INST_LAPPEND_ARRAY_STK, envPtr);
1739 }
1740 }
1741 } else {
1742 TclEmitOpcode(INST_LAPPEND_STK, envPtr);
1743 }
1744
1745 done:
1746 return code;
1747 }
1748
1749 /*
1750 *----------------------------------------------------------------------
1751 *
1752 * TclCompileLindexCmd --
1753 *
1754 * Procedure called to compile the "lindex" command.
1755 *
1756 * Results:
1757 * The return value is a standard Tcl result, which is TCL_OK if the
1758 * compilation was successful. If the command cannot be byte-compiled,
1759 * TCL_OUT_LINE_COMPILE is returned. If an error occurs then the
1760 * interpreter's result contains an error message, and TCL_ERROR is
1761 * returned.
1762 *
1763 * Side effects:
1764 * Instructions are added to envPtr to execute the "lindex" command
1765 * at runtime.
1766 *
1767 *----------------------------------------------------------------------
1768 */
1769
1770 int
1771 TclCompileLindexCmd(interp, parsePtr, envPtr)
1772 Tcl_Interp *interp; /* Used for error reporting. */
1773 Tcl_Parse *parsePtr; /* Points to a parse structure for the
1774 * command created by Tcl_ParseCommand. */
1775 CompileEnv *envPtr; /* Holds resulting instructions. */
1776 {
1777 Tcl_Token *varTokenPtr;
1778 int code, i;
1779
1780 int numWords;
1781 numWords = parsePtr->numWords;
1782
1783 /*
1784 * Quit if too few args
1785 */
1786
1787 if ( numWords <= 1 ) {
1788 return TCL_OUT_LINE_COMPILE;
1789 }
1790
1791 varTokenPtr = parsePtr->tokenPtr
1792 + (parsePtr->tokenPtr->numComponents + 1);
1793
1794 /*
1795 * Push the operands onto the stack.
1796 */
1797
1798 for ( i = 1 ; i < numWords ; i++ ) {
1799 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
1800 TclEmitPush(
1801 TclRegisterNewLiteral( envPtr, varTokenPtr[1].start,
1802 varTokenPtr[1].size), envPtr);
1803 } else {
1804 code = TclCompileTokens(interp, varTokenPtr+1,
1805 varTokenPtr->numComponents, envPtr);
1806 if (code != TCL_OK) {
1807 return code;
1808 }
1809 }
1810 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
1811 }
1812
1813 /*
1814 * Emit INST_LIST_INDEX if objc==3, or INST_LIST_INDEX_MULTI
1815 * if there are multiple index args.
1816 */
1817
1818 if ( numWords == 3 ) {
1819 TclEmitOpcode( INST_LIST_INDEX, envPtr );
1820 } else {
1821 TclEmitInstInt4( INST_LIST_INDEX_MULTI, numWords-1, envPtr );
1822 }
1823
1824 return TCL_OK;
1825 }
1826
1827 /*
1828 *----------------------------------------------------------------------
1829 *
1830 * TclCompileListCmd --
1831 *
1832 * Procedure called to compile the "list" command.
1833 *
1834 * Results:
1835 * The return value is a standard Tcl result, which is normally TCL_OK
1836 * unless there was an error while parsing string. If an error occurs
1837 * then the interpreter's result contains a standard error message. If
1838 * complation fails because the command requires a second level of
1839 * substitutions, TCL_OUT_LINE_COMPILE is returned indicating that the
1840 * command should be compiled "out of line" by emitting code to
1841 * invoke its command procedure (Tcl_ListObjCmd) at runtime.
1842 *
1843 * Side effects:
1844 * Instructions are added to envPtr to execute the "list" command
1845 * at runtime.
1846 *
1847 *----------------------------------------------------------------------
1848 */
1849
1850 int
1851 TclCompileListCmd(interp, parsePtr, envPtr)
1852 Tcl_Interp *interp; /* Used for error reporting. */
1853 Tcl_Parse *parsePtr; /* Points to a parse structure for the
1854 * command created by Tcl_ParseCommand. */
1855 CompileEnv *envPtr; /* Holds resulting instructions. */
1856 {
1857 /*
1858 * If we're not in a procedure, don't compile.
1859 */
1860 if (envPtr->procPtr == NULL) {
1861 return TCL_OUT_LINE_COMPILE;
1862 }
1863
1864 if (parsePtr->numWords == 1) {
1865 /*
1866 * Empty args case
1867 */
1868
1869 TclEmitPush(TclRegisterNewLiteral(envPtr, "", 0), envPtr);
1870 } else {
1871 /*
1872 * Push the all values onto the stack.
1873 */
1874 Tcl_Token *valueTokenPtr;
1875 int i, code, numWords;
1876
1877 numWords = parsePtr->numWords;
1878
1879 valueTokenPtr = parsePtr->tokenPtr
1880 + (parsePtr->tokenPtr->numComponents + 1);
1881 for (i = 1; i < numWords; i++) {
1882 if (valueTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
1883 TclEmitPush(TclRegisterNewLiteral(envPtr,
1884 valueTokenPtr[1].start, valueTokenPtr[1].size), envPtr);
1885 } else {
1886 code = TclCompileTokens(interp, valueTokenPtr+1,
1887 valueTokenPtr->numComponents, envPtr);
1888 if (code != TCL_OK) {
1889 return code;
1890 }
1891 }
1892 valueTokenPtr = valueTokenPtr + (valueTokenPtr->numComponents + 1);
1893 }
1894 TclEmitInstInt4(INST_LIST, numWords - 1, envPtr);
1895 }
1896
1897 return TCL_OK;
1898 }
1899
1900 /*
1901 *----------------------------------------------------------------------
1902 *
1903 * TclCompileLlengthCmd --
1904 *
1905 * Procedure called to compile the "llength" command.
1906 *
1907 * Results:
1908 * The return value is a standard Tcl result, which is TCL_OK if the
1909 * compilation was successful. If the command cannot be byte-compiled,
1910 * TCL_OUT_LINE_COMPILE is returned. If an error occurs then the
1911 * interpreter's result contains an error message, and TCL_ERROR is
1912 * returned.
1913 *
1914 * Side effects:
1915 * Instructions are added to envPtr to execute the "llength" command
1916 * at runtime.
1917 *
1918 *----------------------------------------------------------------------
1919 */
1920
1921 int
1922 TclCompileLlengthCmd(interp, parsePtr, envPtr)
1923 Tcl_Interp *interp; /* Used for error reporting. */
1924 Tcl_Parse *parsePtr; /* Points to a parse structure for the
1925 * command created by Tcl_ParseCommand. */
1926 CompileEnv *envPtr; /* Holds resulting instructions. */
1927 {
1928 Tcl_Token *varTokenPtr;
1929 int code;
1930
1931 if (parsePtr->numWords != 2) {
1932 Tcl_SetResult(interp, "wrong # args: should be \"llength list\"",
1933 TCL_STATIC);
1934 return TCL_ERROR;
1935 }
1936 varTokenPtr = parsePtr->tokenPtr
1937 + (parsePtr->tokenPtr->numComponents + 1);
1938
1939 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
1940 /*
1941 * We could simply count the number of elements here and push
1942 * that value, but that is too rare a case to waste the code space.
1943 */
1944 TclEmitPush(TclRegisterNewLiteral(envPtr, varTokenPtr[1].start,
1945 varTokenPtr[1].size), envPtr);
1946 } else {
1947 code = TclCompileTokens(interp, varTokenPtr+1,
1948 varTokenPtr->numComponents, envPtr);
1949 if (code != TCL_OK) {
1950 return code;
1951 }
1952 }
1953 TclEmitOpcode(INST_LIST_LENGTH, envPtr);
1954 return TCL_OK;
1955 }
1956
1957 /*
1958 *----------------------------------------------------------------------
1959 *
1960 * TclCompileLsetCmd --
1961 *
1962 * Procedure called to compile the "lset" command.
1963 *
1964 * Results:
1965 * The return value is a standard Tcl result, which is TCL_OK if
1966 * the compilation was successful. If the "lset" command is too
1967 * complex for this function, then TCL_OUT_LINE_COMPILE is returned,
1968 * indicating that the command should be compiled "out of line"
1969 * (that is, not byte-compiled). If an error occurs, TCL_ERROR is
1970 * returned, and the interpreter result contains an error message.
1971 *
1972 * Side effects:
1973 * Instructions are added to envPtr to execute the "lset" command
1974 * at runtime.
1975 *
1976 * The general template for execution of the "lset" command is:
1977 * (1) Instructions to push the variable name, unless the
1978 * variable is local to the stack frame.
1979 * (2) If the variable is an array element, instructions
1980 * to push the array element name.
1981 * (3) Instructions to push each of zero or more "index" arguments
1982 * to the stack, followed with the "newValue" element.
1983 * (4) Instructions to duplicate the variable name and/or array
1984 * element name onto the top of the stack, if either was
1985 * pushed at steps (1) and (2).
1986 * (5) The appropriate INST_LOAD_* instruction to place the
1987 * original value of the list variable at top of stack.
1988 * (6) At this point, the stack contains:
1989 * varName? arrayElementName? index1 index2 ... newValue oldList
1990 * The compiler emits one of INST_LSET_FLAT or INST_LSET_LIST
1991 * according as whether there is exactly one index element (LIST)
1992 * or either zero or else two or more (FLAT). This instruction
1993 * removes everything from the stack except for the two names
1994 * and pushes the new value of the variable.
1995 * (7) Finally, INST_STORE_* stores the new value in the variable
1996 * and cleans up the stack.
1997 *
1998 *----------------------------------------------------------------------
1999 */
2000
2001 int
2002 TclCompileLsetCmd( interp, parsePtr, envPtr )
2003 Tcl_Interp* interp; /* Tcl interpreter for error reporting */
2004 Tcl_Parse* parsePtr; /* Points to a parse structure for
2005 * the command */
2006 CompileEnv* envPtr; /* Holds the resulting instructions */
2007 {
2008
2009 int tempDepth; /* Depth used for emitting one part
2010 * of the code burst. */
2011 Tcl_Token* varTokenPtr; /* Pointer to the Tcl_Token representing
2012 * the parse of the variable name */
2013
2014 int result; /* Status return from library calls */
2015
2016 int localIndex; /* Index of var in local var table */
2017 int simpleVarName; /* Flag == 1 if var name is simple */
2018 int isScalar; /* Flag == 1 if scalar, 0 if array */
2019
2020 int i;
2021
2022 /* Check argument count */
2023
2024 if ( parsePtr->numWords < 3 ) {
2025 /* Fail at run time, not in compilation */
2026 return TCL_OUT_LINE_COMPILE;
2027 }
2028
2029 /*
2030 * Decide if we can use a frame slot for the var/array name or if we
2031 * need to emit code to compute and push the name at runtime. We use a
2032 * frame slot (entry in the array of local vars) if we are compiling a
2033 * procedure body and if the name is simple text that does not include
2034 * namespace qualifiers.
2035 */
2036
2037 varTokenPtr = parsePtr->tokenPtr
2038 + (parsePtr->tokenPtr->numComponents + 1);
2039 result = TclPushVarName( interp, varTokenPtr, envPtr,
2040 TCL_CREATE_VAR, &localIndex, &simpleVarName, &isScalar );
2041 if (result != TCL_OK) {
2042 return result;
2043 }
2044
2045 /* Push the "index" args and the new element value. */
2046
2047 for ( i = 2; i < parsePtr->numWords; ++i ) {
2048
2049 /* Advance to next arg */
2050
2051 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2052
2053 /* Push an arg */
2054
2055 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2056 TclEmitPush(TclRegisterNewLiteral( envPtr, varTokenPtr[1].start,
2057 varTokenPtr[1].size), envPtr);
2058 } else {
2059 result = TclCompileTokens(interp, varTokenPtr+1,
2060 varTokenPtr->numComponents, envPtr);
2061 if ( result != TCL_OK ) {
2062 return result;
2063 }
2064 }
2065 }
2066
2067 /*
2068 * Duplicate the variable name if it's been pushed.
2069 */
2070
2071 if ( !simpleVarName || localIndex < 0 ) {
2072 if ( !simpleVarName || isScalar ) {
2073 tempDepth = parsePtr->numWords - 2;
2074 } else {
2075 tempDepth = parsePtr->numWords - 1;
2076 }
2077 TclEmitInstInt4( INST_OVER, tempDepth, envPtr );
2078 }
2079
2080 /*
2081 * Duplicate an array index if one's been pushed
2082 */
2083
2084 if ( simpleVarName && !isScalar ) {
2085 if ( localIndex < 0 ) {
2086 tempDepth = parsePtr->numWords - 1;
2087 } else {
2088 tempDepth = parsePtr->numWords - 2;
2089 }
2090 TclEmitInstInt4( INST_OVER, tempDepth, envPtr );
2091 }
2092
2093 /*
2094 * Emit code to load the variable's value.
2095 */
2096
2097 if ( !simpleVarName ) {
2098 TclEmitOpcode( INST_LOAD_STK, envPtr );
2099 } else if ( isScalar ) {
2100 if ( localIndex < 0 ) {
2101 TclEmitOpcode( INST_LOAD_SCALAR_STK, envPtr );
2102 } else if ( localIndex < 0x100 ) {
2103 TclEmitInstInt1( INST_LOAD_SCALAR1, localIndex, envPtr );
2104 } else {
2105 TclEmitInstInt4( INST_LOAD_SCALAR4, localIndex, envPtr );
2106 }
2107 } else {
2108 if ( localIndex < 0 ) {
2109 TclEmitOpcode( INST_LOAD_ARRAY_STK, envPtr );
2110 } else if ( localIndex < 0x100 ) {
2111 TclEmitInstInt1( INST_LOAD_ARRAY1, localIndex, envPtr );
2112 } else {
2113 TclEmitInstInt4( INST_LOAD_ARRAY4, localIndex, envPtr );
2114 }
2115 }
2116
2117 /*
2118 * Emit the correct variety of 'lset' instruction
2119 */
2120
2121 if ( parsePtr->numWords == 4 ) {
2122 TclEmitOpcode( INST_LSET_LIST, envPtr );
2123 } else {
2124 TclEmitInstInt4( INST_LSET_FLAT, (parsePtr->numWords - 1), envPtr );
2125 }
2126
2127 /*
2128 * Emit code to put the value back in the variable
2129 */
2130
2131 if ( !simpleVarName ) {
2132 TclEmitOpcode( INST_STORE_STK, envPtr );
2133 } else if ( isScalar ) {
2134 if ( localIndex < 0 ) {
2135 TclEmitOpcode( INST_STORE_SCALAR_STK, envPtr );
2136 } else if ( localIndex < 0x100 ) {
2137 TclEmitInstInt1( INST_STORE_SCALAR1, localIndex, envPtr );
2138 } else {
2139 TclEmitInstInt4( INST_STORE_SCALAR4, localIndex, envPtr );
2140 }
2141 } else {
2142 if ( localIndex < 0 ) {
2143 TclEmitOpcode( INST_STORE_ARRAY_STK, envPtr );
2144 } else if ( localIndex < 0x100 ) {
2145 TclEmitInstInt1( INST_STORE_ARRAY1, localIndex, envPtr );
2146 } else {
2147 TclEmitInstInt4( INST_STORE_ARRAY4, localIndex, envPtr );
2148 }
2149 }
2150
2151 return TCL_OK;
2152
2153 }
2154
2155 /*
2156 *----------------------------------------------------------------------
2157 *
2158 * TclCompileRegexpCmd --
2159 *
2160 * Procedure called to compile the "regexp" command.
2161 *
2162 * Results:
2163 * The return value is a standard Tcl result, which is TCL_OK if
2164 * the compilation was successful. If the "regexp" command is too
2165 * complex for this function, then TCL_OUT_LINE_COMPILE is returned,
2166 * indicating that the command should be compiled "out of line"
2167 * (that is, not byte-compiled). If an error occurs, TCL_ERROR is
2168 * returned, and the interpreter result contains an error message.
2169 *
2170 * Side effects:
2171 * Instructions are added to envPtr to execute the "regexp" command
2172 * at runtime.
2173 *
2174 *----------------------------------------------------------------------
2175 */
2176
2177 int
2178 TclCompileRegexpCmd(interp, parsePtr, envPtr)
2179 Tcl_Interp* interp; /* Tcl interpreter for error reporting */
2180 Tcl_Parse* parsePtr; /* Points to a parse structure for
2181 * the command */
2182 CompileEnv* envPtr; /* Holds the resulting instructions */
2183 {
2184 Tcl_Token *varTokenPtr; /* Pointer to the Tcl_Token representing
2185 * the parse of the RE or string */
2186 int i, len, code, nocase, anchorLeft, anchorRight, start;
2187 char *str;
2188
2189 /*
2190 * We are only interested in compiling simple regexp cases.
2191 * Currently supported compile cases are:
2192 * regexp ?-nocase? ?--? staticString $var
2193 * regexp ?-nocase? ?--? {^staticString$} $var
2194 */
2195 if (parsePtr->numWords < 3) {
2196 return TCL_OUT_LINE_COMPILE;
2197 }
2198
2199 nocase = 0;
2200 varTokenPtr = parsePtr->tokenPtr;
2201
2202 /*
2203 * We only look for -nocase and -- as options. Everything else
2204 * gets pushed to runtime execution. This is different than regexp's
2205 * runtime option handling, but satisfies our stricter needs.
2206 */
2207 for (i = 1; i < parsePtr->numWords - 2; i++) {
2208 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2209 if (varTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2210 /* Not a simple string - punt to runtime. */
2211 return TCL_OUT_LINE_COMPILE;
2212 }
2213 str = (char *) varTokenPtr[1].start;
2214 len = varTokenPtr[1].size;
2215 if ((len == 2) && (str[0] == '-') && (str[1] == '-')) {
2216 i++;
2217 break;
2218 } else if ((len > 1)
2219 && (strncmp(str, "-nocase", (unsigned) len) == 0)) {
2220 nocase = 1;
2221 } else {
2222 /* Not an option we recognize. */
2223 return TCL_OUT_LINE_COMPILE;
2224 }
2225 }
2226
2227 if ((parsePtr->numWords - i) != 2) {
2228 /* We don't support capturing to variables */
2229 return TCL_OUT_LINE_COMPILE;
2230 }
2231
2232 /*
2233 * Get the regexp string. If it is not a simple string, punt to runtime.
2234 * If it has a '-', it could be an incorrectly formed regexp command.
2235 */
2236 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2237 str = (char *) varTokenPtr[1].start;
2238 len = varTokenPtr[1].size;
2239 if ((varTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) || (*str == '-')) {
2240 return TCL_OUT_LINE_COMPILE;
2241 }
2242
2243 if (len == 0) {
2244 /*
2245 * The semantics of regexp are always match on re == "".
2246 */
2247 TclEmitPush(TclRegisterNewLiteral(envPtr, "1", 1), envPtr);
2248 return TCL_OK;
2249 }
2250
2251 /*
2252 * Make a copy of the string that is null-terminated for checks which
2253 * require such.
2254 */
2255 str = (char *) ckalloc((unsigned) len + 1);
2256 strncpy(str, varTokenPtr[1].start, (size_t) len);
2257 str[len] = '\0';
2258 start = 0;
2259
2260 /*
2261 * Check for anchored REs (ie ^foo$), so we can use string equal if
2262 * possible. Do not alter the start of str so we can free it correctly.
2263 */
2264 if (str[0] == '^') {
2265 start++;
2266 anchorLeft = 1;
2267 } else {
2268 anchorLeft = 0;
2269 }
2270 if ((str[len-1] == '$') && ((len == 1) || (str[len-2] != '\\'))) {
2271 anchorRight = 1;
2272 str[--len] = '\0';
2273 } else {
2274 anchorRight = 0;
2275 }
2276
2277 /*
2278 * On the first (pattern) arg, check to see if any RE special characters
2279 * are in the word. If not, this is the same as 'string equal'.
2280 */
2281 if ((len > (1+start)) && (str[start] == '.') && (str[start+1] == '*')) {
2282 start += 2;
2283 anchorLeft = 0;
2284 }
2285 if ((len > (2+start)) && (str[len-3] != '\\')
2286 && (str[len-2] == '.') && (str[len-1] == '*')) {
2287 len -= 2;
2288 str[len] = '\0';
2289 anchorRight = 0;
2290 }
2291
2292 /*
2293 * Don't do anything with REs with other special chars. Also check if
2294 * this is a bad RE (do this at the end because it can be expensive).
2295 * If so, let it complain at runtime.
2296 */
2297 if ((strpbrk(str + start, "*+?{}()[].\\|^$") != NULL)
2298 || (Tcl_RegExpCompile(NULL, str) == NULL)) {
2299 ckfree((char *) str);
2300 return TCL_OUT_LINE_COMPILE;
2301 }
2302
2303 if (anchorLeft && anchorRight) {
2304 TclEmitPush(TclRegisterNewLiteral(envPtr, str+start, len-start),
2305 envPtr);
2306 } else {
2307 /*
2308 * This needs to find the substring anywhere in the string, so
2309 * use string match and *foo*, with appropriate anchoring.
2310 */
2311 char *newStr = ckalloc((unsigned) len + 3);
2312 len -= start;
2313 if (anchorLeft) {
2314 strncpy(newStr, str + start, (size_t) len);
2315 } else {
2316 newStr[0] = '*';
2317 strncpy(newStr + 1, str + start, (size_t) len++);
2318 }
2319 if (!anchorRight) {
2320 newStr[len++] = '*';
2321 }
2322 newStr[len] = '\0';
2323 TclEmitPush(TclRegisterNewLiteral(envPtr, newStr, len), envPtr);
2324 ckfree((char *) newStr);
2325 }
2326 ckfree((char *) str);
2327
2328 /*
2329 * Push the string arg
2330 */
2331 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2332 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2333 TclEmitPush(TclRegisterNewLiteral(envPtr,
2334 varTokenPtr[1].start, varTokenPtr[1].size), envPtr);
2335 } else {
2336 code = TclCompileTokens(interp, varTokenPtr+1,
2337 varTokenPtr->numComponents, envPtr);
2338 if (code != TCL_OK) {
2339 return code;
2340 }
2341 }
2342
2343 if (anchorLeft && anchorRight && !nocase) {
2344 TclEmitOpcode(INST_STR_EQ, envPtr);
2345 } else {
2346 TclEmitInstInt1(INST_STR_MATCH, nocase, envPtr);
2347 }
2348
2349 return TCL_OK;
2350 }
2351
2352 /*
2353 *----------------------------------------------------------------------
2354 *
2355 * TclCompileReturnCmd --
2356 *
2357 * Procedure called to compile the "return" command.
2358 *
2359 * Results:
2360 * The return value is a standard Tcl result, which is TCL_OK if the
2361 * compilation was successful. If the particular return command is
2362 * too complex for this function (ie, return with any flags like "-code"
2363 * or "-errorinfo"), TCL_OUT_LINE_COMPILE is returned, indicating that
2364 * the command should be compiled "out of line" (eg, not byte compiled).
2365 * If an error occurs then the interpreter's result contains a standard
2366 * error message.
2367 *
2368 * Side effects:
2369 * Instructions are added to envPtr to execute the "return" command
2370 * at runtime.
2371 *
2372 *----------------------------------------------------------------------
2373 */
2374
2375 int
2376 TclCompileReturnCmd(interp, parsePtr, envPtr)
2377 Tcl_Interp *interp; /* Used for error reporting. */
2378 Tcl_Parse *parsePtr; /* Points to a parse structure for the
2379 * command created by Tcl_ParseCommand. */
2380 CompileEnv *envPtr; /* Holds resulting instructions. */
2381 {
2382 Tcl_Token *varTokenPtr;
2383 int code;
2384 int index = envPtr->exceptArrayNext - 1;
2385
2386 /*
2387 * If we're not in a procedure, don't compile.
2388 */
2389
2390 if (envPtr->procPtr == NULL) {
2391 return TCL_OUT_LINE_COMPILE;
2392 }
2393
2394 /*
2395 * Look back through the ExceptionRanges of the current CompileEnv,
2396 * from exceptArrayPtr[(exceptArrayNext - 1)] down to
2397 * exceptArrayPtr[0] to see if any of them is an enclosing [catch].
2398 * If there's an enclosing [catch], don't compile.
2399 */
2400
2401 while (index >= 0) {
2402 ExceptionRange range = envPtr->exceptArrayPtr[index];
2403 if ((range.type == CATCH_EXCEPTION_RANGE)
2404 && (range.catchOffset == -1)) {
2405 return TCL_OUT_LINE_COMPILE;
2406 }
2407 index--;
2408 }
2409
2410 switch (parsePtr->numWords) {
2411 case 1: {
2412 /*
2413 * Simple case: [return]
2414 * Just push the literal string "".
2415 */
2416 TclEmitPush(TclRegisterNewLiteral(envPtr, "", 0), envPtr);
2417 break;
2418 }
2419 case 2: {
2420 /*
2421 * More complex cases:
2422 * [return "foo"]
2423 * [return $value]
2424 * [return [otherCmd]]
2425 */
2426 varTokenPtr = parsePtr->tokenPtr
2427 + (parsePtr->tokenPtr->numComponents + 1);
2428 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2429 /*
2430 * [return "foo"] case: the parse token is a simple word,
2431 * so just push it.
2432 */
2433 TclEmitPush(TclRegisterNewLiteral(envPtr, varTokenPtr[1].start,
2434 varTokenPtr[1].size), envPtr);
2435 } else {
2436 /*
2437 * Parse token is more complex, so compile it; this handles the
2438 * variable reference and nested command cases. If the
2439 * parse token can be byte-compiled, then this instance of
2440 * "return" will be byte-compiled; otherwise it will be
2441 * out line compiled.
2442 */
2443 code = TclCompileTokens(interp, varTokenPtr+1,
2444 varTokenPtr->numComponents, envPtr);
2445 if (code != TCL_OK) {
2446 return code;
2447 }
2448 }
2449 break;
2450 }
2451 default: {
2452 /*
2453 * Most complex return cases: everything else, including
2454 * [return -code error], etc.
2455 */
2456 return TCL_OUT_LINE_COMPILE;
2457 }
2458 }
2459
2460 /*
2461 * The INST_DONE opcode actually causes the branching out of the
2462 * subroutine, and takes the top stack item as the return result
2463 * (which is why we pushed the value above).
2464 */
2465 TclEmitOpcode(INST_DONE, envPtr);
2466 return TCL_OK;
2467 }
2468
2469 /*
2470 *----------------------------------------------------------------------
2471 *
2472 * TclCompileSetCmd --
2473 *
2474 * Procedure called to compile the "set" command.
2475 *
2476 * Results:
2477 * The return value is a standard Tcl result, which is normally TCL_OK
2478 * unless there was an error while parsing string. If an error occurs
2479 * then the interpreter's result contains a standard error message. If
2480 * complation fails because the set command requires a second level of
2481 * substitutions, TCL_OUT_LINE_COMPILE is returned indicating that the
2482 * set command should be compiled "out of line" by emitting code to
2483 * invoke its command procedure (Tcl_SetCmd) at runtime.
2484 *
2485 * Side effects:
2486 * Instructions are added to envPtr to execute the "set" command
2487 * at runtime.
2488 *
2489 *----------------------------------------------------------------------
2490 */
2491
2492 int
2493 TclCompileSetCmd(interp, parsePtr, envPtr)
2494 Tcl_Interp *interp; /* Used for error reporting. */
2495 Tcl_Parse *parsePtr; /* Points to a parse structure for the
2496 * command created by Tcl_ParseCommand. */
2497 CompileEnv *envPtr; /* Holds resulting instructions. */
2498 {
2499 Tcl_Token *varTokenPtr, *valueTokenPtr;
2500 int isAssignment, isScalar, simpleVarName, localIndex, numWords;
2501 int code = TCL_OK;
2502
2503 numWords = parsePtr->numWords;
2504 if ((numWords != 2) && (numWords != 3)) {
2505 Tcl_ResetResult(interp);
2506 Tcl_AppendToObj(Tcl_GetObjResult(interp),
2507 "wrong # args: should be \"set varName ?newValue?\"", -1);
2508 return TCL_ERROR;
2509 }
2510 isAssignment = (numWords == 3);
2511
2512 /*
2513 * Decide if we can use a frame slot for the var/array name or if we
2514 * need to emit code to compute and push the name at runtime. We use a
2515 * frame slot (entry in the array of local vars) if we are compiling a
2516 * procedure body and if the name is simple text that does not include
2517 * namespace qualifiers.
2518 */
2519
2520 varTokenPtr = parsePtr->tokenPtr
2521 + (parsePtr->tokenPtr->numComponents + 1);
2522
2523 code = TclPushVarName(interp, varTokenPtr, envPtr, TCL_CREATE_VAR,
2524 &localIndex, &simpleVarName, &isScalar);
2525 if (code != TCL_OK) {
2526 goto done;
2527 }
2528
2529 /*
2530 * If we are doing an assignment, push the new value.
2531 */
2532
2533 if (isAssignment) {
2534 valueTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2535 if (valueTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2536 TclEmitPush(TclRegisterNewLiteral(envPtr, valueTokenPtr[1].start,
2537 valueTokenPtr[1].size), envPtr);
2538 } else {
2539 code = TclCompileTokens(interp, valueTokenPtr+1,
2540 valueTokenPtr->numComponents, envPtr);
2541 if (code != TCL_OK) {
2542 goto done;
2543 }
2544 }
2545 }
2546
2547 /*
2548 * Emit instructions to set/get the variable.
2549 */
2550
2551 if (simpleVarName) {
2552 if (isScalar) {
2553 if (localIndex >= 0) {
2554 if (localIndex <= 255) {
2555 TclEmitInstInt1((isAssignment?
2556 INST_STORE_SCALAR1 : INST_LOAD_SCALAR1),
2557 localIndex, envPtr);
2558 } else {
2559 TclEmitInstInt4((isAssignment?
2560 INST_STORE_SCALAR4 : INST_LOAD_SCALAR4),
2561 localIndex, envPtr);
2562 }
2563 } else {
2564 TclEmitOpcode((isAssignment?
2565 INST_STORE_SCALAR_STK : INST_LOAD_SCALAR_STK), envPtr);
2566 }
2567 } else {
2568 if (localIndex >= 0) {
2569 if (localIndex <= 255) {
2570 TclEmitInstInt1((isAssignment?
2571 INST_STORE_ARRAY1 : INST_LOAD_ARRAY1),
2572 localIndex, envPtr);
2573 } else {
2574 TclEmitInstInt4((isAssignment?
2575 INST_STORE_ARRAY4 : INST_LOAD_ARRAY4),
2576 localIndex, envPtr);
2577 }
2578 } else {
2579 TclEmitOpcode((isAssignment?
2580 INST_STORE_ARRAY_STK : INST_LOAD_ARRAY_STK), envPtr);
2581 }
2582 }
2583 } else {
2584 TclEmitOpcode((isAssignment? INST_STORE_STK : INST_LOAD_STK), envPtr);
2585 }
2586
2587 done:
2588 return code;
2589 }
2590
2591 /*
2592 *----------------------------------------------------------------------
2593 *
2594 * TclCompileStringCmd --
2595 *
2596 * Procedure called to compile the "string" command.
2597 *
2598 * Results:
2599 * The return value is a standard Tcl result, which is TCL_OK if the
2600 * compilation was successful. If the command cannot be byte-compiled,
2601 * TCL_OUT_LINE_COMPILE is returned. If an error occurs then the
2602 * interpreter's result contains an error message, and TCL_ERROR is
2603 * returned.
2604 *
2605 * Side effects:
2606 * Instructions are added to envPtr to execute the "string" command
2607 * at runtime.
2608 *
2609 *----------------------------------------------------------------------
2610 */
2611
2612 int
2613 TclCompileStringCmd(interp, parsePtr, envPtr)
2614 Tcl_Interp *interp; /* Used for error reporting. */
2615 Tcl_Parse *parsePtr; /* Points to a parse structure for the
2616 * command created by Tcl_ParseCommand. */
2617 CompileEnv *envPtr; /* Holds resulting instructions. */
2618 {
2619 Tcl_Token *opTokenPtr, *varTokenPtr;
2620 Tcl_Obj *opObj;
2621 int index;
2622 int code;
2623
2624 static CONST char *options[] = {
2625 "bytelength", "compare", "equal", "first",
2626 "index", "is", "last", "length",
2627 "map", "match", "range", "repeat",
2628 "replace", "tolower", "toupper", "totitle",
2629 "trim", "trimleft", "trimright",
2630 "wordend", "wordstart", (char *) NULL
2631 };
2632 enum options {
2633 STR_BYTELENGTH, STR_COMPARE, STR_EQUAL, STR_FIRST,
2634 STR_INDEX, STR_IS, STR_LAST, STR_LENGTH,
2635 STR_MAP, STR_MATCH, STR_RANGE, STR_REPEAT,
2636 STR_REPLACE, STR_TOLOWER, STR_TOUPPER, STR_TOTITLE,
2637 STR_TRIM, STR_TRIMLEFT, STR_TRIMRIGHT,
2638 STR_WORDEND, STR_WORDSTART
2639 };
2640
2641 if (parsePtr->numWords < 2) {
2642 /* Fail at run time, not in compilation */
2643 return TCL_OUT_LINE_COMPILE;
2644 }
2645 opTokenPtr = parsePtr->tokenPtr
2646 + (parsePtr->tokenPtr->numComponents + 1);
2647
2648 opObj = Tcl_NewStringObj(opTokenPtr->start, opTokenPtr->size);
2649 if (Tcl_GetIndexFromObj(interp, opObj, options, "option", 0,
2650 &index) != TCL_OK) {
2651 Tcl_DecrRefCount(opObj);
2652 Tcl_ResetResult(interp);
2653 return TCL_OUT_LINE_COMPILE;
2654 }
2655 Tcl_DecrRefCount(opObj);
2656
2657 varTokenPtr = opTokenPtr + (opTokenPtr->numComponents + 1);
2658
2659 switch ((enum options) index) {
2660 case STR_BYTELENGTH:
2661 case STR_FIRST:
2662 case STR_IS:
2663 case STR_LAST:
2664 case STR_MAP:
2665 case STR_RANGE:
2666 case STR_REPEAT:
2667 case STR_REPLACE:
2668 case STR_TOLOWER:
2669 case STR_TOUPPER:
2670 case STR_TOTITLE:
2671 case STR_TRIM:
2672 case STR_TRIMLEFT:
2673 case STR_TRIMRIGHT:
2674 case STR_WORDEND:
2675 case STR_WORDSTART:
2676 /*
2677 * All other cases: compile out of line.
2678 */
2679 return TCL_OUT_LINE_COMPILE;
2680
2681 case STR_COMPARE:
2682 case STR_EQUAL: {
2683 int i;
2684 /*
2685 * If there are any flags to the command, we can't byte compile it
2686 * because the INST_STR_EQ bytecode doesn't support flags.
2687 */
2688
2689 if (parsePtr->numWords != 4) {
2690 return TCL_OUT_LINE_COMPILE;
2691 }
2692
2693 /*
2694 * Push the two operands onto the stack.
2695 */
2696
2697 for (i = 0; i < 2; i++) {
2698 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2699 TclEmitPush(TclRegisterNewLiteral(envPtr,
2700 varTokenPtr[1].start, varTokenPtr[1].size), envPtr);
2701 } else {
2702 code = TclCompileTokens(interp, varTokenPtr+1,
2703 varTokenPtr->numComponents, envPtr);
2704 if (code != TCL_OK) {
2705 return code;
2706 }
2707 }
2708 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2709 }
2710
2711 TclEmitOpcode(((((enum options) index) == STR_COMPARE) ?
2712 INST_STR_CMP : INST_STR_EQ), envPtr);
2713 return TCL_OK;
2714 }
2715 case STR_INDEX: {
2716 int i;
2717
2718 if (parsePtr->numWords != 4) {
2719 /* Fail at run time, not in compilation */
2720 return TCL_OUT_LINE_COMPILE;
2721 }
2722
2723 /*
2724 * Push the two operands onto the stack.
2725 */
2726
2727 for (i = 0; i < 2; i++) {
2728 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2729 TclEmitPush(TclRegisterNewLiteral(envPtr,
2730 varTokenPtr[1].start, varTokenPtr[1].size), envPtr);
2731 } else {
2732 code = TclCompileTokens(interp, varTokenPtr+1,
2733 varTokenPtr->numComponents, envPtr);
2734 if (code != TCL_OK) {
2735 return code;
2736 }
2737 }
2738 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2739 }
2740
2741 TclEmitOpcode(INST_STR_INDEX, envPtr);
2742 return TCL_OK;
2743 }
2744 case STR_LENGTH: {
2745 if (parsePtr->numWords != 3) {
2746 /* Fail at run time, not in compilation */
2747 return TCL_OUT_LINE_COMPILE;
2748 }
2749
2750 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2751 /*
2752 * Here someone is asking for the length of a static string.
2753 * Just push the actual character (not byte) length.
2754 */
2755 char buf[TCL_INTEGER_SPACE];
2756 int len = Tcl_NumUtfChars(varTokenPtr[1].start,
2757 varTokenPtr[1].size);
2758 len = sprintf(buf, "%d", len);
2759 TclEmitPush(TclRegisterNewLiteral(envPtr, buf, len), envPtr);
2760 return TCL_OK;
2761 } else {
2762 code = TclCompileTokens(interp, varTokenPtr+1,
2763 varTokenPtr->numComponents, envPtr);
2764 if (code != TCL_OK) {
2765 return code;
2766 }
2767 }
2768 TclEmitOpcode(INST_STR_LEN, envPtr);
2769 return TCL_OK;
2770 }
2771 case STR_MATCH: {
2772 int i, length, exactMatch = 0, nocase = 0;
2773 CONST char *str;
2774
2775 if (parsePtr->numWords < 4 || parsePtr->numWords > 5) {
2776 /* Fail at run time, not in compilation */
2777 return TCL_OUT_LINE_COMPILE;
2778 }
2779
2780 if (parsePtr->numWords == 5) {
2781 if (varTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2782 return TCL_OUT_LINE_COMPILE;
2783 }
2784 str = varTokenPtr[1].start;
2785 length = varTokenPtr[1].size;
2786 if ((length > 1) &&
2787 strncmp(str, "-nocase", (size_t) length) == 0) {
2788 nocase = 1;
2789 } else {
2790 /* Fail at run time, not in compilation */
2791 return TCL_OUT_LINE_COMPILE;
2792 }
2793 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2794 }
2795
2796 for (i = 0; i < 2; i++) {
2797 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2798 str = varTokenPtr[1].start;
2799 length = varTokenPtr[1].size;
2800 if (!nocase && (i == 0)) {
2801 /*
2802 * On the first (pattern) arg, check to see if any
2803 * glob special characters are in the word '*[]?\\'.
2804 * If not, this is the same as 'string equal'. We
2805 * can use strpbrk here because the glob chars are all
2806 * in the ascii-7 range. If -nocase was specified,
2807 * we can't do this because INST_STR_EQ has no support
2808 * for nocase.
2809 */
2810 Tcl_Obj *copy = Tcl_NewStringObj(str, length);
2811 Tcl_IncrRefCount(copy);
2812 exactMatch = (strpbrk(Tcl_GetString(copy),
2813 "*[]?\\") == NULL);
2814 Tcl_DecrRefCount(copy);
2815 }
2816 TclEmitPush(
2817 TclRegisterNewLiteral(envPtr, str, length), envPtr);
2818 } else {
2819 code = TclCompileTokens(interp, varTokenPtr+1,
2820 varTokenPtr->numComponents, envPtr);
2821 if (code != TCL_OK) {
2822 return code;
2823 }
2824 }
2825 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2826 }
2827
2828 if (exactMatch) {
2829 TclEmitOpcode(INST_STR_EQ, envPtr);
2830 } else {
2831 TclEmitInstInt1(INST_STR_MATCH, nocase, envPtr);
2832 }
2833 return TCL_OK;
2834 }
2835 }
2836
2837 return TCL_OK;
2838 }
2839
2840 /*
2841 *----------------------------------------------------------------------
2842 *
2843 * TclCompileVariableCmd --
2844 *
2845 * Procedure called to reserve the local variables for the
2846 * "variable" command. The command itself is *not* compiled.
2847 *
2848 * Results:
2849 * Always returns TCL_OUT_LINE_COMPILE.
2850 *
2851 * Side effects:
2852 * Indexed local variables are added to the environment.
2853 *
2854 *----------------------------------------------------------------------
2855 */
2856 int
2857 TclCompileVariableCmd(interp, parsePtr, envPtr)
2858 Tcl_Interp *interp; /* Used for error reporting. */
2859 Tcl_Parse *parsePtr; /* Points to a parse structure for the
2860 * command created by Tcl_ParseCommand. */
2861 CompileEnv *envPtr; /* Holds resulting instructions. */
2862 {
2863 Tcl_Token *varTokenPtr;
2864 int i, numWords;
2865 CONST char *varName, *tail;
2866
2867 if (envPtr->procPtr == NULL) {
2868 return TCL_OUT_LINE_COMPILE;
2869 }
2870
2871 numWords = parsePtr->numWords;
2872
2873 varTokenPtr = parsePtr->tokenPtr
2874 + (parsePtr->tokenPtr->numComponents + 1);
2875 for (i = 1; i < numWords; i += 2) {
2876 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
2877 varName = varTokenPtr[1].start;
2878 tail = varName + varTokenPtr[1].size - 1;
2879 if ((*tail == ')') || (tail < varName)) continue;
2880 while ((tail > varName) && ((*tail != ':') || (*(tail-1) != ':'))) {
2881 tail--;
2882 }
2883 if ((*tail == ':') && (tail > varName)) {
2884 tail++;
2885 }
2886 (void) TclFindCompiledLocal(tail, (tail-varName+1),
2887 /*create*/ 1, /*flags*/ 0, envPtr->procPtr);
2888 varTokenPtr = varTokenPtr + (varTokenPtr->numComponents + 1);
2889 }
2890 }
2891 return TCL_OUT_LINE_COMPILE;
2892 }
2893
2894 /*
2895 *----------------------------------------------------------------------
2896 *
2897 * TclCompileWhileCmd --
2898 *
2899 * Procedure called to compile the "while" command.
2900 *
2901 * Results:
2902 * The return value is a standard Tcl result, which is TCL_OK if
2903 * compilation was successful. If an error occurs then the
2904 * interpreter's result contains a standard error message and TCL_ERROR
2905 * is returned. If compilation failed because the command is too
2906 * complex for TclCompileWhileCmd, TCL_OUT_LINE_COMPILE is returned
2907 * indicating that the while command should be compiled "out of line"
2908 * by emitting code to invoke its command procedure at runtime.
2909 *
2910 * Side effects:
2911 * Instructions are added to envPtr to execute the "while" command
2912 * at runtime.
2913 *
2914 *----------------------------------------------------------------------
2915 */
2916
2917 int
2918 TclCompileWhileCmd(interp, parsePtr, envPtr)
2919 Tcl_Interp *interp; /* Used for error reporting. */
2920 Tcl_Parse *parsePtr; /* Points to a parse structure for the
2921 * command created by Tcl_ParseCommand. */
2922 CompileEnv *envPtr; /* Holds resulting instructions. */
2923 {
2924 Tcl_Token *testTokenPtr, *bodyTokenPtr;
2925 JumpFixup jumpEvalCondFixup;
2926 int testCodeOffset, bodyCodeOffset, jumpDist;
2927 int range, code;
2928 char buffer[32 + TCL_INTEGER_SPACE];
2929 int savedStackDepth = envPtr->currStackDepth;
2930 int loopMayEnd = 1; /* This is set to 0 if it is recognized as
2931 * an infinite loop. */
2932 Tcl_Obj *boolObj;
2933 int boolVal;
2934
2935 if (parsePtr->numWords != 3) {
2936 Tcl_ResetResult(interp);
2937 Tcl_AppendToObj(Tcl_GetObjResult(interp),
2938 "wrong # args: should be \"while test command\"", -1);
2939 return TCL_ERROR;
2940 }
2941
2942 /*
2943 * If the test expression requires substitutions, don't compile the
2944 * while command inline. E.g., the expression might cause the loop to
2945 * never execute or execute forever, as in "while "$x < 5" {}".
2946 *
2947 * Bail out also if the body expression requires substitutions
2948 * in order to insure correct behaviour [Bug 219166]
2949 */
2950
2951 testTokenPtr = parsePtr->tokenPtr
2952 + (parsePtr->tokenPtr->numComponents + 1);
2953 bodyTokenPtr = testTokenPtr + (testTokenPtr->numComponents + 1);
2954 if ((testTokenPtr->type != TCL_TOKEN_SIMPLE_WORD)
2955 || (bodyTokenPtr->type != TCL_TOKEN_SIMPLE_WORD)) {
2956 return TCL_OUT_LINE_COMPILE;
2957 }
2958
2959 /*
2960 * Find out if the condition is a constant.
2961 */
2962
2963 boolObj = Tcl_NewStringObj(testTokenPtr[1].start, testTokenPtr[1].size);
2964 Tcl_IncrRefCount(boolObj);
2965 code = Tcl_GetBooleanFromObj(NULL, boolObj, &boolVal);
2966 Tcl_DecrRefCount(boolObj);
2967 if (code == TCL_OK) {
2968 if (boolVal) {
2969 /*
2970 * it is an infinite loop
2971 */
2972
2973 loopMayEnd = 0;
2974 } else {
2975 /*
2976 * This is an empty loop: "while 0 {...}" or such.
2977 * Compile no bytecodes.
2978 */
2979
2980 goto pushResult;
2981 }
2982 }
2983
2984 /*
2985 * Create a ExceptionRange record for the loop body. This is used to
2986 * implement break and continue.
2987 */
2988
2989 envPtr->exceptDepth++;
2990 envPtr->maxExceptDepth =
2991 TclMax(envPtr->exceptDepth, envPtr->maxExceptDepth);
2992 range = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
2993
2994 /*
2995 * Jump to the evaluation of the condition. This code uses the "loop
2996 * rotation" optimisation (which eliminates one branch from the loop).
2997 * "while cond body" produces then:
2998 * goto A
2999 * B: body : bodyCodeOffset
3000 * A: cond -> result : testCodeOffset, continueOffset
3001 * if (result) goto B
3002 *
3003 * The infinite loop "while 1 body" produces:
3004 * B: body : all three offsets here
3005 * goto B
3006 */
3007
3008 if (loopMayEnd) {
3009 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpEvalCondFixup);
3010 testCodeOffset = 0; /* avoid compiler warning */
3011 } else {
3012 testCodeOffset = (envPtr->codeNext - envPtr->codeStart);
3013 }
3014
3015
3016 /*
3017 * Compile the loop body.
3018 */
3019
3020 bodyCodeOffset = (envPtr->codeNext - envPtr->codeStart);
3021 code = TclCompileCmdWord(interp, bodyTokenPtr+1,
3022 bodyTokenPtr->numComponents, envPtr);
3023 envPtr->currStackDepth = savedStackDepth + 1;
3024 if (code != TCL_OK) {
3025 if (code == TCL_ERROR) {
3026 sprintf(buffer, "\n (\"while\" body line %d)",
3027 interp->errorLine);
3028 Tcl_AddObjErrorInfo(interp, buffer, -1);
3029 }
3030 goto error;
3031 }
3032 envPtr->exceptArrayPtr[range].numCodeBytes =
3033 (envPtr->codeNext - envPtr->codeStart) - bodyCodeOffset;
3034 TclEmitOpcode(INST_POP, envPtr);
3035
3036 /*
3037 * Compile the test expression then emit the conditional jump that
3038 * terminates the while. We already know it's a simple word.
3039 */
3040
3041 if (loopMayEnd) {
3042 testCodeOffset = (envPtr->codeNext - envPtr->codeStart);
3043 jumpDist = testCodeOffset - jumpEvalCondFixup.codeOffset;
3044 if (TclFixupForwardJump(envPtr, &jumpEvalCondFixup, jumpDist, 127)) {
3045 bodyCodeOffset += 3;
3046 testCodeOffset += 3;
3047 }
3048 envPtr->currStackDepth = savedStackDepth;
3049 code = TclCompileExprWords(interp, testTokenPtr, 1, envPtr);
3050 if (code != TCL_OK) {
3051 if (code == TCL_ERROR) {
3052 Tcl_AddObjErrorInfo(interp,
3053 "\n (\"while\" test expression)", -1);
3054 }
3055 goto error;
3056 }
3057 envPtr->currStackDepth = savedStackDepth + 1;
3058
3059 jumpDist = (envPtr->codeNext - envPtr->codeStart) - bodyCodeOffset;
3060 if (jumpDist > 127) {
3061 TclEmitInstInt4(INST_JUMP_TRUE4, -jumpDist, envPtr);
3062 } else {
3063 TclEmitInstInt1(INST_JUMP_TRUE1, -jumpDist, envPtr);
3064 }
3065 } else {
3066 jumpDist = (envPtr->codeNext - envPtr->codeStart) - bodyCodeOffset;
3067 if (jumpDist > 127) {
3068 TclEmitInstInt4(INST_JUMP4, -jumpDist, envPtr);
3069 } else {
3070 TclEmitInstInt1(INST_JUMP1, -jumpDist, envPtr);
3071 }
3072 }
3073
3074
3075 /*
3076 * Set the loop's body, continue and break offsets.
3077 */
3078
3079 envPtr->exceptArrayPtr[range].continueOffset = testCodeOffset;
3080 envPtr->exceptArrayPtr[range].codeOffset = bodyCodeOffset;
3081 envPtr->exceptArrayPtr[range].breakOffset =
3082 (envPtr->codeNext - envPtr->codeStart);
3083
3084 /*
3085 * The while command's result is an empty string.
3086 */
3087
3088 pushResult:
3089 envPtr->currStackDepth = savedStackDepth;
3090 TclEmitPush(TclRegisterNewLiteral(envPtr, "", 0), envPtr);
3091 envPtr->exceptDepth--;
3092 return TCL_OK;
3093
3094 error:
3095 envPtr->exceptDepth--;
3096 return code;
3097 }
3098
3099 /*
3100 *----------------------------------------------------------------------
3101 *
3102 * TclPushVarName --
3103 *
3104 * Procedure used in the compiling where pushing a variable name
3105 * is necessary (append, lappend, set).
3106 *
3107 * Results:
3108 * The return value is a standard Tcl result, which is normally TCL_OK
3109 * unless there was an error while parsing string. If an error occurs
3110 * then the interpreter's result contains a standard error message.
3111 *
3112 * Side effects:
3113 * Instructions are added to envPtr to execute the "set" command
3114 * at runtime.
3115 *
3116 *----------------------------------------------------------------------
3117 */
3118
3119 static int
3120 TclPushVarName(interp, varTokenPtr, envPtr, flags, localIndexPtr,
3121 simpleVarNamePtr, isScalarPtr)
3122 Tcl_Interp *interp; /* Used for error reporting. */
3123 Tcl_Token *varTokenPtr; /* Points to a variable token. */
3124 CompileEnv *envPtr; /* Holds resulting instructions. */
3125 int flags; /* takes TCL_CREATE_VAR or
3126 * TCL_NO_LARGE_INDEX */
3127 int *localIndexPtr; /* must not be NULL */
3128 int *simpleVarNamePtr; /* must not be NULL */
3129 int *isScalarPtr; /* must not be NULL */
3130 {
3131 register CONST char *p;
3132 CONST char *name, *elName;
3133 register int i, n;
3134 int nameChars, elNameChars, simpleVarName, localIndex;
3135 int code = TCL_OK;
3136
3137 Tcl_Token *elemTokenPtr = NULL;
3138 int elemTokenCount = 0;
3139 int allocedTokens = 0;
3140 int removedParen = 0;
3141
3142 /*
3143 * Decide if we can use a frame slot for the var/array name or if we
3144 * need to emit code to compute and push the name at runtime. We use a
3145 * frame slot (entry in the array of local vars) if we are compiling a
3146 * procedure body and if the name is simple text that does not include
3147 * namespace qualifiers.
3148 */
3149
3150 simpleVarName = 0;
3151 name = elName = NULL;
3152 nameChars = elNameChars = 0;
3153 localIndex = -1;
3154
3155 /*
3156 * Check not only that the type is TCL_TOKEN_SIMPLE_WORD, but whether
3157 * curly braces surround the variable name.
3158 * This really matters for array elements to handle things like
3159 * set {x($foo)} 5
3160 * which raises an undefined var error if we are not careful here.
3161 */
3162
3163 if ((varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) &&
3164 (varTokenPtr->start[0] != '{')) {
3165 /*
3166 * A simple variable name. Divide it up into "name" and "elName"
3167 * strings. If it is not a local variable, look it up at runtime.
3168 */
3169 simpleVarName = 1;
3170
3171 name = varTokenPtr[1].start;
3172 nameChars = varTokenPtr[1].size;
3173 if ( *(name + nameChars - 1) == ')') {
3174 /*
3175 * last char is ')' => potential array reference.
3176 */
3177
3178 for (i = 0, p = name; i < nameChars; i++, p++) {
3179 if (*p == '(') {
3180 elName = p + 1;
3181 elNameChars = nameChars - i - 2;
3182 nameChars = i ;
3183 break;
3184 }
3185 }
3186
3187 if ((elName != NULL) && elNameChars) {
3188 /*
3189 * An array element, the element name is a simple
3190 * string: assemble the corresponding token.
3191 */
3192
3193 elemTokenPtr = (Tcl_Token *) ckalloc(sizeof(Tcl_Token));
3194 allocedTokens = 1;
3195 elemTokenPtr->type = TCL_TOKEN_TEXT;
3196 elemTokenPtr->start = elName;
3197 elemTokenPtr->size = elNameChars;
3198 elemTokenPtr->numComponents = 0;
3199 elemTokenCount = 1;
3200 }
3201 }
3202 } else if (((n = varTokenPtr->numComponents) > 1)
3203 && (varTokenPtr[1].type == TCL_TOKEN_TEXT)
3204 && (varTokenPtr[n].type == TCL_TOKEN_TEXT)
3205 && (varTokenPtr[n].start[varTokenPtr[n].size - 1] == ')')) {
3206
3207 /*
3208 * Check for parentheses inside first token
3209 */
3210
3211 simpleVarName = 0;
3212 for (i = 0, p = varTokenPtr[1].start;
3213 i < varTokenPtr[1].size; i++, p++) {
3214 if (*p == '(') {
3215 simpleVarName = 1;
3216 break;
3217 }
3218 }
3219 if (simpleVarName) {
3220 int remainingChars;
3221
3222 /*
3223 * Check the last token: if it is just ')', do not count
3224 * it. Otherwise, remove the ')' and flag so that it is
3225 * restored at the end.
3226 */
3227
3228 if (varTokenPtr[n].size == 1) {
3229 --n;
3230 } else {
3231 --varTokenPtr[n].size;
3232 removedParen = n;
3233 }
3234
3235 name = varTokenPtr[1].start;
3236 nameChars = p - varTokenPtr[1].start;
3237 elName = p + 1;
3238 remainingChars = (varTokenPtr[2].start - p) - 1;
3239 elNameChars = (varTokenPtr[n].start - p) + varTokenPtr[n].size - 2;
3240
3241 if (remainingChars) {
3242 /*
3243 * Make a first token with the extra characters in the first
3244 * token.
3245 */
3246
3247 elemTokenPtr = (Tcl_Token *) ckalloc(n * sizeof(Tcl_Token));
3248 allocedTokens = 1;
3249 elemTokenPtr->type = TCL_TOKEN_TEXT;
3250 elemTokenPtr->start = elName;
3251 elemTokenPtr->size = remainingChars;
3252 elemTokenPtr->numComponents = 0;
3253 elemTokenCount = n;
3254
3255 /*
3256 * Copy the remaining tokens.
3257 */
3258
3259 memcpy((void *) (elemTokenPtr+1), (void *) (&varTokenPtr[2]),
3260 ((n-1) * sizeof(Tcl_Token)));
3261 } else {
3262 /*
3263 * Use the already available tokens.
3264 */
3265
3266 elemTokenPtr = &varTokenPtr[2];
3267 elemTokenCount = n - 1;
3268 }
3269 }
3270 }
3271
3272 if (simpleVarName) {
3273 /*
3274 * See whether name has any namespace separators (::'s).
3275 */
3276
3277 int hasNsQualifiers = 0;
3278 for (i = 0, p = name; i < nameChars; i++, p++) {
3279 if ((*p == ':') && ((i+1) < nameChars) && (*(p+1) == ':')) {
3280 hasNsQualifiers = 1;
3281 break;
3282 }
3283 }
3284
3285 /*
3286 * Look up the var name's index in the array of local vars in the
3287 * proc frame. If retrieving the var's value and it doesn't already
3288 * exist, push its name and look it up at runtime.
3289 */
3290
3291 if ((envPtr->procPtr != NULL) && !hasNsQualifiers) {
3292 localIndex = TclFindCompiledLocal(name, nameChars,
3293 /*create*/ (flags & TCL_CREATE_VAR),
3294 /*flags*/ ((elName==NULL)? VAR_SCALAR : VAR_ARRAY),
3295 envPtr->procPtr);
3296 if ((flags & TCL_NO_LARGE_INDEX) && (localIndex > 255)) {
3297 /* we'll push the name */
3298 localIndex = -1;
3299 }
3300 }
3301 if (localIndex < 0) {
3302 TclEmitPush(TclRegisterNewLiteral(envPtr, name, nameChars), envPtr);
3303 }
3304
3305 /*
3306 * Compile the element script, if any.
3307 */
3308
3309 if (elName != NULL) {
3310 if (elNameChars) {
3311 code = TclCompileTokens(interp, elemTokenPtr,
3312 elemTokenCount, envPtr);
3313 if (code != TCL_OK) {
3314 goto done;
3315 }
3316 } else {
3317 TclEmitPush(TclRegisterNewLiteral(envPtr, "", 0), envPtr);
3318 }
3319 }
3320 } else {
3321 /*
3322 * The var name isn't simple: compile and push it.
3323 */
3324
3325 code = TclCompileTokens(interp, varTokenPtr+1,
3326 varTokenPtr->numComponents, envPtr);
3327 if (code != TCL_OK) {
3328 goto done;
3329 }
3330 }
3331
3332 done:
3333 if (removedParen) {
3334 ++varTokenPtr[removedParen].size;
3335 }
3336 if (allocedTokens) {
3337 ckfree((char *) elemTokenPtr);
3338 }
3339 *localIndexPtr = localIndex;
3340 *simpleVarNamePtr = simpleVarName;
3341 *isScalarPtr = (elName == NULL);
3342 return code;
3343 }