Debian Codegraph @

pTk/mTk/tclGeneric/tclCompile.c

raw symbols SCIP
1 /*
2 * tclCompile.c --
3 *
4 * This file contains procedures that compile Tcl commands or parts
5 * of commands (like quoted strings or nested sub-commands) into a
6 * sequence of instructions ("bytecodes").
7 *
8 * Copyright (c) 1996-1998 Sun Microsystems, Inc.
9 * Copyright (c) 2001 by Kevin B. Kenny. All rights reserved.
10 *
11 * See the file "license.terms" for information on usage and redistribution
12 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 *
14 * RCS: @(#) $Id: tclCompile.c,v 1.43.2.3 2003/07/18 23:35:38 dgp Exp $
15 */
16
17 #include "tclInt.h"
18 #include "tclCompile.h"
19
20 /*
21 * Table of all AuxData types.
22 */
23
24 static Tcl_HashTable auxDataTypeTable;
25 static int auxDataTypeTableInitialized; /* 0 means not yet initialized. */
26
27 TCL_DECLARE_MUTEX(tableMutex)
28
29 /*
30 * Variable that controls whether compilation tracing is enabled and, if so,
31 * what level of tracing is desired:
32 * 0: no compilation tracing
33 * 1: summarize compilation of top level cmds and proc bodies
34 * 2: display all instructions of each ByteCode compiled
35 * This variable is linked to the Tcl variable "tcl_traceCompile".
36 */
37
38 #ifdef TCL_COMPILE_DEBUG
39 int tclTraceCompile = 0;
40 static int traceInitialized = 0;
41 #endif
42
43 /*
44 * A table describing the Tcl bytecode instructions. Entries in this table
45 * must correspond to the instruction opcode definitions in tclCompile.h.
46 * The names "op1" and "op4" refer to an instruction's one or four byte
47 * first operand. Similarly, "stktop" and "stknext" refer to the topmost
48 * and next to topmost stack elements.
49 *
50 * Note that the load, store, and incr instructions do not distinguish local
51 * from global variables; the bytecode interpreter at runtime uses the
52 * existence of a procedure call frame to distinguish these.
53 */
54
55 InstructionDesc tclInstructionTable[] = {
56 /* Name Bytes stackEffect #Opnds Operand types Stack top, next */
57 {"done", 1, -1, 0, {OPERAND_NONE}},
58 /* Finish ByteCode execution and return stktop (top stack item) */
59 {"push1", 2, +1, 1, {OPERAND_UINT1}},
60 /* Push object at ByteCode objArray[op1] */
61 {"push4", 5, +1, 1, {OPERAND_UINT4}},
62 /* Push object at ByteCode objArray[op4] */
63 {"pop", 1, -1, 0, {OPERAND_NONE}},
64 /* Pop the topmost stack object */
65 {"dup", 1, +1, 0, {OPERAND_NONE}},
66 /* Duplicate the topmost stack object and push the result */
67 {"concat1", 2, INT_MIN, 1, {OPERAND_UINT1}},
68 /* Concatenate the top op1 items and push result */
69 {"invokeStk1", 2, INT_MIN, 1, {OPERAND_UINT1}},
70 /* Invoke command named objv[0]; <objc,objv> = <op1,top op1> */
71 {"invokeStk4", 5, INT_MIN, 1, {OPERAND_UINT4}},
72 /* Invoke command named objv[0]; <objc,objv> = <op4,top op4> */
73 {"evalStk", 1, 0, 0, {OPERAND_NONE}},
74 /* Evaluate command in stktop using Tcl_EvalObj. */
75 {"exprStk", 1, 0, 0, {OPERAND_NONE}},
76 /* Execute expression in stktop using Tcl_ExprStringObj. */
77
78 {"loadScalar1", 2, 1, 1, {OPERAND_UINT1}},
79 /* Load scalar variable at index op1 <= 255 in call frame */
80 {"loadScalar4", 5, 1, 1, {OPERAND_UINT4}},
81 /* Load scalar variable at index op1 >= 256 in call frame */
82 {"loadScalarStk", 1, 0, 0, {OPERAND_NONE}},
83 /* Load scalar variable; scalar's name is stktop */
84 {"loadArray1", 2, 0, 1, {OPERAND_UINT1}},
85 /* Load array element; array at slot op1<=255, element is stktop */
86 {"loadArray4", 5, 0, 1, {OPERAND_UINT4}},
87 /* Load array element; array at slot op1 > 255, element is stktop */
88 {"loadArrayStk", 1, -1, 0, {OPERAND_NONE}},
89 /* Load array element; element is stktop, array name is stknext */
90 {"loadStk", 1, 0, 0, {OPERAND_NONE}},
91 /* Load general variable; unparsed variable name is stktop */
92 {"storeScalar1", 2, 0, 1, {OPERAND_UINT1}},
93 /* Store scalar variable at op1<=255 in frame; value is stktop */
94 {"storeScalar4", 5, 0, 1, {OPERAND_UINT4}},
95 /* Store scalar variable at op1 > 255 in frame; value is stktop */
96 {"storeScalarStk", 1, -1, 0, {OPERAND_NONE}},
97 /* Store scalar; value is stktop, scalar name is stknext */
98 {"storeArray1", 2, -1, 1, {OPERAND_UINT1}},
99 /* Store array element; array at op1<=255, value is top then elem */
100 {"storeArray4", 5, -1, 1, {OPERAND_UINT4}},
101 /* Store array element; array at op1>=256, value is top then elem */
102 {"storeArrayStk", 1, -2, 0, {OPERAND_NONE}},
103 /* Store array element; value is stktop, then elem, array names */
104 {"storeStk", 1, -1, 0, {OPERAND_NONE}},
105 /* Store general variable; value is stktop, then unparsed name */
106
107 {"incrScalar1", 2, 0, 1, {OPERAND_UINT1}},
108 /* Incr scalar at index op1<=255 in frame; incr amount is stktop */
109 {"incrScalarStk", 1, -1, 0, {OPERAND_NONE}},
110 /* Incr scalar; incr amount is stktop, scalar's name is stknext */
111 {"incrArray1", 2, -1, 1, {OPERAND_UINT1}},
112 /* Incr array elem; arr at slot op1<=255, amount is top then elem */
113 {"incrArrayStk", 1, -2, 0, {OPERAND_NONE}},
114 /* Incr array element; amount is top then elem then array names */
115 {"incrStk", 1, -1, 0, {OPERAND_NONE}},
116 /* Incr general variable; amount is stktop then unparsed var name */
117 {"incrScalar1Imm", 3, +1, 2, {OPERAND_UINT1, OPERAND_INT1}},
118 /* Incr scalar at slot op1 <= 255; amount is 2nd operand byte */
119 {"incrScalarStkImm", 2, 0, 1, {OPERAND_INT1}},
120 /* Incr scalar; scalar name is stktop; incr amount is op1 */
121 {"incrArray1Imm", 3, 0, 2, {OPERAND_UINT1, OPERAND_INT1}},
122 /* Incr array elem; array at slot op1 <= 255, elem is stktop,
123 * amount is 2nd operand byte */
124 {"incrArrayStkImm", 2, -1, 1, {OPERAND_INT1}},
125 /* Incr array element; elem is top then array name, amount is op1 */
126 {"incrStkImm", 2, 0, 1, {OPERAND_INT1}},
127 /* Incr general variable; unparsed name is top, amount is op1 */
128
129 {"jump1", 2, 0, 1, {OPERAND_INT1}},
130 /* Jump relative to (pc + op1) */
131 {"jump4", 5, 0, 1, {OPERAND_INT4}},
132 /* Jump relative to (pc + op4) */
133 {"jumpTrue1", 2, -1, 1, {OPERAND_INT1}},
134 /* Jump relative to (pc + op1) if stktop expr object is true */
135 {"jumpTrue4", 5, -1, 1, {OPERAND_INT4}},
136 /* Jump relative to (pc + op4) if stktop expr object is true */
137 {"jumpFalse1", 2, -1, 1, {OPERAND_INT1}},
138 /* Jump relative to (pc + op1) if stktop expr object is false */
139 {"jumpFalse4", 5, -1, 1, {OPERAND_INT4}},
140 /* Jump relative to (pc + op4) if stktop expr object is false */
141
142 {"lor", 1, -1, 0, {OPERAND_NONE}},
143 /* Logical or: push (stknext || stktop) */
144 {"land", 1, -1, 0, {OPERAND_NONE}},
145 /* Logical and: push (stknext && stktop) */
146 {"bitor", 1, -1, 0, {OPERAND_NONE}},
147 /* Bitwise or: push (stknext | stktop) */
148 {"bitxor", 1, -1, 0, {OPERAND_NONE}},
149 /* Bitwise xor push (stknext ^ stktop) */
150 {"bitand", 1, -1, 0, {OPERAND_NONE}},
151 /* Bitwise and: push (stknext & stktop) */
152 {"eq", 1, -1, 0, {OPERAND_NONE}},
153 /* Equal: push (stknext == stktop) */
154 {"neq", 1, -1, 0, {OPERAND_NONE}},
155 /* Not equal: push (stknext != stktop) */
156 {"lt", 1, -1, 0, {OPERAND_NONE}},
157 /* Less: push (stknext < stktop) */
158 {"gt", 1, -1, 0, {OPERAND_NONE}},
159 /* Greater: push (stknext || stktop) */
160 {"le", 1, -1, 0, {OPERAND_NONE}},
161 /* Logical or: push (stknext || stktop) */
162 {"ge", 1, -1, 0, {OPERAND_NONE}},
163 /* Logical or: push (stknext || stktop) */
164 {"lshift", 1, -1, 0, {OPERAND_NONE}},
165 /* Left shift: push (stknext << stktop) */
166 {"rshift", 1, -1, 0, {OPERAND_NONE}},
167 /* Right shift: push (stknext >> stktop) */
168 {"add", 1, -1, 0, {OPERAND_NONE}},
169 /* Add: push (stknext + stktop) */
170 {"sub", 1, -1, 0, {OPERAND_NONE}},
171 /* Sub: push (stkext - stktop) */
172 {"mult", 1, -1, 0, {OPERAND_NONE}},
173 /* Multiply: push (stknext * stktop) */
174 {"div", 1, -1, 0, {OPERAND_NONE}},
175 /* Divide: push (stknext / stktop) */
176 {"mod", 1, -1, 0, {OPERAND_NONE}},
177 /* Mod: push (stknext % stktop) */
178 {"uplus", 1, 0, 0, {OPERAND_NONE}},
179 /* Unary plus: push +stktop */
180 {"uminus", 1, 0, 0, {OPERAND_NONE}},
181 /* Unary minus: push -stktop */
182 {"bitnot", 1, 0, 0, {OPERAND_NONE}},
183 /* Bitwise not: push ~stktop */
184 {"not", 1, 0, 0, {OPERAND_NONE}},
185 /* Logical not: push !stktop */
186 {"callBuiltinFunc1", 2, 1, 1, {OPERAND_UINT1}},
187 /* Call builtin math function with index op1; any args are on stk */
188 {"callFunc1", 2, INT_MIN, 1, {OPERAND_UINT1}},
189 /* Call non-builtin func objv[0]; <objc,objv>=<op1,top op1> */
190 {"tryCvtToNumeric", 1, 0, 0, {OPERAND_NONE}},
191 /* Try converting stktop to first int then double if possible. */
192
193 {"break", 1, 0, 0, {OPERAND_NONE}},
194 /* Abort closest enclosing loop; if none, return TCL_BREAK code. */
195 {"continue", 1, 0, 0, {OPERAND_NONE}},
196 /* Skip to next iteration of closest enclosing loop; if none,
197 * return TCL_CONTINUE code. */
198
199 {"foreach_start4", 5, 0, 1, {OPERAND_UINT4}},
200 /* Initialize execution of a foreach loop. Operand is aux data index
201 * of the ForeachInfo structure for the foreach command. */
202 {"foreach_step4", 5, +1, 1, {OPERAND_UINT4}},
203 /* "Step" or begin next iteration of foreach loop. Push 0 if to
204 * terminate loop, else push 1. */
205
206 {"beginCatch4", 5, 0, 1, {OPERAND_UINT4}},
207 /* Record start of catch with the operand's exception index.
208 * Push the current stack depth onto a special catch stack. */
209 {"endCatch", 1, 0, 0, {OPERAND_NONE}},
210 /* End of last catch. Pop the bytecode interpreter's catch stack. */
211 {"pushResult", 1, +1, 0, {OPERAND_NONE}},
212 /* Push the interpreter's object result onto the stack. */
213 {"pushReturnCode", 1, +1, 0, {OPERAND_NONE}},
214 /* Push interpreter's return code (e.g. TCL_OK or TCL_ERROR) as
215 * a new object onto the stack. */
216 {"streq", 1, -1, 0, {OPERAND_NONE}},
217 /* Str Equal: push (stknext eq stktop) */
218 {"strneq", 1, -1, 0, {OPERAND_NONE}},
219 /* Str !Equal: push (stknext neq stktop) */
220 {"strcmp", 1, -1, 0, {OPERAND_NONE}},
221 /* Str Compare: push (stknext cmp stktop) */
222 {"strlen", 1, 0, 0, {OPERAND_NONE}},
223 /* Str Length: push (strlen stktop) */
224 {"strindex", 1, -1, 0, {OPERAND_NONE}},
225 /* Str Index: push (strindex stknext stktop) */
226 {"strmatch", 2, -1, 1, {OPERAND_INT1}},
227 /* Str Match: push (strmatch stknext stktop) opnd == nocase */
228 {"list", 5, INT_MIN, 1, {OPERAND_UINT4}},
229 /* List: push (stk1 stk2 ... stktop) */
230 {"listindex", 1, -1, 0, {OPERAND_NONE}},
231 /* List Index: push (listindex stknext stktop) */
232 {"listlength", 1, 0, 0, {OPERAND_NONE}},
233 /* List Len: push (listlength stktop) */
234 {"appendScalar1", 2, 0, 1, {OPERAND_UINT1}},
235 /* Append scalar variable at op1<=255 in frame; value is stktop */
236 {"appendScalar4", 5, 0, 1, {OPERAND_UINT4}},
237 /* Append scalar variable at op1 > 255 in frame; value is stktop */
238 {"appendArray1", 2, -1, 1, {OPERAND_UINT1}},
239 /* Append array element; array at op1<=255, value is top then elem */
240 {"appendArray4", 5, -1, 1, {OPERAND_UINT4}},
241 /* Append array element; array at op1>=256, value is top then elem */
242 {"appendArrayStk", 1, -2, 0, {OPERAND_NONE}},
243 /* Append array element; value is stktop, then elem, array names */
244 {"appendStk", 1, -1, 0, {OPERAND_NONE}},
245 /* Append general variable; value is stktop, then unparsed name */
246 {"lappendScalar1", 2, 0, 1, {OPERAND_UINT1}},
247 /* Lappend scalar variable at op1<=255 in frame; value is stktop */
248 {"lappendScalar4", 5, 0, 1, {OPERAND_UINT4}},
249 /* Lappend scalar variable at op1 > 255 in frame; value is stktop */
250 {"lappendArray1", 2, -1, 1, {OPERAND_UINT1}},
251 /* Lappend array element; array at op1<=255, value is top then elem */
252 {"lappendArray4", 5, -1, 1, {OPERAND_UINT4}},
253 /* Lappend array element; array at op1>=256, value is top then elem */
254 {"lappendArrayStk", 1, -2, 0, {OPERAND_NONE}},
255 /* Lappend array element; value is stktop, then elem, array names */
256 {"lappendStk", 1, -1, 0, {OPERAND_NONE}},
257 /* Lappend general variable; value is stktop, then unparsed name */
258 {"lindexMulti", 5, INT_MIN, 1, {OPERAND_UINT4}},
259 /* Lindex with generalized args, operand is number of stacked objs
260 * used: (operand-1) entries from stktop are the indices; then list
261 * to process. */
262 {"over", 5, +1, 1, {OPERAND_UINT4}},
263 /* Duplicate the arg-th element from top of stack (TOS=0) */
264 {"lsetList", 1, -2, 0, {OPERAND_NONE}},
265 /* Four-arg version of 'lset'. stktop is old value; next is
266 * new element value, next is the index list; pushes new value */
267 {"lsetFlat", 5, INT_MIN, 1, {OPERAND_UINT4}},
268 /* Three- or >=5-arg version of 'lset', operand is number of
269 * stacked objs: stktop is old value, next is new element value, next
270 * come (operand-2) indices; pushes the new value.
271 */
272 {0}
273 };
274
275 /*
276 * Prototypes for procedures defined later in this file:
277 */
278
279 static void DupByteCodeInternalRep _ANSI_ARGS_((Tcl_Obj *srcPtr,
280 Tcl_Obj *copyPtr));
281 static unsigned char * EncodeCmdLocMap _ANSI_ARGS_((
282 CompileEnv *envPtr, ByteCode *codePtr,
283 unsigned char *startPtr));
284 static void EnterCmdExtentData _ANSI_ARGS_((
285 CompileEnv *envPtr, int cmdNumber,
286 int numSrcBytes, int numCodeBytes));
287 static void EnterCmdStartData _ANSI_ARGS_((
288 CompileEnv *envPtr, int cmdNumber,
289 int srcOffset, int codeOffset));
290 static void FreeByteCodeInternalRep _ANSI_ARGS_((
291 Tcl_Obj *objPtr));
292 static int GetCmdLocEncodingSize _ANSI_ARGS_((
293 CompileEnv *envPtr));
294 static void LogCompilationInfo _ANSI_ARGS_((Tcl_Interp *interp,
295 CONST char *script, CONST char *command,
296 int length));
297 #ifdef TCL_COMPILE_STATS
298 static void RecordByteCodeStats _ANSI_ARGS_((
299 ByteCode *codePtr));
300 #endif /* TCL_COMPILE_STATS */
301 static int SetByteCodeFromAny _ANSI_ARGS_((Tcl_Interp *interp,
302 Tcl_Obj *objPtr));
303
304 /*
305 * The structure below defines the bytecode Tcl object type by
306 * means of procedures that can be invoked by generic object code.
307 */
308
309 Tcl_ObjType tclByteCodeType = {
310 "bytecode", /* name */
311 FreeByteCodeInternalRep, /* freeIntRepProc */
312 DupByteCodeInternalRep, /* dupIntRepProc */
313 (Tcl_UpdateStringProc *) NULL, /* updateStringProc */
314 SetByteCodeFromAny /* setFromAnyProc */
315 };
316
317 /*
318 *----------------------------------------------------------------------
319 *
320 * TclSetByteCodeFromAny --
321 *
322 * Part of the bytecode Tcl object type implementation. Attempts to
323 * generate an byte code internal form for the Tcl object "objPtr" by
324 * compiling its string representation. This function also takes
325 * a hook procedure that will be invoked to perform any needed post
326 * processing on the compilation results before generating byte
327 * codes.
328 *
329 * Results:
330 * The return value is a standard Tcl object result. If an error occurs
331 * during compilation, an error message is left in the interpreter's
332 * result unless "interp" is NULL.
333 *
334 * Side effects:
335 * Frees the old internal representation. If no error occurs, then the
336 * compiled code is stored as "objPtr"s bytecode representation.
337 * Also, if debugging, initializes the "tcl_traceCompile" Tcl variable
338 * used to trace compilations.
339 *
340 *----------------------------------------------------------------------
341 */
342
343 int
344 TclSetByteCodeFromAny(interp, objPtr, hookProc, clientData)
345 Tcl_Interp *interp; /* The interpreter for which the code is
346 * being compiled. Must not be NULL. */
347 Tcl_Obj *objPtr; /* The object to make a ByteCode object. */
348 CompileHookProc *hookProc; /* Procedure to invoke after compilation. */
349 ClientData clientData; /* Hook procedure private data. */
350 {
351 Interp *iPtr = (Interp *) interp;
352 CompileEnv compEnv; /* Compilation environment structure
353 * allocated in frame. */
354 LiteralTable *localTablePtr = &(compEnv.localLitTable);
355 register AuxData *auxDataPtr;
356 LiteralEntry *entryPtr;
357 register int i;
358 int length, nested, result;
359 char *string;
360
361 #ifdef TCL_COMPILE_DEBUG
362 if (!traceInitialized) {
363 if (Tcl_LinkVar(interp, "tcl_traceCompile",
364 (char *) &tclTraceCompile, TCL_LINK_INT) != TCL_OK) {
365 panic("SetByteCodeFromAny: unable to create link for tcl_traceCompile variable");
366 }
367 traceInitialized = 1;
368 }
369 #endif
370
371 if (iPtr->evalFlags & TCL_BRACKET_TERM) {
372 nested = 1;
373 } else {
374 nested = 0;
375 }
376 string = Tcl_GetStringFromObj(objPtr, &length);
377 TclInitCompileEnv(interp, &compEnv, string, length);
378 result = TclCompileScript(interp, string, length, nested, &compEnv);
379
380 if (result == TCL_OK) {
381 /*
382 * Successful compilation. Add a "done" instruction at the end.
383 */
384
385 compEnv.numSrcBytes = iPtr->termOffset;
386 TclEmitOpcode(INST_DONE, &compEnv);
387
388 /*
389 * Invoke the compilation hook procedure if one exists.
390 */
391
392 if (hookProc) {
393 result = (*hookProc)(interp, &compEnv, clientData);
394 }
395
396 /*
397 * Change the object into a ByteCode object. Ownership of the literal
398 * objects and aux data items is given to the ByteCode object.
399 */
400
401 #ifdef TCL_COMPILE_DEBUG
402 TclVerifyLocalLiteralTable(&compEnv);
403 #endif /*TCL_COMPILE_DEBUG*/
404
405 TclInitByteCodeObj(objPtr, &compEnv);
406 #ifdef TCL_COMPILE_DEBUG
407 if (tclTraceCompile >= 2) {
408 TclPrintByteCodeObj(interp, objPtr);
409 }
410 #endif /* TCL_COMPILE_DEBUG */
411 }
412
413 if (result != TCL_OK) {
414 /*
415 * Compilation errors.
416 */
417
418 entryPtr = compEnv.literalArrayPtr;
419 for (i = 0; i < compEnv.literalArrayNext; i++) {
420 TclReleaseLiteral(interp, entryPtr->objPtr);
421 entryPtr++;
422 }
423 #ifdef TCL_COMPILE_DEBUG
424 TclVerifyGlobalLiteralTable(iPtr);
425 #endif /*TCL_COMPILE_DEBUG*/
426
427 auxDataPtr = compEnv.auxDataArrayPtr;
428 for (i = 0; i < compEnv.auxDataArrayNext; i++) {
429 if (auxDataPtr->type->freeProc != NULL) {
430 auxDataPtr->type->freeProc(auxDataPtr->clientData);
431 }
432 auxDataPtr++;
433 }
434 }
435
436
437 /*
438 * Free storage allocated during compilation.
439 */
440
441 if (localTablePtr->buckets != localTablePtr->staticBuckets) {
442 ckfree((char *) localTablePtr->buckets);
443 }
444 TclFreeCompileEnv(&compEnv);
445 return result;
446 }
447
448 /*
449 *-----------------------------------------------------------------------
450 *
451 * SetByteCodeFromAny --
452 *
453 * Part of the bytecode Tcl object type implementation. Attempts to
454 * generate an byte code internal form for the Tcl object "objPtr" by
455 * compiling its string representation.
456 *
457 * Results:
458 * The return value is a standard Tcl object result. If an error occurs
459 * during compilation, an error message is left in the interpreter's
460 * result unless "interp" is NULL.
461 *
462 * Side effects:
463 * Frees the old internal representation. If no error occurs, then the
464 * compiled code is stored as "objPtr"s bytecode representation.
465 * Also, if debugging, initializes the "tcl_traceCompile" Tcl variable
466 * used to trace compilations.
467 *
468 *----------------------------------------------------------------------
469 */
470
471 static int
472 SetByteCodeFromAny(interp, objPtr)
473 Tcl_Interp *interp; /* The interpreter for which the code is
474 * being compiled. Must not be NULL. */
475 Tcl_Obj *objPtr; /* The object to make a ByteCode object. */
476 {
477 return TclSetByteCodeFromAny(interp, objPtr,
478 (CompileHookProc *) NULL, (ClientData) NULL);
479 }
480
481 /*
482 *----------------------------------------------------------------------
483 *
484 * DupByteCodeInternalRep --
485 *
486 * Part of the bytecode Tcl object type implementation. However, it
487 * does not copy the internal representation of a bytecode Tcl_Obj, but
488 * instead leaves the new object untyped (with a NULL type pointer).
489 * Code will be compiled for the new object only if necessary.
490 *
491 * Results:
492 * None.
493 *
494 * Side effects:
495 * None.
496 *
497 *----------------------------------------------------------------------
498 */
499
500 static void
501 DupByteCodeInternalRep(srcPtr, copyPtr)
502 Tcl_Obj *srcPtr; /* Object with internal rep to copy. */
503 Tcl_Obj *copyPtr; /* Object with internal rep to set. */
504 {
505 return;
506 }
507
508 /*
509 *----------------------------------------------------------------------
510 *
511 * FreeByteCodeInternalRep --
512 *
513 * Part of the bytecode Tcl object type implementation. Frees the
514 * storage associated with a bytecode object's internal representation
515 * unless its code is actively being executed.
516 *
517 * Results:
518 * None.
519 *
520 * Side effects:
521 * The bytecode object's internal rep is marked invalid and its
522 * code gets freed unless the code is actively being executed.
523 * In that case the cleanup is delayed until the last execution
524 * of the code completes.
525 *
526 *----------------------------------------------------------------------
527 */
528
529 static void
530 FreeByteCodeInternalRep(objPtr)
531 register Tcl_Obj *objPtr; /* Object whose internal rep to free. */
532 {
533 register ByteCode *codePtr =
534 (ByteCode *) objPtr->internalRep.otherValuePtr;
535
536 codePtr->refCount--;
537 if (codePtr->refCount <= 0) {
538 TclCleanupByteCode(codePtr);
539 }
540 objPtr->typePtr = NULL;
541 objPtr->internalRep.otherValuePtr = NULL;
542 }
543
544 /*
545 *----------------------------------------------------------------------
546 *
547 * TclCleanupByteCode --
548 *
549 * This procedure does all the real work of freeing up a bytecode
550 * object's ByteCode structure. It's called only when the structure's
551 * reference count becomes zero.
552 *
553 * Results:
554 * None.
555 *
556 * Side effects:
557 * Frees objPtr's bytecode internal representation and sets its type
558 * and objPtr->internalRep.otherValuePtr NULL. Also releases its
559 * literals and frees its auxiliary data items.
560 *
561 *----------------------------------------------------------------------
562 */
563
564 void
565 TclCleanupByteCode(codePtr)
566 register ByteCode *codePtr; /* Points to the ByteCode to free. */
567 {
568 Tcl_Interp *interp = (Tcl_Interp *) *codePtr->interpHandle;
569 int numLitObjects = codePtr->numLitObjects;
570 int numAuxDataItems = codePtr->numAuxDataItems;
571 register Tcl_Obj **objArrayPtr;
572 register AuxData *auxDataPtr;
573 int i;
574 #ifdef TCL_COMPILE_STATS
575
576 if (interp != NULL) {
577 ByteCodeStats *statsPtr;
578 Tcl_Time destroyTime;
579 int lifetimeSec, lifetimeMicroSec, log2;
580
581 statsPtr = &((Interp *) interp)->stats;
582
583 statsPtr->numByteCodesFreed++;
584 statsPtr->currentSrcBytes -= (double) codePtr->numSrcBytes;
585 statsPtr->currentByteCodeBytes -= (double) codePtr->structureSize;
586
587 statsPtr->currentInstBytes -= (double) codePtr->numCodeBytes;
588 statsPtr->currentLitBytes -=
589 (double) (codePtr->numLitObjects * sizeof(Tcl_Obj *));
590 statsPtr->currentExceptBytes -=
591 (double) (codePtr->numExceptRanges * sizeof(ExceptionRange));
592 statsPtr->currentAuxBytes -=
593 (double) (codePtr->numAuxDataItems * sizeof(AuxData));
594 statsPtr->currentCmdMapBytes -= (double) codePtr->numCmdLocBytes;
595
596 Tcl_GetTime(&destroyTime);
597 lifetimeSec = destroyTime.sec - codePtr->createTime.sec;
598 if (lifetimeSec > 2000) { /* avoid overflow */
599 lifetimeSec = 2000;
600 }
601 lifetimeMicroSec =
602 1000000*lifetimeSec + (destroyTime.usec - codePtr->createTime.usec);
603
604 log2 = TclLog2(lifetimeMicroSec);
605 if (log2 > 31) {
606 log2 = 31;
607 }
608 statsPtr->lifetimeCount[log2]++;
609 }
610 #endif /* TCL_COMPILE_STATS */
611
612 /*
613 * A single heap object holds the ByteCode structure and its code,
614 * object, command location, and auxiliary data arrays. This means we
615 * only need to 1) decrement the ref counts of the LiteralEntry's in
616 * its literal array, 2) call the free procs for the auxiliary data
617 * items, and 3) free the ByteCode structure's heap object.
618 *
619 * The case for TCL_BYTECODE_PRECOMPILED (precompiled ByteCodes,
620 * like those generated from tbcload) is special, as they doesn't
621 * make use of the global literal table. They instead maintain
622 * private references to their literals which must be decremented.
623 */
624
625 if (codePtr->flags & TCL_BYTECODE_PRECOMPILED) {
626 register Tcl_Obj *objPtr;
627
628 objArrayPtr = codePtr->objArrayPtr;
629 for (i = 0; i < numLitObjects; i++) {
630 objPtr = *objArrayPtr;
631 if (objPtr) {
632 Tcl_DecrRefCount(objPtr);
633 }
634 objArrayPtr++;
635 }
636 codePtr->numLitObjects = 0;
637 } else if (interp != NULL) {
638 /*
639 * If the interp has already been freed, then Tcl will have already
640 * forcefully released all the literals used by ByteCodes compiled
641 * with respect to that interp.
642 */
643
644 objArrayPtr = codePtr->objArrayPtr;
645 for (i = 0; i < numLitObjects; i++) {
646 /*
647 * TclReleaseLiteral sets a ByteCode's object array entry NULL to
648 * indicate that it has already freed the literal.
649 */
650
651 if (*objArrayPtr != NULL) {
652 TclReleaseLiteral(interp, *objArrayPtr);
653 }
654 objArrayPtr++;
655 }
656 }
657
658 auxDataPtr = codePtr->auxDataArrayPtr;
659 for (i = 0; i < numAuxDataItems; i++) {
660 if (auxDataPtr->type->freeProc != NULL) {
661 (*auxDataPtr->type->freeProc)(auxDataPtr->clientData);
662 }
663 auxDataPtr++;
664 }
665
666 TclHandleRelease(codePtr->interpHandle);
667 ckfree((char *) codePtr);
668 }
669
670 /*
671 *----------------------------------------------------------------------
672 *
673 * TclInitCompileEnv --
674 *
675 * Initializes a CompileEnv compilation environment structure for the
676 * compilation of a string in an interpreter.
677 *
678 * Results:
679 * None.
680 *
681 * Side effects:
682 * The CompileEnv structure is initialized.
683 *
684 *----------------------------------------------------------------------
685 */
686
687 void
688 TclInitCompileEnv(interp, envPtr, string, numBytes)
689 Tcl_Interp *interp; /* The interpreter for which a CompileEnv
690 * structure is initialized. */
691 register CompileEnv *envPtr; /* Points to the CompileEnv structure to
692 * initialize. */
693 char *string; /* The source string to be compiled. */
694 int numBytes; /* Number of bytes in source string. */
695 {
696 Interp *iPtr = (Interp *) interp;
697
698 envPtr->iPtr = iPtr;
699 envPtr->source = string;
700 envPtr->numSrcBytes = numBytes;
701 envPtr->procPtr = iPtr->compiledProcPtr;
702 envPtr->numCommands = 0;
703 envPtr->exceptDepth = 0;
704 envPtr->maxExceptDepth = 0;
705 envPtr->maxStackDepth = 0;
706 envPtr->currStackDepth = 0;
707 TclInitLiteralTable(&(envPtr->localLitTable));
708
709 envPtr->codeStart = envPtr->staticCodeSpace;
710 envPtr->codeNext = envPtr->codeStart;
711 envPtr->codeEnd = (envPtr->codeStart + COMPILEENV_INIT_CODE_BYTES);
712 envPtr->mallocedCodeArray = 0;
713
714 envPtr->literalArrayPtr = envPtr->staticLiteralSpace;
715 envPtr->literalArrayNext = 0;
716 envPtr->literalArrayEnd = COMPILEENV_INIT_NUM_OBJECTS;
717 envPtr->mallocedLiteralArray = 0;
718
719 envPtr->exceptArrayPtr = envPtr->staticExceptArraySpace;
720 envPtr->exceptArrayNext = 0;
721 envPtr->exceptArrayEnd = COMPILEENV_INIT_EXCEPT_RANGES;
722 envPtr->mallocedExceptArray = 0;
723
724 envPtr->cmdMapPtr = envPtr->staticCmdMapSpace;
725 envPtr->cmdMapEnd = COMPILEENV_INIT_CMD_MAP_SIZE;
726 envPtr->mallocedCmdMap = 0;
727
728 envPtr->auxDataArrayPtr = envPtr->staticAuxDataArraySpace;
729 envPtr->auxDataArrayNext = 0;
730 envPtr->auxDataArrayEnd = COMPILEENV_INIT_AUX_DATA_SIZE;
731 envPtr->mallocedAuxDataArray = 0;
732 }
733
734 /*
735 *----------------------------------------------------------------------
736 *
737 * TclFreeCompileEnv --
738 *
739 * Free the storage allocated in a CompileEnv compilation environment
740 * structure.
741 *
742 * Results:
743 * None.
744 *
745 * Side effects:
746 * Allocated storage in the CompileEnv structure is freed. Note that
747 * its local literal table is not deleted and its literal objects are
748 * not released. In addition, storage referenced by its auxiliary data
749 * items is not freed. This is done so that, when compilation is
750 * successful, "ownership" of these objects and aux data items is
751 * handed over to the corresponding ByteCode structure.
752 *
753 *----------------------------------------------------------------------
754 */
755
756 void
757 TclFreeCompileEnv(envPtr)
758 register CompileEnv *envPtr; /* Points to the CompileEnv structure. */
759 {
760 if (envPtr->mallocedCodeArray) {
761 ckfree((char *) envPtr->codeStart);
762 }
763 if (envPtr->mallocedLiteralArray) {
764 ckfree((char *) envPtr->literalArrayPtr);
765 }
766 if (envPtr->mallocedExceptArray) {
767 ckfree((char *) envPtr->exceptArrayPtr);
768 }
769 if (envPtr->mallocedCmdMap) {
770 ckfree((char *) envPtr->cmdMapPtr);
771 }
772 if (envPtr->mallocedAuxDataArray) {
773 ckfree((char *) envPtr->auxDataArrayPtr);
774 }
775 }
776
777 /*
778 *----------------------------------------------------------------------
779 *
780 * TclCompileScript --
781 *
782 * Compile a Tcl script in a string.
783 *
784 * Results:
785 * The return value is TCL_OK on a successful compilation and TCL_ERROR
786 * on failure. If TCL_ERROR is returned, then the interpreter's result
787 * contains an error message.
788 *
789 * interp->termOffset is set to the offset of the character in the
790 * script just after the last one successfully processed; this will be
791 * the offset of the ']' if (flags & TCL_BRACKET_TERM).
792 *
793 * Side effects:
794 * Adds instructions to envPtr to evaluate the script at runtime.
795 *
796 *----------------------------------------------------------------------
797 */
798
799 int
800 TclCompileScript(interp, script, numBytes, nested, envPtr)
801 Tcl_Interp *interp; /* Used for error and status reporting.
802 * Also serves as context for finding and
803 * compiling commands. May not be NULL. */
804 CONST char *script; /* The source script to compile. */
805 int numBytes; /* Number of bytes in script. If < 0, the
806 * script consists of all bytes up to the
807 * first null character. */
808 int nested; /* Non-zero means this is a nested command:
809 * close bracket ']' should be considered a
810 * command terminator. If zero, close
811 * bracket has no special meaning. */
812 CompileEnv *envPtr; /* Holds resulting instructions. */
813 {
814 Interp *iPtr = (Interp *) interp;
815 Tcl_Parse parse;
816 int lastTopLevelCmdIndex = -1;
817 /* Index of most recent toplevel command in
818 * the command location table. Initialized
819 * to avoid compiler warning. */
820 int startCodeOffset = -1; /* Offset of first byte of current command's
821 * code. Init. to avoid compiler warning. */
822 unsigned char *entryCodeNext = envPtr->codeNext;
823 CONST char *p, *next;
824 Namespace *cmdNsPtr;
825 Command *cmdPtr;
826 Tcl_Token *tokenPtr;
827 int bytesLeft, isFirstCmd, gotParse, wordIdx, currCmdIndex;
828 int commandLength, objIndex, code;
829 Tcl_DString ds;
830
831 Tcl_DStringInit(&ds);
832
833 if (numBytes < 0) {
834 numBytes = strlen(script);
835 }
836 Tcl_ResetResult(interp);
837 isFirstCmd = 1;
838
839 /*
840 * Each iteration through the following loop compiles the next
841 * command from the script.
842 */
843
844 p = script;
845 bytesLeft = numBytes;
846 gotParse = 0;
847 do {
848 if (Tcl_ParseCommand(interp, p, bytesLeft, nested, &parse) != TCL_OK) {
849 code = TCL_ERROR;
850 goto error;
851 }
852 gotParse = 1;
853 if (nested) {
854 /*
855 * This is an unusual situation where the caller has passed us
856 * a non-zero value for "nested". How unusual? Well, this
857 * procedure, TclCompileScript, is internal to Tcl, so all
858 * callers should be within Tcl itself. All but one of those
859 * callers explicitly pass in (nested = 0). The exceptional
860 * caller is TclSetByteCodeFromAny, which will pass in
861 * (nested = 1) if and only if the flag TCL_BRACKET_TERM
862 * is set in the evalFlags field of interp.
863 *
864 * It appears that the TCL_BRACKET_TERM flag is only ever set
865 * by Tcl_SubstObj, and it immediately calls Tcl_EvalEx
866 * which clears the flag before passing the interp along.
867 * So, I don't think this procedure, TclCompileScript, is
868 * **ever** called with (nested != 0).
869 * (The testsuite indeed doesn't exercise this code. MS)
870 *
871 * This means that the branches in this procedure that are
872 * only active when (nested != 0) are probably never exercised.
873 * This means that any bugs in them go unnoticed, and any bug
874 * fixes in them have a semi-theoretical nature.
875 *
876 * All that said, the spec for this procedure says it should
877 * handle the (nested != 0) case, so here's an attempt to fix
878 * bugs (Tcl Bug 681841) in that case. Just in case some
879 * callers eventually come along and expect it to work...
880 */
881
882 if (parse.term == (script + numBytes)) {
883 /*
884 * The (nested != 0) case is meant to indicate that the
885 * caller found an open bracket ([) and asked us to
886 * parse and compile Tcl commands up to the matching
887 * close bracket (]). We have to detect and handle
888 * the case where the close bracket is missing.
889 */
890
891 Tcl_SetObjResult(interp,
892 Tcl_NewStringObj("missing close-bracket", -1));
893 code = TCL_ERROR;
894 goto error;
895 }
896 }
897 if (parse.numWords > 0) {
898 /*
899 * If not the first command, pop the previous command's result
900 * and, if we're compiling a top level command, update the last
901 * command's code size to account for the pop instruction.
902 */
903
904 if (!isFirstCmd) {
905 TclEmitOpcode(INST_POP, envPtr);
906 if (!nested) {
907 envPtr->cmdMapPtr[lastTopLevelCmdIndex].numCodeBytes =
908 (envPtr->codeNext - envPtr->codeStart)
909 - startCodeOffset;
910 }
911 }
912
913 /*
914 * Determine the actual length of the command.
915 */
916
917 commandLength = parse.commandSize;
918 if (parse.term == parse.commandStart + commandLength - 1) {
919 /*
920 * The command terminator character (such as ; or ]) is
921 * the last character in the parsed command. Reduce the
922 * length by one so that the trace message doesn't include
923 * the terminator character.
924 */
925
926 commandLength -= 1;
927 }
928
929 #ifdef TCL_COMPILE_DEBUG
930 /*
931 * If tracing, print a line for each top level command compiled.
932 */
933
934 if ((tclTraceCompile >= 1)
935 && !nested && (envPtr->procPtr == NULL)) {
936 fprintf(stdout, " Compiling: ");
937 TclPrintSource(stdout, parse.commandStart,
938 TclMin(commandLength, 55));
939 fprintf(stdout, "\n");
940 }
941 #endif
942 /*
943 * Each iteration of the following loop compiles one word
944 * from the command.
945 */
946
947 envPtr->numCommands++;
948 currCmdIndex = (envPtr->numCommands - 1);
949 if (!nested) {
950 lastTopLevelCmdIndex = currCmdIndex;
951 }
952 startCodeOffset = (envPtr->codeNext - envPtr->codeStart);
953 EnterCmdStartData(envPtr, currCmdIndex,
954 (parse.commandStart - envPtr->source), startCodeOffset);
955
956 for (wordIdx = 0, tokenPtr = parse.tokenPtr;
957 wordIdx < parse.numWords;
958 wordIdx++, tokenPtr += (tokenPtr->numComponents + 1)) {
959 if (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
960 /*
961 * If this is the first word and the command has a
962 * compile procedure, let it compile the command.
963 */
964
965 if (wordIdx == 0) {
966 if (envPtr->procPtr != NULL) {
967 cmdNsPtr = envPtr->procPtr->cmdPtr->nsPtr;
968 } else {
969 cmdNsPtr = NULL; /* use current NS */
970 }
971
972 /*
973 * We copy the string before trying to find the command
974 * by name. We used to modify the string in place, but
975 * this is not safe because the name resolution
976 * handlers could have side effects that rely on the
977 * unmodified string.
978 */
979
980 Tcl_DStringSetLength(&ds, 0);
981 Tcl_DStringAppend(&ds, tokenPtr[1].start,
982 tokenPtr[1].size);
983
984 cmdPtr = (Command *) Tcl_FindCommand(interp,
985 Tcl_DStringValue(&ds),
986 (Tcl_Namespace *) cmdNsPtr, /*flags*/ 0);
987
988 if ((cmdPtr != NULL)
989 && (cmdPtr->compileProc != NULL)
990 && !(cmdPtr->flags & CMD_HAS_EXEC_TRACES)
991 && !(iPtr->flags & DONT_COMPILE_CMDS_INLINE)) {
992 int savedNumCmds = envPtr->numCommands;
993
994 code = (*(cmdPtr->compileProc))(interp, &parse,
995 envPtr);
996 if (code == TCL_OK) {
997 goto finishCommand;
998 } else if (code == TCL_OUT_LINE_COMPILE) {
999 /*
1000 * Restore numCommands to its correct value, removing
1001 * any commands compiled before TCL_OUT_LINE_COMPILE
1002 * [Bug 705406]
1003 */
1004 envPtr->numCommands = savedNumCmds;
1005 } else { /* an error */
1006 /*
1007 * There was a compilation error, the last
1008 * command did not get compiled into (*envPtr).
1009 * Decrement the number of commands
1010 * claimed to be in (*envPtr).
1011 */
1012 envPtr->numCommands--;
1013 goto log;
1014 }
1015 }
1016
1017 /*
1018 * No compile procedure so push the word. If the
1019 * command was found, push a CmdName object to
1020 * reduce runtime lookups.
1021 */
1022
1023 objIndex = TclRegisterNewLiteral(envPtr,
1024 tokenPtr[1].start, tokenPtr[1].size);
1025 if (cmdPtr != NULL) {
1026 TclSetCmdNameObj(interp,
1027 envPtr->literalArrayPtr[objIndex].objPtr,
1028 cmdPtr);
1029 }
1030 } else {
1031 objIndex = TclRegisterNewLiteral(envPtr,
1032 tokenPtr[1].start, tokenPtr[1].size);
1033 }
1034 TclEmitPush(objIndex, envPtr);
1035 } else {
1036 /*
1037 * The word is not a simple string of characters.
1038 */
1039
1040 code = TclCompileTokens(interp, tokenPtr+1,
1041 tokenPtr->numComponents, envPtr);
1042 if (code != TCL_OK) {
1043 goto log;
1044 }
1045 }
1046 }
1047
1048 /*
1049 * Emit an invoke instruction for the command. We skip this
1050 * if a compile procedure was found for the command.
1051 */
1052
1053 if (wordIdx > 0) {
1054 if (wordIdx <= 255) {
1055 TclEmitInstInt1(INST_INVOKE_STK1, wordIdx, envPtr);
1056 } else {
1057 TclEmitInstInt4(INST_INVOKE_STK4, wordIdx, envPtr);
1058 }
1059 }
1060
1061 /*
1062 * Update the compilation environment structure and record the
1063 * offsets of the source and code for the command.
1064 */
1065
1066 finishCommand:
1067 EnterCmdExtentData(envPtr, currCmdIndex, commandLength,
1068 (envPtr->codeNext-envPtr->codeStart) - startCodeOffset);
1069 isFirstCmd = 0;
1070 } /* end if parse.numWords > 0 */
1071
1072 /*
1073 * Advance to the next command in the script.
1074 */
1075
1076 next = parse.commandStart + parse.commandSize;
1077 bytesLeft -= (next - p);
1078 p = next;
1079 Tcl_FreeParse(&parse);
1080 gotParse = 0;
1081 if (nested && (*parse.term == ']')) {
1082 /*
1083 * We get here in the special case where TCL_BRACKET_TERM was
1084 * set in the interpreter and the latest parsed command was
1085 * terminated by the matching close-bracket we were looking for.
1086 * Stop compilation.
1087 */
1088
1089 break;
1090 }
1091 } while (bytesLeft > 0);
1092
1093 /*
1094 * If the source script yielded no instructions (e.g., if it was empty),
1095 * push an empty string as the command's result.
1096 */
1097
1098 if (envPtr->codeNext == entryCodeNext) {
1099 TclEmitPush(TclRegisterLiteral(envPtr, "", 0, /*onHeap*/ 0),
1100 envPtr);
1101 }
1102
1103 if (nested) {
1104 /*
1105 * When (nested != 0) back up 1 character to have
1106 * iPtr->termOffset indicate the offset to the matching
1107 * close-bracket.
1108 */
1109
1110 iPtr->termOffset = (p - 1) - script;
1111 } else {
1112 iPtr->termOffset = (p - script);
1113 }
1114 Tcl_DStringFree(&ds);
1115 return TCL_OK;
1116
1117 error:
1118 /*
1119 * Generate various pieces of error information, such as the line
1120 * number where the error occurred and information to add to the
1121 * errorInfo variable. Then free resources that had been allocated
1122 * to the command.
1123 */
1124
1125 commandLength = parse.commandSize;
1126 if (parse.term == parse.commandStart + commandLength - 1) {
1127 /*
1128 * The terminator character (such as ; or ]) of the command where
1129 * the error occurred is the last character in the parsed command.
1130 * Reduce the length by one so that the error message doesn't
1131 * include the terminator character.
1132 */
1133
1134 commandLength -= 1;
1135 }
1136
1137 log:
1138 LogCompilationInfo(interp, script, parse.commandStart, commandLength);
1139 if (gotParse) {
1140 Tcl_FreeParse(&parse);
1141 }
1142 iPtr->termOffset = (p - script);
1143 Tcl_DStringFree(&ds);
1144 return code;
1145 }
1146
1147 /*
1148 *----------------------------------------------------------------------
1149 *
1150 * TclCompileTokens --
1151 *
1152 * Given an array of tokens parsed from a Tcl command (e.g., the tokens
1153 * that make up a word) this procedure emits instructions to evaluate
1154 * the tokens and concatenate their values to form a single result
1155 * value on the interpreter's runtime evaluation stack.
1156 *
1157 * Results:
1158 * The return value is a standard Tcl result. If an error occurs, an
1159 * error message is left in the interpreter's result.
1160 *
1161 * Side effects:
1162 * Instructions are added to envPtr to push and evaluate the tokens
1163 * at runtime.
1164 *
1165 *----------------------------------------------------------------------
1166 */
1167
1168 int
1169 TclCompileTokens(interp, tokenPtr, count, envPtr)
1170 Tcl_Interp *interp; /* Used for error and status reporting. */
1171 Tcl_Token *tokenPtr; /* Pointer to first in an array of tokens
1172 * to compile. */
1173 int count; /* Number of tokens to consider at tokenPtr.
1174 * Must be at least 1. */
1175 CompileEnv *envPtr; /* Holds the resulting instructions. */
1176 {
1177 Tcl_DString textBuffer; /* Holds concatenated chars from adjacent
1178 * TCL_TOKEN_TEXT, TCL_TOKEN_BS tokens. */
1179 char buffer[TCL_UTF_MAX];
1180 CONST char *name, *p;
1181 int numObjsToConcat, nameBytes, localVarName, localVar;
1182 int length, i, code;
1183 unsigned char *entryCodeNext = envPtr->codeNext;
1184
1185 Tcl_DStringInit(&textBuffer);
1186 numObjsToConcat = 0;
1187 for ( ; count > 0; count--, tokenPtr++) {
1188 switch (tokenPtr->type) {
1189 case TCL_TOKEN_TEXT:
1190 Tcl_DStringAppend(&textBuffer, tokenPtr->start,
1191 tokenPtr->size);
1192 break;
1193
1194 case TCL_TOKEN_BS:
1195 length = Tcl_UtfBackslash(tokenPtr->start, (int *) NULL,
1196 buffer);
1197 Tcl_DStringAppend(&textBuffer, buffer, length);
1198 break;
1199
1200 case TCL_TOKEN_COMMAND:
1201 /*
1202 * Push any accumulated chars appearing before the command.
1203 */
1204
1205 if (Tcl_DStringLength(&textBuffer) > 0) {
1206 int literal;
1207
1208 literal = TclRegisterLiteral(envPtr,
1209 Tcl_DStringValue(&textBuffer),
1210 Tcl_DStringLength(&textBuffer), /*onHeap*/ 0);
1211 TclEmitPush(literal, envPtr);
1212 numObjsToConcat++;
1213 Tcl_DStringFree(&textBuffer);
1214 }
1215
1216 code = TclCompileScript(interp, tokenPtr->start+1,
1217 tokenPtr->size-2, /*nested*/ 0, envPtr);
1218 if (code != TCL_OK) {
1219 goto error;
1220 }
1221 numObjsToConcat++;
1222 break;
1223
1224 case TCL_TOKEN_VARIABLE:
1225 /*
1226 * Push any accumulated chars appearing before the $<var>.
1227 */
1228
1229 if (Tcl_DStringLength(&textBuffer) > 0) {
1230 int literal;
1231
1232 literal = TclRegisterLiteral(envPtr,
1233 Tcl_DStringValue(&textBuffer),
1234 Tcl_DStringLength(&textBuffer), /*onHeap*/ 0);
1235 TclEmitPush(literal, envPtr);
1236 numObjsToConcat++;
1237 Tcl_DStringFree(&textBuffer);
1238 }
1239
1240 /*
1241 * Determine how the variable name should be handled: if it contains
1242 * any namespace qualifiers it is not a local variable (localVarName=-1);
1243 * if it looks like an array element and the token has a single component,
1244 * it should not be created here [Bug 569438] (localVarName=0); otherwise,
1245 * the local variable can safely be created (localVarName=1).
1246 */
1247
1248 name = tokenPtr[1].start;
1249 nameBytes = tokenPtr[1].size;
1250 localVarName = -1;
1251 if (envPtr->procPtr != NULL) {
1252 localVarName = 1;
1253 for (i = 0, p = name; i < nameBytes; i++, p++) {
1254 if ((*p == ':') && (i < (nameBytes-1))
1255 && (*(p+1) == ':')) {
1256 localVarName = -1;
1257 break;
1258 } else if ((*p == '(')
1259 && (tokenPtr->numComponents == 1)
1260 && (*(name + nameBytes - 1) == ')')) {
1261 localVarName = 0;
1262 break;
1263 }
1264 }
1265 }
1266
1267 /*
1268 * Either push the variable's name, or find its index in
1269 * the array of local variables in a procedure frame.
1270 */
1271
1272 localVar = -1;
1273 if (localVarName != -1) {
1274 localVar = TclFindCompiledLocal(name, nameBytes,
1275 localVarName, /*flags*/ 0, envPtr->procPtr);
1276 }
1277 if (localVar < 0) {
1278 TclEmitPush(TclRegisterNewLiteral(envPtr, name, nameBytes),
1279 envPtr);
1280 }
1281
1282 /*
1283 * Emit instructions to load the variable.
1284 */
1285
1286 if (tokenPtr->numComponents == 1) {
1287 if (localVar < 0) {
1288 TclEmitOpcode(INST_LOAD_SCALAR_STK, envPtr);
1289 } else if (localVar <= 255) {
1290 TclEmitInstInt1(INST_LOAD_SCALAR1, localVar,
1291 envPtr);
1292 } else {
1293 TclEmitInstInt4(INST_LOAD_SCALAR4, localVar,
1294 envPtr);
1295 }
1296 } else {
1297 code = TclCompileTokens(interp, tokenPtr+2,
1298 tokenPtr->numComponents-1, envPtr);
1299 if (code != TCL_OK) {
1300 char errorBuffer[150];
1301 sprintf(errorBuffer,
1302 "\n (parsing index for array \"%.*s\")",
1303 ((nameBytes > 100)? 100 : nameBytes), name);
1304 Tcl_AddObjErrorInfo(interp, errorBuffer, -1);
1305 goto error;
1306 }
1307 if (localVar < 0) {
1308 TclEmitOpcode(INST_LOAD_ARRAY_STK, envPtr);
1309 } else if (localVar <= 255) {
1310 TclEmitInstInt1(INST_LOAD_ARRAY1, localVar,
1311 envPtr);
1312 } else {
1313 TclEmitInstInt4(INST_LOAD_ARRAY4, localVar,
1314 envPtr);
1315 }
1316 }
1317 numObjsToConcat++;
1318 count -= tokenPtr->numComponents;
1319 tokenPtr += tokenPtr->numComponents;
1320 break;
1321
1322 default:
1323 panic("Unexpected token type in TclCompileTokens");
1324 }
1325 }
1326
1327 /*
1328 * Push any accumulated characters appearing at the end.
1329 */
1330
1331 if (Tcl_DStringLength(&textBuffer) > 0) {
1332 int literal;
1333
1334 literal = TclRegisterLiteral(envPtr, Tcl_DStringValue(&textBuffer),
1335 Tcl_DStringLength(&textBuffer), /*onHeap*/ 0);
1336 TclEmitPush(literal, envPtr);
1337 numObjsToConcat++;
1338 }
1339
1340 /*
1341 * If necessary, concatenate the parts of the word.
1342 */
1343
1344 while (numObjsToConcat > 255) {
1345 TclEmitInstInt1(INST_CONCAT1, 255, envPtr);
1346 numObjsToConcat -= 254; /* concat pushes 1 obj, the result */
1347 }
1348 if (numObjsToConcat > 1) {
1349 TclEmitInstInt1(INST_CONCAT1, numObjsToConcat, envPtr);
1350 }
1351
1352 /*
1353 * If the tokens yielded no instructions, push an empty string.
1354 */
1355
1356 if (envPtr->codeNext == entryCodeNext) {
1357 TclEmitPush(TclRegisterLiteral(envPtr, "", 0, /*onHeap*/ 0),
1358 envPtr);
1359 }
1360 Tcl_DStringFree(&textBuffer);
1361 return TCL_OK;
1362
1363 error:
1364 Tcl_DStringFree(&textBuffer);
1365 return code;
1366 }
1367
1368 /*
1369 *----------------------------------------------------------------------
1370 *
1371 * TclCompileCmdWord --
1372 *
1373 * Given an array of parse tokens for a word containing one or more Tcl
1374 * commands, emit inline instructions to execute them. This procedure
1375 * differs from TclCompileTokens in that a simple word such as a loop
1376 * body enclosed in braces is not just pushed as a string, but is
1377 * itself parsed into tokens and compiled.
1378 *
1379 * Results:
1380 * The return value is a standard Tcl result. If an error occurs, an
1381 * error message is left in the interpreter's result.
1382 *
1383 * Side effects:
1384 * Instructions are added to envPtr to execute the tokens at runtime.
1385 *
1386 *----------------------------------------------------------------------
1387 */
1388
1389 int
1390 TclCompileCmdWord(interp, tokenPtr, count, envPtr)
1391 Tcl_Interp *interp; /* Used for error and status reporting. */
1392 Tcl_Token *tokenPtr; /* Pointer to first in an array of tokens
1393 * for a command word to compile inline. */
1394 int count; /* Number of tokens to consider at tokenPtr.
1395 * Must be at least 1. */
1396 CompileEnv *envPtr; /* Holds the resulting instructions. */
1397 {
1398 int code;
1399
1400 /*
1401 * Handle the common case: if there is a single text token, compile it
1402 * into an inline sequence of instructions.
1403 */
1404
1405 if ((count == 1) && (tokenPtr->type == TCL_TOKEN_TEXT)) {
1406 code = TclCompileScript(interp, tokenPtr->start, tokenPtr->size,
1407 /*nested*/ 0, envPtr);
1408 return code;
1409 }
1410
1411 /*
1412 * Multiple tokens or the single token involves substitutions. Emit
1413 * instructions to invoke the eval command procedure at runtime on the
1414 * result of evaluating the tokens.
1415 */
1416
1417 code = TclCompileTokens(interp, tokenPtr, count, envPtr);
1418 if (code != TCL_OK) {
1419 return code;
1420 }
1421 TclEmitOpcode(INST_EVAL_STK, envPtr);
1422 return TCL_OK;
1423 }
1424
1425 /*
1426 *----------------------------------------------------------------------
1427 *
1428 * TclCompileExprWords --
1429 *
1430 * Given an array of parse tokens representing one or more words that
1431 * contain a Tcl expression, emit inline instructions to execute the
1432 * expression. This procedure differs from TclCompileExpr in that it
1433 * supports Tcl's two-level substitution semantics for expressions that
1434 * appear as command words.
1435 *
1436 * Results:
1437 * The return value is a standard Tcl result. If an error occurs, an
1438 * error message is left in the interpreter's result.
1439 *
1440 * Side effects:
1441 * Instructions are added to envPtr to execute the expression.
1442 *
1443 *----------------------------------------------------------------------
1444 */
1445
1446 int
1447 TclCompileExprWords(interp, tokenPtr, numWords, envPtr)
1448 Tcl_Interp *interp; /* Used for error and status reporting. */
1449 Tcl_Token *tokenPtr; /* Points to first in an array of word
1450 * tokens tokens for the expression to
1451 * compile inline. */
1452 int numWords; /* Number of word tokens starting at
1453 * tokenPtr. Must be at least 1. Each word
1454 * token contains one or more subtokens. */
1455 CompileEnv *envPtr; /* Holds the resulting instructions. */
1456 {
1457 Tcl_Token *wordPtr;
1458 int numBytes, i, code;
1459 CONST char *script;
1460
1461 code = TCL_OK;
1462
1463 /*
1464 * If the expression is a single word that doesn't require
1465 * substitutions, just compile its string into inline instructions.
1466 */
1467
1468 if ((numWords == 1) && (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD)) {
1469 script = tokenPtr[1].start;
1470 numBytes = tokenPtr[1].size;
1471 code = TclCompileExpr(interp, script, numBytes, envPtr);
1472 return code;
1473 }
1474
1475 /*
1476 * Emit code to call the expr command proc at runtime. Concatenate the
1477 * (already substituted once) expr tokens with a space between each.
1478 */
1479
1480 wordPtr = tokenPtr;
1481 for (i = 0; i < numWords; i++) {
1482 code = TclCompileTokens(interp, wordPtr+1, wordPtr->numComponents,
1483 envPtr);
1484 if (code != TCL_OK) {
1485 break;
1486 }
1487 if (i < (numWords - 1)) {
1488 TclEmitPush(TclRegisterLiteral(envPtr, " ", 1, /*onHeap*/ 0),
1489 envPtr);
1490 }
1491 wordPtr += (wordPtr->numComponents + 1);
1492 }
1493 if (code == TCL_OK) {
1494 int concatItems = 2*numWords - 1;
1495 while (concatItems > 255) {
1496 TclEmitInstInt1(INST_CONCAT1, 255, envPtr);
1497 concatItems -= 254;
1498 }
1499 if (concatItems > 1) {
1500 TclEmitInstInt1(INST_CONCAT1, concatItems, envPtr);
1501 }
1502 TclEmitOpcode(INST_EXPR_STK, envPtr);
1503 }
1504
1505 return code;
1506 }
1507
1508 /*
1509 *----------------------------------------------------------------------
1510 *
1511 * TclInitByteCodeObj --
1512 *
1513 * Create a ByteCode structure and initialize it from a CompileEnv
1514 * compilation environment structure. The ByteCode structure is
1515 * smaller and contains just that information needed to execute
1516 * the bytecode instructions resulting from compiling a Tcl script.
1517 * The resulting structure is placed in the specified object.
1518 *
1519 * Results:
1520 * A newly constructed ByteCode object is stored in the internal
1521 * representation of the objPtr.
1522 *
1523 * Side effects:
1524 * A single heap object is allocated to hold the new ByteCode structure
1525 * and its code, object, command location, and aux data arrays. Note
1526 * that "ownership" (i.e., the pointers to) the Tcl objects and aux
1527 * data items will be handed over to the new ByteCode structure from
1528 * the CompileEnv structure.
1529 *
1530 *----------------------------------------------------------------------
1531 */
1532
1533 void
1534 TclInitByteCodeObj(objPtr, envPtr)
1535 Tcl_Obj *objPtr; /* Points object that should be
1536 * initialized, and whose string rep
1537 * contains the source code. */
1538 register CompileEnv *envPtr; /* Points to the CompileEnv structure from
1539 * which to create a ByteCode structure. */
1540 {
1541 register ByteCode *codePtr;
1542 size_t codeBytes, objArrayBytes, exceptArrayBytes, cmdLocBytes;
1543 size_t auxDataArrayBytes, structureSize;
1544 register unsigned char *p;
1545 unsigned char *nextPtr;
1546 int numLitObjects = envPtr->literalArrayNext;
1547 Namespace *namespacePtr;
1548 int i;
1549 Interp *iPtr;
1550
1551 iPtr = envPtr->iPtr;
1552
1553 codeBytes = (envPtr->codeNext - envPtr->codeStart);
1554 objArrayBytes = (envPtr->literalArrayNext * sizeof(Tcl_Obj *));
1555 exceptArrayBytes = (envPtr->exceptArrayNext * sizeof(ExceptionRange));
1556 auxDataArrayBytes = (envPtr->auxDataArrayNext * sizeof(AuxData));
1557 cmdLocBytes = GetCmdLocEncodingSize(envPtr);
1558
1559 /*
1560 * Compute the total number of bytes needed for this bytecode.
1561 */
1562
1563 structureSize = sizeof(ByteCode);
1564 structureSize += TCL_ALIGN(codeBytes); /* align object array */
1565 structureSize += TCL_ALIGN(objArrayBytes); /* align exc range arr */
1566 structureSize += TCL_ALIGN(exceptArrayBytes); /* align AuxData array */
1567 structureSize += auxDataArrayBytes;
1568 structureSize += cmdLocBytes;
1569
1570 if (envPtr->iPtr->varFramePtr != NULL) {
1571 namespacePtr = envPtr->iPtr->varFramePtr->nsPtr;
1572 } else {
1573 namespacePtr = envPtr->iPtr->globalNsPtr;
1574 }
1575
1576 p = (unsigned char *) ckalloc((size_t) structureSize);
1577 codePtr = (ByteCode *) p;
1578 codePtr->interpHandle = TclHandlePreserve(iPtr->handle);
1579 codePtr->compileEpoch = iPtr->compileEpoch;
1580 codePtr->nsPtr = namespacePtr;
1581 codePtr->nsEpoch = namespacePtr->resolverEpoch;
1582 codePtr->refCount = 1;
1583 codePtr->flags = 0;
1584 codePtr->source = envPtr->source;
1585 codePtr->procPtr = envPtr->procPtr;
1586
1587 codePtr->numCommands = envPtr->numCommands;
1588 codePtr->numSrcBytes = envPtr->numSrcBytes;
1589 codePtr->numCodeBytes = codeBytes;
1590 codePtr->numLitObjects = numLitObjects;
1591 codePtr->numExceptRanges = envPtr->exceptArrayNext;
1592 codePtr->numAuxDataItems = envPtr->auxDataArrayNext;
1593 codePtr->numCmdLocBytes = cmdLocBytes;
1594 codePtr->maxExceptDepth = envPtr->maxExceptDepth;
1595 codePtr->maxStackDepth = envPtr->maxStackDepth;
1596
1597 p += sizeof(ByteCode);
1598 codePtr->codeStart = p;
1599 memcpy((VOID *) p, (VOID *) envPtr->codeStart, (size_t) codeBytes);
1600
1601 p += TCL_ALIGN(codeBytes); /* align object array */
1602 codePtr->objArrayPtr = (Tcl_Obj **) p;
1603 for (i = 0; i < numLitObjects; i++) {
1604 codePtr->objArrayPtr[i] = envPtr->literalArrayPtr[i].objPtr;
1605 }
1606
1607 p += TCL_ALIGN(objArrayBytes); /* align exception range array */
1608 if (exceptArrayBytes > 0) {
1609 codePtr->exceptArrayPtr = (ExceptionRange *) p;
1610 memcpy((VOID *) p, (VOID *) envPtr->exceptArrayPtr,
1611 (size_t) exceptArrayBytes);
1612 } else {
1613 codePtr->exceptArrayPtr = NULL;
1614 }
1615
1616 p += TCL_ALIGN(exceptArrayBytes); /* align AuxData array */
1617 if (auxDataArrayBytes > 0) {
1618 codePtr->auxDataArrayPtr = (AuxData *) p;
1619 memcpy((VOID *) p, (VOID *) envPtr->auxDataArrayPtr,
1620 (size_t) auxDataArrayBytes);
1621 } else {
1622 codePtr->auxDataArrayPtr = NULL;
1623 }
1624
1625 p += auxDataArrayBytes;
1626 nextPtr = EncodeCmdLocMap(envPtr, codePtr, (unsigned char *) p);
1627 #ifdef TCL_COMPILE_DEBUG
1628 if (((size_t)(nextPtr - p)) != cmdLocBytes) {
1629 panic("TclInitByteCodeObj: encoded cmd location bytes %d != expected size %d\n", (nextPtr - p), cmdLocBytes);
1630 }
1631 #endif
1632
1633 /*
1634 * Record various compilation-related statistics about the new ByteCode
1635 * structure. Don't include overhead for statistics-related fields.
1636 */
1637
1638 #ifdef TCL_COMPILE_STATS
1639 codePtr->structureSize = structureSize
1640 - (sizeof(size_t) + sizeof(Tcl_Time));
1641 Tcl_GetTime(&(codePtr->createTime));
1642
1643 RecordByteCodeStats(codePtr);
1644 #endif /* TCL_COMPILE_STATS */
1645
1646 /*
1647 * Free the old internal rep then convert the object to a
1648 * bytecode object by making its internal rep point to the just
1649 * compiled ByteCode.
1650 */
1651
1652 if ((objPtr->typePtr != NULL) &&
1653 (objPtr->typePtr->freeIntRepProc != NULL)) {
1654 (*objPtr->typePtr->freeIntRepProc)(objPtr);
1655 }
1656 objPtr->internalRep.otherValuePtr = (VOID *) codePtr;
1657 objPtr->typePtr = &tclByteCodeType;
1658 }
1659
1660 /*
1661 *----------------------------------------------------------------------
1662 *
1663 * LogCompilationInfo --
1664 *
1665 * This procedure is invoked after an error occurs during compilation.
1666 * It adds information to the "errorInfo" variable to describe the
1667 * command that was being compiled when the error occurred.
1668 *
1669 * Results:
1670 * None.
1671 *
1672 * Side effects:
1673 * Information about the command is added to errorInfo and the
1674 * line number stored internally in the interpreter is set. If this
1675 * is the first call to this procedure or Tcl_AddObjErrorInfo since
1676 * an error occurred, then old information in errorInfo is
1677 * deleted.
1678 *
1679 *----------------------------------------------------------------------
1680 */
1681
1682 static void
1683 LogCompilationInfo(interp, script, command, length)
1684 Tcl_Interp *interp; /* Interpreter in which to log the
1685 * information. */
1686 CONST char *script; /* First character in script containing
1687 * command (must be <= command). */
1688 CONST char *command; /* First character in command that
1689 * generated the error. */
1690 int length; /* Number of bytes in command (-1 means
1691 * use all bytes up to first null byte). */
1692 {
1693 char buffer[200];
1694 register CONST char *p;
1695 char *ellipsis = "";
1696 Interp *iPtr = (Interp *) interp;
1697
1698 if (iPtr->flags & ERR_ALREADY_LOGGED) {
1699 /*
1700 * Someone else has already logged error information for this
1701 * command; we shouldn't add anything more.
1702 */
1703
1704 return;
1705 }
1706
1707 /*
1708 * Compute the line number where the error occurred.
1709 */
1710
1711 iPtr->errorLine = 1;
1712 for (p = script; p != command; p++) {
1713 if (*p == '\n') {
1714 iPtr->errorLine++;
1715 }
1716 }
1717
1718 /*
1719 * Create an error message to add to errorInfo, including up to a
1720 * maximum number of characters of the command.
1721 */
1722
1723 if (length < 0) {
1724 length = strlen(command);
1725 }
1726 if (length > 150) {
1727 length = 150;
1728 ellipsis = "...";
1729 }
1730 while ( (command[length] & 0xC0) == 0x80 ) {
1731 /*
1732 * Back up truncation point so that we don't truncate in the
1733 * middle of a multi-byte character (in UTF-8)
1734 */
1735 length--;
1736 ellipsis = "...";
1737 }
1738 sprintf(buffer, "\n while compiling\n\"%.*s%s\"",
1739 length, command, ellipsis);
1740 Tcl_AddObjErrorInfo(interp, buffer, -1);
1741 }
1742
1743 /*
1744 *----------------------------------------------------------------------
1745 *
1746 * TclFindCompiledLocal --
1747 *
1748 * This procedure is called at compile time to look up and optionally
1749 * allocate an entry ("slot") for a variable in a procedure's array of
1750 * local variables. If the variable's name is NULL, a new temporary
1751 * variable is always created. (Such temporary variables can only be
1752 * referenced using their slot index.)
1753 *
1754 * Results:
1755 * If create is 0 and the name is non-NULL, then if the variable is
1756 * found, the index of its entry in the procedure's array of local
1757 * variables is returned; otherwise -1 is returned. If name is NULL,
1758 * the index of a new temporary variable is returned. Finally, if
1759 * create is 1 and name is non-NULL, the index of a new entry is
1760 * returned.
1761 *
1762 * Side effects:
1763 * Creates and registers a new local variable if create is 1 and
1764 * the variable is unknown, or if the name is NULL.
1765 *
1766 *----------------------------------------------------------------------
1767 */
1768
1769 int
1770 TclFindCompiledLocal(name, nameBytes, create, flags, procPtr)
1771 register CONST char *name; /* Points to first character of the name of
1772 * a scalar or array variable. If NULL, a
1773 * temporary var should be created. */
1774 int nameBytes; /* Number of bytes in the name. */
1775 int create; /* If 1, allocate a local frame entry for
1776 * the variable if it is new. */
1777 int flags; /* Flag bits for the compiled local if
1778 * created. Only VAR_SCALAR, VAR_ARRAY, and
1779 * VAR_LINK make sense. */
1780 register Proc *procPtr; /* Points to structure describing procedure
1781 * containing the variable reference. */
1782 {
1783 register CompiledLocal *localPtr;
1784 int localVar = -1;
1785 register int i;
1786
1787 /*
1788 * If not creating a temporary, does a local variable of the specified
1789 * name already exist?
1790 */
1791
1792 if (name != NULL) {
1793 int localCt = procPtr->numCompiledLocals;
1794 localPtr = procPtr->firstLocalPtr;
1795 for (i = 0; i < localCt; i++) {
1796 if (!TclIsVarTemporary(localPtr)) {
1797 char *localName = localPtr->name;
1798 if ((nameBytes == localPtr->nameLength)
1799 && (strncmp(name, localName, (unsigned) nameBytes) == 0)) {
1800 return i;
1801 }
1802 }
1803 localPtr = localPtr->nextPtr;
1804 }
1805 }
1806
1807 /*
1808 * Create a new variable if appropriate.
1809 */
1810
1811 if (create || (name == NULL)) {
1812 localVar = procPtr->numCompiledLocals;
1813 localPtr = (CompiledLocal *) ckalloc((unsigned)
1814 (sizeof(CompiledLocal) - sizeof(localPtr->name)
1815 + nameBytes+1));
1816 if (procPtr->firstLocalPtr == NULL) {
1817 procPtr->firstLocalPtr = procPtr->lastLocalPtr = localPtr;
1818 } else {
1819 procPtr->lastLocalPtr->nextPtr = localPtr;
1820 procPtr->lastLocalPtr = localPtr;
1821 }
1822 localPtr->nextPtr = NULL;
1823 localPtr->nameLength = nameBytes;
1824 localPtr->frameIndex = localVar;
1825 localPtr->flags = flags | VAR_UNDEFINED;
1826 if (name == NULL) {
1827 localPtr->flags |= VAR_TEMPORARY;
1828 }
1829 localPtr->defValuePtr = NULL;
1830 localPtr->resolveInfo = NULL;
1831
1832 if (name != NULL) {
1833 memcpy((VOID *) localPtr->name, (VOID *) name,
1834 (size_t) nameBytes);
1835 }
1836 localPtr->name[nameBytes] = '\0';
1837 procPtr->numCompiledLocals++;
1838 }
1839 return localVar;
1840 }
1841
1842 /*
1843 *----------------------------------------------------------------------
1844 *
1845 * TclInitCompiledLocals --
1846 *
1847 * This routine is invoked in order to initialize the compiled
1848 * locals table for a new call frame.
1849 *
1850 * Results:
1851 * None.
1852 *
1853 * Side effects:
1854 * May invoke various name resolvers in order to determine which
1855 * variables are being referenced at runtime.
1856 *
1857 *----------------------------------------------------------------------
1858 */
1859
1860 void
1861 TclInitCompiledLocals(interp, framePtr, nsPtr)
1862 Tcl_Interp *interp; /* Current interpreter. */
1863 CallFrame *framePtr; /* Call frame to initialize. */
1864 Namespace *nsPtr; /* Pointer to current namespace. */
1865 {
1866 register CompiledLocal *localPtr;
1867 Interp *iPtr = (Interp*) interp;
1868 Tcl_ResolvedVarInfo *vinfo, *resVarInfo;
1869 Var *varPtr = framePtr->compiledLocals;
1870 Var *resolvedVarPtr;
1871 ResolverScheme *resPtr;
1872 int result;
1873
1874 /*
1875 * Initialize the array of local variables stored in the call frame.
1876 * Some variables may have special resolution rules. In that case,
1877 * we call their "resolver" procs to get our hands on the variable,
1878 * and we make the compiled local a link to the real variable.
1879 */
1880
1881 for (localPtr = framePtr->procPtr->firstLocalPtr;
1882 localPtr != NULL;
1883 localPtr = localPtr->nextPtr) {
1884
1885 /*
1886 * Check to see if this local is affected by namespace or
1887 * interp resolvers. The resolver to use is cached for the
1888 * next invocation of the procedure.
1889 */
1890
1891 if (!(localPtr->flags & (VAR_ARGUMENT|VAR_TEMPORARY|VAR_RESOLVED))
1892 && (nsPtr->compiledVarResProc || iPtr->resolverPtr)) {
1893 resPtr = iPtr->resolverPtr;
1894
1895 if (nsPtr->compiledVarResProc) {
1896 result = (*nsPtr->compiledVarResProc)(nsPtr->interp,
1897 localPtr->name, localPtr->nameLength,
1898 (Tcl_Namespace *) nsPtr, &vinfo);
1899 } else {
1900 result = TCL_CONTINUE;
1901 }
1902
1903 while ((result == TCL_CONTINUE) && resPtr) {
1904 if (resPtr->compiledVarResProc) {
1905 result = (*resPtr->compiledVarResProc)(nsPtr->interp,
1906 localPtr->name, localPtr->nameLength,
1907 (Tcl_Namespace *) nsPtr, &vinfo);
1908 }
1909 resPtr = resPtr->nextPtr;
1910 }
1911 if (result == TCL_OK) {
1912 localPtr->resolveInfo = vinfo;
1913 localPtr->flags |= VAR_RESOLVED;
1914 }
1915 }
1916
1917 /*
1918 * Now invoke the resolvers to determine the exact variables that
1919 * should be used.
1920 */
1921
1922 resVarInfo = localPtr->resolveInfo;
1923 resolvedVarPtr = NULL;
1924
1925 if (resVarInfo && resVarInfo->fetchProc) {
1926 resolvedVarPtr = (Var*) (*resVarInfo->fetchProc)(interp,
1927 resVarInfo);
1928 }
1929
1930 if (resolvedVarPtr) {
1931 varPtr->name = localPtr->name; /* will be just '\0' if temp var */
1932 varPtr->nsPtr = NULL;
1933 varPtr->hPtr = NULL;
1934 varPtr->refCount = 0;
1935 varPtr->tracePtr = NULL;
1936 varPtr->searchPtr = NULL;
1937 varPtr->flags = 0;
1938 TclSetVarLink(varPtr);
1939 varPtr->value.linkPtr = resolvedVarPtr;
1940 resolvedVarPtr->refCount++;
1941 } else {
1942 varPtr->value.objPtr = NULL;
1943 varPtr->name = localPtr->name; /* will be just '\0' if temp var */
1944 varPtr->nsPtr = NULL;
1945 varPtr->hPtr = NULL;
1946 varPtr->refCount = 0;
1947 varPtr->tracePtr = NULL;
1948 varPtr->searchPtr = NULL;
1949 varPtr->flags = localPtr->flags;
1950 }
1951 varPtr++;
1952 }
1953 }
1954
1955 /*
1956 *----------------------------------------------------------------------
1957 *
1958 * TclExpandCodeArray --
1959 *
1960 * Procedure that uses malloc to allocate more storage for a
1961 * CompileEnv's code array.
1962 *
1963 * Results:
1964 * None.
1965 *
1966 * Side effects:
1967 * The byte code array in *envPtr is reallocated to a new array of
1968 * double the size, and if envPtr->mallocedCodeArray is non-zero the
1969 * old array is freed. Byte codes are copied from the old array to the
1970 * new one.
1971 *
1972 *----------------------------------------------------------------------
1973 */
1974
1975 void
1976 TclExpandCodeArray(envArgPtr)
1977 void *envArgPtr; /* Points to the CompileEnv whose code array
1978 * must be enlarged. */
1979 {
1980 CompileEnv *envPtr = (CompileEnv*) envArgPtr; /* Points to the CompileEnv whose code array
1981 * must be enlarged. */
1982
1983 /*
1984 * envPtr->codeNext is equal to envPtr->codeEnd. The currently defined
1985 * code bytes are stored between envPtr->codeStart and
1986 * (envPtr->codeNext - 1) [inclusive].
1987 */
1988
1989 size_t currBytes = (envPtr->codeNext - envPtr->codeStart);
1990 size_t newBytes = 2*(envPtr->codeEnd - envPtr->codeStart);
1991 unsigned char *newPtr = (unsigned char *) ckalloc((unsigned) newBytes);
1992
1993 /*
1994 * Copy from old code array to new, free old code array if needed, and
1995 * mark new code array as malloced.
1996 */
1997
1998 memcpy((VOID *) newPtr, (VOID *) envPtr->codeStart, currBytes);
1999 if (envPtr->mallocedCodeArray) {
2000 ckfree((char *) envPtr->codeStart);
2001 }
2002 envPtr->codeStart = newPtr;
2003 envPtr->codeNext = (newPtr + currBytes);
2004 envPtr->codeEnd = (newPtr + newBytes);
2005 envPtr->mallocedCodeArray = 1;
2006 }
2007
2008 /*
2009 *----------------------------------------------------------------------
2010 *
2011 * EnterCmdStartData --
2012 *
2013 * Registers the starting source and bytecode location of a
2014 * command. This information is used at runtime to map between
2015 * instruction pc and source locations.
2016 *
2017 * Results:
2018 * None.
2019 *
2020 * Side effects:
2021 * Inserts source and code location information into the compilation
2022 * environment envPtr for the command at index cmdIndex. The
2023 * compilation environment's CmdLocation array is grown if necessary.
2024 *
2025 *----------------------------------------------------------------------
2026 */
2027
2028 static void
2029 EnterCmdStartData(envPtr, cmdIndex, srcOffset, codeOffset)
2030 CompileEnv *envPtr; /* Points to the compilation environment
2031 * structure in which to enter command
2032 * location information. */
2033 int cmdIndex; /* Index of the command whose start data
2034 * is being set. */
2035 int srcOffset; /* Offset of first char of the command. */
2036 int codeOffset; /* Offset of first byte of command code. */
2037 {
2038 CmdLocation *cmdLocPtr;
2039
2040 if ((cmdIndex < 0) || (cmdIndex >= envPtr->numCommands)) {
2041 panic("EnterCmdStartData: bad command index %d\n", cmdIndex);
2042 }
2043
2044 if (cmdIndex >= envPtr->cmdMapEnd) {
2045 /*
2046 * Expand the command location array by allocating more storage from
2047 * the heap. The currently allocated CmdLocation entries are stored
2048 * from cmdMapPtr[0] up to cmdMapPtr[envPtr->cmdMapEnd] (inclusive).
2049 */
2050
2051 size_t currElems = envPtr->cmdMapEnd;
2052 size_t newElems = 2*currElems;
2053 size_t currBytes = currElems * sizeof(CmdLocation);
2054 size_t newBytes = newElems * sizeof(CmdLocation);
2055 CmdLocation *newPtr = (CmdLocation *) ckalloc((unsigned) newBytes);
2056
2057 /*
2058 * Copy from old command location array to new, free old command
2059 * location array if needed, and mark new array as malloced.
2060 */
2061
2062 memcpy((VOID *) newPtr, (VOID *) envPtr->cmdMapPtr, currBytes);
2063 if (envPtr->mallocedCmdMap) {
2064 ckfree((char *) envPtr->cmdMapPtr);
2065 }
2066 envPtr->cmdMapPtr = (CmdLocation *) newPtr;
2067 envPtr->cmdMapEnd = newElems;
2068 envPtr->mallocedCmdMap = 1;
2069 }
2070
2071 if (cmdIndex > 0) {
2072 if (codeOffset < envPtr->cmdMapPtr[cmdIndex-1].codeOffset) {
2073 panic("EnterCmdStartData: cmd map not sorted by code offset");
2074 }
2075 }
2076
2077 cmdLocPtr = &(envPtr->cmdMapPtr[cmdIndex]);
2078 cmdLocPtr->codeOffset = codeOffset;
2079 cmdLocPtr->srcOffset = srcOffset;
2080 cmdLocPtr->numSrcBytes = -1;
2081 cmdLocPtr->numCodeBytes = -1;
2082 }
2083
2084 /*
2085 *----------------------------------------------------------------------
2086 *
2087 * EnterCmdExtentData --
2088 *
2089 * Registers the source and bytecode length for a command. This
2090 * information is used at runtime to map between instruction pc and
2091 * source locations.
2092 *
2093 * Results:
2094 * None.
2095 *
2096 * Side effects:
2097 * Inserts source and code length information into the compilation
2098 * environment envPtr for the command at index cmdIndex. Starting
2099 * source and bytecode information for the command must already
2100 * have been registered.
2101 *
2102 *----------------------------------------------------------------------
2103 */
2104
2105 static void
2106 EnterCmdExtentData(envPtr, cmdIndex, numSrcBytes, numCodeBytes)
2107 CompileEnv *envPtr; /* Points to the compilation environment
2108 * structure in which to enter command
2109 * location information. */
2110 int cmdIndex; /* Index of the command whose source and
2111 * code length data is being set. */
2112 int numSrcBytes; /* Number of command source chars. */
2113 int numCodeBytes; /* Offset of last byte of command code. */
2114 {
2115 CmdLocation *cmdLocPtr;
2116
2117 if ((cmdIndex < 0) || (cmdIndex >= envPtr->numCommands)) {
2118 panic("EnterCmdExtentData: bad command index %d\n", cmdIndex);
2119 }
2120
2121 if (cmdIndex > envPtr->cmdMapEnd) {
2122 panic("EnterCmdExtentData: missing start data for command %d\n",
2123 cmdIndex);
2124 }
2125
2126 cmdLocPtr = &(envPtr->cmdMapPtr[cmdIndex]);
2127 cmdLocPtr->numSrcBytes = numSrcBytes;
2128 cmdLocPtr->numCodeBytes = numCodeBytes;
2129 }
2130
2131 /*
2132 *----------------------------------------------------------------------
2133 *
2134 * TclCreateExceptRange --
2135 *
2136 * Procedure that allocates and initializes a new ExceptionRange
2137 * structure of the specified kind in a CompileEnv.
2138 *
2139 * Results:
2140 * Returns the index for the newly created ExceptionRange.
2141 *
2142 * Side effects:
2143 * If there is not enough room in the CompileEnv's ExceptionRange
2144 * array, the array in expanded: a new array of double the size is
2145 * allocated, if envPtr->mallocedExceptArray is non-zero the old
2146 * array is freed, and ExceptionRange entries are copied from the old
2147 * array to the new one.
2148 *
2149 *----------------------------------------------------------------------
2150 */
2151
2152 int
2153 TclCreateExceptRange(type, envPtr)
2154 ExceptionRangeType type; /* The kind of ExceptionRange desired. */
2155 register CompileEnv *envPtr;/* Points to CompileEnv for which to
2156 * create a new ExceptionRange structure. */
2157 {
2158 register ExceptionRange *rangePtr;
2159 int index = envPtr->exceptArrayNext;
2160
2161 if (index >= envPtr->exceptArrayEnd) {
2162 /*
2163 * Expand the ExceptionRange array. The currently allocated entries
2164 * are stored between elements 0 and (envPtr->exceptArrayNext - 1)
2165 * [inclusive].
2166 */
2167
2168 size_t currBytes =
2169 envPtr->exceptArrayNext * sizeof(ExceptionRange);
2170 int newElems = 2*envPtr->exceptArrayEnd;
2171 size_t newBytes = newElems * sizeof(ExceptionRange);
2172 ExceptionRange *newPtr = (ExceptionRange *)
2173 ckalloc((unsigned) newBytes);
2174
2175 /*
2176 * Copy from old ExceptionRange array to new, free old
2177 * ExceptionRange array if needed, and mark the new ExceptionRange
2178 * array as malloced.
2179 */
2180
2181 memcpy((VOID *) newPtr, (VOID *) envPtr->exceptArrayPtr,
2182 currBytes);
2183 if (envPtr->mallocedExceptArray) {
2184 ckfree((char *) envPtr->exceptArrayPtr);
2185 }
2186 envPtr->exceptArrayPtr = (ExceptionRange *) newPtr;
2187 envPtr->exceptArrayEnd = newElems;
2188 envPtr->mallocedExceptArray = 1;
2189 }
2190 envPtr->exceptArrayNext++;
2191
2192 rangePtr = &(envPtr->exceptArrayPtr[index]);
2193 rangePtr->type = type;
2194 rangePtr->nestingLevel = envPtr->exceptDepth;
2195 rangePtr->codeOffset = -1;
2196 rangePtr->numCodeBytes = -1;
2197 rangePtr->breakOffset = -1;
2198 rangePtr->continueOffset = -1;
2199 rangePtr->catchOffset = -1;
2200 return index;
2201 }
2202
2203 /*
2204 *----------------------------------------------------------------------
2205 *
2206 * TclCreateAuxData --
2207 *
2208 * Procedure that allocates and initializes a new AuxData structure in
2209 * a CompileEnv's array of compilation auxiliary data records. These
2210 * AuxData records hold information created during compilation by
2211 * CompileProcs and used by instructions during execution.
2212 *
2213 * Results:
2214 * Returns the index for the newly created AuxData structure.
2215 *
2216 * Side effects:
2217 * If there is not enough room in the CompileEnv's AuxData array,
2218 * the AuxData array in expanded: a new array of double the size
2219 * is allocated, if envPtr->mallocedAuxDataArray is non-zero
2220 * the old array is freed, and AuxData entries are copied from
2221 * the old array to the new one.
2222 *
2223 *----------------------------------------------------------------------
2224 */
2225
2226 int
2227 TclCreateAuxData(clientData, typePtr, envPtr)
2228 ClientData clientData; /* The compilation auxiliary data to store
2229 * in the new aux data record. */
2230 AuxDataType *typePtr; /* Pointer to the type to attach to this AuxData */
2231 register CompileEnv *envPtr;/* Points to the CompileEnv for which a new
2232 * aux data structure is to be allocated. */
2233 {
2234 int index; /* Index for the new AuxData structure. */
2235 register AuxData *auxDataPtr;
2236 /* Points to the new AuxData structure */
2237
2238 index = envPtr->auxDataArrayNext;
2239 if (index >= envPtr->auxDataArrayEnd) {
2240 /*
2241 * Expand the AuxData array. The currently allocated entries are
2242 * stored between elements 0 and (envPtr->auxDataArrayNext - 1)
2243 * [inclusive].
2244 */
2245
2246 size_t currBytes = envPtr->auxDataArrayNext * sizeof(AuxData);
2247 int newElems = 2*envPtr->auxDataArrayEnd;
2248 size_t newBytes = newElems * sizeof(AuxData);
2249 AuxData *newPtr = (AuxData *) ckalloc((unsigned) newBytes);
2250
2251 /*
2252 * Copy from old AuxData array to new, free old AuxData array if
2253 * needed, and mark the new AuxData array as malloced.
2254 */
2255
2256 memcpy((VOID *) newPtr, (VOID *) envPtr->auxDataArrayPtr,
2257 currBytes);
2258 if (envPtr->mallocedAuxDataArray) {
2259 ckfree((char *) envPtr->auxDataArrayPtr);
2260 }
2261 envPtr->auxDataArrayPtr = newPtr;
2262 envPtr->auxDataArrayEnd = newElems;
2263 envPtr->mallocedAuxDataArray = 1;
2264 }
2265 envPtr->auxDataArrayNext++;
2266
2267 auxDataPtr = &(envPtr->auxDataArrayPtr[index]);
2268 auxDataPtr->clientData = clientData;
2269 auxDataPtr->type = typePtr;
2270 return index;
2271 }
2272
2273 /*
2274 *----------------------------------------------------------------------
2275 *
2276 * TclInitJumpFixupArray --
2277 *
2278 * Initializes a JumpFixupArray structure to hold some number of
2279 * jump fixup entries.
2280 *
2281 * Results:
2282 * None.
2283 *
2284 * Side effects:
2285 * The JumpFixupArray structure is initialized.
2286 *
2287 *----------------------------------------------------------------------
2288 */
2289
2290 void
2291 TclInitJumpFixupArray(fixupArrayPtr)
2292 register JumpFixupArray *fixupArrayPtr;
2293 /* Points to the JumpFixupArray structure
2294 * to initialize. */
2295 {
2296 fixupArrayPtr->fixup = fixupArrayPtr->staticFixupSpace;
2297 fixupArrayPtr->next = 0;
2298 fixupArrayPtr->end = (JUMPFIXUP_INIT_ENTRIES - 1);
2299 fixupArrayPtr->mallocedArray = 0;
2300 }
2301
2302 /*
2303 *----------------------------------------------------------------------
2304 *
2305 * TclExpandJumpFixupArray --
2306 *
2307 * Procedure that uses malloc to allocate more storage for a
2308 * jump fixup array.
2309 *
2310 * Results:
2311 * None.
2312 *
2313 * Side effects:
2314 * The jump fixup array in *fixupArrayPtr is reallocated to a new array
2315 * of double the size, and if fixupArrayPtr->mallocedArray is non-zero
2316 * the old array is freed. Jump fixup structures are copied from the
2317 * old array to the new one.
2318 *
2319 *----------------------------------------------------------------------
2320 */
2321
2322 void
2323 TclExpandJumpFixupArray(fixupArrayPtr)
2324 register JumpFixupArray *fixupArrayPtr;
2325 /* Points to the JumpFixupArray structure
2326 * to enlarge. */
2327 {
2328 /*
2329 * The currently allocated jump fixup entries are stored from fixup[0]
2330 * up to fixup[fixupArrayPtr->fixupNext] (*not* inclusive). We assume
2331 * fixupArrayPtr->fixupNext is equal to fixupArrayPtr->fixupEnd.
2332 */
2333
2334 size_t currBytes = fixupArrayPtr->next * sizeof(JumpFixup);
2335 int newElems = 2*(fixupArrayPtr->end + 1);
2336 size_t newBytes = newElems * sizeof(JumpFixup);
2337 JumpFixup *newPtr = (JumpFixup *) ckalloc((unsigned) newBytes);
2338
2339 /*
2340 * Copy from the old array to new, free the old array if needed,
2341 * and mark the new array as malloced.
2342 */
2343
2344 memcpy((VOID *) newPtr, (VOID *) fixupArrayPtr->fixup, currBytes);
2345 if (fixupArrayPtr->mallocedArray) {
2346 ckfree((char *) fixupArrayPtr->fixup);
2347 }
2348 fixupArrayPtr->fixup = (JumpFixup *) newPtr;
2349 fixupArrayPtr->end = newElems;
2350 fixupArrayPtr->mallocedArray = 1;
2351 }
2352
2353 /*
2354 *----------------------------------------------------------------------
2355 *
2356 * TclFreeJumpFixupArray --
2357 *
2358 * Free any storage allocated in a jump fixup array structure.
2359 *
2360 * Results:
2361 * None.
2362 *
2363 * Side effects:
2364 * Allocated storage in the JumpFixupArray structure is freed.
2365 *
2366 *----------------------------------------------------------------------
2367 */
2368
2369 void
2370 TclFreeJumpFixupArray(fixupArrayPtr)
2371 register JumpFixupArray *fixupArrayPtr;
2372 /* Points to the JumpFixupArray structure
2373 * to free. */
2374 {
2375 if (fixupArrayPtr->mallocedArray) {
2376 ckfree((char *) fixupArrayPtr->fixup);
2377 }
2378 }
2379
2380 /*
2381 *----------------------------------------------------------------------
2382 *
2383 * TclEmitForwardJump --
2384 *
2385 * Procedure to emit a two-byte forward jump of kind "jumpType". Since
2386 * the jump may later have to be grown to five bytes if the jump target
2387 * is more than, say, 127 bytes away, this procedure also initializes a
2388 * JumpFixup record with information about the jump.
2389 *
2390 * Results:
2391 * None.
2392 *
2393 * Side effects:
2394 * The JumpFixup record pointed to by "jumpFixupPtr" is initialized
2395 * with information needed later if the jump is to be grown. Also,
2396 * a two byte jump of the designated type is emitted at the current
2397 * point in the bytecode stream.
2398 *
2399 *----------------------------------------------------------------------
2400 */
2401
2402 void
2403 TclEmitForwardJump(envPtr, jumpType, jumpFixupPtr)
2404 CompileEnv *envPtr; /* Points to the CompileEnv structure that
2405 * holds the resulting instruction. */
2406 TclJumpType jumpType; /* Indicates the kind of jump: if true or
2407 * false or unconditional. */
2408 JumpFixup *jumpFixupPtr; /* Points to the JumpFixup structure to
2409 * initialize with information about this
2410 * forward jump. */
2411 {
2412 /*
2413 * Initialize the JumpFixup structure:
2414 * - codeOffset is offset of first byte of jump below
2415 * - cmdIndex is index of the command after the current one
2416 * - exceptIndex is the index of the first ExceptionRange after
2417 * the current one.
2418 */
2419
2420 jumpFixupPtr->jumpType = jumpType;
2421 jumpFixupPtr->codeOffset = (envPtr->codeNext - envPtr->codeStart);
2422 jumpFixupPtr->cmdIndex = envPtr->numCommands;
2423 jumpFixupPtr->exceptIndex = envPtr->exceptArrayNext;
2424
2425 switch (jumpType) {
2426 case TCL_UNCONDITIONAL_JUMP:
2427 TclEmitInstInt1(INST_JUMP1, 0, envPtr);
2428 break;
2429 case TCL_TRUE_JUMP:
2430 TclEmitInstInt1(INST_JUMP_TRUE1, 0, envPtr);
2431 break;
2432 default:
2433 TclEmitInstInt1(INST_JUMP_FALSE1, 0, envPtr);
2434 break;
2435 }
2436 }
2437
2438 /*
2439 *----------------------------------------------------------------------
2440 *
2441 * TclFixupForwardJump --
2442 *
2443 * Procedure that updates a previously-emitted forward jump to jump
2444 * a specified number of bytes, "jumpDist". If necessary, the jump is
2445 * grown from two to five bytes; this is done if the jump distance is
2446 * greater than "distThreshold" (normally 127 bytes). The jump is
2447 * described by a JumpFixup record previously initialized by
2448 * TclEmitForwardJump.
2449 *
2450 * Results:
2451 * 1 if the jump was grown and subsequent instructions had to be moved;
2452 * otherwise 0. This result is returned to allow callers to update
2453 * any additional code offsets they may hold.
2454 *
2455 * Side effects:
2456 * The jump may be grown and subsequent instructions moved. If this
2457 * happens, the code offsets for any commands and any ExceptionRange
2458 * records between the jump and the current code address will be
2459 * updated to reflect the moved code. Also, the bytecode instruction
2460 * array in the CompileEnv structure may be grown and reallocated.
2461 *
2462 *----------------------------------------------------------------------
2463 */
2464
2465 int
2466 TclFixupForwardJump(envPtr, jumpFixupPtr, jumpDist, distThreshold)
2467 CompileEnv *envPtr; /* Points to the CompileEnv structure that
2468 * holds the resulting instruction. */
2469 JumpFixup *jumpFixupPtr; /* Points to the JumpFixup structure that
2470 * describes the forward jump. */
2471 int jumpDist; /* Jump distance to set in jump
2472 * instruction. */
2473 int distThreshold; /* Maximum distance before the two byte
2474 * jump is grown to five bytes. */
2475 {
2476 unsigned char *jumpPc, *p;
2477 int firstCmd, lastCmd, firstRange, lastRange, k;
2478 unsigned int numBytes;
2479
2480 if (jumpDist <= distThreshold) {
2481 jumpPc = (envPtr->codeStart + jumpFixupPtr->codeOffset);
2482 switch (jumpFixupPtr->jumpType) {
2483 case TCL_UNCONDITIONAL_JUMP:
2484 TclUpdateInstInt1AtPc(INST_JUMP1, jumpDist, jumpPc);
2485 break;
2486 case TCL_TRUE_JUMP:
2487 TclUpdateInstInt1AtPc(INST_JUMP_TRUE1, jumpDist, jumpPc);
2488 break;
2489 default:
2490 TclUpdateInstInt1AtPc(INST_JUMP_FALSE1, jumpDist, jumpPc);
2491 break;
2492 }
2493 return 0;
2494 }
2495
2496 /*
2497 * We must grow the jump then move subsequent instructions down.
2498 * Note that if we expand the space for generated instructions,
2499 * code addresses might change; be careful about updating any of
2500 * these addresses held in variables.
2501 */
2502
2503 if ((envPtr->codeNext + 3) > envPtr->codeEnd) {
2504 TclExpandCodeArray(envPtr);
2505 }
2506 jumpPc = (envPtr->codeStart + jumpFixupPtr->codeOffset);
2507 for (numBytes = envPtr->codeNext-jumpPc-2, p = jumpPc+2+numBytes-1;
2508 numBytes > 0; numBytes--, p--) {
2509 p[3] = p[0];
2510 }
2511 envPtr->codeNext += 3;
2512 jumpDist += 3;
2513 switch (jumpFixupPtr->jumpType) {
2514 case TCL_UNCONDITIONAL_JUMP:
2515 TclUpdateInstInt4AtPc(INST_JUMP4, jumpDist, jumpPc);
2516 break;
2517 case TCL_TRUE_JUMP:
2518 TclUpdateInstInt4AtPc(INST_JUMP_TRUE4, jumpDist, jumpPc);
2519 break;
2520 default:
2521 TclUpdateInstInt4AtPc(INST_JUMP_FALSE4, jumpDist, jumpPc);
2522 break;
2523 }
2524
2525 /*
2526 * Adjust the code offsets for any commands and any ExceptionRange
2527 * records between the jump and the current code address.
2528 */
2529
2530 firstCmd = jumpFixupPtr->cmdIndex;
2531 lastCmd = (envPtr->numCommands - 1);
2532 if (firstCmd < lastCmd) {
2533 for (k = firstCmd; k <= lastCmd; k++) {
2534 (envPtr->cmdMapPtr[k]).codeOffset += 3;
2535 }
2536 }
2537
2538 firstRange = jumpFixupPtr->exceptIndex;
2539 lastRange = (envPtr->exceptArrayNext - 1);
2540 for (k = firstRange; k <= lastRange; k++) {
2541 ExceptionRange *rangePtr = &(envPtr->exceptArrayPtr[k]);
2542 rangePtr->codeOffset += 3;
2543
2544 switch (rangePtr->type) {
2545 case LOOP_EXCEPTION_RANGE:
2546 rangePtr->breakOffset += 3;
2547 if (rangePtr->continueOffset != -1) {
2548 rangePtr->continueOffset += 3;
2549 }
2550 break;
2551 case CATCH_EXCEPTION_RANGE:
2552 rangePtr->catchOffset += 3;
2553 break;
2554 default:
2555 panic("TclFixupForwardJump: bad ExceptionRange type %d\n",
2556 rangePtr->type);
2557 }
2558 }
2559 return 1; /* the jump was grown */
2560 }
2561
2562 /*
2563 *----------------------------------------------------------------------
2564 *
2565 * TclGetInstructionTable --
2566 *
2567 * Returns a pointer to the table describing Tcl bytecode instructions.
2568 * This procedure is defined so that clients can access the pointer from
2569 * outside the TCL DLLs.
2570 *
2571 * Results:
2572 * Returns a pointer to the global instruction table, same as the
2573 * expression (&tclInstructionTable[0]).
2574 *
2575 * Side effects:
2576 * None.
2577 *
2578 *----------------------------------------------------------------------
2579 */
2580
2581 void * /* == InstructionDesc* == */
2582 TclGetInstructionTable()
2583 {
2584 return &tclInstructionTable[0];
2585 }
2586
2587 /*
2588 *--------------------------------------------------------------
2589 *
2590 * TclRegisterAuxDataType --
2591 *
2592 * This procedure is called to register a new AuxData type
2593 * in the table of all AuxData types supported by Tcl.
2594 *
2595 * Results:
2596 * None.
2597 *
2598 * Side effects:
2599 * The type is registered in the AuxData type table. If there was already
2600 * a type with the same name as in typePtr, it is replaced with the
2601 * new type.
2602 *
2603 *--------------------------------------------------------------
2604 */
2605
2606 void
2607 TclRegisterAuxDataType(typePtr)
2608 AuxDataType *typePtr; /* Information about object type;
2609 * storage must be statically
2610 * allocated (must live forever). */
2611 {
2612 register Tcl_HashEntry *hPtr;
2613 int new;
2614
2615 Tcl_MutexLock(&tableMutex);
2616 if (!auxDataTypeTableInitialized) {
2617 TclInitAuxDataTypeTable();
2618 }
2619
2620 /*
2621 * If there's already a type with the given name, remove it.
2622 */
2623
2624 hPtr = Tcl_FindHashEntry(&auxDataTypeTable, typePtr->name);
2625 if (hPtr != (Tcl_HashEntry *) NULL) {
2626 Tcl_DeleteHashEntry(hPtr);
2627 }
2628
2629 /*
2630 * Now insert the new object type.
2631 */
2632
2633 hPtr = Tcl_CreateHashEntry(&auxDataTypeTable, typePtr->name, &new);
2634 if (new) {
2635 Tcl_SetHashValue(hPtr, typePtr);
2636 }
2637 Tcl_MutexUnlock(&tableMutex);
2638 }
2639
2640 /*
2641 *----------------------------------------------------------------------
2642 *
2643 * TclGetAuxDataType --
2644 *
2645 * This procedure looks up an Auxdata type by name.
2646 *
2647 * Results:
2648 * If an AuxData type with name matching "typeName" is found, a pointer
2649 * to its AuxDataType structure is returned; otherwise, NULL is returned.
2650 *
2651 * Side effects:
2652 * None.
2653 *
2654 *----------------------------------------------------------------------
2655 */
2656
2657 AuxDataType *
2658 TclGetAuxDataType(typeName)
2659 char *typeName; /* Name of AuxData type to look up. */
2660 {
2661 register Tcl_HashEntry *hPtr;
2662 AuxDataType *typePtr = NULL;
2663
2664 Tcl_MutexLock(&tableMutex);
2665 if (!auxDataTypeTableInitialized) {
2666 TclInitAuxDataTypeTable();
2667 }
2668
2669 hPtr = Tcl_FindHashEntry(&auxDataTypeTable, typeName);
2670 if (hPtr != (Tcl_HashEntry *) NULL) {
2671 typePtr = (AuxDataType *) Tcl_GetHashValue(hPtr);
2672 }
2673 Tcl_MutexUnlock(&tableMutex);
2674
2675 return typePtr;
2676 }
2677
2678 /*
2679 *--------------------------------------------------------------
2680 *
2681 * TclInitAuxDataTypeTable --
2682 *
2683 * This procedure is invoked to perform once-only initialization of
2684 * the AuxData type table. It also registers the AuxData types defined in
2685 * this file.
2686 *
2687 * Results:
2688 * None.
2689 *
2690 * Side effects:
2691 * Initializes the table of defined AuxData types "auxDataTypeTable" with
2692 * builtin AuxData types defined in this file.
2693 *
2694 *--------------------------------------------------------------
2695 */
2696
2697 void
2698 TclInitAuxDataTypeTable()
2699 {
2700 /*
2701 * The table mutex must already be held before this routine is invoked.
2702 */
2703
2704 auxDataTypeTableInitialized = 1;
2705 Tcl_InitHashTable(&auxDataTypeTable, TCL_STRING_KEYS);
2706
2707 /*
2708 * There is only one AuxData type at this time, so register it here.
2709 */
2710
2711 TclRegisterAuxDataType(&tclForeachInfoType);
2712 }
2713
2714 /*
2715 *----------------------------------------------------------------------
2716 *
2717 * TclFinalizeAuxDataTypeTable --
2718 *
2719 * This procedure is called by Tcl_Finalize after all exit handlers
2720 * have been run to free up storage associated with the table of AuxData
2721 * types. This procedure is called by TclFinalizeExecution() which
2722 * is called by Tcl_Finalize().
2723 *
2724 * Results:
2725 * None.
2726 *
2727 * Side effects:
2728 * Deletes all entries in the hash table of AuxData types.
2729 *
2730 *----------------------------------------------------------------------
2731 */
2732
2733 void
2734 TclFinalizeAuxDataTypeTable()
2735 {
2736 Tcl_MutexLock(&tableMutex);
2737 if (auxDataTypeTableInitialized) {
2738 Tcl_DeleteHashTable(&auxDataTypeTable);
2739 auxDataTypeTableInitialized = 0;
2740 }
2741 Tcl_MutexUnlock(&tableMutex);
2742 }
2743
2744 /*
2745 *----------------------------------------------------------------------
2746 *
2747 * GetCmdLocEncodingSize --
2748 *
2749 * Computes the total number of bytes needed to encode the command
2750 * location information for some compiled code.
2751 *
2752 * Results:
2753 * The byte count needed to encode the compiled location information.
2754 *
2755 * Side effects:
2756 * None.
2757 *
2758 *----------------------------------------------------------------------
2759 */
2760
2761 static int
2762 GetCmdLocEncodingSize(envPtr)
2763 CompileEnv *envPtr; /* Points to compilation environment
2764 * structure containing the CmdLocation
2765 * structure to encode. */
2766 {
2767 register CmdLocation *mapPtr = envPtr->cmdMapPtr;
2768 int numCmds = envPtr->numCommands;
2769 int codeDelta, codeLen, srcDelta, srcLen;
2770 int codeDeltaNext, codeLengthNext, srcDeltaNext, srcLengthNext;
2771 /* The offsets in their respective byte
2772 * sequences where the next encoded offset
2773 * or length should go. */
2774 int prevCodeOffset, prevSrcOffset, i;
2775
2776 codeDeltaNext = codeLengthNext = srcDeltaNext = srcLengthNext = 0;
2777 prevCodeOffset = prevSrcOffset = 0;
2778 for (i = 0; i < numCmds; i++) {
2779 codeDelta = (mapPtr[i].codeOffset - prevCodeOffset);
2780 if (codeDelta < 0) {
2781 panic("GetCmdLocEncodingSize: bad code offset");
2782 } else if (codeDelta <= 127) {
2783 codeDeltaNext++;
2784 } else {
2785 codeDeltaNext += 5; /* 1 byte for 0xFF, 4 for positive delta */
2786 }
2787 prevCodeOffset = mapPtr[i].codeOffset;
2788
2789 codeLen = mapPtr[i].numCodeBytes;
2790 if (codeLen < 0) {
2791 panic("GetCmdLocEncodingSize: bad code length");
2792 } else if (codeLen <= 127) {
2793 codeLengthNext++;
2794 } else {
2795 codeLengthNext += 5; /* 1 byte for 0xFF, 4 for length */
2796 }
2797
2798 srcDelta = (mapPtr[i].srcOffset - prevSrcOffset);
2799 if ((-127 <= srcDelta) && (srcDelta <= 127)) {
2800 srcDeltaNext++;
2801 } else {
2802 srcDeltaNext += 5; /* 1 byte for 0xFF, 4 for delta */
2803 }
2804 prevSrcOffset = mapPtr[i].srcOffset;
2805
2806 srcLen = mapPtr[i].numSrcBytes;
2807 if (srcLen < 0) {
2808 panic("GetCmdLocEncodingSize: bad source length");
2809 } else if (srcLen <= 127) {
2810 srcLengthNext++;
2811 } else {
2812 srcLengthNext += 5; /* 1 byte for 0xFF, 4 for length */
2813 }
2814 }
2815
2816 return (codeDeltaNext + codeLengthNext + srcDeltaNext + srcLengthNext);
2817 }
2818
2819 /*
2820 *----------------------------------------------------------------------
2821 *
2822 * EncodeCmdLocMap --
2823 *
2824 * Encode the command location information for some compiled code into
2825 * a ByteCode structure. The encoded command location map is stored as
2826 * three adjacent byte sequences.
2827 *
2828 * Results:
2829 * Pointer to the first byte after the encoded command location
2830 * information.
2831 *
2832 * Side effects:
2833 * The encoded information is stored into the block of memory headed
2834 * by codePtr. Also records pointers to the start of the four byte
2835 * sequences in fields in codePtr's ByteCode header structure.
2836 *
2837 *----------------------------------------------------------------------
2838 */
2839
2840 static unsigned char *
2841 EncodeCmdLocMap(envPtr, codePtr, startPtr)
2842 CompileEnv *envPtr; /* Points to compilation environment
2843 * structure containing the CmdLocation
2844 * structure to encode. */
2845 ByteCode *codePtr; /* ByteCode in which to encode envPtr's
2846 * command location information. */
2847 unsigned char *startPtr; /* Points to the first byte in codePtr's
2848 * memory block where the location
2849 * information is to be stored. */
2850 {
2851 register CmdLocation *mapPtr = envPtr->cmdMapPtr;
2852 int numCmds = envPtr->numCommands;
2853 register unsigned char *p = startPtr;
2854 int codeDelta, codeLen, srcDelta, srcLen, prevOffset;
2855 register int i;
2856
2857 /*
2858 * Encode the code offset for each command as a sequence of deltas.
2859 */
2860
2861 codePtr->codeDeltaStart = p;
2862 prevOffset = 0;
2863 for (i = 0; i < numCmds; i++) {
2864 codeDelta = (mapPtr[i].codeOffset - prevOffset);
2865 if (codeDelta < 0) {
2866 panic("EncodeCmdLocMap: bad code offset");
2867 } else if (codeDelta <= 127) {
2868 TclStoreInt1AtPtr(codeDelta, p);
2869 p++;
2870 } else {
2871 TclStoreInt1AtPtr(0xFF, p);
2872 p++;
2873 TclStoreInt4AtPtr(codeDelta, p);
2874 p += 4;
2875 }
2876 prevOffset = mapPtr[i].codeOffset;
2877 }
2878
2879 /*
2880 * Encode the code length for each command.
2881 */
2882
2883 codePtr->codeLengthStart = p;
2884 for (i = 0; i < numCmds; i++) {
2885 codeLen = mapPtr[i].numCodeBytes;
2886 if (codeLen < 0) {
2887 panic("EncodeCmdLocMap: bad code length");
2888 } else if (codeLen <= 127) {
2889 TclStoreInt1AtPtr(codeLen, p);
2890 p++;
2891 } else {
2892 TclStoreInt1AtPtr(0xFF, p);
2893 p++;
2894 TclStoreInt4AtPtr(codeLen, p);
2895 p += 4;
2896 }
2897 }
2898
2899 /*
2900 * Encode the source offset for each command as a sequence of deltas.
2901 */
2902
2903 codePtr->srcDeltaStart = p;
2904 prevOffset = 0;
2905 for (i = 0; i < numCmds; i++) {
2906 srcDelta = (mapPtr[i].srcOffset - prevOffset);
2907 if ((-127 <= srcDelta) && (srcDelta <= 127)) {
2908 TclStoreInt1AtPtr(srcDelta, p);
2909 p++;
2910 } else {
2911 TclStoreInt1AtPtr(0xFF, p);
2912 p++;
2913 TclStoreInt4AtPtr(srcDelta, p);
2914 p += 4;
2915 }
2916 prevOffset = mapPtr[i].srcOffset;
2917 }
2918
2919 /*
2920 * Encode the source length for each command.
2921 */
2922
2923 codePtr->srcLengthStart = p;
2924 for (i = 0; i < numCmds; i++) {
2925 srcLen = mapPtr[i].numSrcBytes;
2926 if (srcLen < 0) {
2927 panic("EncodeCmdLocMap: bad source length");
2928 } else if (srcLen <= 127) {
2929 TclStoreInt1AtPtr(srcLen, p);
2930 p++;
2931 } else {
2932 TclStoreInt1AtPtr(0xFF, p);
2933 p++;
2934 TclStoreInt4AtPtr(srcLen, p);
2935 p += 4;
2936 }
2937 }
2938
2939 return p;
2940 }
2941
2942 #ifdef TCL_COMPILE_DEBUG
2943 /*
2944 *----------------------------------------------------------------------
2945 *
2946 * TclPrintByteCodeObj --
2947 *
2948 * This procedure prints ("disassembles") the instructions of a
2949 * bytecode object to stdout.
2950 *
2951 * Results:
2952 * None.
2953 *
2954 * Side effects:
2955 * None.
2956 *
2957 *----------------------------------------------------------------------
2958 */
2959
2960 void
2961 TclPrintByteCodeObj(interp, objPtr)
2962 Tcl_Interp *interp; /* Used only for Tcl_GetStringFromObj. */
2963 Tcl_Obj *objPtr; /* The bytecode object to disassemble. */
2964 {
2965 ByteCode* codePtr = (ByteCode *) objPtr->internalRep.otherValuePtr;
2966 unsigned char *codeStart, *codeLimit, *pc;
2967 unsigned char *codeDeltaNext, *codeLengthNext;
2968 unsigned char *srcDeltaNext, *srcLengthNext;
2969 int codeOffset, codeLen, srcOffset, srcLen, numCmds, delta, i;
2970 Interp *iPtr = (Interp *) *codePtr->interpHandle;
2971
2972 if (codePtr->refCount <= 0) {
2973 return; /* already freed */
2974 }
2975
2976 codeStart = codePtr->codeStart;
2977 codeLimit = (codeStart + codePtr->numCodeBytes);
2978 numCmds = codePtr->numCommands;
2979
2980 /*
2981 * Print header lines describing the ByteCode.
2982 */
2983
2984 fprintf(stdout, "\nByteCode 0x%x, refCt %u, epoch %u, interp 0x%x (epoch %u)\n",
2985 (unsigned int) codePtr, codePtr->refCount,
2986 codePtr->compileEpoch, (unsigned int) iPtr,
2987 iPtr->compileEpoch);
2988 fprintf(stdout, " Source ");
2989 TclPrintSource(stdout, codePtr->source,
2990 TclMin(codePtr->numSrcBytes, 55));
2991 fprintf(stdout, "\n Cmds %d, src %d, inst %d, litObjs %u, aux %d, stkDepth %u, code/src %.2f\n",
2992 numCmds, codePtr->numSrcBytes, codePtr->numCodeBytes,
2993 codePtr->numLitObjects, codePtr->numAuxDataItems,
2994 codePtr->maxStackDepth,
2995 #ifdef TCL_COMPILE_STATS
2996 (codePtr->numSrcBytes?
2997 ((float)codePtr->structureSize)/((float)codePtr->numSrcBytes) : 0.0));
2998 #else
2999 0.0);
3000 #endif
3001 #ifdef TCL_COMPILE_STATS
3002 fprintf(stdout,
3003 " Code %d = header %d+inst %d+litObj %d+exc %d+aux %d+cmdMap %d\n",
3004 codePtr->structureSize,
3005 (sizeof(ByteCode) - (sizeof(size_t) + sizeof(Tcl_Time))),
3006 codePtr->numCodeBytes,
3007 (codePtr->numLitObjects * sizeof(Tcl_Obj *)),
3008 (codePtr->numExceptRanges * sizeof(ExceptionRange)),
3009 (codePtr->numAuxDataItems * sizeof(AuxData)),
3010 codePtr->numCmdLocBytes);
3011 #endif /* TCL_COMPILE_STATS */
3012
3013 /*
3014 * If the ByteCode is the compiled body of a Tcl procedure, print
3015 * information about that procedure. Note that we don't know the
3016 * procedure's name since ByteCode's can be shared among procedures.
3017 */
3018
3019 if (codePtr->procPtr != NULL) {
3020 Proc *procPtr = codePtr->procPtr;
3021 int numCompiledLocals = procPtr->numCompiledLocals;
3022 fprintf(stdout,
3023 " Proc 0x%x, refCt %d, args %d, compiled locals %d\n",
3024 (unsigned int) procPtr, procPtr->refCount, procPtr->numArgs,
3025 numCompiledLocals);
3026 if (numCompiledLocals > 0) {
3027 CompiledLocal *localPtr = procPtr->firstLocalPtr;
3028 for (i = 0; i < numCompiledLocals; i++) {
3029 fprintf(stdout, " slot %d%s%s%s%s%s%s", i,
3030 ((localPtr->flags & VAR_SCALAR)? ", scalar" : ""),
3031 ((localPtr->flags & VAR_ARRAY)? ", array" : ""),
3032 ((localPtr->flags & VAR_LINK)? ", link" : ""),
3033 ((localPtr->flags & VAR_ARGUMENT)? ", arg" : ""),
3034 ((localPtr->flags & VAR_TEMPORARY)? ", temp" : ""),
3035 ((localPtr->flags & VAR_RESOLVED)? ", resolved" : ""));
3036 if (TclIsVarTemporary(localPtr)) {
3037 fprintf(stdout, "\n");
3038 } else {
3039 fprintf(stdout, ", \"%s\"\n", localPtr->name);
3040 }
3041 localPtr = localPtr->nextPtr;
3042 }
3043 }
3044 }
3045
3046 /*
3047 * Print the ExceptionRange array.
3048 */
3049
3050 if (codePtr->numExceptRanges > 0) {
3051 fprintf(stdout, " Exception ranges %d, depth %d:\n",
3052 codePtr->numExceptRanges, codePtr->maxExceptDepth);
3053 for (i = 0; i < codePtr->numExceptRanges; i++) {
3054 ExceptionRange *rangePtr = &(codePtr->exceptArrayPtr[i]);
3055 fprintf(stdout, " %d: level %d, %s, pc %d-%d, ",
3056 i, rangePtr->nestingLevel,
3057 ((rangePtr->type == LOOP_EXCEPTION_RANGE)
3058 ? "loop" : "catch"),
3059 rangePtr->codeOffset,
3060 (rangePtr->codeOffset + rangePtr->numCodeBytes - 1));
3061 switch (rangePtr->type) {
3062 case LOOP_EXCEPTION_RANGE:
3063 fprintf(stdout, "continue %d, break %d\n",
3064 rangePtr->continueOffset, rangePtr->breakOffset);
3065 break;
3066 case CATCH_EXCEPTION_RANGE:
3067 fprintf(stdout, "catch %d\n", rangePtr->catchOffset);
3068 break;
3069 default:
3070 panic("TclPrintByteCodeObj: bad ExceptionRange type %d\n",
3071 rangePtr->type);
3072 }
3073 }
3074 }
3075
3076 /*
3077 * If there were no commands (e.g., an expression or an empty string
3078 * was compiled), just print all instructions and return.
3079 */
3080
3081 if (numCmds == 0) {
3082 pc = codeStart;
3083 while (pc < codeLimit) {
3084 fprintf(stdout, " ");
3085 pc += TclPrintInstruction(codePtr, pc);
3086 }
3087 return;
3088 }
3089
3090 /*
3091 * Print table showing the code offset, source offset, and source
3092 * length for each command. These are encoded as a sequence of bytes.
3093 */
3094
3095 fprintf(stdout, " Commands %d:", numCmds);
3096 codeDeltaNext = codePtr->codeDeltaStart;
3097 codeLengthNext = codePtr->codeLengthStart;
3098 srcDeltaNext = codePtr->srcDeltaStart;
3099 srcLengthNext = codePtr->srcLengthStart;
3100 codeOffset = srcOffset = 0;
3101 for (i = 0; i < numCmds; i++) {
3102 if ((unsigned int) (*codeDeltaNext) == (unsigned int) 0xFF) {
3103 codeDeltaNext++;
3104 delta = TclGetInt4AtPtr(codeDeltaNext);
3105 codeDeltaNext += 4;
3106 } else {
3107 delta = TclGetInt1AtPtr(codeDeltaNext);
3108 codeDeltaNext++;
3109 }
3110 codeOffset += delta;
3111
3112 if ((unsigned int) (*codeLengthNext) == (unsigned int) 0xFF) {
3113 codeLengthNext++;
3114 codeLen = TclGetInt4AtPtr(codeLengthNext);
3115 codeLengthNext += 4;
3116 } else {
3117 codeLen = TclGetInt1AtPtr(codeLengthNext);
3118 codeLengthNext++;
3119 }
3120
3121 if ((unsigned int) (*srcDeltaNext) == (unsigned int) 0xFF) {
3122 srcDeltaNext++;
3123 delta = TclGetInt4AtPtr(srcDeltaNext);
3124 srcDeltaNext += 4;
3125 } else {
3126 delta = TclGetInt1AtPtr(srcDeltaNext);
3127 srcDeltaNext++;
3128 }
3129 srcOffset += delta;
3130
3131 if ((unsigned int) (*srcLengthNext) == (unsigned int) 0xFF) {
3132 srcLengthNext++;
3133 srcLen = TclGetInt4AtPtr(srcLengthNext);
3134 srcLengthNext += 4;
3135 } else {
3136 srcLen = TclGetInt1AtPtr(srcLengthNext);
3137 srcLengthNext++;
3138 }
3139
3140 fprintf(stdout, "%s%4d: pc %d-%d, src %d-%d",
3141 ((i % 2)? " " : "\n "),
3142 (i+1), codeOffset, (codeOffset + codeLen - 1),
3143 srcOffset, (srcOffset + srcLen - 1));
3144 }
3145 if (numCmds > 0) {
3146 fprintf(stdout, "\n");
3147 }
3148
3149 /*
3150 * Print each instruction. If the instruction corresponds to the start
3151 * of a command, print the command's source. Note that we don't need
3152 * the code length here.
3153 */
3154
3155 codeDeltaNext = codePtr->codeDeltaStart;
3156 srcDeltaNext = codePtr->srcDeltaStart;
3157 srcLengthNext = codePtr->srcLengthStart;
3158 codeOffset = srcOffset = 0;
3159 pc = codeStart;
3160 for (i = 0; i < numCmds; i++) {
3161 if ((unsigned int) (*codeDeltaNext) == (unsigned int) 0xFF) {
3162 codeDeltaNext++;
3163 delta = TclGetInt4AtPtr(codeDeltaNext);
3164 codeDeltaNext += 4;
3165 } else {
3166 delta = TclGetInt1AtPtr(codeDeltaNext);
3167 codeDeltaNext++;
3168 }
3169 codeOffset += delta;
3170
3171 if ((unsigned int) (*srcDeltaNext) == (unsigned int) 0xFF) {
3172 srcDeltaNext++;
3173 delta = TclGetInt4AtPtr(srcDeltaNext);
3174 srcDeltaNext += 4;
3175 } else {
3176 delta = TclGetInt1AtPtr(srcDeltaNext);
3177 srcDeltaNext++;
3178 }
3179 srcOffset += delta;
3180
3181 if ((unsigned int) (*srcLengthNext) == (unsigned int) 0xFF) {
3182 srcLengthNext++;
3183 srcLen = TclGetInt4AtPtr(srcLengthNext);
3184 srcLengthNext += 4;
3185 } else {
3186 srcLen = TclGetInt1AtPtr(srcLengthNext);
3187 srcLengthNext++;
3188 }
3189
3190 /*
3191 * Print instructions before command i.
3192 */
3193
3194 while ((pc-codeStart) < codeOffset) {
3195 fprintf(stdout, " ");
3196 pc += TclPrintInstruction(codePtr, pc);
3197 }
3198
3199 fprintf(stdout, " Command %d: ", (i+1));
3200 TclPrintSource(stdout, (codePtr->source + srcOffset),
3201 TclMin(srcLen, 55));
3202 fprintf(stdout, "\n");
3203 }
3204 if (pc < codeLimit) {
3205 /*
3206 * Print instructions after the last command.
3207 */
3208
3209 while (pc < codeLimit) {
3210 fprintf(stdout, " ");
3211 pc += TclPrintInstruction(codePtr, pc);
3212 }
3213 }
3214 }
3215 #endif /* TCL_COMPILE_DEBUG */
3216
3217 /*
3218 *----------------------------------------------------------------------
3219 *
3220 * TclPrintInstruction --
3221 *
3222 * This procedure prints ("disassembles") one instruction from a
3223 * bytecode object to stdout.
3224 *
3225 * Results:
3226 * Returns the length in bytes of the current instruiction.
3227 *
3228 * Side effects:
3229 * None.
3230 *
3231 *----------------------------------------------------------------------
3232 */
3233
3234 int
3235 TclPrintInstruction(codePtr, pc)
3236 ByteCode* codePtr; /* Bytecode containing the instruction. */
3237 unsigned char *pc; /* Points to first byte of instruction. */
3238 {
3239 Proc *procPtr = codePtr->procPtr;
3240 unsigned char opCode = *pc;
3241 register InstructionDesc *instDesc = &tclInstructionTable[opCode];
3242 unsigned char *codeStart = codePtr->codeStart;
3243 unsigned int pcOffset = (pc - codeStart);
3244 int opnd, i, j;
3245
3246 fprintf(stdout, "(%u) %s ", pcOffset, instDesc->name);
3247 for (i = 0; i < instDesc->numOperands; i++) {
3248 switch (instDesc->opTypes[i]) {
3249 case OPERAND_INT1:
3250 opnd = TclGetInt1AtPtr(pc+1+i);
3251 if ((i == 0) && ((opCode == INST_JUMP1)
3252 || (opCode == INST_JUMP_TRUE1)
3253 || (opCode == INST_JUMP_FALSE1))) {
3254 fprintf(stdout, "%d # pc %u", opnd, (pcOffset + opnd));
3255 } else {
3256 fprintf(stdout, "%d", opnd);
3257 }
3258 break;
3259 case OPERAND_INT4:
3260 opnd = TclGetInt4AtPtr(pc+1+i);
3261 if ((i == 0) && ((opCode == INST_JUMP4)
3262 || (opCode == INST_JUMP_TRUE4)
3263 || (opCode == INST_JUMP_FALSE4))) {
3264 fprintf(stdout, "%d # pc %u", opnd, (pcOffset + opnd));
3265 } else {
3266 fprintf(stdout, "%d", opnd);
3267 }
3268 break;
3269 case OPERAND_UINT1:
3270 opnd = TclGetUInt1AtPtr(pc+1+i);
3271 if ((i == 0) && (opCode == INST_PUSH1)) {
3272 fprintf(stdout, "%u # ", (unsigned int) opnd);
3273 TclPrintObject(stdout, codePtr->objArrayPtr[opnd], 40);
3274 } else if ((i == 0) && ((opCode == INST_LOAD_SCALAR1)
3275 || (opCode == INST_LOAD_ARRAY1)
3276 || (opCode == INST_STORE_SCALAR1)
3277 || (opCode == INST_STORE_ARRAY1))) {
3278 int localCt = procPtr->numCompiledLocals;
3279 CompiledLocal *localPtr = procPtr->firstLocalPtr;
3280 if (opnd >= localCt) {
3281 panic("TclPrintInstruction: bad local var index %u (%u locals)\n",
3282 (unsigned int) opnd, localCt);
3283 return instDesc->numBytes;
3284 }
3285 for (j = 0; j < opnd; j++) {
3286 localPtr = localPtr->nextPtr;
3287 }
3288 if (TclIsVarTemporary(localPtr)) {
3289 fprintf(stdout, "%u # temp var %u",
3290 (unsigned int) opnd, (unsigned int) opnd);
3291 } else {
3292 fprintf(stdout, "%u # var ", (unsigned int) opnd);
3293 TclPrintSource(stdout, localPtr->name, 40);
3294 }
3295 } else {
3296 fprintf(stdout, "%u ", (unsigned int) opnd);
3297 }
3298 break;
3299 case OPERAND_UINT4:
3300 opnd = TclGetUInt4AtPtr(pc+1+i);
3301 if (opCode == INST_PUSH4) {
3302 fprintf(stdout, "%u # ", opnd);
3303 TclPrintObject(stdout, codePtr->objArrayPtr[opnd], 40);
3304 } else if ((i == 0) && ((opCode == INST_LOAD_SCALAR4)
3305 || (opCode == INST_LOAD_ARRAY4)
3306 || (opCode == INST_STORE_SCALAR4)
3307 || (opCode == INST_STORE_ARRAY4))) {
3308 int localCt = procPtr->numCompiledLocals;
3309 CompiledLocal *localPtr = procPtr->firstLocalPtr;
3310 if (opnd >= localCt) {
3311 panic("TclPrintInstruction: bad local var index %u (%u locals)\n",
3312 (unsigned int) opnd, localCt);
3313 return instDesc->numBytes;
3314 }
3315 for (j = 0; j < opnd; j++) {
3316 localPtr = localPtr->nextPtr;
3317 }
3318 if (TclIsVarTemporary(localPtr)) {
3319 fprintf(stdout, "%u # temp var %u",
3320 (unsigned int) opnd, (unsigned int) opnd);
3321 } else {
3322 fprintf(stdout, "%u # var ", (unsigned int) opnd);
3323 TclPrintSource(stdout, localPtr->name, 40);
3324 }
3325 } else {
3326 fprintf(stdout, "%u ", (unsigned int) opnd);
3327 }
3328 break;
3329 case OPERAND_NONE:
3330 default:
3331 break;
3332 }
3333 }
3334 fprintf(stdout, "\n");
3335 return instDesc->numBytes;
3336 }
3337
3338 /*
3339 *----------------------------------------------------------------------
3340 *
3341 * TclPrintObject --
3342 *
3343 * This procedure prints up to a specified number of characters from
3344 * the argument Tcl object's string representation to a specified file.
3345 *
3346 * Results:
3347 * None.
3348 *
3349 * Side effects:
3350 * Outputs characters to the specified file.
3351 *
3352 *----------------------------------------------------------------------
3353 */
3354
3355 void
3356 TclPrintObject(outFile, objPtr, maxChars)
3357 FILE *outFile; /* The file to print the source to. */
3358 Tcl_Obj *objPtr; /* Points to the Tcl object whose string
3359 * representation should be printed. */
3360 int maxChars; /* Maximum number of chars to print. */
3361 {
3362 char *bytes;
3363 int length;
3364
3365 bytes = Tcl_GetStringFromObj(objPtr, &length);
3366 TclPrintSource(outFile, bytes, TclMin(length, maxChars));
3367 }
3368
3369 /*
3370 *----------------------------------------------------------------------
3371 *
3372 * TclPrintSource --
3373 *
3374 * This procedure prints up to a specified number of characters from
3375 * the argument string to a specified file. It tries to produce legible
3376 * output by adding backslashes as necessary.
3377 *
3378 * Results:
3379 * None.
3380 *
3381 * Side effects:
3382 * Outputs characters to the specified file.
3383 *
3384 *----------------------------------------------------------------------
3385 */
3386
3387 void
3388 TclPrintSource(outFile, string, maxChars)
3389 FILE *outFile; /* The file to print the source to. */
3390 CONST char *string; /* The string to print. */
3391 int maxChars; /* Maximum number of chars to print. */
3392 {
3393 register CONST char *p;
3394 register int i = 0;
3395
3396 if (string == NULL) {
3397 fprintf(outFile, "\"\"");
3398 return;
3399 }
3400
3401 fprintf(outFile, "\"");
3402 p = string;
3403 for (; (*p != '\0') && (i < maxChars); p++, i++) {
3404 switch (*p) {
3405 case '"':
3406 fprintf(outFile, "\\\"");
3407 continue;
3408 case '\f':
3409 fprintf(outFile, "\\f");
3410 continue;
3411 case '\n':
3412 fprintf(outFile, "\\n");
3413 continue;
3414 case '\r':
3415 fprintf(outFile, "\\r");
3416 continue;
3417 case '\t':
3418 fprintf(outFile, "\\t");
3419 continue;
3420 case '\v':
3421 fprintf(outFile, "\\v");
3422 continue;
3423 default:
3424 fprintf(outFile, "%c", *p);
3425 continue;
3426 }
3427 }
3428 fprintf(outFile, "\"");
3429 }
3430
3431 #ifdef TCL_COMPILE_STATS
3432 /*
3433 *----------------------------------------------------------------------
3434 *
3435 * RecordByteCodeStats --
3436 *
3437 * Accumulates various compilation-related statistics for each newly
3438 * compiled ByteCode. Called by the TclInitByteCodeObj when Tcl is
3439 * compiled with the -DTCL_COMPILE_STATS flag
3440 *
3441 * Results:
3442 * None.
3443 *
3444 * Side effects:
3445 * Accumulates aggregate code-related statistics in the interpreter's
3446 * ByteCodeStats structure. Records statistics specific to a ByteCode
3447 * in its ByteCode structure.
3448 *
3449 *----------------------------------------------------------------------
3450 */
3451
3452 void
3453 RecordByteCodeStats(codePtr)
3454 ByteCode *codePtr; /* Points to ByteCode structure with info
3455 * to add to accumulated statistics. */
3456 {
3457 Interp *iPtr = (Interp *) *codePtr->interpHandle;
3458 register ByteCodeStats *statsPtr = &(iPtr->stats);
3459
3460 statsPtr->numCompilations++;
3461 statsPtr->totalSrcBytes += (double) codePtr->numSrcBytes;
3462 statsPtr->totalByteCodeBytes += (double) codePtr->structureSize;
3463 statsPtr->currentSrcBytes += (double) codePtr->numSrcBytes;
3464 statsPtr->currentByteCodeBytes += (double) codePtr->structureSize;
3465
3466 statsPtr->srcCount[TclLog2(codePtr->numSrcBytes)]++;
3467 statsPtr->byteCodeCount[TclLog2((int)(codePtr->structureSize))]++;
3468
3469 statsPtr->currentInstBytes += (double) codePtr->numCodeBytes;
3470 statsPtr->currentLitBytes +=
3471 (double) (codePtr->numLitObjects * sizeof(Tcl_Obj *));
3472 statsPtr->currentExceptBytes +=
3473 (double) (codePtr->numExceptRanges * sizeof(ExceptionRange));
3474 statsPtr->currentAuxBytes +=
3475 (double) (codePtr->numAuxDataItems * sizeof(AuxData));
3476 statsPtr->currentCmdMapBytes += (double) codePtr->numCmdLocBytes;
3477 }
3478 #endif /* TCL_COMPILE_STATS */