Debian Codegraph @

generic/tclCompCmds.c

raw
1 /*
2 * tclCompCmds.c --
3 *
4 * This file contains compilation procedures that compile various Tcl
5 * commands into a sequence of instructions ("bytecodes").
6 *
7 * Copyright (c) 1997-1998 Sun Microsystems, Inc.
8 * Copyright (c) 2001 Kevin B. Kenny. All rights reserved.
9 * Copyright (c) 2002 ActiveState Corporation.
10 * Copyright (c) 2004-2013 Donal K. Fellows.
11 *
12 * See the file "license.terms" for information on usage and redistribution of
13 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 */
15
16 #include "tclInt.h"
17 #include "tclCompile.h"
18 #include <assert.h>
19
20 /*
21 * Prototypes for procedures defined later in this file:
22 */
23
24 static AuxDataDupProc DupDictUpdateInfo;
25 static AuxDataFreeProc FreeDictUpdateInfo;
26 static AuxDataPrintProc PrintDictUpdateInfo;
27 static AuxDataPrintProc DisassembleDictUpdateInfo;
28 static AuxDataDupProc DupForeachInfo;
29 static AuxDataFreeProc FreeForeachInfo;
30 static AuxDataPrintProc PrintForeachInfo;
31 static AuxDataPrintProc DisassembleForeachInfo;
32 static AuxDataPrintProc PrintNewForeachInfo;
33 static AuxDataPrintProc DisassembleNewForeachInfo;
34 static int CompileEachloopCmd(Tcl_Interp *interp,
35 Tcl_Parse *parsePtr, Command *cmdPtr,
36 CompileEnv *envPtr, int collect);
37 static int CompileDictEachCmd(Tcl_Interp *interp,
38 Tcl_Parse *parsePtr, Command *cmdPtr,
39 struct CompileEnv *envPtr, int collect);
40
41 /*
42 * The structures below define the AuxData types defined in this file.
43 */
44
45 static const AuxDataType foreachInfoType = {
46 "ForeachInfo", /* name */
47 DupForeachInfo, /* dupProc */
48 FreeForeachInfo, /* freeProc */
49 PrintForeachInfo, /* printProc */
50 DisassembleForeachInfo /* disassembleProc */
51 };
52
53 static const AuxDataType newForeachInfoType = {
54 "NewForeachInfo", /* name */
55 DupForeachInfo, /* dupProc */
56 FreeForeachInfo, /* freeProc */
57 PrintNewForeachInfo, /* printProc */
58 DisassembleNewForeachInfo /* disassembleProc */
59 };
60
61 static const AuxDataType dictUpdateInfoType = {
62 "DictUpdateInfo", /* name */
63 DupDictUpdateInfo, /* dupProc */
64 FreeDictUpdateInfo, /* freeProc */
65 PrintDictUpdateInfo, /* printProc */
66 DisassembleDictUpdateInfo /* disassembleProc */
67 };
68
69 /*
70 *----------------------------------------------------------------------
71 *
72 * TclGetAuxDataType --
73 *
74 * This procedure looks up an Auxdata type by name.
75 *
76 * Results:
77 * If an AuxData type with name matching "typeName" is found, a pointer
78 * to its AuxDataType structure is returned; otherwise, NULL is returned.
79 *
80 * Side effects:
81 * None.
82 *
83 *----------------------------------------------------------------------
84 */
85
86 const AuxDataType *
87 TclGetAuxDataType(
88 const char *typeName) /* Name of AuxData type to look up. */
89 {
90 if (!strcmp(typeName, foreachInfoType.name)) {
91 return &foreachInfoType;
92 } else if (!strcmp(typeName, newForeachInfoType.name)) {
93 return &newForeachInfoType;
94 } else if (!strcmp(typeName, dictUpdateInfoType.name)) {
95 return &dictUpdateInfoType;
96 } else if (!strcmp(typeName, tclJumptableInfoType.name)) {
97 return &tclJumptableInfoType;
98 }
99 return NULL;
100 }
101
102 /*
103 *----------------------------------------------------------------------
104 *
105 * TclCompileAppendCmd --
106 *
107 * Procedure called to compile the "append" command.
108 *
109 * Results:
110 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
111 * evaluation to runtime.
112 *
113 * Side effects:
114 * Instructions are added to envPtr to execute the "append" command at
115 * runtime.
116 *
117 *----------------------------------------------------------------------
118 */
119
120 int
121 TclCompileAppendCmd(
122 Tcl_Interp *interp, /* Used for error reporting. */
123 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
124 * created by Tcl_ParseCommand. */
125 Command *cmdPtr, /* Points to definition of command being
126 * compiled. */
127 CompileEnv *envPtr) /* Holds resulting instructions. */
128 {
129 DefineLineInformation; /* TIP #280 */
130 Tcl_Token *varTokenPtr, *valueTokenPtr;
131 int isScalar, localIndex, numWords, i;
132
133 /* TODO: Consider support for compiling expanded args. */
134 numWords = parsePtr->numWords;
135 if (numWords == 1) {
136 return TCL_ERROR;
137 } else if (numWords == 2) {
138 /*
139 * append varName == set varName
140 */
141
142 return TclCompileSetCmd(interp, parsePtr, cmdPtr, envPtr);
143 } else if (numWords > 3) {
144 /*
145 * APPEND instructions currently only handle one value, but we can
146 * handle some multi-value cases by stringing them together.
147 */
148
149 goto appendMultiple;
150 }
151
152 /*
153 * Decide if we can use a frame slot for the var/array name or if we need
154 * to emit code to compute and push the name at runtime. We use a frame
155 * slot (entry in the array of local vars) if we are compiling a procedure
156 * body and if the name is simple text that does not include namespace
157 * qualifiers.
158 */
159
160 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
161
162 PushVarNameWord(interp, varTokenPtr, envPtr, 0,
163 &localIndex, &isScalar, 1);
164
165 /*
166 * We are doing an assignment, otherwise TclCompileSetCmd was called, so
167 * push the new value. This will need to be extended to push a value for
168 * each argument.
169 */
170
171 valueTokenPtr = TokenAfter(varTokenPtr);
172 CompileWord(envPtr, valueTokenPtr, interp, 2);
173
174 /*
175 * Emit instructions to set/get the variable.
176 */
177
178 if (isScalar) {
179 if (localIndex < 0) {
180 TclEmitOpcode(INST_APPEND_STK, envPtr);
181 } else {
182 Emit14Inst(INST_APPEND_SCALAR, localIndex, envPtr);
183 }
184 } else {
185 if (localIndex < 0) {
186 TclEmitOpcode(INST_APPEND_ARRAY_STK, envPtr);
187 } else {
188 Emit14Inst(INST_APPEND_ARRAY, localIndex, envPtr);
189 }
190 }
191
192 return TCL_OK;
193
194 appendMultiple:
195 /*
196 * Can only handle the case where we are appending to a local scalar when
197 * there are multiple values to append. Fortunately, this is common.
198 */
199
200 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
201
202 localIndex = LocalScalarFromToken(varTokenPtr, envPtr);
203 if (localIndex < 0) {
204 return TCL_ERROR;
205 }
206
207 /*
208 * Definitely appending to a local scalar; generate the words and append
209 * them.
210 */
211
212 valueTokenPtr = TokenAfter(varTokenPtr);
213 for (i = 2 ; i < numWords ; i++) {
214 CompileWord(envPtr, valueTokenPtr, interp, i);
215 valueTokenPtr = TokenAfter(valueTokenPtr);
216 }
217 TclEmitInstInt4( INST_REVERSE, numWords-2, envPtr);
218 for (i = 2 ; i < numWords ;) {
219 Emit14Inst( INST_APPEND_SCALAR, localIndex, envPtr);
220 if (++i < numWords) {
221 TclEmitOpcode(INST_POP, envPtr);
222 }
223 }
224
225 return TCL_OK;
226 }
227
228 /*
229 *----------------------------------------------------------------------
230 *
231 * TclCompileArray*Cmd --
232 *
233 * Functions called to compile "array" subcommands.
234 *
235 * Results:
236 * All return TCL_OK for a successful compile, and TCL_ERROR to defer
237 * evaluation to runtime.
238 *
239 * Side effects:
240 * Instructions are added to envPtr to execute the "array" subcommand at
241 * runtime.
242 *
243 *----------------------------------------------------------------------
244 */
245
246 int
247 TclCompileArrayExistsCmd(
248 Tcl_Interp *interp, /* Used for looking up stuff. */
249 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
250 * created by Tcl_ParseCommand. */
251 Command *cmdPtr, /* Points to definition of command being
252 * compiled. */
253 CompileEnv *envPtr) /* Holds resulting instructions. */
254 {
255 DefineLineInformation; /* TIP #280 */
256 Tcl_Token *tokenPtr;
257 int isScalar, localIndex;
258
259 if (parsePtr->numWords != 2) {
260 return TCL_ERROR;
261 }
262
263 tokenPtr = TokenAfter(parsePtr->tokenPtr);
264 PushVarNameWord(interp, tokenPtr, envPtr, TCL_NO_ELEMENT,
265 &localIndex, &isScalar, 1);
266 if (!isScalar) {
267 return TCL_ERROR;
268 }
269
270 if (localIndex >= 0) {
271 TclEmitInstInt4(INST_ARRAY_EXISTS_IMM, localIndex, envPtr);
272 } else {
273 TclEmitOpcode( INST_ARRAY_EXISTS_STK, envPtr);
274 }
275 return TCL_OK;
276 }
277
278 int
279 TclCompileArraySetCmd(
280 Tcl_Interp *interp, /* Used for looking up stuff. */
281 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
282 * created by Tcl_ParseCommand. */
283 Command *cmdPtr, /* Points to definition of command being
284 * compiled. */
285 CompileEnv *envPtr) /* Holds resulting instructions. */
286 {
287 DefineLineInformation; /* TIP #280 */
288 Tcl_Token *varTokenPtr, *dataTokenPtr;
289 int isScalar, localIndex, code = TCL_OK;
290 int isDataLiteral, isDataValid, isDataEven, len;
291 int keyVar, valVar, infoIndex;
292 int fwd, offsetBack, offsetFwd;
293 Tcl_Obj *literalObj;
294 ForeachInfo *infoPtr;
295
296 if (parsePtr->numWords != 3) {
297 return TCL_ERROR;
298 }
299
300 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
301 dataTokenPtr = TokenAfter(varTokenPtr);
302 TclNewObj(literalObj);
303 isDataLiteral = TclWordKnownAtCompileTime(dataTokenPtr, literalObj);
304 isDataValid = (isDataLiteral
305 && TclListObjLength(NULL, literalObj, &len) == TCL_OK);
306 isDataEven = (isDataValid && (len & 1) == 0);
307
308 /*
309 * Special case: literal odd-length argument is always an error.
310 */
311
312 if (isDataValid && !isDataEven) {
313 /* Abandon custom compile and let invocation raise the error */
314 code = TclCompileBasic2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
315 goto done;
316
317 /*
318 * We used to compile to the bytecode that would throw the error,
319 * but that was wrong because it would not invoke the array trace
320 * on the variable.
321 *
322 PushStringLiteral(envPtr, "list must have an even number of elements");
323 PushStringLiteral(envPtr, "-errorcode {TCL ARGUMENT FORMAT}");
324 TclEmitInstInt4(INST_RETURN_IMM, TCL_ERROR, envPtr);
325 TclEmitInt4( 0, envPtr);
326 goto done;
327 *
328 */
329 }
330
331 /*
332 * Except for the special "ensure array" case below, when we're not in
333 * a proc, we cannot do a better compile than generic.
334 */
335
336 if ((varTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) ||
337 (envPtr->procPtr == NULL && !(isDataEven && len == 0))) {
338 code = TclCompileBasic2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
339 goto done;
340 }
341
342 PushVarNameWord(interp, varTokenPtr, envPtr, TCL_NO_ELEMENT,
343 &localIndex, &isScalar, 1);
344 if (!isScalar) {
345 code = TCL_ERROR;
346 goto done;
347 }
348
349 /*
350 * Special case: literal empty value argument is just an "ensure array"
351 * operation.
352 */
353
354 if (isDataEven && len == 0) {
355 if (localIndex >= 0) {
356 TclEmitInstInt4(INST_ARRAY_EXISTS_IMM, localIndex, envPtr);
357 TclEmitInstInt1(INST_JUMP_TRUE1, 7, envPtr);
358 TclEmitInstInt4(INST_ARRAY_MAKE_IMM, localIndex, envPtr);
359 } else {
360 TclEmitOpcode( INST_DUP, envPtr);
361 TclEmitOpcode( INST_ARRAY_EXISTS_STK, envPtr);
362 TclEmitInstInt1(INST_JUMP_TRUE1, 5, envPtr);
363 TclEmitOpcode( INST_ARRAY_MAKE_STK, envPtr);
364 TclEmitInstInt1(INST_JUMP1, 3, envPtr);
365 /* Each branch decrements stack depth, but we only take one. */
366 TclAdjustStackDepth(1, envPtr);
367 TclEmitOpcode( INST_POP, envPtr);
368 }
369 PushStringLiteral(envPtr, "");
370 goto done;
371 }
372
373 if (localIndex < 0) {
374 /*
375 * a non-local variable: upvar from a local one! This consumes the
376 * variable name that was left at stacktop.
377 */
378
379 localIndex = TclFindCompiledLocal(varTokenPtr->start,
380 varTokenPtr->size, 1, envPtr);
381 PushStringLiteral(envPtr, "0");
382 TclEmitInstInt4(INST_REVERSE, 2, envPtr);
383 TclEmitInstInt4(INST_UPVAR, localIndex, envPtr);
384 TclEmitOpcode(INST_POP, envPtr);
385 }
386
387 /*
388 * Prepare for the internal foreach.
389 */
390
391 keyVar = AnonymousLocal(envPtr);
392 valVar = AnonymousLocal(envPtr);
393
394 infoPtr = (ForeachInfo *)ckalloc(TclOffset(ForeachInfo, varLists) + sizeof(ForeachVarList *));
395 infoPtr->numLists = 1;
396 infoPtr->varLists[0] = (ForeachVarList *)ckalloc(TclOffset(ForeachVarList, varIndexes) + 2 * sizeof(int));
397 infoPtr->varLists[0]->numVars = 2;
398 infoPtr->varLists[0]->varIndexes[0] = keyVar;
399 infoPtr->varLists[0]->varIndexes[1] = valVar;
400 infoIndex = TclCreateAuxData(infoPtr, &newForeachInfoType, envPtr);
401
402 /*
403 * Start issuing instructions to write to the array.
404 */
405
406 TclEmitInstInt4(INST_ARRAY_EXISTS_IMM, localIndex, envPtr);
407 TclEmitInstInt1(INST_JUMP_TRUE1, 7, envPtr);
408 TclEmitInstInt4(INST_ARRAY_MAKE_IMM, localIndex, envPtr);
409
410 CompileWord(envPtr, dataTokenPtr, interp, 2);
411 if (!isDataLiteral || !isDataValid) {
412 /*
413 * Only need this safety check if we're handling a non-literal or list
414 * containing an invalid literal; with valid list literals, we've
415 * already checked (worth it because literals are a very common
416 * use-case with [array set]).
417 */
418
419 TclEmitOpcode( INST_DUP, envPtr);
420 TclEmitOpcode( INST_LIST_LENGTH, envPtr);
421 PushStringLiteral(envPtr, "1");
422 TclEmitOpcode( INST_BITAND, envPtr);
423 offsetFwd = CurrentOffset(envPtr);
424 TclEmitInstInt1(INST_JUMP_FALSE1, 0, envPtr);
425 PushStringLiteral(envPtr, "list must have an even number of elements");
426 PushStringLiteral(envPtr, "-errorcode {TCL ARGUMENT FORMAT}");
427 TclEmitInstInt4(INST_RETURN_IMM, TCL_ERROR, envPtr);
428 TclEmitInt4( 0, envPtr);
429 TclAdjustStackDepth(-1, envPtr);
430 fwd = CurrentOffset(envPtr) - offsetFwd;
431 TclStoreInt1AtPtr(fwd, envPtr->codeStart+offsetFwd+1);
432 }
433
434 TclEmitInstInt4(INST_FOREACH_START, infoIndex, envPtr);
435 offsetBack = CurrentOffset(envPtr);
436 Emit14Inst( INST_LOAD_SCALAR, keyVar, envPtr);
437 Emit14Inst( INST_LOAD_SCALAR, valVar, envPtr);
438 Emit14Inst( INST_STORE_ARRAY, localIndex, envPtr);
439 TclEmitOpcode( INST_POP, envPtr);
440 infoPtr->loopCtTemp = offsetBack - CurrentOffset(envPtr); /*misuse */
441 TclEmitOpcode( INST_FOREACH_STEP, envPtr);
442 TclEmitOpcode( INST_FOREACH_END, envPtr);
443 TclAdjustStackDepth(-3, envPtr);
444 PushStringLiteral(envPtr, "");
445
446 done:
447 Tcl_DecrRefCount(literalObj);
448 return code;
449 }
450
451 int
452 TclCompileArrayUnsetCmd(
453 Tcl_Interp *interp, /* Used for looking up stuff. */
454 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
455 * created by Tcl_ParseCommand. */
456 Command *cmdPtr, /* Points to definition of command being
457 * compiled. */
458 CompileEnv *envPtr) /* Holds resulting instructions. */
459 {
460 DefineLineInformation; /* TIP #280 */
461 Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
462 int isScalar, localIndex;
463
464 if (parsePtr->numWords != 2) {
465 return TclCompileBasic2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
466 }
467
468 PushVarNameWord(interp, tokenPtr, envPtr, TCL_NO_ELEMENT,
469 &localIndex, &isScalar, 1);
470 if (!isScalar) {
471 return TCL_ERROR;
472 }
473
474 if (localIndex >= 0) {
475 TclEmitInstInt4(INST_ARRAY_EXISTS_IMM, localIndex, envPtr);
476 TclEmitInstInt1(INST_JUMP_FALSE1, 8, envPtr);
477 TclEmitInstInt1(INST_UNSET_SCALAR, 1, envPtr);
478 TclEmitInt4( localIndex, envPtr);
479 } else {
480 TclEmitOpcode( INST_DUP, envPtr);
481 TclEmitOpcode( INST_ARRAY_EXISTS_STK, envPtr);
482 TclEmitInstInt1(INST_JUMP_FALSE1, 6, envPtr);
483 TclEmitInstInt1(INST_UNSET_STK, 1, envPtr);
484 TclEmitInstInt1(INST_JUMP1, 3, envPtr);
485 /* Each branch decrements stack depth, but we only take one. */
486 TclAdjustStackDepth(1, envPtr);
487 TclEmitOpcode( INST_POP, envPtr);
488 }
489 PushStringLiteral(envPtr, "");
490 return TCL_OK;
491 }
492
493 /*
494 *----------------------------------------------------------------------
495 *
496 * TclCompileBreakCmd --
497 *
498 * Procedure called to compile the "break" command.
499 *
500 * Results:
501 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
502 * evaluation to runtime.
503 *
504 * Side effects:
505 * Instructions are added to envPtr to execute the "break" command at
506 * runtime.
507 *
508 *----------------------------------------------------------------------
509 */
510
511 int
512 TclCompileBreakCmd(
513 Tcl_Interp *interp, /* Used for error reporting. */
514 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
515 * created by Tcl_ParseCommand. */
516 Command *cmdPtr, /* Points to definition of command being
517 * compiled. */
518 CompileEnv *envPtr) /* Holds resulting instructions. */
519 {
520 ExceptionRange *rangePtr;
521 ExceptionAux *auxPtr;
522
523 if (parsePtr->numWords != 1) {
524 return TCL_ERROR;
525 }
526
527 /*
528 * Find the innermost exception range that contains this command.
529 */
530
531 rangePtr = TclGetInnermostExceptionRange(envPtr, TCL_BREAK, &auxPtr);
532 if (rangePtr && rangePtr->type == LOOP_EXCEPTION_RANGE) {
533 /*
534 * Found the target! No need for a nasty INST_BREAK here.
535 */
536
537 TclCleanupStackForBreakContinue(envPtr, auxPtr);
538 TclAddLoopBreakFixup(envPtr, auxPtr);
539 } else {
540 /*
541 * Emit a real break.
542 */
543
544 TclEmitOpcode(INST_BREAK, envPtr);
545 }
546 TclAdjustStackDepth(1, envPtr);
547
548 return TCL_OK;
549 }
550
551 /*
552 *----------------------------------------------------------------------
553 *
554 * TclCompileCatchCmd --
555 *
556 * Procedure called to compile the "catch" command.
557 *
558 * Results:
559 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
560 * evaluation to runtime.
561 *
562 * Side effects:
563 * Instructions are added to envPtr to execute the "catch" command at
564 * runtime.
565 *
566 *----------------------------------------------------------------------
567 */
568
569 int
570 TclCompileCatchCmd(
571 Tcl_Interp *interp, /* Used for error reporting. */
572 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
573 * created by Tcl_ParseCommand. */
574 Command *cmdPtr, /* Points to definition of command being
575 * compiled. */
576 CompileEnv *envPtr) /* Holds resulting instructions. */
577 {
578 DefineLineInformation; /* TIP #280 */
579 JumpFixup jumpFixup;
580 Tcl_Token *cmdTokenPtr, *resultNameTokenPtr, *optsNameTokenPtr;
581 int resultIndex, optsIndex, range, dropScript = 0;
582 int depth = TclGetStackDepth(envPtr);
583
584 /*
585 * If syntax does not match what we expect for [catch], do not compile.
586 * Let runtime checks determine if syntax has changed.
587 */
588
589 if ((parsePtr->numWords < 2) || (parsePtr->numWords > 4)) {
590 return TCL_ERROR;
591 }
592
593 /*
594 * If variables were specified and the catch command is at global level
595 * (not in a procedure), don't compile it inline: the payoff is too small.
596 */
597
598 if ((parsePtr->numWords >= 3) && !EnvHasLVT(envPtr)) {
599 return TCL_ERROR;
600 }
601
602 /*
603 * Make sure the variable names, if any, have no substitutions and just
604 * refer to local scalars.
605 */
606
607 resultIndex = optsIndex = -1;
608 cmdTokenPtr = TokenAfter(parsePtr->tokenPtr);
609 if (parsePtr->numWords >= 3) {
610 resultNameTokenPtr = TokenAfter(cmdTokenPtr);
611 /* DGP */
612 resultIndex = LocalScalarFromToken(resultNameTokenPtr, envPtr);
613 if (resultIndex < 0) {
614 return TCL_ERROR;
615 }
616
617 /* DKF */
618 if (parsePtr->numWords == 4) {
619 optsNameTokenPtr = TokenAfter(resultNameTokenPtr);
620 optsIndex = LocalScalarFromToken(optsNameTokenPtr, envPtr);
621 if (optsIndex < 0) {
622 return TCL_ERROR;
623 }
624 }
625 }
626
627 /*
628 * We will compile the catch command. Declare the exception range that it
629 * uses.
630 *
631 * If the body is a simple word, compile a BEGIN_CATCH instruction,
632 * followed by the instructions to eval the body.
633 * Otherwise, compile instructions to substitute the body text before
634 * starting the catch, then BEGIN_CATCH, and then EVAL_STK to evaluate the
635 * substituted body.
636 * Care has to be taken to make sure that substitution happens outside the
637 * catch range so that errors in the substitution are not caught.
638 * [Bug 219184]
639 * The reason for duplicating the script is that EVAL_STK would otherwise
640 * begin by underflowing the stack below the mark set by BEGIN_CATCH4.
641 */
642
643 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
644 if (cmdTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
645 TclEmitInstInt4( INST_BEGIN_CATCH4, range, envPtr);
646 ExceptionRangeStarts(envPtr, range);
647 BODY(cmdTokenPtr, 1);
648 } else {
649 SetLineInformation(1);
650 CompileTokens(envPtr, cmdTokenPtr, interp);
651 TclEmitInstInt4( INST_BEGIN_CATCH4, range, envPtr);
652 ExceptionRangeStarts(envPtr, range);
653 TclEmitOpcode( INST_DUP, envPtr);
654 TclEmitInvoke(envPtr, INST_EVAL_STK);
655 /* drop the script */
656 dropScript = 1;
657 TclEmitInstInt4( INST_REVERSE, 2, envPtr);
658 TclEmitOpcode( INST_POP, envPtr);
659 }
660 ExceptionRangeEnds(envPtr, range);
661
662
663 /*
664 * Emit the "no errors" epilogue: push "0" (TCL_OK) as the catch result,
665 * and jump around the "error case" code.
666 */
667
668 TclCheckStackDepth(depth+1, envPtr);
669 PushStringLiteral(envPtr, "0");
670 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpFixup);
671
672 /*
673 * Emit the "error case" epilogue. Push the interpreter result and the
674 * return code.
675 */
676
677 ExceptionRangeTarget(envPtr, range, catchOffset);
678 TclSetStackDepth(depth + dropScript, envPtr);
679
680 if (dropScript) {
681 TclEmitOpcode( INST_POP, envPtr);
682 }
683
684
685 /* Stack at this point is empty */
686 TclEmitOpcode( INST_PUSH_RESULT, envPtr);
687 TclEmitOpcode( INST_PUSH_RETURN_CODE, envPtr);
688
689 /* Stack at this point on both branches: result returnCode */
690
691 if (TclFixupForwardJumpToHere(envPtr, &jumpFixup, 127)) {
692 Tcl_Panic("TclCompileCatchCmd: bad jump distance %d",
693 (int)(CurrentOffset(envPtr) - jumpFixup.codeOffset));
694 }
695
696 /*
697 * Push the return options if the caller wants them. This needs to happen
698 * before INST_END_CATCH
699 */
700
701 if (optsIndex != -1) {
702 TclEmitOpcode( INST_PUSH_RETURN_OPTIONS, envPtr);
703 }
704
705 /*
706 * End the catch
707 */
708
709 TclEmitOpcode( INST_END_CATCH, envPtr);
710
711 /*
712 * Save the result and return options if the caller wants them. This needs
713 * to happen after INST_END_CATCH (compile-3.6/7).
714 */
715
716 if (optsIndex != -1) {
717 Emit14Inst( INST_STORE_SCALAR, optsIndex, envPtr);
718 TclEmitOpcode( INST_POP, envPtr);
719 }
720
721 /*
722 * At this point, the top of the stack is inconveniently ordered:
723 * result returnCode
724 * Reverse the stack to store the result.
725 */
726
727 TclEmitInstInt4( INST_REVERSE, 2, envPtr);
728 if (resultIndex != -1) {
729 Emit14Inst( INST_STORE_SCALAR, resultIndex, envPtr);
730 }
731 TclEmitOpcode( INST_POP, envPtr);
732
733 TclCheckStackDepth(depth+1, envPtr);
734 return TCL_OK;
735 }
736
737 /*----------------------------------------------------------------------
738 *
739 * TclCompileClockClicksCmd --
740 *
741 * Procedure called to compile the "tcl::clock::clicks" command.
742 *
743 * Results:
744 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
745 * evaluation to run time.
746 *
747 * Side effects:
748 * Instructions are added to envPtr to execute the "clock clicks"
749 * command at runtime.
750 *
751 *----------------------------------------------------------------------
752 */
753
754 int
755 TclCompileClockClicksCmd(
756 Tcl_Interp* interp, /* Tcl interpreter */
757 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
758 * created by Tcl_ParseCommand. */
759 Command *cmdPtr, /* Points to definition of command being
760 * compiled. */
761 CompileEnv *envPtr) /* Holds resulting instructions. */
762 {
763 Tcl_Token* tokenPtr;
764
765 switch (parsePtr->numWords) {
766 case 1:
767 /*
768 * No args
769 */
770 TclEmitInstInt1(INST_CLOCK_READ, 0, envPtr);
771 break;
772 case 2:
773 /*
774 * -milliseconds or -microseconds
775 */
776 tokenPtr = TokenAfter(parsePtr->tokenPtr);
777 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD
778 || tokenPtr[1].size < 4
779 || tokenPtr[1].size > 13) {
780 return TCL_ERROR;
781 } else if (!strncmp(tokenPtr[1].start, "-microseconds",
782 tokenPtr[1].size)) {
783 TclEmitInstInt1(INST_CLOCK_READ, 1, envPtr);
784 break;
785 } else if (!strncmp(tokenPtr[1].start, "-milliseconds",
786 tokenPtr[1].size)) {
787 TclEmitInstInt1(INST_CLOCK_READ, 2, envPtr);
788 break;
789 } else {
790 return TCL_ERROR;
791 }
792 default:
793 return TCL_ERROR;
794 }
795 return TCL_OK;
796 }
797
798
799 /*----------------------------------------------------------------------
800 *
801 * TclCompileClockReadingCmd --
802 *
803 * Procedure called to compile the "tcl::clock::microseconds",
804 * "tcl::clock::milliseconds" and "tcl::clock::seconds" commands.
805 *
806 * Results:
807 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
808 * evaluation to run time.
809 *
810 * Side effects:
811 * Instructions are added to envPtr to execute the "clock clicks"
812 * command at runtime.
813 *
814 * Client data is 1 for microseconds, 2 for milliseconds, 3 for seconds.
815 *----------------------------------------------------------------------
816 */
817
818 int
819 TclCompileClockReadingCmd(
820 Tcl_Interp* interp, /* Tcl interpreter */
821 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
822 * created by Tcl_ParseCommand. */
823 Command *cmdPtr, /* Points to definition of command being
824 * compiled. */
825 CompileEnv *envPtr) /* Holds resulting instructions. */
826 {
827 if (parsePtr->numWords != 1) {
828 return TCL_ERROR;
829 }
830
831 TclEmitInstInt1(INST_CLOCK_READ, PTR2INT(cmdPtr->objClientData), envPtr);
832
833 return TCL_OK;
834 }
835
836 /*
837 *----------------------------------------------------------------------
838 *
839 * TclCompileConcatCmd --
840 *
841 * Procedure called to compile the "concat" command.
842 *
843 * Results:
844 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
845 * evaluation to runtime.
846 *
847 * Side effects:
848 * Instructions are added to envPtr to execute the "concat" command at
849 * runtime.
850 *
851 *----------------------------------------------------------------------
852 */
853
854 int
855 TclCompileConcatCmd(
856 Tcl_Interp *interp, /* Used for error reporting. */
857 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
858 * created by Tcl_ParseCommand. */
859 Command *cmdPtr, /* Points to definition of command being
860 * compiled. */
861 CompileEnv *envPtr) /* Holds resulting instructions. */
862 {
863 DefineLineInformation; /* TIP #280 */
864 Tcl_Obj *objPtr, *listObj;
865 Tcl_Token *tokenPtr;
866 int i;
867
868 /* TODO: Consider compiling expansion case. */
869 if (parsePtr->numWords == 1) {
870 /*
871 * [concat] without arguments just pushes an empty object.
872 */
873
874 PushStringLiteral(envPtr, "");
875 return TCL_OK;
876 }
877
878 /*
879 * Test if all arguments are compile-time known. If they are, we can
880 * implement with a simple push.
881 */
882
883 TclNewObj(listObj);
884 for (i = 1, tokenPtr = parsePtr->tokenPtr; i < parsePtr->numWords; i++) {
885 tokenPtr = TokenAfter(tokenPtr);
886 TclNewObj(objPtr);
887 if (!TclWordKnownAtCompileTime(tokenPtr, objPtr)) {
888 Tcl_DecrRefCount(objPtr);
889 Tcl_DecrRefCount(listObj);
890 listObj = NULL;
891 break;
892 }
893 (void) Tcl_ListObjAppendElement(NULL, listObj, objPtr);
894 }
895 if (listObj != NULL) {
896 Tcl_Obj **objs;
897 const char *bytes;
898 int len;
899
900 TclListObjGetElements(NULL, listObj, &len, &objs);
901 objPtr = Tcl_ConcatObj(len, objs);
902 Tcl_DecrRefCount(listObj);
903 bytes = Tcl_GetStringFromObj(objPtr, &len);
904 PushLiteral(envPtr, bytes, len);
905 Tcl_DecrRefCount(objPtr);
906 return TCL_OK;
907 }
908
909 /*
910 * General case: runtime concat.
911 */
912
913 for (i = 1, tokenPtr = parsePtr->tokenPtr; i < parsePtr->numWords; i++) {
914 tokenPtr = TokenAfter(tokenPtr);
915 CompileWord(envPtr, tokenPtr, interp, i);
916 }
917
918 TclEmitInstInt4( INST_CONCAT_STK, i-1, envPtr);
919
920 return TCL_OK;
921 }
922
923 /*
924 *----------------------------------------------------------------------
925 *
926 * TclCompileContinueCmd --
927 *
928 * Procedure called to compile the "continue" command.
929 *
930 * Results:
931 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
932 * evaluation to runtime.
933 *
934 * Side effects:
935 * Instructions are added to envPtr to execute the "continue" command at
936 * runtime.
937 *
938 *----------------------------------------------------------------------
939 */
940
941 int
942 TclCompileContinueCmd(
943 Tcl_Interp *interp, /* Used for error reporting. */
944 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
945 * created by Tcl_ParseCommand. */
946 Command *cmdPtr, /* Points to definition of command being
947 * compiled. */
948 CompileEnv *envPtr) /* Holds resulting instructions. */
949 {
950 ExceptionRange *rangePtr;
951 ExceptionAux *auxPtr;
952
953 /*
954 * There should be no argument after the "continue".
955 */
956
957 if (parsePtr->numWords != 1) {
958 return TCL_ERROR;
959 }
960
961 /*
962 * See if we can find a valid continueOffset (i.e., not -1) in the
963 * innermost containing exception range.
964 */
965
966 rangePtr = TclGetInnermostExceptionRange(envPtr, TCL_CONTINUE, &auxPtr);
967 if (rangePtr && rangePtr->type == LOOP_EXCEPTION_RANGE) {
968 /*
969 * Found the target! No need for a nasty INST_CONTINUE here.
970 */
971
972 TclCleanupStackForBreakContinue(envPtr, auxPtr);
973 TclAddLoopContinueFixup(envPtr, auxPtr);
974 } else {
975 /*
976 * Emit a real continue.
977 */
978
979 TclEmitOpcode(INST_CONTINUE, envPtr);
980 }
981 TclAdjustStackDepth(1, envPtr);
982
983 return TCL_OK;
984 }
985
986 /*
987 *----------------------------------------------------------------------
988 *
989 * TclCompileDict*Cmd --
990 *
991 * Functions called to compile "dict" subcommands.
992 *
993 * Results:
994 * All return TCL_OK for a successful compile, and TCL_ERROR to defer
995 * evaluation to runtime.
996 *
997 * Side effects:
998 * Instructions are added to envPtr to execute the "dict" subcommand at
999 * runtime.
1000 *
1001 *----------------------------------------------------------------------
1002 */
1003
1004 int
1005 TclCompileDictSetCmd(
1006 Tcl_Interp *interp, /* Used for looking up stuff. */
1007 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1008 * created by Tcl_ParseCommand. */
1009 Command *cmdPtr, /* Points to definition of command being
1010 * compiled. */
1011 CompileEnv *envPtr) /* Holds resulting instructions. */
1012 {
1013 DefineLineInformation; /* TIP #280 */
1014 Tcl_Token *tokenPtr, *varTokenPtr;
1015 int i, dictVarIndex;
1016
1017 /*
1018 * There must be at least one argument after the command.
1019 */
1020
1021 if (parsePtr->numWords < 4) {
1022 return TCL_ERROR;
1023 }
1024
1025 /*
1026 * The dictionary variable must be a local scalar that is knowable at
1027 * compile time; anything else exceeds the complexity of the opcode. So
1028 * discover what the index is.
1029 */
1030
1031 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
1032 dictVarIndex = LocalScalarFromToken(varTokenPtr, envPtr);
1033 if (dictVarIndex < 0) {
1034 return TCL_ERROR;
1035 }
1036
1037 /*
1038 * Remaining words (key path and value to set) can be handled normally.
1039 */
1040
1041 tokenPtr = TokenAfter(varTokenPtr);
1042 for (i=2 ; i< parsePtr->numWords ; i++) {
1043 CompileWord(envPtr, tokenPtr, interp, i);
1044 tokenPtr = TokenAfter(tokenPtr);
1045 }
1046
1047 /*
1048 * Now emit the instruction to do the dict manipulation.
1049 */
1050
1051 TclEmitInstInt4( INST_DICT_SET, parsePtr->numWords-3, envPtr);
1052 TclEmitInt4( dictVarIndex, envPtr);
1053 TclAdjustStackDepth(-1, envPtr);
1054 return TCL_OK;
1055 }
1056
1057 int
1058 TclCompileDictIncrCmd(
1059 Tcl_Interp *interp, /* Used for looking up stuff. */
1060 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1061 * created by Tcl_ParseCommand. */
1062 Command *cmdPtr, /* Points to definition of command being
1063 * compiled. */
1064 CompileEnv *envPtr) /* Holds resulting instructions. */
1065 {
1066 DefineLineInformation; /* TIP #280 */
1067 Tcl_Token *varTokenPtr, *keyTokenPtr;
1068 int dictVarIndex, incrAmount;
1069
1070 /*
1071 * There must be at least two arguments after the command.
1072 */
1073
1074 if (parsePtr->numWords < 3 || parsePtr->numWords > 4) {
1075 return TCL_ERROR;
1076 }
1077 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
1078 keyTokenPtr = TokenAfter(varTokenPtr);
1079
1080 /*
1081 * Parse the increment amount, if present.
1082 */
1083
1084 if (parsePtr->numWords == 4) {
1085 const char *word;
1086 int numBytes, code;
1087 Tcl_Token *incrTokenPtr;
1088 Tcl_Obj *intObj;
1089
1090 incrTokenPtr = TokenAfter(keyTokenPtr);
1091 if (incrTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
1092 return TclCompileBasic2Or3ArgCmd(interp, parsePtr,cmdPtr, envPtr);
1093 }
1094 word = incrTokenPtr[1].start;
1095 numBytes = incrTokenPtr[1].size;
1096
1097 intObj = Tcl_NewStringObj(word, numBytes);
1098 Tcl_IncrRefCount(intObj);
1099 code = TclGetIntFromObj(NULL, intObj, &incrAmount);
1100 TclDecrRefCount(intObj);
1101 if (code != TCL_OK) {
1102 return TclCompileBasic2Or3ArgCmd(interp, parsePtr,cmdPtr, envPtr);
1103 }
1104 } else {
1105 incrAmount = 1;
1106 }
1107
1108 /*
1109 * The dictionary variable must be a local scalar that is knowable at
1110 * compile time; anything else exceeds the complexity of the opcode. So
1111 * discover what the index is.
1112 */
1113
1114 dictVarIndex = LocalScalarFromToken(varTokenPtr, envPtr);
1115 if (dictVarIndex < 0) {
1116 return TclCompileBasic2Or3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1117 }
1118
1119 /*
1120 * Emit the key and the code to actually do the increment.
1121 */
1122
1123 CompileWord(envPtr, keyTokenPtr, interp, 2);
1124 TclEmitInstInt4( INST_DICT_INCR_IMM, incrAmount, envPtr);
1125 TclEmitInt4( dictVarIndex, envPtr);
1126 return TCL_OK;
1127 }
1128
1129 int
1130 TclCompileDictGetCmd(
1131 Tcl_Interp *interp, /* Used for looking up stuff. */
1132 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1133 * created by Tcl_ParseCommand. */
1134 Command *cmdPtr, /* Points to definition of command being
1135 * compiled. */
1136 CompileEnv *envPtr) /* Holds resulting instructions. */
1137 {
1138 DefineLineInformation; /* TIP #280 */
1139 Tcl_Token *tokenPtr;
1140 int i;
1141
1142 /*
1143 * There must be at least two arguments after the command (the single-arg
1144 * case is legal, but too special and magic for us to deal with here).
1145 */
1146
1147 /* TODO: Consider support for compiling expanded args. */
1148 if (parsePtr->numWords < 3) {
1149 return TCL_ERROR;
1150 }
1151 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1152
1153 /*
1154 * Only compile this because we need INST_DICT_GET anyway.
1155 */
1156
1157 for (i=1 ; i<parsePtr->numWords ; i++) {
1158 CompileWord(envPtr, tokenPtr, interp, i);
1159 tokenPtr = TokenAfter(tokenPtr);
1160 }
1161 TclEmitInstInt4(INST_DICT_GET, parsePtr->numWords-2, envPtr);
1162 TclAdjustStackDepth(-1, envPtr);
1163 return TCL_OK;
1164 }
1165
1166 int
1167 TclCompileDictExistsCmd(
1168 Tcl_Interp *interp, /* Used for looking up stuff. */
1169 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1170 * created by Tcl_ParseCommand. */
1171 Command *cmdPtr, /* Points to definition of command being
1172 * compiled. */
1173 CompileEnv *envPtr) /* Holds resulting instructions. */
1174 {
1175 DefineLineInformation; /* TIP #280 */
1176 Tcl_Token *tokenPtr;
1177 int i;
1178
1179 /*
1180 * There must be at least two arguments after the command (the single-arg
1181 * case is legal, but too special and magic for us to deal with here).
1182 */
1183
1184 /* TODO: Consider support for compiling expanded args. */
1185 if (parsePtr->numWords < 3) {
1186 return TCL_ERROR;
1187 }
1188 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1189
1190 /*
1191 * Now we do the code generation.
1192 */
1193
1194 for (i=1 ; i<parsePtr->numWords ; i++) {
1195 CompileWord(envPtr, tokenPtr, interp, i);
1196 tokenPtr = TokenAfter(tokenPtr);
1197 }
1198 TclEmitInstInt4(INST_DICT_EXISTS, parsePtr->numWords-2, envPtr);
1199 TclAdjustStackDepth(-1, envPtr);
1200 return TCL_OK;
1201 }
1202
1203 int
1204 TclCompileDictUnsetCmd(
1205 Tcl_Interp *interp, /* Used for looking up stuff. */
1206 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1207 * created by Tcl_ParseCommand. */
1208 Command *cmdPtr, /* Points to definition of command being
1209 * compiled. */
1210 CompileEnv *envPtr) /* Holds resulting instructions. */
1211 {
1212 DefineLineInformation; /* TIP #280 */
1213 Tcl_Token *tokenPtr;
1214 int i, dictVarIndex;
1215
1216 /*
1217 * There must be at least one argument after the variable name for us to
1218 * compile to bytecode.
1219 */
1220
1221 /* TODO: Consider support for compiling expanded args. */
1222 if (parsePtr->numWords < 3) {
1223 return TCL_ERROR;
1224 }
1225
1226 /*
1227 * The dictionary variable must be a local scalar that is knowable at
1228 * compile time; anything else exceeds the complexity of the opcode. So
1229 * discover what the index is.
1230 */
1231
1232 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1233 dictVarIndex = LocalScalarFromToken(tokenPtr, envPtr);
1234 if (dictVarIndex < 0) {
1235 return TclCompileBasicMin2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1236 }
1237
1238 /*
1239 * Remaining words (the key path) can be handled normally.
1240 */
1241
1242 for (i=2 ; i<parsePtr->numWords ; i++) {
1243 tokenPtr = TokenAfter(tokenPtr);
1244 CompileWord(envPtr, tokenPtr, interp, i);
1245 }
1246
1247 /*
1248 * Now emit the instruction to do the dict manipulation.
1249 */
1250
1251 TclEmitInstInt4( INST_DICT_UNSET, parsePtr->numWords-2, envPtr);
1252 TclEmitInt4( dictVarIndex, envPtr);
1253 return TCL_OK;
1254 }
1255
1256 int
1257 TclCompileDictCreateCmd(
1258 Tcl_Interp *interp, /* Used for looking up stuff. */
1259 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1260 * created by Tcl_ParseCommand. */
1261 Command *cmdPtr, /* Points to definition of command being
1262 * compiled. */
1263 CompileEnv *envPtr) /* Holds resulting instructions. */
1264 {
1265 DefineLineInformation; /* TIP #280 */
1266 int worker; /* Temp var for building the value in. */
1267 Tcl_Token *tokenPtr;
1268 Tcl_Obj *keyObj, *valueObj, *dictObj;
1269 const char *bytes;
1270 int i, len;
1271
1272 if ((parsePtr->numWords & 1) == 0) {
1273 return TCL_ERROR;
1274 }
1275
1276 /*
1277 * See if we can build the value at compile time...
1278 */
1279
1280 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1281 TclNewObj(dictObj);
1282 Tcl_IncrRefCount(dictObj);
1283 for (i=1 ; i<parsePtr->numWords ; i+=2) {
1284 TclNewObj(keyObj);
1285 Tcl_IncrRefCount(keyObj);
1286 if (!TclWordKnownAtCompileTime(tokenPtr, keyObj)) {
1287 Tcl_DecrRefCount(keyObj);
1288 Tcl_DecrRefCount(dictObj);
1289 goto nonConstant;
1290 }
1291 tokenPtr = TokenAfter(tokenPtr);
1292 TclNewObj(valueObj);
1293 Tcl_IncrRefCount(valueObj);
1294 if (!TclWordKnownAtCompileTime(tokenPtr, valueObj)) {
1295 Tcl_DecrRefCount(keyObj);
1296 Tcl_DecrRefCount(valueObj);
1297 Tcl_DecrRefCount(dictObj);
1298 goto nonConstant;
1299 }
1300 tokenPtr = TokenAfter(tokenPtr);
1301 Tcl_DictObjPut(NULL, dictObj, keyObj, valueObj);
1302 Tcl_DecrRefCount(keyObj);
1303 Tcl_DecrRefCount(valueObj);
1304 }
1305
1306 /*
1307 * We did! Excellent. The "verifyDict" is to do type forcing.
1308 */
1309
1310 bytes = Tcl_GetStringFromObj(dictObj, &len);
1311 PushLiteral(envPtr, bytes, len);
1312 TclEmitOpcode( INST_DUP, envPtr);
1313 TclEmitOpcode( INST_DICT_VERIFY, envPtr);
1314 Tcl_DecrRefCount(dictObj);
1315 return TCL_OK;
1316
1317 /*
1318 * Otherwise, we've got to issue runtime code to do the building, which we
1319 * do by [dict set]ting into an unnamed local variable. This requires that
1320 * we are in a context with an LVT.
1321 */
1322
1323 nonConstant:
1324 worker = AnonymousLocal(envPtr);
1325 if (worker < 0) {
1326 return TclCompileBasicMin0ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1327 }
1328
1329 PushStringLiteral(envPtr, "");
1330 Emit14Inst( INST_STORE_SCALAR, worker, envPtr);
1331 TclEmitOpcode( INST_POP, envPtr);
1332 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1333 for (i=1 ; i<parsePtr->numWords ; i+=2) {
1334 CompileWord(envPtr, tokenPtr, interp, i);
1335 tokenPtr = TokenAfter(tokenPtr);
1336 CompileWord(envPtr, tokenPtr, interp, i+1);
1337 tokenPtr = TokenAfter(tokenPtr);
1338 TclEmitInstInt4( INST_DICT_SET, 1, envPtr);
1339 TclEmitInt4( worker, envPtr);
1340 TclAdjustStackDepth(-1, envPtr);
1341 TclEmitOpcode( INST_POP, envPtr);
1342 }
1343 Emit14Inst( INST_LOAD_SCALAR, worker, envPtr);
1344 TclEmitInstInt1( INST_UNSET_SCALAR, 0, envPtr);
1345 TclEmitInt4( worker, envPtr);
1346 return TCL_OK;
1347 }
1348
1349 int
1350 TclCompileDictMergeCmd(
1351 Tcl_Interp *interp, /* Used for looking up stuff. */
1352 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1353 * created by Tcl_ParseCommand. */
1354 Command *cmdPtr, /* Points to definition of command being
1355 * compiled. */
1356 CompileEnv *envPtr) /* Holds resulting instructions. */
1357 {
1358 DefineLineInformation; /* TIP #280 */
1359 Tcl_Token *tokenPtr;
1360 int i, workerIndex, infoIndex, outLoop;
1361
1362 /*
1363 * Deal with some special edge cases. Note that in the case with one
1364 * argument, the only thing to do is to verify the dict-ness.
1365 */
1366
1367 /* TODO: Consider support for compiling expanded args. (less likely) */
1368 if (parsePtr->numWords < 2) {
1369 PushStringLiteral(envPtr, "");
1370 return TCL_OK;
1371 } else if (parsePtr->numWords == 2) {
1372 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1373 CompileWord(envPtr, tokenPtr, interp, 1);
1374 TclEmitOpcode( INST_DUP, envPtr);
1375 TclEmitOpcode( INST_DICT_VERIFY, envPtr);
1376 return TCL_OK;
1377 }
1378
1379 /*
1380 * There's real merging work to do.
1381 *
1382 * Allocate some working space. This means we'll only ever compile this
1383 * command when there's an LVT present.
1384 */
1385
1386 workerIndex = AnonymousLocal(envPtr);
1387 if (workerIndex < 0) {
1388 return TclCompileBasicMin2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1389 }
1390 infoIndex = AnonymousLocal(envPtr);
1391
1392 /*
1393 * Get the first dictionary and verify that it is so.
1394 */
1395
1396 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1397 CompileWord(envPtr, tokenPtr, interp, 1);
1398 TclEmitOpcode( INST_DUP, envPtr);
1399 TclEmitOpcode( INST_DICT_VERIFY, envPtr);
1400 Emit14Inst( INST_STORE_SCALAR, workerIndex, envPtr);
1401 TclEmitOpcode( INST_POP, envPtr);
1402
1403 /*
1404 * For each of the remaining dictionaries...
1405 */
1406
1407 outLoop = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
1408 TclEmitInstInt4( INST_BEGIN_CATCH4, outLoop, envPtr);
1409 ExceptionRangeStarts(envPtr, outLoop);
1410 for (i=2 ; i<parsePtr->numWords ; i++) {
1411 /*
1412 * Get the dictionary, and merge its pairs into the first dict (using
1413 * a small loop).
1414 */
1415
1416 tokenPtr = TokenAfter(tokenPtr);
1417 CompileWord(envPtr, tokenPtr, interp, i);
1418 TclEmitInstInt4( INST_DICT_FIRST, infoIndex, envPtr);
1419 TclEmitInstInt1( INST_JUMP_TRUE1, 24, envPtr);
1420 TclEmitInstInt4( INST_REVERSE, 2, envPtr);
1421 TclEmitInstInt4( INST_DICT_SET, 1, envPtr);
1422 TclEmitInt4( workerIndex, envPtr);
1423 TclAdjustStackDepth(-1, envPtr);
1424 TclEmitOpcode( INST_POP, envPtr);
1425 TclEmitInstInt4( INST_DICT_NEXT, infoIndex, envPtr);
1426 TclEmitInstInt1( INST_JUMP_FALSE1, -20, envPtr);
1427 TclEmitOpcode( INST_POP, envPtr);
1428 TclEmitOpcode( INST_POP, envPtr);
1429 TclEmitInstInt1( INST_UNSET_SCALAR, 0, envPtr);
1430 TclEmitInt4( infoIndex, envPtr);
1431 }
1432 ExceptionRangeEnds(envPtr, outLoop);
1433 TclEmitOpcode( INST_END_CATCH, envPtr);
1434
1435 /*
1436 * Clean up any state left over.
1437 */
1438
1439 Emit14Inst( INST_LOAD_SCALAR, workerIndex, envPtr);
1440 TclEmitInstInt1( INST_UNSET_SCALAR, 0, envPtr);
1441 TclEmitInt4( workerIndex, envPtr);
1442 TclEmitInstInt1( INST_JUMP1, 18, envPtr);
1443
1444 /*
1445 * If an exception happens when starting to iterate over the second (and
1446 * subsequent) dicts. This is strictly not necessary, but it is nice.
1447 */
1448
1449 TclAdjustStackDepth(-1, envPtr);
1450 ExceptionRangeTarget(envPtr, outLoop, catchOffset);
1451 TclEmitOpcode( INST_PUSH_RETURN_OPTIONS, envPtr);
1452 TclEmitOpcode( INST_PUSH_RESULT, envPtr);
1453 TclEmitOpcode( INST_END_CATCH, envPtr);
1454 TclEmitInstInt1( INST_UNSET_SCALAR, 0, envPtr);
1455 TclEmitInt4( workerIndex, envPtr);
1456 TclEmitInstInt1( INST_UNSET_SCALAR, 0, envPtr);
1457 TclEmitInt4( infoIndex, envPtr);
1458 TclEmitOpcode( INST_RETURN_STK, envPtr);
1459
1460 return TCL_OK;
1461 }
1462
1463 int
1464 TclCompileDictForCmd(
1465 Tcl_Interp *interp, /* Used for looking up stuff. */
1466 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1467 * created by Tcl_ParseCommand. */
1468 Command *cmdPtr, /* Points to definition of command being
1469 * compiled. */
1470 CompileEnv *envPtr) /* Holds resulting instructions. */
1471 {
1472 return CompileDictEachCmd(interp, parsePtr, cmdPtr, envPtr,
1473 TCL_EACH_KEEP_NONE);
1474 }
1475
1476 int
1477 TclCompileDictMapCmd(
1478 Tcl_Interp *interp, /* Used for looking up stuff. */
1479 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1480 * created by Tcl_ParseCommand. */
1481 Command *cmdPtr, /* Points to definition of command being
1482 * compiled. */
1483 CompileEnv *envPtr) /* Holds resulting instructions. */
1484 {
1485 return CompileDictEachCmd(interp, parsePtr, cmdPtr, envPtr,
1486 TCL_EACH_COLLECT);
1487 }
1488
1489 int
1490 CompileDictEachCmd(
1491 Tcl_Interp *interp, /* Used for looking up stuff. */
1492 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1493 * created by Tcl_ParseCommand. */
1494 Command *cmdPtr, /* Points to definition of command being
1495 * compiled. */
1496 CompileEnv *envPtr, /* Holds resulting instructions. */
1497 int collect) /* Flag == TCL_EACH_COLLECT to collect and
1498 * construct a new dictionary with the loop
1499 * body result. */
1500 {
1501 DefineLineInformation; /* TIP #280 */
1502 Tcl_Token *varsTokenPtr, *dictTokenPtr, *bodyTokenPtr;
1503 int keyVarIndex, valueVarIndex, nameChars, loopRange, catchRange;
1504 int infoIndex, jumpDisplacement, bodyTargetOffset, emptyTargetOffset;
1505 int numVars, endTargetOffset;
1506 int collectVar = -1; /* Index of temp var holding the result
1507 * dict. */
1508 const char **argv;
1509 Tcl_DString buffer;
1510
1511 /*
1512 * There must be three arguments after the command.
1513 */
1514
1515 if (parsePtr->numWords != 4) {
1516 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1517 }
1518
1519 varsTokenPtr = TokenAfter(parsePtr->tokenPtr);
1520 dictTokenPtr = TokenAfter(varsTokenPtr);
1521 bodyTokenPtr = TokenAfter(dictTokenPtr);
1522 if (varsTokenPtr->type != TCL_TOKEN_SIMPLE_WORD ||
1523 bodyTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
1524 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1525 }
1526
1527 /*
1528 * Create temporary variable to capture return values from loop body when
1529 * we're collecting results.
1530 */
1531
1532 if (collect == TCL_EACH_COLLECT) {
1533 collectVar = AnonymousLocal(envPtr);
1534 if (collectVar < 0) {
1535 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1536 }
1537 }
1538
1539 /*
1540 * Check we've got a pair of variables and that they are local variables.
1541 * Then extract their indices in the LVT.
1542 */
1543
1544 Tcl_DStringInit(&buffer);
1545 TclDStringAppendToken(&buffer, &varsTokenPtr[1]);
1546 if (Tcl_SplitList(NULL, Tcl_DStringValue(&buffer), &numVars,
1547 &argv) != TCL_OK) {
1548 Tcl_DStringFree(&buffer);
1549 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1550 }
1551 Tcl_DStringFree(&buffer);
1552 if (numVars != 2) {
1553 ckfree(argv);
1554 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1555 }
1556
1557 nameChars = strlen(argv[0]);
1558 keyVarIndex = LocalScalar(argv[0], nameChars, envPtr);
1559 nameChars = strlen(argv[1]);
1560 valueVarIndex = LocalScalar(argv[1], nameChars, envPtr);
1561 ckfree(argv);
1562
1563 if ((keyVarIndex < 0) || (valueVarIndex < 0)) {
1564 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1565 }
1566
1567 /*
1568 * Allocate a temporary variable to store the iterator reference. The
1569 * variable will contain a Tcl_DictSearch reference which will be
1570 * allocated by INST_DICT_FIRST and disposed when the variable is unset
1571 * (at which point it should also have been finished with).
1572 */
1573
1574 infoIndex = AnonymousLocal(envPtr);
1575 if (infoIndex < 0) {
1576 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1577 }
1578
1579 /*
1580 * Preparation complete; issue instructions. Note that this code issues
1581 * fixed-sized jumps. That simplifies things a lot!
1582 *
1583 * First up, initialize the accumulator dictionary if needed.
1584 */
1585
1586 if (collect == TCL_EACH_COLLECT) {
1587 PushStringLiteral(envPtr, "");
1588 Emit14Inst( INST_STORE_SCALAR, collectVar, envPtr);
1589 TclEmitOpcode( INST_POP, envPtr);
1590 }
1591
1592 /*
1593 * Get the dictionary and start the iteration. No catching of errors at
1594 * this point.
1595 */
1596
1597 CompileWord(envPtr, dictTokenPtr, interp, 2);
1598
1599 /*
1600 * Now we catch errors from here on so that we can finalize the search
1601 * started by Tcl_DictObjFirst above.
1602 */
1603
1604 catchRange = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
1605 TclEmitInstInt4( INST_BEGIN_CATCH4, catchRange, envPtr);
1606 ExceptionRangeStarts(envPtr, catchRange);
1607
1608 TclEmitInstInt4( INST_DICT_FIRST, infoIndex, envPtr);
1609 emptyTargetOffset = CurrentOffset(envPtr);
1610 TclEmitInstInt4( INST_JUMP_TRUE4, 0, envPtr);
1611
1612 /*
1613 * Inside the iteration, write the loop variables.
1614 */
1615
1616 bodyTargetOffset = CurrentOffset(envPtr);
1617 Emit14Inst( INST_STORE_SCALAR, keyVarIndex, envPtr);
1618 TclEmitOpcode( INST_POP, envPtr);
1619 Emit14Inst( INST_STORE_SCALAR, valueVarIndex, envPtr);
1620 TclEmitOpcode( INST_POP, envPtr);
1621
1622 /*
1623 * Set up the loop exception targets.
1624 */
1625
1626 loopRange = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
1627 ExceptionRangeStarts(envPtr, loopRange);
1628
1629 /*
1630 * Compile the loop body itself. It should be stack-neutral.
1631 */
1632
1633 BODY(bodyTokenPtr, 3);
1634 if (collect == TCL_EACH_COLLECT) {
1635 Emit14Inst( INST_LOAD_SCALAR, keyVarIndex, envPtr);
1636 TclEmitInstInt4(INST_OVER, 1, envPtr);
1637 TclEmitInstInt4(INST_DICT_SET, 1, envPtr);
1638 TclEmitInt4( collectVar, envPtr);
1639 TclAdjustStackDepth(-1, envPtr);
1640 TclEmitOpcode( INST_POP, envPtr);
1641 }
1642 TclEmitOpcode( INST_POP, envPtr);
1643
1644 /*
1645 * Both exception target ranges (error and loop) end here.
1646 */
1647
1648 ExceptionRangeEnds(envPtr, loopRange);
1649 ExceptionRangeEnds(envPtr, catchRange);
1650
1651 /*
1652 * Continue (or just normally process) by getting the next pair of items
1653 * from the dictionary and jumping back to the code to write them into
1654 * variables if there is another pair.
1655 */
1656
1657 ExceptionRangeTarget(envPtr, loopRange, continueOffset);
1658 TclEmitInstInt4( INST_DICT_NEXT, infoIndex, envPtr);
1659 jumpDisplacement = bodyTargetOffset - CurrentOffset(envPtr);
1660 TclEmitInstInt4( INST_JUMP_FALSE4, jumpDisplacement, envPtr);
1661 endTargetOffset = CurrentOffset(envPtr);
1662 TclEmitInstInt1( INST_JUMP1, 0, envPtr);
1663
1664 /*
1665 * Error handler "finally" clause, which force-terminates the iteration
1666 * and re-throws the error.
1667 */
1668
1669 TclAdjustStackDepth(-1, envPtr);
1670 ExceptionRangeTarget(envPtr, catchRange, catchOffset);
1671 TclEmitOpcode( INST_PUSH_RETURN_OPTIONS, envPtr);
1672 TclEmitOpcode( INST_PUSH_RESULT, envPtr);
1673 TclEmitOpcode( INST_END_CATCH, envPtr);
1674 TclEmitInstInt1( INST_UNSET_SCALAR, 0, envPtr);
1675 TclEmitInt4( infoIndex, envPtr);
1676 if (collect == TCL_EACH_COLLECT) {
1677 TclEmitInstInt1(INST_UNSET_SCALAR, 0, envPtr);
1678 TclEmitInt4( collectVar, envPtr);
1679 }
1680 TclEmitOpcode( INST_RETURN_STK, envPtr);
1681
1682 /*
1683 * Otherwise we're done (the jump after the DICT_FIRST points here) and we
1684 * need to pop the bogus key/value pair (pushed to keep stack calculations
1685 * easy!) Note that we skip the END_CATCH. [Bug 1382528]
1686 */
1687
1688 jumpDisplacement = CurrentOffset(envPtr) - emptyTargetOffset;
1689 TclUpdateInstInt4AtPc(INST_JUMP_TRUE4, jumpDisplacement,
1690 envPtr->codeStart + emptyTargetOffset);
1691 jumpDisplacement = CurrentOffset(envPtr) - endTargetOffset;
1692 TclUpdateInstInt1AtPc(INST_JUMP1, jumpDisplacement,
1693 envPtr->codeStart + endTargetOffset);
1694 TclEmitOpcode( INST_POP, envPtr);
1695 TclEmitOpcode( INST_POP, envPtr);
1696 ExceptionRangeTarget(envPtr, loopRange, breakOffset);
1697 TclFinalizeLoopExceptionRange(envPtr, loopRange);
1698 TclEmitOpcode( INST_END_CATCH, envPtr);
1699
1700 /*
1701 * Final stage of the command (normal case) is that we push an empty
1702 * object (or push the accumulator as the result object). This is done
1703 * last to promote peephole optimization when it's dropped immediately.
1704 */
1705
1706 TclEmitInstInt1( INST_UNSET_SCALAR, 0, envPtr);
1707 TclEmitInt4( infoIndex, envPtr);
1708 if (collect == TCL_EACH_COLLECT) {
1709 Emit14Inst( INST_LOAD_SCALAR, collectVar, envPtr);
1710 TclEmitInstInt1(INST_UNSET_SCALAR, 0, envPtr);
1711 TclEmitInt4( collectVar, envPtr);
1712 } else {
1713 PushStringLiteral(envPtr, "");
1714 }
1715 return TCL_OK;
1716 }
1717
1718 int
1719 TclCompileDictUpdateCmd(
1720 Tcl_Interp *interp, /* Used for looking up stuff. */
1721 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1722 * created by Tcl_ParseCommand. */
1723 Command *cmdPtr, /* Points to definition of command being
1724 * compiled. */
1725 CompileEnv *envPtr) /* Holds resulting instructions. */
1726 {
1727 DefineLineInformation; /* TIP #280 */
1728 int i, dictIndex, numVars, range, infoIndex;
1729 Tcl_Token **keyTokenPtrs, *dictVarTokenPtr, *bodyTokenPtr, *tokenPtr;
1730 DictUpdateInfo *duiPtr;
1731 JumpFixup jumpFixup;
1732
1733 /*
1734 * There must be at least one argument after the command.
1735 */
1736
1737 if (parsePtr->numWords < 5) {
1738 return TCL_ERROR;
1739 }
1740
1741 /*
1742 * Parse the command. Expect the following:
1743 * dict update <lit(eral)> <any> <lit> ?<any> <lit> ...? <lit>
1744 */
1745
1746 if ((parsePtr->numWords - 1) & 1) {
1747 return TCL_ERROR;
1748 }
1749 numVars = (parsePtr->numWords - 3) / 2;
1750
1751 /*
1752 * The dictionary variable must be a local scalar that is knowable at
1753 * compile time; anything else exceeds the complexity of the opcode. So
1754 * discover what the index is.
1755 */
1756
1757 dictVarTokenPtr = TokenAfter(parsePtr->tokenPtr);
1758 dictIndex = LocalScalarFromToken(dictVarTokenPtr, envPtr);
1759 if (dictIndex < 0) {
1760 goto issueFallback;
1761 }
1762
1763 /*
1764 * Assemble the instruction metadata. This is complex enough that it is
1765 * represented as auxData; it holds an ordered list of variable indices
1766 * that are to be used.
1767 */
1768
1769 duiPtr = (DictUpdateInfo *)ckalloc(TclOffset(DictUpdateInfo, varIndices) + sizeof(int) * numVars);
1770 duiPtr->length = numVars;
1771 keyTokenPtrs = (Tcl_Token **)TclStackAlloc(interp, sizeof(Tcl_Token *) * numVars);
1772 tokenPtr = TokenAfter(dictVarTokenPtr);
1773
1774 for (i=0 ; i<numVars ; i++) {
1775 /*
1776 * Put keys to one side for later compilation to bytecode.
1777 */
1778
1779 keyTokenPtrs[i] = tokenPtr;
1780 tokenPtr = TokenAfter(tokenPtr);
1781
1782 /*
1783 * Stash the index in the auxiliary data (if it is indeed a local
1784 * scalar that is resolvable at compile-time).
1785 */
1786
1787 duiPtr->varIndices[i] = LocalScalarFromToken(tokenPtr, envPtr);
1788 if (duiPtr->varIndices[i] < 0) {
1789 goto failedUpdateInfoAssembly;
1790 }
1791 tokenPtr = TokenAfter(tokenPtr);
1792 }
1793 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
1794 goto failedUpdateInfoAssembly;
1795 }
1796 bodyTokenPtr = tokenPtr;
1797
1798 /*
1799 * The list of variables to bind is stored in auxiliary data so that it
1800 * can't be snagged by literal sharing and forced to shimmer dangerously.
1801 */
1802
1803 infoIndex = TclCreateAuxData(duiPtr, &dictUpdateInfoType, envPtr);
1804
1805 for (i=0 ; i<numVars ; i++) {
1806 CompileWord(envPtr, keyTokenPtrs[i], interp, 2*i+2);
1807 }
1808 TclEmitInstInt4( INST_LIST, numVars, envPtr);
1809 TclEmitInstInt4( INST_DICT_UPDATE_START, dictIndex, envPtr);
1810 TclEmitInt4( infoIndex, envPtr);
1811
1812 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
1813 TclEmitInstInt4( INST_BEGIN_CATCH4, range, envPtr);
1814
1815 ExceptionRangeStarts(envPtr, range);
1816 BODY(bodyTokenPtr, parsePtr->numWords - 1);
1817 ExceptionRangeEnds(envPtr, range);
1818
1819 /*
1820 * Normal termination code: the stack has the key list below the result of
1821 * the body evaluation: swap them and finish the update code.
1822 */
1823
1824 TclEmitOpcode( INST_END_CATCH, envPtr);
1825 TclEmitInstInt4( INST_REVERSE, 2, envPtr);
1826 TclEmitInstInt4( INST_DICT_UPDATE_END, dictIndex, envPtr);
1827 TclEmitInt4( infoIndex, envPtr);
1828
1829 /*
1830 * Jump around the exceptional termination code.
1831 */
1832
1833 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpFixup);
1834
1835 /*
1836 * Termination code for non-ok returns: stash the result and return
1837 * options in the stack, bring up the key list, finish the update code,
1838 * and finally return with the caught return data
1839 */
1840
1841 ExceptionRangeTarget(envPtr, range, catchOffset);
1842 TclEmitOpcode( INST_PUSH_RESULT, envPtr);
1843 TclEmitOpcode( INST_PUSH_RETURN_OPTIONS, envPtr);
1844 TclEmitOpcode( INST_END_CATCH, envPtr);
1845 TclEmitInstInt4( INST_REVERSE, 3, envPtr);
1846
1847 TclEmitInstInt4( INST_DICT_UPDATE_END, dictIndex, envPtr);
1848 TclEmitInt4( infoIndex, envPtr);
1849 TclEmitInvoke(envPtr,INST_RETURN_STK);
1850
1851 if (TclFixupForwardJumpToHere(envPtr, &jumpFixup, 127)) {
1852 Tcl_Panic("TclCompileDictCmd(update): bad jump distance %d",
1853 (int) (CurrentOffset(envPtr) - jumpFixup.codeOffset));
1854 }
1855 TclStackFree(interp, keyTokenPtrs);
1856 return TCL_OK;
1857
1858 /*
1859 * Clean up after a failure to create the DictUpdateInfo structure.
1860 */
1861
1862 failedUpdateInfoAssembly:
1863 ckfree(duiPtr);
1864 TclStackFree(interp, keyTokenPtrs);
1865 issueFallback:
1866 return TclCompileBasicMin2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1867 }
1868
1869 int
1870 TclCompileDictAppendCmd(
1871 Tcl_Interp *interp, /* Used for looking up stuff. */
1872 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1873 * created by Tcl_ParseCommand. */
1874 Command *cmdPtr, /* Points to definition of command being
1875 * compiled. */
1876 CompileEnv *envPtr) /* Holds resulting instructions. */
1877 {
1878 DefineLineInformation; /* TIP #280 */
1879 Tcl_Token *tokenPtr;
1880 int i, dictVarIndex;
1881
1882 /*
1883 * There must be at least two argument after the command. And we impose an
1884 * (arbitrary) safe limit; anyone exceeding it should stop worrying about
1885 * speed quite so much. ;-)
1886 */
1887
1888 /* TODO: Consider support for compiling expanded args. */
1889 if (parsePtr->numWords<4 || parsePtr->numWords>100) {
1890 return TCL_ERROR;
1891 }
1892
1893 /*
1894 * Get the index of the local variable that we will be working with.
1895 */
1896
1897 tokenPtr = TokenAfter(parsePtr->tokenPtr);
1898 dictVarIndex = LocalScalarFromToken(tokenPtr, envPtr);
1899 if (dictVarIndex < 0) {
1900 return TclCompileBasicMin2ArgCmd(interp, parsePtr,cmdPtr, envPtr);
1901 }
1902
1903 /*
1904 * Produce the string to concatenate onto the dictionary entry.
1905 */
1906
1907 tokenPtr = TokenAfter(tokenPtr);
1908 for (i=2 ; i<parsePtr->numWords ; i++) {
1909 CompileWord(envPtr, tokenPtr, interp, i);
1910 tokenPtr = TokenAfter(tokenPtr);
1911 }
1912 if (parsePtr->numWords > 4) {
1913 TclEmitInstInt1(INST_STR_CONCAT1, parsePtr->numWords-3, envPtr);
1914 }
1915
1916 /*
1917 * Do the concatenation.
1918 */
1919
1920 TclEmitInstInt4(INST_DICT_APPEND, dictVarIndex, envPtr);
1921 return TCL_OK;
1922 }
1923
1924 int
1925 TclCompileDictLappendCmd(
1926 Tcl_Interp *interp, /* Used for looking up stuff. */
1927 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1928 * created by Tcl_ParseCommand. */
1929 Command *cmdPtr, /* Points to definition of command being
1930 * compiled. */
1931 CompileEnv *envPtr) /* Holds resulting instructions. */
1932 {
1933 DefineLineInformation; /* TIP #280 */
1934 Tcl_Token *varTokenPtr, *keyTokenPtr, *valueTokenPtr;
1935 int dictVarIndex;
1936
1937 /*
1938 * There must be three arguments after the command.
1939 */
1940
1941 /* TODO: Consider support for compiling expanded args. */
1942 /* Probably not. Why is INST_DICT_LAPPEND limited to one value? */
1943 if (parsePtr->numWords != 4) {
1944 return TCL_ERROR;
1945 }
1946
1947 /*
1948 * Parse the arguments.
1949 */
1950
1951 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
1952 keyTokenPtr = TokenAfter(varTokenPtr);
1953 valueTokenPtr = TokenAfter(keyTokenPtr);
1954 dictVarIndex = LocalScalarFromToken(varTokenPtr, envPtr);
1955 if (dictVarIndex < 0) {
1956 return TclCompileBasic3ArgCmd(interp, parsePtr, cmdPtr, envPtr);
1957 }
1958
1959 /*
1960 * Issue the implementation.
1961 */
1962
1963 CompileWord(envPtr, keyTokenPtr, interp, 2);
1964 CompileWord(envPtr, valueTokenPtr, interp, 3);
1965 TclEmitInstInt4( INST_DICT_LAPPEND, dictVarIndex, envPtr);
1966 return TCL_OK;
1967 }
1968
1969 int
1970 TclCompileDictWithCmd(
1971 Tcl_Interp *interp, /* Used for looking up stuff. */
1972 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
1973 * created by Tcl_ParseCommand. */
1974 Command *cmdPtr, /* Points to definition of command being
1975 * compiled. */
1976 CompileEnv *envPtr) /* Holds resulting instructions. */
1977 {
1978 DefineLineInformation; /* TIP #280 */
1979 int i, range, varNameTmp = -1, pathTmp = -1, keysTmp, gotPath;
1980 int dictVar, bodyIsEmpty = 1;
1981 Tcl_Token *varTokenPtr, *tokenPtr;
1982 JumpFixup jumpFixup;
1983 const char *ptr, *end;
1984
1985 /*
1986 * There must be at least one argument after the command.
1987 */
1988
1989 /* TODO: Consider support for compiling expanded args. */
1990 if (parsePtr->numWords < 3) {
1991 return TCL_ERROR;
1992 }
1993
1994 /*
1995 * Parse the command (trivially). Expect the following:
1996 * dict with <any (varName)> ?<any> ...? <literal>
1997 */
1998
1999 varTokenPtr = TokenAfter(parsePtr->tokenPtr);
2000 tokenPtr = TokenAfter(varTokenPtr);
2001 for (i=3 ; i<parsePtr->numWords ; i++) {
2002 tokenPtr = TokenAfter(tokenPtr);
2003 }
2004 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2005 return TclCompileBasicMin2ArgCmd(interp, parsePtr, cmdPtr, envPtr);
2006 }
2007
2008 /*
2009 * Test if the last word is an empty script; if so, we can compile it in
2010 * all cases, but if it is non-empty we need local variable table entries
2011 * to hold the temporary variables (used to keep stack usage simple).
2012 */
2013
2014 for (ptr=tokenPtr[1].start,end=ptr+tokenPtr[1].size ; ptr!=end ; ptr++) {
2015 if (*ptr!=' ' && *ptr!='\t' && *ptr!='\n' && *ptr!='\r') {
2016 if (envPtr->procPtr == NULL) {
2017 return TclCompileBasicMin2ArgCmd(interp, parsePtr, cmdPtr,
2018 envPtr);
2019 }
2020 bodyIsEmpty = 0;
2021 break;
2022 }
2023 }
2024
2025 /*
2026 * Determine if we're manipulating a dict in a simple local variable.
2027 */
2028
2029 gotPath = (parsePtr->numWords > 3);
2030 dictVar = LocalScalarFromToken(varTokenPtr, envPtr);
2031
2032 /*
2033 * Special case: an empty body means we definitely have no need to issue
2034 * try-finally style code or to allocate local variable table entries for
2035 * storing temporaries. Still need to do both INST_DICT_EXPAND and
2036 * INST_DICT_RECOMBINE_* though, because we can't determine if we're free
2037 * of traces.
2038 */
2039
2040 if (bodyIsEmpty) {
2041 if (dictVar >= 0) {
2042 if (gotPath) {
2043 /*
2044 * Case: Path into dict in LVT with empty body.
2045 */
2046
2047 tokenPtr = TokenAfter(varTokenPtr);
2048 for (i=2 ; i<parsePtr->numWords-1 ; i++) {
2049 CompileWord(envPtr, tokenPtr, interp, i);
2050 tokenPtr = TokenAfter(tokenPtr);
2051 }
2052 TclEmitInstInt4(INST_LIST, parsePtr->numWords-3,envPtr);
2053 Emit14Inst( INST_LOAD_SCALAR, dictVar, envPtr);
2054 TclEmitInstInt4(INST_OVER, 1, envPtr);
2055 TclEmitOpcode( INST_DICT_EXPAND, envPtr);
2056 TclEmitInstInt4(INST_DICT_RECOMBINE_IMM, dictVar, envPtr);
2057 } else {
2058 /*
2059 * Case: Direct dict in LVT with empty body.
2060 */
2061
2062 PushStringLiteral(envPtr, "");
2063 Emit14Inst( INST_LOAD_SCALAR, dictVar, envPtr);
2064 PushStringLiteral(envPtr, "");
2065 TclEmitOpcode( INST_DICT_EXPAND, envPtr);
2066 TclEmitInstInt4(INST_DICT_RECOMBINE_IMM, dictVar, envPtr);
2067 }
2068 } else {
2069 if (gotPath) {
2070 /*
2071 * Case: Path into dict in non-simple var with empty body.
2072 */
2073
2074 tokenPtr = varTokenPtr;
2075 for (i=1 ; i<parsePtr->numWords-1 ; i++) {
2076 CompileWord(envPtr, tokenPtr, interp, i);
2077 tokenPtr = TokenAfter(tokenPtr);
2078 }
2079 TclEmitInstInt4(INST_LIST, parsePtr->numWords-3,envPtr);
2080 TclEmitInstInt4(INST_OVER, 1, envPtr);
2081 TclEmitOpcode( INST_LOAD_STK, envPtr);
2082 TclEmitInstInt4(INST_OVER, 1, envPtr);
2083 TclEmitOpcode( INST_DICT_EXPAND, envPtr);
2084 TclEmitOpcode( INST_DICT_RECOMBINE_STK, envPtr);
2085 } else {
2086 /*
2087 * Case: Direct dict in non-simple var with empty body.
2088 */
2089
2090 CompileWord(envPtr, varTokenPtr, interp, 1);
2091 TclEmitOpcode( INST_DUP, envPtr);
2092 TclEmitOpcode( INST_LOAD_STK, envPtr);
2093 PushStringLiteral(envPtr, "");
2094 TclEmitOpcode( INST_DICT_EXPAND, envPtr);
2095 PushStringLiteral(envPtr, "");
2096 TclEmitInstInt4(INST_REVERSE, 2, envPtr);
2097 TclEmitOpcode( INST_DICT_RECOMBINE_STK, envPtr);
2098 }
2099 }
2100 PushStringLiteral(envPtr, "");
2101 return TCL_OK;
2102 }
2103
2104 /*
2105 * OK, we have a non-trivial body. This means that the focus is on
2106 * generating a try-finally structure where the INST_DICT_RECOMBINE_* goes
2107 * in the 'finally' clause.
2108 *
2109 * Start by allocating local (unnamed, untraced) working variables.
2110 */
2111
2112 if (dictVar == -1) {
2113 varNameTmp = AnonymousLocal(envPtr);
2114 }
2115 if (gotPath) {
2116 pathTmp = AnonymousLocal(envPtr);
2117 }
2118 keysTmp = AnonymousLocal(envPtr);
2119
2120 /*
2121 * Issue instructions. First, the part to expand the dictionary.
2122 */
2123
2124 if (dictVar == -1) {
2125 CompileWord(envPtr, varTokenPtr, interp, 1);
2126 Emit14Inst( INST_STORE_SCALAR, varNameTmp, envPtr);
2127 }
2128 tokenPtr = TokenAfter(varTokenPtr);
2129 if (gotPath) {
2130 for (i=2 ; i<parsePtr->numWords-1 ; i++) {
2131 CompileWord(envPtr, tokenPtr, interp, i);
2132 tokenPtr = TokenAfter(tokenPtr);
2133 }
2134 TclEmitInstInt4( INST_LIST, parsePtr->numWords-3,envPtr);
2135 Emit14Inst( INST_STORE_SCALAR, pathTmp, envPtr);
2136 TclEmitOpcode( INST_POP, envPtr);
2137 }
2138 if (dictVar == -1) {
2139 TclEmitOpcode( INST_LOAD_STK, envPtr);
2140 } else {
2141 Emit14Inst( INST_LOAD_SCALAR, dictVar, envPtr);
2142 }
2143 if (gotPath) {
2144 Emit14Inst( INST_LOAD_SCALAR, pathTmp, envPtr);
2145 } else {
2146 PushStringLiteral(envPtr, "");
2147 }
2148 TclEmitOpcode( INST_DICT_EXPAND, envPtr);
2149 Emit14Inst( INST_STORE_SCALAR, keysTmp, envPtr);
2150 TclEmitOpcode( INST_POP, envPtr);
2151
2152 /*
2153 * Now the body of the [dict with].
2154 */
2155
2156 range = TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
2157 TclEmitInstInt4( INST_BEGIN_CATCH4, range, envPtr);
2158
2159 ExceptionRangeStarts(envPtr, range);
2160 BODY(tokenPtr, parsePtr->numWords - 1);
2161 ExceptionRangeEnds(envPtr, range);
2162
2163 /*
2164 * Now fold the results back into the dictionary in the OK case.
2165 */
2166
2167 TclEmitOpcode( INST_END_CATCH, envPtr);
2168 if (dictVar == -1) {
2169 Emit14Inst( INST_LOAD_SCALAR, varNameTmp, envPtr);
2170 }
2171 if (gotPath) {
2172 Emit14Inst( INST_LOAD_SCALAR, pathTmp, envPtr);
2173 } else {
2174 PushStringLiteral(envPtr, "");
2175 }
2176 Emit14Inst( INST_LOAD_SCALAR, keysTmp, envPtr);
2177 if (dictVar == -1) {
2178 TclEmitOpcode( INST_DICT_RECOMBINE_STK, envPtr);
2179 } else {
2180 TclEmitInstInt4( INST_DICT_RECOMBINE_IMM, dictVar, envPtr);
2181 }
2182 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpFixup);
2183
2184 /*
2185 * Now fold the results back into the dictionary in the exception case.
2186 */
2187
2188 TclAdjustStackDepth(-1, envPtr);
2189 ExceptionRangeTarget(envPtr, range, catchOffset);
2190 TclEmitOpcode( INST_PUSH_RETURN_OPTIONS, envPtr);
2191 TclEmitOpcode( INST_PUSH_RESULT, envPtr);
2192 TclEmitOpcode( INST_END_CATCH, envPtr);
2193 if (dictVar == -1) {
2194 Emit14Inst( INST_LOAD_SCALAR, varNameTmp, envPtr);
2195 }
2196 if (parsePtr->numWords > 3) {
2197 Emit14Inst( INST_LOAD_SCALAR, pathTmp, envPtr);
2198 } else {
2199 PushStringLiteral(envPtr, "");
2200 }
2201 Emit14Inst( INST_LOAD_SCALAR, keysTmp, envPtr);
2202 if (dictVar == -1) {
2203 TclEmitOpcode( INST_DICT_RECOMBINE_STK, envPtr);
2204 } else {
2205 TclEmitInstInt4( INST_DICT_RECOMBINE_IMM, dictVar, envPtr);
2206 }
2207 TclEmitInvoke(envPtr, INST_RETURN_STK);
2208
2209 /*
2210 * Prepare for the start of the next command.
2211 */
2212
2213 if (TclFixupForwardJumpToHere(envPtr, &jumpFixup, 127)) {
2214 Tcl_Panic("TclCompileDictCmd(update): bad jump distance %d",
2215 (int) (CurrentOffset(envPtr) - jumpFixup.codeOffset));
2216 }
2217 return TCL_OK;
2218 }
2219
2220 /*
2221 *----------------------------------------------------------------------
2222 *
2223 * DupDictUpdateInfo, FreeDictUpdateInfo --
2224 *
2225 * Functions to duplicate, release and print the aux data created for use
2226 * with the INST_DICT_UPDATE_START and INST_DICT_UPDATE_END instructions.
2227 *
2228 * Results:
2229 * DupDictUpdateInfo: a copy of the auxiliary data
2230 * FreeDictUpdateInfo: none
2231 * PrintDictUpdateInfo: none
2232 * DisassembleDictUpdateInfo: none
2233 *
2234 * Side effects:
2235 * DupDictUpdateInfo: allocates memory
2236 * FreeDictUpdateInfo: releases memory
2237 * PrintDictUpdateInfo: none
2238 * DisassembleDictUpdateInfo: none
2239 *
2240 *----------------------------------------------------------------------
2241 */
2242
2243 static ClientData
2244 DupDictUpdateInfo(
2245 ClientData clientData)
2246 {
2247 DictUpdateInfo *dui1Ptr, *dui2Ptr;
2248 size_t len;
2249
2250 dui1Ptr = (DictUpdateInfo *)clientData;
2251 len = TclOffset(DictUpdateInfo, varIndices) + sizeof(int) * dui1Ptr->length;
2252 dui2Ptr = (DictUpdateInfo *)ckalloc(len);
2253 memcpy(dui2Ptr, dui1Ptr, len);
2254 return dui2Ptr;
2255 }
2256
2257 static void
2258 FreeDictUpdateInfo(
2259 ClientData clientData)
2260 {
2261 ckfree(clientData);
2262 }
2263
2264 static void
2265 PrintDictUpdateInfo(
2266 ClientData clientData,
2267 Tcl_Obj *appendObj,
2268 ByteCode *codePtr,
2269 unsigned int pcOffset)
2270 {
2271 DictUpdateInfo *duiPtr = (DictUpdateInfo *)clientData;
2272 int i;
2273
2274 for (i=0 ; i<duiPtr->length ; i++) {
2275 if (i) {
2276 Tcl_AppendToObj(appendObj, ", ", -1);
2277 }
2278 Tcl_AppendPrintfToObj(appendObj, "%%v%u", duiPtr->varIndices[i]);
2279 }
2280 }
2281
2282 static void
2283 DisassembleDictUpdateInfo(
2284 ClientData clientData,
2285 Tcl_Obj *dictObj,
2286 ByteCode *codePtr,
2287 unsigned int pcOffset)
2288 {
2289 DictUpdateInfo *duiPtr = (DictUpdateInfo *)clientData;
2290 int i;
2291 Tcl_Obj *variables;
2292
2293 TclNewObj(variables);
2294 for (i=0 ; i<duiPtr->length ; i++) {
2295 Tcl_ListObjAppendElement(NULL, variables,
2296 Tcl_NewIntObj(duiPtr->varIndices[i]));
2297 }
2298 TclDictPut(NULL, dictObj, "variables", variables);
2299 }
2300
2301 /*
2302 *----------------------------------------------------------------------
2303 *
2304 * TclCompileErrorCmd --
2305 *
2306 * Procedure called to compile the "error" command.
2307 *
2308 * Results:
2309 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2310 * evaluation to runtime.
2311 *
2312 * Side effects:
2313 * Instructions are added to envPtr to execute the "error" command at
2314 * runtime.
2315 *
2316 *----------------------------------------------------------------------
2317 */
2318
2319 int
2320 TclCompileErrorCmd(
2321 Tcl_Interp *interp, /* Used for context. */
2322 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2323 * created by Tcl_ParseCommand. */
2324 Command *cmdPtr, /* Points to definition of command being
2325 * compiled. */
2326 CompileEnv *envPtr) /* Holds resulting instructions. */
2327 {
2328 DefineLineInformation; /* TIP #280 */
2329 Tcl_Token *tokenPtr;
2330
2331 /*
2332 * General syntax: [error message ?errorInfo? ?errorCode?]
2333 */
2334
2335 if (parsePtr->numWords < 2 || parsePtr->numWords > 4) {
2336 return TCL_ERROR;
2337 }
2338
2339 /*
2340 * Handle the message.
2341 */
2342
2343 tokenPtr = TokenAfter(parsePtr->tokenPtr);
2344 CompileWord(envPtr, tokenPtr, interp, 1);
2345
2346 /*
2347 * Construct the options. Note that -code and -level are not here.
2348 */
2349
2350 if (parsePtr->numWords == 2) {
2351 PushStringLiteral(envPtr, "");
2352 } else {
2353 PushStringLiteral(envPtr, "-errorinfo");
2354 tokenPtr = TokenAfter(tokenPtr);
2355 CompileWord(envPtr, tokenPtr, interp, 2);
2356 if (parsePtr->numWords == 3) {
2357 TclEmitInstInt4( INST_LIST, 2, envPtr);
2358 } else {
2359 PushStringLiteral(envPtr, "-errorcode");
2360 tokenPtr = TokenAfter(tokenPtr);
2361 CompileWord(envPtr, tokenPtr, interp, 3);
2362 TclEmitInstInt4( INST_LIST, 4, envPtr);
2363 }
2364 }
2365
2366 /*
2367 * Issue the error via 'returnImm error 0'.
2368 */
2369
2370 TclEmitInstInt4( INST_RETURN_IMM, TCL_ERROR, envPtr);
2371 TclEmitInt4( 0, envPtr);
2372 return TCL_OK;
2373 }
2374
2375 /*
2376 *----------------------------------------------------------------------
2377 *
2378 * TclCompileExprCmd --
2379 *
2380 * Procedure called to compile the "expr" command.
2381 *
2382 * Results:
2383 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2384 * evaluation to runtime.
2385 *
2386 * Side effects:
2387 * Instructions are added to envPtr to execute the "expr" command at
2388 * runtime.
2389 *
2390 *----------------------------------------------------------------------
2391 */
2392
2393 int
2394 TclCompileExprCmd(
2395 Tcl_Interp *interp, /* Used for error reporting. */
2396 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2397 * created by Tcl_ParseCommand. */
2398 Command *cmdPtr, /* Points to definition of command being
2399 * compiled. */
2400 CompileEnv *envPtr) /* Holds resulting instructions. */
2401 {
2402 Tcl_Token *firstWordPtr;
2403
2404 if (parsePtr->numWords == 1) {
2405 return TCL_ERROR;
2406 }
2407
2408 /*
2409 * TIP #280: Use the per-word line information of the current command.
2410 */
2411
2412 envPtr->line = envPtr->extCmdMapPtr->loc[
2413 envPtr->extCmdMapPtr->nuloc-1].line[1];
2414
2415 firstWordPtr = TokenAfter(parsePtr->tokenPtr);
2416 TclCompileExprWords(interp, firstWordPtr, parsePtr->numWords-1, envPtr);
2417 return TCL_OK;
2418 }
2419
2420 /*
2421 *----------------------------------------------------------------------
2422 *
2423 * TclCompileForCmd --
2424 *
2425 * Procedure called to compile the "for" command.
2426 *
2427 * Results:
2428 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2429 * evaluation to runtime.
2430 *
2431 * Side effects:
2432 * Instructions are added to envPtr to execute the "for" command at
2433 * runtime.
2434 *
2435 *----------------------------------------------------------------------
2436 */
2437
2438 int
2439 TclCompileForCmd(
2440 Tcl_Interp *interp, /* Used for error reporting. */
2441 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2442 * created by Tcl_ParseCommand. */
2443 Command *cmdPtr, /* Points to definition of command being
2444 * compiled. */
2445 CompileEnv *envPtr) /* Holds resulting instructions. */
2446 {
2447 DefineLineInformation; /* TIP #280 */
2448 Tcl_Token *startTokenPtr, *testTokenPtr, *nextTokenPtr, *bodyTokenPtr;
2449 JumpFixup jumpEvalCondFixup;
2450 int bodyCodeOffset, nextCodeOffset, jumpDist;
2451 int bodyRange, nextRange;
2452
2453 if (parsePtr->numWords != 5) {
2454 return TCL_ERROR;
2455 }
2456
2457 /*
2458 * If the test expression requires substitutions, don't compile the for
2459 * command inline. E.g., the expression might cause the loop to never
2460 * execute or execute forever, as in "for {} "$x > 5" {incr x} {}".
2461 */
2462
2463 startTokenPtr = TokenAfter(parsePtr->tokenPtr);
2464 testTokenPtr = TokenAfter(startTokenPtr);
2465 if (testTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2466 return TCL_ERROR;
2467 }
2468
2469 /*
2470 * Bail out also if the body or the next expression require substitutions
2471 * in order to insure correct behaviour [Bug 219166]
2472 */
2473
2474 nextTokenPtr = TokenAfter(testTokenPtr);
2475 bodyTokenPtr = TokenAfter(nextTokenPtr);
2476 if ((nextTokenPtr->type != TCL_TOKEN_SIMPLE_WORD)
2477 || (bodyTokenPtr->type != TCL_TOKEN_SIMPLE_WORD)) {
2478 return TCL_ERROR;
2479 }
2480
2481 /*
2482 * Inline compile the initial command.
2483 */
2484
2485 BODY(startTokenPtr, 1);
2486 TclEmitOpcode(INST_POP, envPtr);
2487
2488 /*
2489 * Jump to the evaluation of the condition. This code uses the "loop
2490 * rotation" optimisation (which eliminates one branch from the loop).
2491 * "for start cond next body" produces then:
2492 * start
2493 * goto A
2494 * B: body : bodyCodeOffset
2495 * next : nextCodeOffset, continueOffset
2496 * A: cond -> result : testCodeOffset
2497 * if (result) goto B
2498 */
2499
2500 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpEvalCondFixup);
2501
2502 /*
2503 * Compile the loop body.
2504 */
2505
2506 bodyRange = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
2507 bodyCodeOffset = ExceptionRangeStarts(envPtr, bodyRange);
2508 BODY(bodyTokenPtr, 4);
2509 ExceptionRangeEnds(envPtr, bodyRange);
2510 TclEmitOpcode(INST_POP, envPtr);
2511
2512 /*
2513 * Compile the "next" subcommand. Note that this exception range will not
2514 * have a continueOffset (other than -1) connected to it; it won't trap
2515 * TCL_CONTINUE but rather just TCL_BREAK.
2516 */
2517
2518 nextRange = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
2519 envPtr->exceptAuxArrayPtr[nextRange].supportsContinue = 0;
2520 nextCodeOffset = ExceptionRangeStarts(envPtr, nextRange);
2521 BODY(nextTokenPtr, 3);
2522 ExceptionRangeEnds(envPtr, nextRange);
2523 TclEmitOpcode(INST_POP, envPtr);
2524
2525 /*
2526 * Compile the test expression then emit the conditional jump that
2527 * terminates the for.
2528 */
2529
2530 if (TclFixupForwardJumpToHere(envPtr, &jumpEvalCondFixup, 127)) {
2531 bodyCodeOffset += 3;
2532 nextCodeOffset += 3;
2533 }
2534
2535 SetLineInformation(2);
2536 TclCompileExprWords(interp, testTokenPtr, 1, envPtr);
2537
2538 jumpDist = CurrentOffset(envPtr) - bodyCodeOffset;
2539 if (jumpDist > 127) {
2540 TclEmitInstInt4(INST_JUMP_TRUE4, -jumpDist, envPtr);
2541 } else {
2542 TclEmitInstInt1(INST_JUMP_TRUE1, -jumpDist, envPtr);
2543 }
2544
2545 /*
2546 * Fix the starting points of the exception ranges (may have moved due to
2547 * jump type modification) and set where the exceptions target.
2548 */
2549
2550 envPtr->exceptArrayPtr[bodyRange].codeOffset = bodyCodeOffset;
2551 envPtr->exceptArrayPtr[bodyRange].continueOffset = nextCodeOffset;
2552
2553 envPtr->exceptArrayPtr[nextRange].codeOffset = nextCodeOffset;
2554
2555 ExceptionRangeTarget(envPtr, bodyRange, breakOffset);
2556 ExceptionRangeTarget(envPtr, nextRange, breakOffset);
2557 TclFinalizeLoopExceptionRange(envPtr, bodyRange);
2558 TclFinalizeLoopExceptionRange(envPtr, nextRange);
2559
2560 /*
2561 * The for command's result is an empty string.
2562 */
2563
2564 PushStringLiteral(envPtr, "");
2565
2566 return TCL_OK;
2567 }
2568
2569 /*
2570 *----------------------------------------------------------------------
2571 *
2572 * TclCompileForeachCmd --
2573 *
2574 * Procedure called to compile the "foreach" command.
2575 *
2576 * Results:
2577 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2578 * evaluation to runtime.
2579 *
2580 * Side effects:
2581 * Instructions are added to envPtr to execute the "foreach" command at
2582 * runtime.
2583 *
2584 *----------------------------------------------------------------------
2585 */
2586
2587 int
2588 TclCompileForeachCmd(
2589 Tcl_Interp *interp, /* Used for error reporting. */
2590 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2591 * created by Tcl_ParseCommand. */
2592 Command *cmdPtr, /* Points to definition of command being
2593 * compiled. */
2594 CompileEnv *envPtr) /* Holds resulting instructions. */
2595 {
2596 return CompileEachloopCmd(interp, parsePtr, cmdPtr, envPtr,
2597 TCL_EACH_KEEP_NONE);
2598 }
2599
2600 /*
2601 *----------------------------------------------------------------------
2602 *
2603 * TclCompileLmapCmd --
2604 *
2605 * Procedure called to compile the "lmap" command.
2606 *
2607 * Results:
2608 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2609 * evaluation to runtime.
2610 *
2611 * Side effects:
2612 * Instructions are added to envPtr to execute the "lmap" command at
2613 * runtime.
2614 *
2615 *----------------------------------------------------------------------
2616 */
2617
2618 int
2619 TclCompileLmapCmd(
2620 Tcl_Interp *interp, /* Used for error reporting. */
2621 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2622 * created by Tcl_ParseCommand. */
2623 Command *cmdPtr, /* Points to the definition of the command
2624 * being compiled. */
2625 CompileEnv *envPtr) /* Holds resulting instructions. */
2626 {
2627 return CompileEachloopCmd(interp, parsePtr, cmdPtr, envPtr,
2628 TCL_EACH_COLLECT);
2629 }
2630
2631 /*
2632 *----------------------------------------------------------------------
2633 *
2634 * CompileEachloopCmd --
2635 *
2636 * Procedure called to compile the "foreach" and "lmap" commands.
2637 *
2638 * Results:
2639 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
2640 * evaluation to runtime.
2641 *
2642 * Side effects:
2643 * Instructions are added to envPtr to execute the "foreach" command at
2644 * runtime.
2645 *
2646 *----------------------------------------------------------------------
2647 */
2648
2649 static int
2650 CompileEachloopCmd(
2651 Tcl_Interp *interp, /* Used for error reporting. */
2652 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
2653 * created by Tcl_ParseCommand. */
2654 Command *cmdPtr, /* Points to definition of command being
2655 * compiled. */
2656 CompileEnv *envPtr, /* Holds resulting instructions. */
2657 int collect) /* Select collecting or accumulating mode
2658 * (TCL_EACH_*) */
2659 {
2660 DefineLineInformation; /* TIP #280 */
2661 Proc *procPtr = envPtr->procPtr;
2662 ForeachInfo *infoPtr=NULL; /* Points to the structure describing this
2663 * foreach command. Stored in a AuxData
2664 * record in the ByteCode. */
2665
2666 Tcl_Token *tokenPtr, *bodyTokenPtr;
2667 int jumpBackOffset, infoIndex, range;
2668 int numWords, numLists, i, j, code = TCL_OK;
2669 Tcl_Obj *varListObj = NULL;
2670
2671 /*
2672 * If the foreach command isn't in a procedure, don't compile it inline:
2673 * the payoff is too small.
2674 */
2675
2676 if (procPtr == NULL) {
2677 return TCL_ERROR;
2678 }
2679
2680 numWords = parsePtr->numWords;
2681 if ((numWords < 4) || (numWords%2 != 0)) {
2682 return TCL_ERROR;
2683 }
2684
2685 /*
2686 * Bail out if the body requires substitutions in order to ensure correct
2687 * behaviour. [Bug 219166]
2688 */
2689
2690 for (i = 0, tokenPtr = parsePtr->tokenPtr; i < numWords-1; i++) {
2691 tokenPtr = TokenAfter(tokenPtr);
2692 }
2693 bodyTokenPtr = tokenPtr;
2694 if (bodyTokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
2695 return TCL_ERROR;
2696 }
2697
2698 /*
2699 * Create and initialize the ForeachInfo and ForeachVarList data
2700 * structures describing this command. Then create a AuxData record
2701 * pointing to the ForeachInfo structure.
2702 */
2703
2704 numLists = (numWords - 2)/2;
2705 infoPtr = (ForeachInfo *)ckalloc(TclOffset(ForeachInfo, varLists)
2706 + numLists * sizeof(ForeachVarList *));
2707 infoPtr->numLists = 0; /* Count this up as we go */
2708
2709 /*
2710 * Parse each var list into sequence of var names. Don't
2711 * compile the foreach inline if any var name needs substitutions or isn't
2712 * a scalar, or if any var list needs substitutions.
2713 */
2714
2715 TclNewObj(varListObj);
2716 for (i = 0, tokenPtr = parsePtr->tokenPtr;
2717 i < numWords-1;
2718 i++, tokenPtr = TokenAfter(tokenPtr)) {
2719 ForeachVarList *varListPtr;
2720 int numVars;
2721
2722 if (i%2 != 1) {
2723 continue;
2724 }
2725
2726 /*
2727 * If the variable list is empty, we can enter an infinite loop when
2728 * the interpreted version would not. Take care to ensure this does
2729 * not happen. [Bug 1671138]
2730 */
2731
2732 if (!TclWordKnownAtCompileTime(tokenPtr, varListObj) ||
2733 TCL_OK != TclListObjLength(NULL, varListObj, &numVars) ||
2734 numVars == 0) {
2735 code = TCL_ERROR;
2736 goto done;
2737 }
2738
2739 varListPtr = (ForeachVarList *)ckalloc(TclOffset(ForeachVarList, varIndexes)
2740 + numVars * sizeof(int));
2741 varListPtr->numVars = numVars;
2742 infoPtr->varLists[i/2] = varListPtr;
2743 infoPtr->numLists++;
2744
2745 for (j = 0; j < numVars; j++) {
2746 Tcl_Obj *varNameObj;
2747 const char *bytes;
2748 int numBytes, varIndex;
2749
2750 Tcl_ListObjIndex(NULL, varListObj, j, &varNameObj);
2751 bytes = Tcl_GetStringFromObj(varNameObj, &numBytes);
2752 varIndex = LocalScalar(bytes, numBytes, envPtr);
2753 if (varIndex < 0) {
2754 code = TCL_ERROR;
2755 goto done;
2756 }
2757 varListPtr->varIndexes[j] = varIndex;
2758 }
2759 Tcl_SetObjLength(varListObj, 0);
2760 }
2761
2762 /*
2763 * We will compile the foreach command.
2764 */
2765
2766 infoIndex = TclCreateAuxData(infoPtr, &newForeachInfoType, envPtr);
2767
2768 /*
2769 * Create the collecting object, unshared.
2770 */
2771
2772 if (collect == TCL_EACH_COLLECT) {
2773 TclEmitInstInt4(INST_LIST, 0, envPtr);
2774 }
2775
2776 /*
2777 * Evaluate each value list and leave it on stack.
2778 */
2779
2780 for (i = 0, tokenPtr = parsePtr->tokenPtr;
2781 i < numWords-1;
2782 i++, tokenPtr = TokenAfter(tokenPtr)) {
2783 if ((i%2 == 0) && (i > 0)) {
2784 CompileWord(envPtr, tokenPtr, interp, i);
2785 }
2786 }
2787
2788 TclEmitInstInt4(INST_FOREACH_START, infoIndex, envPtr);
2789
2790 /*
2791 * Inline compile the loop body.
2792 */
2793
2794 range = TclCreateExceptRange(LOOP_EXCEPTION_RANGE, envPtr);
2795
2796 ExceptionRangeStarts(envPtr, range);
2797 BODY(bodyTokenPtr, numWords - 1);
2798 ExceptionRangeEnds(envPtr, range);
2799
2800 if (collect == TCL_EACH_COLLECT) {
2801 TclEmitOpcode(INST_LMAP_COLLECT, envPtr);
2802 } else {
2803 TclEmitOpcode( INST_POP, envPtr);
2804 }
2805
2806 /*
2807 * Bottom of loop code: assign each loop variable and check whether
2808 * to terminate the loop. Set the loop's break target.
2809 */
2810
2811 ExceptionRangeTarget(envPtr, range, continueOffset);
2812 TclEmitOpcode(INST_FOREACH_STEP, envPtr);
2813 ExceptionRangeTarget(envPtr, range, breakOffset);
2814 TclFinalizeLoopExceptionRange(envPtr, range);
2815 TclEmitOpcode(INST_FOREACH_END, envPtr);
2816 TclAdjustStackDepth(-(numLists+2), envPtr);
2817
2818 /*
2819 * Set the jumpback distance from INST_FOREACH_STEP to the start of the
2820 * body's code. Misuse loopCtTemp for storing the jump size.
2821 */
2822
2823 jumpBackOffset = envPtr->exceptArrayPtr[range].continueOffset -
2824 envPtr->exceptArrayPtr[range].codeOffset;
2825 infoPtr->loopCtTemp = -jumpBackOffset;
2826
2827 /*
2828 * The command's result is an empty string if not collecting. If
2829 * collecting, it is automatically left on stack after FOREACH_END.
2830 */
2831
2832 if (collect != TCL_EACH_COLLECT) {
2833 PushStringLiteral(envPtr, "");
2834 }
2835
2836 done:
2837 if (code == TCL_ERROR) {
2838 FreeForeachInfo(infoPtr);
2839 }
2840 Tcl_DecrRefCount(varListObj);
2841 return code;
2842 }
2843
2844 /*
2845 *----------------------------------------------------------------------
2846 *
2847 * DupForeachInfo --
2848 *
2849 * This procedure duplicates a ForeachInfo structure created as auxiliary
2850 * data during the compilation of a foreach command.
2851 *
2852 * Results:
2853 * A pointer to a newly allocated copy of the existing ForeachInfo
2854 * structure is returned.
2855 *
2856 * Side effects:
2857 * Storage for the copied ForeachInfo record is allocated. If the
2858 * original ForeachInfo structure pointed to any ForeachVarList records,
2859 * these structures are also copied and pointers to them are stored in
2860 * the new ForeachInfo record.
2861 *
2862 *----------------------------------------------------------------------
2863 */
2864
2865 static ClientData
2866 DupForeachInfo(
2867 ClientData clientData) /* The foreach command's compilation auxiliary
2868 * data to duplicate. */
2869 {
2870 ForeachInfo *srcPtr = (ForeachInfo *)clientData;
2871 ForeachInfo *dupPtr;
2872 ForeachVarList *srcListPtr, *dupListPtr;
2873 int numVars, i, j, numLists = srcPtr->numLists;
2874
2875 dupPtr = (ForeachInfo *)ckalloc(TclOffset(ForeachInfo, varLists)
2876 + numLists * sizeof(ForeachVarList *));
2877 dupPtr->numLists = numLists;
2878 dupPtr->firstValueTemp = srcPtr->firstValueTemp;
2879 dupPtr->loopCtTemp = srcPtr->loopCtTemp;
2880
2881 for (i = 0; i < numLists; i++) {
2882 srcListPtr = srcPtr->varLists[i];
2883 numVars = srcListPtr->numVars;
2884 dupListPtr = (ForeachVarList *)ckalloc(TclOffset(ForeachVarList, varIndexes)
2885 + numVars * sizeof(int));
2886 dupListPtr->numVars = numVars;
2887 for (j = 0; j < numVars; j++) {
2888 dupListPtr->varIndexes[j] = srcListPtr->varIndexes[j];
2889 }
2890 dupPtr->varLists[i] = dupListPtr;
2891 }
2892 return dupPtr;
2893 }
2894
2895 /*
2896 *----------------------------------------------------------------------
2897 *
2898 * FreeForeachInfo --
2899 *
2900 * Procedure to free a ForeachInfo structure created as auxiliary data
2901 * during the compilation of a foreach command.
2902 *
2903 * Results:
2904 * None.
2905 *
2906 * Side effects:
2907 * Storage for the ForeachInfo structure pointed to by the ClientData
2908 * argument is freed as is any ForeachVarList record pointed to by the
2909 * ForeachInfo structure.
2910 *
2911 *----------------------------------------------------------------------
2912 */
2913
2914 static void
2915 FreeForeachInfo(
2916 ClientData clientData) /* The foreach command's compilation auxiliary
2917 * data to free. */
2918 {
2919 ForeachInfo *infoPtr = (ForeachInfo *)clientData;
2920 ForeachVarList *listPtr;
2921 int numLists = infoPtr->numLists;
2922 int i;
2923
2924 for (i = 0; i < numLists; i++) {
2925 listPtr = infoPtr->varLists[i];
2926 ckfree(listPtr);
2927 }
2928 ckfree(infoPtr);
2929 }
2930
2931 /*
2932 *----------------------------------------------------------------------
2933 *
2934 * PrintForeachInfo, DisassembleForeachInfo --
2935 *
2936 * Functions to write a human-readable or script-readablerepresentation
2937 * of a ForeachInfo structure to a Tcl_Obj for debugging.
2938 *
2939 * Results:
2940 * None.
2941 *
2942 * Side effects:
2943 * None.
2944 *
2945 *----------------------------------------------------------------------
2946 */
2947
2948 static void
2949 PrintForeachInfo(
2950 ClientData clientData,
2951 Tcl_Obj *appendObj,
2952 ByteCode *codePtr,
2953 unsigned int pcOffset)
2954 {
2955 ForeachInfo *infoPtr = (ForeachInfo *)clientData;
2956 ForeachVarList *varsPtr;
2957 int i, j;
2958
2959 Tcl_AppendToObj(appendObj, "data=[", -1);
2960
2961 for (i=0 ; i<infoPtr->numLists ; i++) {
2962 if (i) {
2963 Tcl_AppendToObj(appendObj, ", ", -1);
2964 }
2965 Tcl_AppendPrintfToObj(appendObj, "%%v%u",
2966 (unsigned) (infoPtr->firstValueTemp + i));
2967 }
2968 Tcl_AppendPrintfToObj(appendObj, "], loop=%%v%u",
2969 (unsigned) infoPtr->loopCtTemp);
2970 for (i=0 ; i<infoPtr->numLists ; i++) {
2971 if (i) {
2972 Tcl_AppendToObj(appendObj, ",", -1);
2973 }
2974 Tcl_AppendPrintfToObj(appendObj, "\n\t\t it%%v%u\t[",
2975 (unsigned) (infoPtr->firstValueTemp + i));
2976 varsPtr = infoPtr->varLists[i];
2977 for (j=0 ; j<varsPtr->numVars ; j++) {
2978 if (j) {
2979 Tcl_AppendToObj(appendObj, ", ", -1);
2980 }
2981 Tcl_AppendPrintfToObj(appendObj, "%%v%u",
2982 (unsigned) varsPtr->varIndexes[j]);
2983 }
2984 Tcl_AppendToObj(appendObj, "]", -1);
2985 }
2986 }
2987
2988 static void
2989 PrintNewForeachInfo(
2990 ClientData clientData,
2991 Tcl_Obj *appendObj,
2992 ByteCode *codePtr,
2993 unsigned int pcOffset)
2994 {
2995 ForeachInfo *infoPtr = (ForeachInfo *)clientData;
2996 ForeachVarList *varsPtr;
2997 int i, j;
2998
2999 Tcl_AppendPrintfToObj(appendObj, "jumpOffset=%+d, vars=",
3000 infoPtr->loopCtTemp);
3001 for (i=0 ; i<infoPtr->numLists ; i++) {
3002 if (i) {
3003 Tcl_AppendToObj(appendObj, ",", -1);
3004 }
3005 Tcl_AppendToObj(appendObj, "[", -1);
3006 varsPtr = infoPtr->varLists[i];
3007 for (j=0 ; j<varsPtr->numVars ; j++) {
3008 if (j) {
3009 Tcl_AppendToObj(appendObj, ",", -1);
3010 }
3011 Tcl_AppendPrintfToObj(appendObj, "%%v%u",
3012 (unsigned) varsPtr->varIndexes[j]);
3013 }
3014 Tcl_AppendToObj(appendObj, "]", -1);
3015 }
3016 }
3017
3018 static void
3019 DisassembleForeachInfo(
3020 ClientData clientData,
3021 Tcl_Obj *dictObj,
3022 ByteCode *codePtr,
3023 unsigned int pcOffset)
3024 {
3025 ForeachInfo *infoPtr = (ForeachInfo *)clientData;
3026 ForeachVarList *varsPtr;
3027 int i, j;
3028 Tcl_Obj *objPtr, *innerPtr;
3029
3030 /*
3031 * Data stores.
3032 */
3033
3034 TclNewObj(objPtr);
3035 for (i=0 ; i<infoPtr->numLists ; i++) {
3036 Tcl_ListObjAppendElement(NULL, objPtr,
3037 Tcl_NewIntObj(infoPtr->firstValueTemp + i));
3038 }
3039 TclDictPut(NULL, dictObj, "data", objPtr);
3040
3041 /*
3042 * Loop counter.
3043 */
3044
3045 TclDictPut(NULL, dictObj, "loop", Tcl_NewIntObj(infoPtr->loopCtTemp));
3046
3047 /*
3048 * Assignment targets.
3049 */
3050
3051 TclNewObj(objPtr);
3052 for (i=0 ; i<infoPtr->numLists ; i++) {
3053 TclNewObj(innerPtr);
3054 varsPtr = infoPtr->varLists[i];
3055 for (j=0 ; j<varsPtr->numVars ; j++) {
3056 Tcl_ListObjAppendElement(NULL, innerPtr,
3057 Tcl_NewIntObj(varsPtr->varIndexes[j]));
3058 }
3059 Tcl_ListObjAppendElement(NULL, objPtr, innerPtr);
3060 }
3061 TclDictPut(NULL, dictObj, "assign", objPtr);
3062 }
3063
3064 static void
3065 DisassembleNewForeachInfo(
3066 ClientData clientData,
3067 Tcl_Obj *dictObj,
3068 ByteCode *codePtr,
3069 unsigned int pcOffset)
3070 {
3071 ForeachInfo *infoPtr = (ForeachInfo *)clientData;
3072 ForeachVarList *varsPtr;
3073 int i, j;
3074 Tcl_Obj *objPtr, *innerPtr;
3075
3076 /*
3077 * Jump offset.
3078 */
3079
3080 TclDictPut(NULL, dictObj, "jumpOffset", Tcl_NewIntObj(infoPtr->loopCtTemp));
3081
3082 /*
3083 * Assignment targets.
3084 */
3085
3086 TclNewObj(objPtr);
3087 for (i=0 ; i<infoPtr->numLists ; i++) {
3088 TclNewObj(innerPtr);
3089 varsPtr = infoPtr->varLists[i];
3090 for (j=0 ; j<varsPtr->numVars ; j++) {
3091 Tcl_ListObjAppendElement(NULL, innerPtr,
3092 Tcl_NewIntObj(varsPtr->varIndexes[j]));
3093 }
3094 Tcl_ListObjAppendElement(NULL, objPtr, innerPtr);
3095 }
3096 TclDictPut(NULL, dictObj, "assign", objPtr);
3097 }
3098
3099 /*
3100 *----------------------------------------------------------------------
3101 *
3102 * TclCompileFormatCmd --
3103 *
3104 * Procedure called to compile the "format" command. Handles cases that
3105 * can be done as constants or simple string concatenation only.
3106 *
3107 * Results:
3108 * Returns TCL_OK for a successful compile. Returns TCL_ERROR to defer
3109 * evaluation to runtime.
3110 *
3111 * Side effects:
3112 * Instructions are added to envPtr to execute the "format" command at
3113 * runtime.
3114 *
3115 *----------------------------------------------------------------------
3116 */
3117
3118 int
3119 TclCompileFormatCmd(
3120 Tcl_Interp *interp, /* Used for error reporting. */
3121 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
3122 * created by Tcl_ParseCommand. */
3123 Command *cmdPtr, /* Points to definition of command being
3124 * compiled. */
3125 CompileEnv *envPtr) /* Holds resulting instructions. */
3126 {
3127 DefineLineInformation; /* TIP #280 */
3128 Tcl_Token *tokenPtr = parsePtr->tokenPtr;
3129 Tcl_Obj **objv, *formatObj, *tmpObj;
3130 const char *bytes, *start;
3131 int i, j, len;
3132
3133 /*
3134 * Don't handle any guaranteed-error cases.
3135 */
3136
3137 if (parsePtr->numWords < 2) {
3138 return TCL_ERROR;
3139 }
3140
3141 /*
3142 * Check if the argument words are all compile-time-known literals; that's
3143 * a case we can handle by compiling to a constant.
3144 */
3145
3146 TclNewObj(formatObj);
3147 Tcl_IncrRefCount(formatObj);
3148 tokenPtr = TokenAfter(tokenPtr);
3149 if (!TclWordKnownAtCompileTime(tokenPtr, formatObj)) {
3150 Tcl_DecrRefCount(formatObj);
3151 return TCL_ERROR;
3152 }
3153
3154 objv = (Tcl_Obj **)ckalloc((parsePtr->numWords-2) * sizeof(Tcl_Obj *));
3155 for (i=0 ; i+2 < parsePtr->numWords ; i++) {
3156 tokenPtr = TokenAfter(tokenPtr);
3157 TclNewObj(objv[i]);
3158 Tcl_IncrRefCount(objv[i]);
3159 if (!TclWordKnownAtCompileTime(tokenPtr, objv[i])) {
3160 goto checkForStringConcatCase;
3161 }
3162 }
3163
3164 /*
3165 * Everything is a literal, so the result is constant too (or an error if
3166 * the format is broken). Do the format now.
3167 */
3168
3169 tmpObj = Tcl_Format(interp, Tcl_GetString(formatObj),
3170 parsePtr->numWords-2, objv);
3171 for (; --i>=0 ;) {
3172 Tcl_DecrRefCount(objv[i]);
3173 }
3174 ckfree(objv);
3175 Tcl_DecrRefCount(formatObj);
3176 if (tmpObj == NULL) {
3177 TclCompileSyntaxError(interp, envPtr);
3178 return TCL_OK;
3179 }
3180
3181 /*
3182 * Not an error, always a constant result, so just push the result as a
3183 * literal. Job done.
3184 */
3185
3186 bytes = Tcl_GetStringFromObj(tmpObj, &len);
3187 PushLiteral(envPtr, bytes, len);
3188 Tcl_DecrRefCount(tmpObj);
3189 return TCL_OK;
3190
3191 checkForStringConcatCase:
3192 /*
3193 * See if we can generate a sequence of things to concatenate. This
3194 * requires that all the % sequences be %s or %%, as everything else is
3195 * sufficiently complex that we don't bother.
3196 *
3197 * First, get the state of the system relatively sensible (cleaning up
3198 * after our attempt to spot a literal).
3199 */
3200
3201 for (; i>=0 ; i--) {
3202 Tcl_DecrRefCount(objv[i]);
3203 }
3204 ckfree(objv);
3205 tokenPtr = TokenAfter(parsePtr->tokenPtr);
3206 tokenPtr = TokenAfter(tokenPtr);
3207 i = 0;
3208
3209 /*
3210 * Now scan through and check for non-%s and non-%% substitutions.
3211 */
3212
3213 for (bytes = Tcl_GetString(formatObj) ; *bytes ; bytes++) {
3214 if (*bytes == '%') {
3215 bytes++;
3216 if (*bytes == 's') {
3217 i++;
3218 continue;
3219 } else if (*bytes == '%') {
3220 continue;
3221 }
3222 Tcl_DecrRefCount(formatObj);
3223 return TCL_ERROR;
3224 }
3225 }
3226
3227 /*
3228 * Check if the number of things to concatenate will fit in a byte.
3229 */
3230
3231 if (i+2 != parsePtr->numWords || i > 125) {
3232 Tcl_DecrRefCount(formatObj);
3233 return TCL_ERROR;
3234 }
3235
3236 /*
3237 * Generate the pushes of the things to concatenate, a sequence of
3238 * literals and compiled tokens (of which at least one is non-literal or
3239 * we'd have the case in the first half of this function) which we will
3240 * concatenate.
3241 */
3242
3243 i = 0; /* The count of things to concat. */
3244 j = 2; /* The index into the argument tokens, for
3245 * TIP#280 handling. */
3246 start = Tcl_GetString(formatObj);
3247 /* The start of the currently-scanned literal
3248 * in the format string. */
3249 TclNewObj(tmpObj); /* The buffer used to accumulate the literal
3250 * being built. */
3251 for (bytes = start ; *bytes ; bytes++) {
3252 if (*bytes == '%') {
3253 Tcl_AppendToObj(tmpObj, start, bytes - start);
3254 if (*++bytes == '%') {
3255 Tcl_AppendToObj(tmpObj, "%", 1);
3256 } else {
3257 const char *b = Tcl_GetStringFromObj(tmpObj, &len);
3258
3259 /*
3260 * If there is a non-empty literal from the format string,
3261 * push it and reset.
3262 */
3263
3264 if (len > 0) {
3265 PushLiteral(envPtr, b, len);
3266 Tcl_DecrRefCount(tmpObj);
3267 TclNewObj(tmpObj);
3268 i++;
3269 }
3270
3271 /*
3272 * Push the code to produce the string that would be
3273 * substituted with %s, except we'll be concatenating
3274 * directly.
3275 */
3276
3277 CompileWord(envPtr, tokenPtr, interp, j);
3278 tokenPtr = TokenAfter(tokenPtr);
3279 j++;
3280 i++;
3281 }
3282 start = bytes + 1;
3283 }
3284 }
3285
3286 /*
3287 * Handle the case of a trailing literal.
3288 */
3289
3290 Tcl_AppendToObj(tmpObj, start, bytes - start);
3291 bytes = Tcl_GetStringFromObj(tmpObj, &len);
3292 if (len > 0) {
3293 PushLiteral(envPtr, bytes, len);
3294 i++;
3295 }
3296 Tcl_DecrRefCount(tmpObj);
3297 Tcl_DecrRefCount(formatObj);
3298
3299 if (i > 1) {
3300 /*
3301 * Do the concatenation, which produces the result.
3302 */
3303
3304 TclEmitInstInt1(INST_STR_CONCAT1, i, envPtr);
3305 }
3306 return TCL_OK;
3307 }
3308
3309 /*
3310 *----------------------------------------------------------------------
3311 *
3312 * TclLocalScalarFromToken --
3313 *
3314 * Get the index into the table of compiled locals that corresponds
3315 * to a local scalar variable name.
3316 *
3317 * Results:
3318 * Returns the non-negative integer index value into the table of
3319 * compiled locals corresponding to a local scalar variable name.
3320 * If the arguments passed in do not identify a local scalar variable
3321 * then return -1.
3322 *
3323 * Side effects:
3324 * May add an entry into the table of compiled locals.
3325 *
3326 *----------------------------------------------------------------------
3327 */
3328
3329 int
3330 TclLocalScalarFromToken(
3331 Tcl_Token *tokenPtr,
3332 CompileEnv *envPtr)
3333 {
3334 int isScalar, index;
3335
3336 TclPushVarName(NULL, tokenPtr, envPtr, TCL_NO_ELEMENT, &index, &isScalar);
3337 if (!isScalar) {
3338 index = -1;
3339 }
3340 return index;
3341 }
3342
3343 int
3344 TclLocalScalar(
3345 const char *bytes,
3346 int numBytes,
3347 CompileEnv *envPtr)
3348 {
3349 Tcl_Token token[2] = {{TCL_TOKEN_SIMPLE_WORD, NULL, 0, 1},
3350 {TCL_TOKEN_TEXT, NULL, 0, 0}};
3351
3352 token[1].start = bytes;
3353 token[1].size = numBytes;
3354 return TclLocalScalarFromToken(token, envPtr);
3355 }
3356
3357 /*
3358 *----------------------------------------------------------------------
3359 *
3360 * TclPushVarName --
3361 *
3362 * Procedure used in the compiling where pushing a variable name is
3363 * necessary (append, lappend, set).
3364 *
3365 * Results:
3366 * The values written to *localIndexPtr and *isScalarPtr signal to
3367 * the caller what the instructions emitted by this routine will do:
3368 *
3369 * *isScalarPtr (*localIndexPtr < 0)
3370 * 1 1 Push the varname on the stack. (Stack +1)
3371 * 1 0 *localIndexPtr is the index of the compiled
3372 * local for this varname. No instructions
3373 * emitted. (Stack +0)
3374 * 0 1 Push part1 and part2 names of array element
3375 * on the stack. (Stack +2)
3376 * 0 0 *localIndexPtr is the index of the compiled
3377 * local for this array. Element name is pushed
3378 * on the stack. (Stack +1)
3379 *
3380 * Side effects:
3381 * Instructions are added to envPtr.
3382 *
3383 *----------------------------------------------------------------------
3384 */
3385
3386 void
3387 TclPushVarName(
3388 Tcl_Interp *interp, /* Used for error reporting. */
3389 Tcl_Token *varTokenPtr, /* Points to a variable token. */
3390 CompileEnv *envPtr, /* Holds resulting instructions. */
3391 int flags, /* TCL_NO_LARGE_INDEX | TCL_NO_ELEMENT. */
3392 int *localIndexPtr, /* Must not be NULL. */
3393 int *isScalarPtr) /* Must not be NULL. */
3394 {
3395 const char *p;
3396 const char *last, *name, *elName;
3397 int n;
3398 Tcl_Token *elemTokenPtr = NULL;
3399 int nameLen, elNameLen, simpleVarName, localIndex;
3400 int elemTokenCount = 0, allocedTokens = 0, removedParen = 0;
3401
3402 /*
3403 * Decide if we can use a frame slot for the var/array name or if we need
3404 * to emit code to compute and push the name at runtime. We use a frame
3405 * slot (entry in the array of local vars) if we are compiling a procedure
3406 * body and if the name is simple text that does not include namespace
3407 * qualifiers.
3408 */
3409
3410 simpleVarName = 0;
3411 name = elName = NULL;
3412 nameLen = elNameLen = 0;
3413 localIndex = -1;
3414
3415 if (varTokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
3416 /*
3417 * A simple variable name. Divide it up into "name" and "elName"
3418 * strings. If it is not a local variable, look it up at runtime.
3419 */
3420
3421 simpleVarName = 1;
3422
3423 name = varTokenPtr[1].start;
3424 nameLen = varTokenPtr[1].size;
3425 if (nameLen > 0 && name[nameLen-1] == ')') {
3426 /*
3427 * last char is ')' => potential array reference.
3428 */
3429 last = &name[nameLen-1];
3430
3431 if (*last == ')') {
3432 for (p = name; p < last; p++) {
3433 if (*p == '(') {
3434 elName = p + 1;
3435 elNameLen = last - elName;
3436 nameLen = p - name;
3437 break;
3438 }
3439 }
3440 }
3441
3442 if (!(flags & TCL_NO_ELEMENT) && elNameLen) {
3443 /*
3444 * An array element, the element name is a simple string:
3445 * assemble the corresponding token.
3446 */
3447
3448 elemTokenPtr = (Tcl_Token *)TclStackAlloc(interp, sizeof(Tcl_Token));
3449 allocedTokens = 1;
3450 elemTokenPtr->type = TCL_TOKEN_TEXT;
3451 elemTokenPtr->start = elName;
3452 elemTokenPtr->size = elNameLen;
3453 elemTokenPtr->numComponents = 0;
3454 elemTokenCount = 1;
3455 }
3456 }
3457 } else if (interp && ((n = varTokenPtr->numComponents) > 1)
3458 && (varTokenPtr[1].type == TCL_TOKEN_TEXT)
3459 && (varTokenPtr[n].type == TCL_TOKEN_TEXT)
3460 && (*(varTokenPtr[n].start + varTokenPtr[n].size - 1) == ')')) {
3461 /*
3462 * Check for parentheses inside first token.
3463 */
3464
3465 simpleVarName = 0;
3466 for (p = varTokenPtr[1].start,
3467 last = p + varTokenPtr[1].size; p < last; p++) {
3468 if (*p == '(') {
3469 simpleVarName = 1;
3470 break;
3471 }
3472 }
3473 if (simpleVarName) {
3474 int remainingLen;
3475
3476 /*
3477 * Check the last token: if it is just ')', do not count it.
3478 * Otherwise, remove the ')' and flag so that it is restored at
3479 * the end.
3480 */
3481
3482 if (varTokenPtr[n].size == 1) {
3483 n--;
3484 } else {
3485 varTokenPtr[n].size--;
3486 removedParen = n;
3487 }
3488
3489 name = varTokenPtr[1].start;
3490 nameLen = p - varTokenPtr[1].start;
3491 elName = p + 1;
3492 remainingLen = (varTokenPtr[2].start - p) - 1;
3493 elNameLen = (varTokenPtr[n].start-p) + varTokenPtr[n].size - 1;
3494
3495 if (!(flags & TCL_NO_ELEMENT)) {
3496 if (remainingLen) {
3497 /*
3498 * Make a first token with the extra characters in the first
3499 * token.
3500 */
3501
3502 elemTokenPtr = (Tcl_Token *)TclStackAlloc(interp, n * sizeof(Tcl_Token));
3503 allocedTokens = 1;
3504 elemTokenPtr->type = TCL_TOKEN_TEXT;
3505 elemTokenPtr->start = elName;
3506 elemTokenPtr->size = remainingLen;
3507 elemTokenPtr->numComponents = 0;
3508 elemTokenCount = n;
3509
3510 /*
3511 * Copy the remaining tokens.
3512 */
3513
3514 memcpy(elemTokenPtr+1, varTokenPtr+2,
3515 (n-1) * sizeof(Tcl_Token));
3516 } else {
3517 /*
3518 * Use the already available tokens.
3519 */
3520
3521 elemTokenPtr = &varTokenPtr[2];
3522 elemTokenCount = n - 1;
3523 }
3524 }
3525 }
3526 }
3527
3528 if (simpleVarName) {
3529 /*
3530 * See whether name has any namespace separators (::'s).
3531 */
3532
3533 int hasNsQualifiers = 0;
3534
3535 for (p = name, last = p + nameLen-1; p < last; p++) {
3536 if ((*p == ':') && (*(p+1) == ':')) {
3537 hasNsQualifiers = 1;
3538 break;
3539 }
3540 }
3541
3542 /*
3543 * Look up the var name's index in the array of local vars in the proc
3544 * frame. If retrieving the var's value and it doesn't already exist,
3545 * push its name and look it up at runtime.
3546 */
3547
3548 if (!hasNsQualifiers) {
3549 localIndex = TclFindCompiledLocal(name, nameLen, 1, envPtr);
3550 if ((flags & TCL_NO_LARGE_INDEX) && (localIndex > 255)) {
3551 /*
3552 * We'll push the name.
3553 */
3554
3555 localIndex = -1;
3556 }
3557 }
3558 if (interp && localIndex < 0) {
3559 PushLiteral(envPtr, name, nameLen);
3560 }
3561
3562 /*
3563 * Compile the element script, if any, and only if not inhibited. [Bug
3564 * 3600328]
3565 */
3566
3567 if (elName != NULL && !(flags & TCL_NO_ELEMENT)) {
3568 if (elNameLen) {
3569 TclCompileTokens(interp, elemTokenPtr, elemTokenCount,
3570 envPtr);
3571 } else {
3572 PushStringLiteral(envPtr, "");
3573 }
3574 }
3575 } else if (interp) {
3576 /*
3577 * The var name isn't simple: compile and push it.
3578 */
3579
3580 CompileTokens(envPtr, varTokenPtr, interp);
3581 }
3582
3583 if (removedParen) {
3584 varTokenPtr[removedParen].size++;
3585 }
3586 if (allocedTokens) {
3587 TclStackFree(interp, elemTokenPtr);
3588 }
3589 *localIndexPtr = localIndex;
3590 *isScalarPtr = (elName == NULL);
3591 }
3592
3593 /*
3594 * Local Variables:
3595 * mode: c
3596 * c-basic-offset: 4
3597 * fill-column: 78
3598 * End:
3599 */