1 /*
2  * tclCompile.h --
3  *
4  * Copyright (c) 1996-1998 Sun Microsystems, Inc.
5  * Copyright (c) 1998-2000 by Scriptics Corporation.
6  * Copyright (c) 2001 by Kevin B. Kenny.  All rights reserved.
7  *
8  * See the file "license.terms" for information on usage and redistribution
9  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
10  *
11  * RCS: @(#) $Id: tclCompile.h,v 1.33 2002/10/09 11:54:05 das Exp $
12  */
13 
14 #ifndef _TCLCOMPILATION
15 #define _TCLCOMPILATION 1
16 
17 #ifndef _TCLINT
18 #include "tclInt.h"
19 #endif /* _TCLINT */
20 
21 #ifdef BUILD_tcl
22 # undef TCL_STORAGE_CLASS
23 # define TCL_STORAGE_CLASS DLLEXPORT
24 #endif
25 
26 /*
27  *------------------------------------------------------------------------
28  * Variables related to compilation. These are used in tclCompile.c,
29  * tclExecute.c, tclBasic.c, and their clients.
30  *------------------------------------------------------------------------
31  */
32 
33 #ifdef TCL_COMPILE_DEBUG
34 /*
35  * Variable that controls whether compilation tracing is enabled and, if so,
36  * what level of tracing is desired:
37  *    0: no compilation tracing
38  *    1: summarize compilation of top level cmds and proc bodies
39  *    2: display all instructions of each ByteCode compiled
40  * This variable is linked to the Tcl variable "tcl_traceCompile".
41  */
42 
43 extern int 		tclTraceCompile;
44 #endif
45 
46 #ifdef TCL_COMPILE_DEBUG
47 /*
48  * Variable that controls whether execution tracing is enabled and, if so,
49  * what level of tracing is desired:
50  *    0: no execution tracing
51  *    1: trace invocations of Tcl procs only
52  *    2: trace invocations of all (not compiled away) commands
53  *    3: display each instruction executed
54  * This variable is linked to the Tcl variable "tcl_traceExec".
55  */
56 
57 extern int 		tclTraceExec;
58 #endif
59 
60 /*
61  *------------------------------------------------------------------------
62  * Data structures related to compilation.
63  *------------------------------------------------------------------------
64  */
65 
66 /*
67  * The structure used to implement Tcl "exceptions" (exceptional returns):
68  * for example, those generated in loops by the break and continue commands,
69  * and those generated by scripts and caught by the catch command. This
70  * ExceptionRange structure describes a range of code (e.g., a loop body),
71  * the kind of exceptions (e.g., a break or continue) that might occur, and
72  * the PC offsets to jump to if a matching exception does occur. Exception
73  * ranges can nest so this structure includes a nesting level that is used
74  * at runtime to find the closest exception range surrounding a PC. For
75  * example, when a break command is executed, the ExceptionRange structure
76  * for the most deeply nested loop, if any, is found and used. These
77  * structures are also generated for the "next" subcommands of for loops
78  * since a break there terminates the for command. This means a for command
79  * actually generates two LoopInfo structures.
80  */
81 
82 typedef enum {
83     LOOP_EXCEPTION_RANGE,	/* Exception's range is part of a loop.
84 				 * Break and continue "exceptions" cause
85 				 * jumps to appropriate PC offsets. */
86     CATCH_EXCEPTION_RANGE	/* Exception's range is controlled by a
87 				 * catch command. Errors in the range cause
88 				 * a jump to a catch PC offset. */
89 } ExceptionRangeType;
90 
91 typedef struct ExceptionRange {
92     ExceptionRangeType type;	/* The kind of ExceptionRange. */
93     int nestingLevel;		/* Static depth of the exception range.
94 				 * Used to find the most deeply-nested
95 				 * range surrounding a PC at runtime. */
96     int codeOffset;		/* Offset of the first instruction byte of
97 				 * the code range. */
98     int numCodeBytes;		/* Number of bytes in the code range. */
99     int breakOffset;		/* If LOOP_EXCEPTION_RANGE, the target PC
100 				 * offset for a break command in the range. */
101     int continueOffset;		/* If LOOP_EXCEPTION_RANGE and not -1, the
102 				 * target PC offset for a continue command in
103 				 * the code range. Otherwise, ignore this range
104 				 * when processing a continue command. */
105     int catchOffset;		/* If a CATCH_EXCEPTION_RANGE, the target PC
106 				 * offset for any "exception" in range. */
107 } ExceptionRange;
108 
109 /*
110  * Structure used to map between instruction pc and source locations. It
111  * defines for each compiled Tcl command its code's starting offset and
112  * its source's starting offset and length. Note that the code offset
113  * increases monotonically: that is, the table is sorted in code offset
114  * order. The source offset is not monotonic.
115  */
116 
117 typedef struct CmdLocation {
118     int codeOffset;		/* Offset of first byte of command code. */
119     int numCodeBytes;		/* Number of bytes for command's code. */
120     int srcOffset;		/* Offset of first char of the command. */
121     int numSrcBytes;		/* Number of command source chars. */
122 } CmdLocation;
123 
124 /*
125  * CompileProcs need the ability to record information during compilation
126  * that can be used by bytecode instructions during execution. The AuxData
127  * structure provides this "auxiliary data" mechanism. An arbitrary number
128  * of these structures can be stored in the ByteCode record (during
129  * compilation they are stored in a CompileEnv structure). Each AuxData
130  * record holds one word of client-specified data (often a pointer) and is
131  * given an index that instructions can later use to look up the structure
132  * and its data.
133  *
134  * The following definitions declare the types of procedures that are called
135  * to duplicate or free this auxiliary data when the containing ByteCode
136  * objects are duplicated and freed. Pointers to these procedures are kept
137  * in the AuxData structure.
138  */
139 
140 typedef ClientData (AuxDataDupProc)  _ANSI_ARGS_((ClientData clientData));
141 typedef void       (AuxDataFreeProc) _ANSI_ARGS_((ClientData clientData));
142 
143 /*
144  * We define a separate AuxDataType struct to hold type-related information
145  * for the AuxData structure. This separation makes it possible for clients
146  * outside of the TCL core to manipulate (in a limited fashion!) AuxData;
147  * for example, it makes it possible to pickle and unpickle AuxData structs.
148  */
149 
150 typedef struct AuxDataType {
151     char *name;					/* the name of the type. Types can be
152                                  * registered and found by name */
153     AuxDataDupProc *dupProc;	/* Callback procedure to invoke when the
154                                  * aux data is duplicated (e.g., when the
155                                  * ByteCode structure containing the aux
156                                  * data is duplicated). NULL means just
157                                  * copy the source clientData bits; no
158                                  * proc need be called. */
159     AuxDataFreeProc *freeProc;	/* Callback procedure to invoke when the
160                                  * aux data is freed. NULL means no
161                                  * proc need be called. */
162 } AuxDataType;
163 
164 /*
165  * The definition of the AuxData structure that holds information created
166  * during compilation by CompileProcs and used by instructions during
167  * execution.
168  */
169 
170 typedef struct AuxData {
171     AuxDataType *type;		/* pointer to the AuxData type associated with
172                              * this ClientData. */
173     ClientData clientData;	/* The compilation data itself. */
174 } AuxData;
175 
176 /*
177  * Structure defining the compilation environment. After compilation, fields
178  * describing bytecode instructions are copied out into the more compact
179  * ByteCode structure defined below.
180  */
181 
182 #define COMPILEENV_INIT_CODE_BYTES    250
183 #define COMPILEENV_INIT_NUM_OBJECTS    60
184 #define COMPILEENV_INIT_EXCEPT_RANGES   5
185 #define COMPILEENV_INIT_CMD_MAP_SIZE   40
186 #define COMPILEENV_INIT_AUX_DATA_SIZE   5
187 
188 typedef struct CompileEnv {
189     Interp *iPtr;		/* Interpreter containing the code being
190 				 * compiled. Commands and their compile
191 				 * procs are specific to an interpreter so
192 				 * the code emitted will depend on the
193 				 * interpreter. */
194     char *source;		/* The source string being compiled by
195 				 * SetByteCodeFromAny. This pointer is not
196 				 * owned by the CompileEnv and must not be
197 				 * freed or changed by it. */
198     int numSrcBytes;		/* Number of bytes in source. */
199     Proc *procPtr;		/* If a procedure is being compiled, a
200 				 * pointer to its Proc structure; otherwise
201 				 * NULL. Used to compile local variables.
202 				 * Set from information provided by
203 				 * ObjInterpProc in tclProc.c. */
204     int numCommands;		/* Number of commands compiled. */
205     int exceptDepth;		/* Current exception range nesting level;
206 				 * -1 if not in any range currently. */
207     int maxExceptDepth;		/* Max nesting level of exception ranges;
208 				 * -1 if no ranges have been compiled. */
209     int maxStackDepth;		/* Maximum number of stack elements needed
210 				 * to execute the code. Set by compilation
211 				 * procedures before returning. */
212     int currStackDepth;         /* Current stack depth. */
213     LiteralTable localLitTable;	/* Contains LiteralEntry's describing
214 				 * all Tcl objects referenced by this
215 				 * compiled code. Indexed by the string
216 				 * representations of the literals. Used to
217 				 * avoid creating duplicate objects. */
218     unsigned char *codeStart;	/* Points to the first byte of the code. */
219     unsigned char *codeNext;	/* Points to next code array byte to use. */
220     unsigned char *codeEnd;	/* Points just after the last allocated
221 				 * code array byte. */
222     int mallocedCodeArray;      /* Set 1 if code array was expanded
223 				 * and codeStart points into the heap.*/
224     LiteralEntry *literalArrayPtr;
225     				/* Points to start of LiteralEntry array. */
226     int literalArrayNext;	/* Index of next free object array entry. */
227     int literalArrayEnd;	/* Index just after last obj array entry. */
228     int mallocedLiteralArray;   /* 1 if object array was expanded and
229                                  * objArray points into the heap, else 0. */
230     ExceptionRange *exceptArrayPtr;
231     				/* Points to start of the ExceptionRange
232 				 * array. */
233     int exceptArrayNext;	/* Next free ExceptionRange array index.
234 				 * exceptArrayNext is the number of ranges
235 				 * and (exceptArrayNext-1) is the index of
236 				 * the current range's array entry. */
237     int exceptArrayEnd;		/* Index after the last ExceptionRange
238 				 * array entry. */
239     int mallocedExceptArray;	/* 1 if ExceptionRange array was expanded
240 				 * and exceptArrayPtr points in heap,
241 				 * else 0. */
242     CmdLocation *cmdMapPtr;	/* Points to start of CmdLocation array.
243 				 * numCommands is the index of the next
244 				 * entry to use; (numCommands-1) is the
245 				 * entry index for the last command. */
246     int cmdMapEnd;		/* Index after last CmdLocation entry. */
247     int mallocedCmdMap;		/* 1 if command map array was expanded and
248 				 * cmdMapPtr points in the heap, else 0. */
249     AuxData *auxDataArrayPtr;   /* Points to auxiliary data array start. */
250     int auxDataArrayNext;	/* Next free compile aux data array index.
251 				 * auxDataArrayNext is the number of aux
252 				 * data items and (auxDataArrayNext-1) is
253 				 * index of current aux data array entry. */
254     int auxDataArrayEnd;	/* Index after last aux data array entry. */
255     int mallocedAuxDataArray;	/* 1 if aux data array was expanded and
256 				 * auxDataArrayPtr points in heap else 0. */
257     unsigned char staticCodeSpace[COMPILEENV_INIT_CODE_BYTES];
258                                 /* Initial storage for code. */
259     LiteralEntry staticLiteralSpace[COMPILEENV_INIT_NUM_OBJECTS];
260                                 /* Initial storage of LiteralEntry array. */
261     ExceptionRange staticExceptArraySpace[COMPILEENV_INIT_EXCEPT_RANGES];
262                                 /* Initial ExceptionRange array storage. */
263     CmdLocation staticCmdMapSpace[COMPILEENV_INIT_CMD_MAP_SIZE];
264                                 /* Initial storage for cmd location map. */
265     AuxData staticAuxDataArraySpace[COMPILEENV_INIT_AUX_DATA_SIZE];
266                                 /* Initial storage for aux data array. */
267 } CompileEnv;
268 
269 /*
270  * The structure defining the bytecode instructions resulting from compiling
271  * a Tcl script. Note that this structure is variable length: a single heap
272  * object is allocated to hold the ByteCode structure immediately followed
273  * by the code bytes, the literal object array, the ExceptionRange array,
274  * the CmdLocation map, and the compilation AuxData array.
275  */
276 
277 /*
278  * A PRECOMPILED bytecode struct is one that was generated from a compiled
279  * image rather than implicitly compiled from source
280  */
281 #define TCL_BYTECODE_PRECOMPILED		0x0001
282 
283 typedef struct ByteCode {
284     TclHandle interpHandle;	/* Handle for interpreter containing the
285 				 * compiled code.  Commands and their compile
286 				 * procs are specific to an interpreter so the
287 				 * code emitted will depend on the
288 				 * interpreter. */
289     int compileEpoch;		/* Value of iPtr->compileEpoch when this
290 				 * ByteCode was compiled. Used to invalidate
291 				 * code when, e.g., commands with compile
292 				 * procs are redefined. */
293     Namespace *nsPtr;		/* Namespace context in which this code
294 				 * was compiled. If the code is executed
295 				 * if a different namespace, it must be
296 				 * recompiled. */
297     int nsEpoch;		/* Value of nsPtr->resolverEpoch when this
298 				 * ByteCode was compiled. Used to invalidate
299 				 * code when new namespace resolution rules
300 				 * are put into effect. */
301     int refCount;		/* Reference count: set 1 when created
302 				 * plus 1 for each execution of the code
303 				 * currently active. This structure can be
304 				 * freed when refCount becomes zero. */
305     unsigned int flags;		/* flags describing state for the codebyte.
306                                  * this variable holds ORed values from the
307                                  * TCL_BYTECODE_ masks defined above */
308     char *source;		/* The source string from which this
309 				 * ByteCode was compiled. Note that this
310 				 * pointer is not owned by the ByteCode and
311 				 * must not be freed or modified by it. */
312     Proc *procPtr;		/* If the ByteCode was compiled from a
313 				 * procedure body, this is a pointer to its
314 				 * Proc structure; otherwise NULL. This
315 				 * pointer is also not owned by the ByteCode
316 				 * and must not be freed by it. */
317     size_t structureSize;	/* Number of bytes in the ByteCode structure
318 				 * itself. Does not include heap space for
319 				 * literal Tcl objects or storage referenced
320 				 * by AuxData entries. */
321     int numCommands;		/* Number of commands compiled. */
322     int numSrcBytes;		/* Number of source bytes compiled. */
323     int numCodeBytes;		/* Number of code bytes. */
324     int numLitObjects;		/* Number of objects in literal array. */
325     int numExceptRanges;	/* Number of ExceptionRange array elems. */
326     int numAuxDataItems;	/* Number of AuxData items. */
327     int numCmdLocBytes;		/* Number of bytes needed for encoded
328 				 * command location information. */
329     int maxExceptDepth;		/* Maximum nesting level of ExceptionRanges;
330 				 * -1 if no ranges were compiled. */
331     int maxStackDepth;		/* Maximum number of stack elements needed
332 				 * to execute the code. */
333     unsigned char *codeStart;	/* Points to the first byte of the code.
334 				 * This is just after the final ByteCode
335 				 * member cmdMapPtr. */
336     Tcl_Obj **objArrayPtr;	/* Points to the start of the literal
337 				 * object array. This is just after the
338 				 * last code byte. */
339     ExceptionRange *exceptArrayPtr;
340     				/* Points to the start of the ExceptionRange
341 				 * array. This is just after the last
342 				 * object in the object array. */
343     AuxData *auxDataArrayPtr;   /* Points to the start of the auxiliary data
344 				 * array. This is just after the last entry
345 				 * in the ExceptionRange array. */
346     unsigned char *codeDeltaStart;
347 				/* Points to the first of a sequence of
348 				 * bytes that encode the change in the
349 				 * starting offset of each command's code.
350 				 * If -127<=delta<=127, it is encoded as 1
351 				 * byte, otherwise 0xFF (128) appears and
352 				 * the delta is encoded by the next 4 bytes.
353 				 * Code deltas are always positive. This
354 				 * sequence is just after the last entry in
355 				 * the AuxData array. */
356     unsigned char *codeLengthStart;
357 				/* Points to the first of a sequence of
358 				 * bytes that encode the length of each
359 				 * command's code. The encoding is the same
360 				 * as for code deltas. Code lengths are
361 				 * always positive. This sequence is just
362 				 * after the last entry in the code delta
363 				 * sequence. */
364     unsigned char *srcDeltaStart;
365 				/* Points to the first of a sequence of
366 				 * bytes that encode the change in the
367 				 * starting offset of each command's source.
368 				 * The encoding is the same as for code
369 				 * deltas. Source deltas can be negative.
370 				 * This sequence is just after the last byte
371 				 * in the code length sequence. */
372     unsigned char *srcLengthStart;
373 				/* Points to the first of a sequence of
374 				 * bytes that encode the length of each
375 				 * command's source. The encoding is the
376 				 * same as for code deltas. Source lengths
377 				 * are always positive. This sequence is
378 				 * just after the last byte in the source
379 				 * delta sequence. */
380 #ifdef TCL_COMPILE_STATS
381     Tcl_Time createTime;	/* Absolute time when the ByteCode was
382 				 * created. */
383 #endif /* TCL_COMPILE_STATS */
384 } ByteCode;
385 
386 /*
387  * Opcodes for the Tcl bytecode instructions. These must correspond to
388  * the entries in the table of instruction descriptions,
389  * tclInstructionTable, in tclCompile.c. Also, the order and number of
390  * the expression opcodes (e.g., INST_LOR) must match the entries in
391  * the array operatorStrings in tclExecute.c.
392  */
393 
394 /* Opcodes 0 to 9 */
395 #define INST_DONE			0
396 #define INST_PUSH1			1
397 #define INST_PUSH4			2
398 #define INST_POP			3
399 #define INST_DUP			4
400 #define INST_CONCAT1			5
401 #define INST_INVOKE_STK1		6
402 #define INST_INVOKE_STK4		7
403 #define INST_EVAL_STK			8
404 #define INST_EXPR_STK			9
405 
406 /* Opcodes 10 to 23 */
407 #define INST_LOAD_SCALAR1		10
408 #define INST_LOAD_SCALAR4		11
409 #define INST_LOAD_SCALAR_STK		12
410 #define INST_LOAD_ARRAY1		13
411 #define INST_LOAD_ARRAY4		14
412 #define INST_LOAD_ARRAY_STK		15
413 #define INST_LOAD_STK			16
414 #define INST_STORE_SCALAR1		17
415 #define INST_STORE_SCALAR4		18
416 #define INST_STORE_SCALAR_STK		19
417 #define INST_STORE_ARRAY1		20
418 #define INST_STORE_ARRAY4		21
419 #define INST_STORE_ARRAY_STK		22
420 #define INST_STORE_STK			23
421 
422 /* Opcodes 24 to 33 */
423 #define INST_INCR_SCALAR1		24
424 #define INST_INCR_SCALAR_STK		25
425 #define INST_INCR_ARRAY1		26
426 #define INST_INCR_ARRAY_STK		27
427 #define INST_INCR_STK			28
428 #define INST_INCR_SCALAR1_IMM		29
429 #define INST_INCR_SCALAR_STK_IMM	30
430 #define INST_INCR_ARRAY1_IMM		31
431 #define INST_INCR_ARRAY_STK_IMM		32
432 #define INST_INCR_STK_IMM		33
433 
434 /* Opcodes 34 to 39 */
435 #define INST_JUMP1			34
436 #define INST_JUMP4			35
437 #define INST_JUMP_TRUE1			36
438 #define INST_JUMP_TRUE4			37
439 #define INST_JUMP_FALSE1		38
440 #define INST_JUMP_FALSE4	        39
441 
442 /* Opcodes 40 to 64 */
443 #define INST_LOR			40
444 #define INST_LAND			41
445 #define INST_BITOR			42
446 #define INST_BITXOR			43
447 #define INST_BITAND			44
448 #define INST_EQ				45
449 #define INST_NEQ			46
450 #define INST_LT				47
451 #define INST_GT				48
452 #define INST_LE				49
453 #define INST_GE				50
454 #define INST_LSHIFT			51
455 #define INST_RSHIFT			52
456 #define INST_ADD			53
457 #define INST_SUB			54
458 #define INST_MULT			55
459 #define INST_DIV			56
460 #define INST_MOD			57
461 #define INST_UPLUS			58
462 #define INST_UMINUS			59
463 #define INST_BITNOT			60
464 #define INST_LNOT			61
465 #define INST_CALL_BUILTIN_FUNC1		62
466 #define INST_CALL_FUNC1			63
467 #define INST_TRY_CVT_TO_NUMERIC		64
468 
469 /* Opcodes 65 to 66 */
470 #define INST_BREAK			65
471 #define INST_CONTINUE			66
472 
473 /* Opcodes 67 to 68 */
474 #define INST_FOREACH_START4		67
475 #define INST_FOREACH_STEP4		68
476 
477 /* Opcodes 69 to 72 */
478 #define INST_BEGIN_CATCH4		69
479 #define INST_END_CATCH			70
480 #define INST_PUSH_RESULT		71
481 #define INST_PUSH_RETURN_CODE		72
482 
483 /* Opcodes 73 to 78 */
484 #define INST_STR_EQ			73
485 #define INST_STR_NEQ			74
486 #define INST_STR_CMP			75
487 #define INST_STR_LEN			76
488 #define INST_STR_INDEX			77
489 #define INST_STR_MATCH			78
490 
491 /* Opcodes 78 to 81 */
492 #define INST_LIST			79
493 #define INST_LIST_INDEX			80
494 #define INST_LIST_LENGTH		81
495 
496 /* Opcodes 82 to 87 */
497 #define INST_APPEND_SCALAR1		82
498 #define INST_APPEND_SCALAR4		83
499 #define INST_APPEND_ARRAY1		84
500 #define INST_APPEND_ARRAY4		85
501 #define INST_APPEND_ARRAY_STK		86
502 #define INST_APPEND_STK			87
503 
504 /* Opcodes 88 to 93 */
505 #define INST_LAPPEND_SCALAR1		88
506 #define INST_LAPPEND_SCALAR4		89
507 #define INST_LAPPEND_ARRAY1		90
508 #define INST_LAPPEND_ARRAY4		91
509 #define INST_LAPPEND_ARRAY_STK		92
510 #define INST_LAPPEND_STK		93
511 
512 /* TIP #22 - LINDEX operator with flat arg list */
513 
514 #define INST_LIST_INDEX_MULTI		94
515 
516 /*
517  * TIP #33 - 'lset' command.  Code gen also required a Forth-like
518  *           OVER operation.
519  */
520 
521 #define INST_OVER                       95
522 #define INST_LSET_LIST			96
523 #define INST_LSET_FLAT                  97
524 
525 /* The last opcode */
526 #define LAST_INST_OPCODE        	97
527 
528 /*
529  * Table describing the Tcl bytecode instructions: their name (for
530  * displaying code), total number of code bytes required (including
531  * operand bytes), and a description of the type of each operand.
532  * These operand types include signed and unsigned integers of length
533  * one and four bytes. The unsigned integers are used for indexes or
534  * for, e.g., the count of objects to push in a "push" instruction.
535  */
536 
537 #define MAX_INSTRUCTION_OPERANDS 2
538 
539 typedef enum InstOperandType {
540     OPERAND_NONE,
541     OPERAND_INT1,		/* One byte signed integer. */
542     OPERAND_INT4,		/* Four byte signed integer. */
543     OPERAND_UINT1,		/* One byte unsigned integer. */
544     OPERAND_UINT4		/* Four byte unsigned integer. */
545 } InstOperandType;
546 
547 typedef struct InstructionDesc {
548     char *name;			/* Name of instruction. */
549     int numBytes;		/* Total number of bytes for instruction. */
550     int stackEffect;            /* The worst-case balance stack effect of the
551 				 * instruction, used for stack requirements
552 				 * computations. The value INT_MIN signals
553 				 * that the instruction's worst case effect
554 				 * is (1-opnd1).
555 				 */
556     int numOperands;		/* Number of operands. */
557     InstOperandType opTypes[MAX_INSTRUCTION_OPERANDS];
558 				/* The type of each operand. */
559 } InstructionDesc;
560 
561 extern InstructionDesc tclInstructionTable[];
562 
563 /*
564  * Definitions of the values of the INST_CALL_BUILTIN_FUNC instruction's
565  * operand byte. Each value denotes a builtin Tcl math function. These
566  * values must correspond to the entries in the tclBuiltinFuncTable array
567  * below and to the values stored in the tclInt.h MathFunc structure's
568  * builtinFuncIndex field.
569  */
570 
571 #define BUILTIN_FUNC_ACOS		0
572 #define BUILTIN_FUNC_ASIN		1
573 #define BUILTIN_FUNC_ATAN		2
574 #define BUILTIN_FUNC_ATAN2		3
575 #define BUILTIN_FUNC_CEIL		4
576 #define BUILTIN_FUNC_COS		5
577 #define BUILTIN_FUNC_COSH		6
578 #define BUILTIN_FUNC_EXP		7
579 #define BUILTIN_FUNC_FLOOR		8
580 #define BUILTIN_FUNC_FMOD		9
581 #define BUILTIN_FUNC_HYPOT		10
582 #define BUILTIN_FUNC_LOG		11
583 #define BUILTIN_FUNC_LOG10		12
584 #define BUILTIN_FUNC_POW		13
585 #define BUILTIN_FUNC_SIN		14
586 #define BUILTIN_FUNC_SINH		15
587 #define BUILTIN_FUNC_SQRT		16
588 #define BUILTIN_FUNC_TAN		17
589 #define BUILTIN_FUNC_TANH		18
590 #define BUILTIN_FUNC_ABS		19
591 #define BUILTIN_FUNC_DOUBLE		20
592 #define BUILTIN_FUNC_INT		21
593 #define BUILTIN_FUNC_RAND		22
594 #define BUILTIN_FUNC_ROUND		23
595 #define BUILTIN_FUNC_SRAND		24
596 #define BUILTIN_FUNC_WIDE		25
597 
598 #define LAST_BUILTIN_FUNC        	25
599 
600 /*
601  * Table describing the built-in math functions. Entries in this table are
602  * indexed by the values of the INST_CALL_BUILTIN_FUNC instruction's
603  * operand byte.
604  */
605 
606 typedef int (CallBuiltinFuncProc) _ANSI_ARGS_((Tcl_Interp *interp,
607         ExecEnv *eePtr, ClientData clientData));
608 
609 typedef struct {
610     char *name;			/* Name of function. */
611     int numArgs;		/* Number of arguments for function. */
612     Tcl_ValueType argTypes[MAX_MATH_ARGS];
613 				/* Acceptable types for each argument. */
614     CallBuiltinFuncProc *proc;	/* Procedure implementing this function. */
615     ClientData clientData;	/* Additional argument to pass to the
616 				 * function when invoking it. */
617 } BuiltinFunc;
618 
619 extern BuiltinFunc tclBuiltinFuncTable[];
620 
621 /*
622  * Compilation of some Tcl constructs such as if commands and the logical or
623  * (||) and logical and (&&) operators in expressions requires the
624  * generation of forward jumps. Since the PC target of these jumps isn't
625  * known when the jumps are emitted, we record the offset of each jump in an
626  * array of JumpFixup structures. There is one array for each sequence of
627  * jumps to one target PC. When we learn the target PC, we update the jumps
628  * with the correct distance. Also, if the distance is too great (> 127
629  * bytes), we replace the single-byte jump with a four byte jump
630  * instruction, move the instructions after the jump down, and update the
631  * code offsets for any commands between the jump and the target.
632  */
633 
634 typedef enum {
635     TCL_UNCONDITIONAL_JUMP,
636     TCL_TRUE_JUMP,
637     TCL_FALSE_JUMP
638 } TclJumpType;
639 
640 typedef struct JumpFixup {
641     TclJumpType jumpType;	/* Indicates the kind of jump. */
642     int codeOffset;		/* Offset of the first byte of the one-byte
643 				 * forward jump's code. */
644     int cmdIndex;		/* Index of the first command after the one
645 				 * for which the jump was emitted. Used to
646 				 * update the code offsets for subsequent
647 				 * commands if the two-byte jump at jumpPc
648 				 * must be replaced with a five-byte one. */
649     int exceptIndex;		/* Index of the first range entry in the
650 				 * ExceptionRange array after the current
651 				 * one. This field is used to adjust the
652 				 * code offsets in subsequent ExceptionRange
653 				 * records when a jump is grown from 2 bytes
654 				 * to 5 bytes. */
655 } JumpFixup;
656 
657 #define JUMPFIXUP_INIT_ENTRIES    10
658 
659 typedef struct JumpFixupArray {
660     JumpFixup *fixup;		/* Points to start of jump fixup array. */
661     int next;			/* Index of next free array entry. */
662     int end;			/* Index of last usable entry in array. */
663     int mallocedArray;		/* 1 if array was expanded and fixups points
664 				 * into the heap, else 0. */
665     JumpFixup staticFixupSpace[JUMPFIXUP_INIT_ENTRIES];
666 				/* Initial storage for jump fixup array. */
667 } JumpFixupArray;
668 
669 /*
670  * The structure describing one variable list of a foreach command. Note
671  * that only foreach commands inside procedure bodies are compiled inline so
672  * a ForeachVarList structure always describes local variables. Furthermore,
673  * only scalar variables are supported for inline-compiled foreach loops.
674  */
675 
676 typedef struct ForeachVarList {
677     int numVars;		/* The number of variables in the list. */
678     int varIndexes[1];		/* An array of the indexes ("slot numbers")
679 				 * for each variable in the procedure's
680 				 * array of local variables. Only scalar
681 				 * variables are supported. The actual
682 				 * size of this field will be large enough
683 				 * to numVars indexes. THIS MUST BE THE
684 				 * LAST FIELD IN THE STRUCTURE! */
685 } ForeachVarList;
686 
687 /*
688  * Structure used to hold information about a foreach command that is needed
689  * during program execution. These structures are stored in CompileEnv and
690  * ByteCode structures as auxiliary data.
691  */
692 
693 typedef struct ForeachInfo {
694     int numLists;		/* The number of both the variable and value
695 				 * lists of the foreach command. */
696     int firstValueTemp;		/* Index of the first temp var in a proc
697 				 * frame used to point to a value list. */
698     int loopCtTemp;		/* Index of temp var in a proc frame
699 				 * holding the loop's iteration count. Used
700 				 * to determine next value list element to
701 				 * assign each loop var. */
702     ForeachVarList *varLists[1];/* An array of pointers to ForeachVarList
703 				 * structures describing each var list. The
704 				 * actual size of this field will be large
705 				 * enough to numVars indexes. THIS MUST BE
706 				 * THE LAST FIELD IN THE STRUCTURE! */
707 } ForeachInfo;
708 
709 extern AuxDataType		tclForeachInfoType;
710 
711 
712 /*
713  *----------------------------------------------------------------
714  * Procedures exported by tclBasic.c to be used within the engine.
715  *----------------------------------------------------------------
716  */
717 
718 EXTERN int		TclEvalObjvInternal _ANSI_ARGS_((Tcl_Interp *interp, int objc,
719 			    Tcl_Obj *CONST objv[], CONST char *command, int length,
720 			    int flags));
721 EXTERN int              TclInterpReady _ANSI_ARGS_((Tcl_Interp *interp));
722 
723 
724 /*
725  *----------------------------------------------------------------
726  * Procedures exported by the engine to be used by tclBasic.c
727  *----------------------------------------------------------------
728  */
729 
730 EXTERN int		TclCompEvalObj _ANSI_ARGS_((Tcl_Interp *interp,
731 			    Tcl_Obj *objPtr));
732 
733 /*
734  *----------------------------------------------------------------
735  * Procedures shared among Tcl bytecode compilation and execution
736  * modules but not used outside:
737  *----------------------------------------------------------------
738  */
739 
740 EXTERN void		TclCleanupByteCode _ANSI_ARGS_((ByteCode *codePtr));
741 EXTERN int		TclCompileCmdWord _ANSI_ARGS_((Tcl_Interp *interp,
742 			    Tcl_Token *tokenPtr, int count,
743 			    CompileEnv *envPtr));
744 EXTERN int		TclCompileExpr _ANSI_ARGS_((Tcl_Interp *interp,
745 			    CONST char *script, int numBytes,
746 			    CompileEnv *envPtr));
747 EXTERN int		TclCompileExprWords _ANSI_ARGS_((Tcl_Interp *interp,
748 			    Tcl_Token *tokenPtr, int numWords,
749 			    CompileEnv *envPtr));
750 EXTERN int		TclCompileScript _ANSI_ARGS_((Tcl_Interp *interp,
751 			    CONST char *script, int numBytes, int nested,
752 			    CompileEnv *envPtr));
753 EXTERN int		TclCompileTokens _ANSI_ARGS_((Tcl_Interp *interp,
754 			    Tcl_Token *tokenPtr, int count,
755 			    CompileEnv *envPtr));
756 EXTERN int		TclCreateAuxData _ANSI_ARGS_((ClientData clientData,
757 			    AuxDataType *typePtr, CompileEnv *envPtr));
758 EXTERN int		TclCreateExceptRange _ANSI_ARGS_((
759 			    ExceptionRangeType type, CompileEnv *envPtr));
760 EXTERN ExecEnv *	TclCreateExecEnv _ANSI_ARGS_((Tcl_Interp *interp));
761 EXTERN void		TclDeleteExecEnv _ANSI_ARGS_((ExecEnv *eePtr));
762 EXTERN void		TclDeleteLiteralTable _ANSI_ARGS_((
763 			    Tcl_Interp *interp, LiteralTable *tablePtr));
764 EXTERN void		TclEmitForwardJump _ANSI_ARGS_((CompileEnv *envPtr,
765 			    TclJumpType jumpType, JumpFixup *jumpFixupPtr));
766 EXTERN ExceptionRange *	TclGetExceptionRangeForPc _ANSI_ARGS_((
767 			    unsigned char *pc, int catchOnly,
768 			    ByteCode* codePtr));
769 EXTERN void		TclExpandJumpFixupArray _ANSI_ARGS_((
770                             JumpFixupArray *fixupArrayPtr));
771 EXTERN void		TclFinalizeAuxDataTypeTable _ANSI_ARGS_((void));
772 EXTERN int		TclFindCompiledLocal _ANSI_ARGS_((CONST char *name,
773         		    int nameChars, int create, int flags,
774 			    Proc *procPtr));
775 EXTERN LiteralEntry *	TclLookupLiteralEntry _ANSI_ARGS_((
776 			    Tcl_Interp *interp, Tcl_Obj *objPtr));
777 EXTERN int		TclFixupForwardJump _ANSI_ARGS_((
778 			    CompileEnv *envPtr, JumpFixup *jumpFixupPtr,
779 			    int jumpDist, int distThreshold));
780 EXTERN void		TclFreeCompileEnv _ANSI_ARGS_((CompileEnv *envPtr));
781 EXTERN void		TclFreeJumpFixupArray _ANSI_ARGS_((
782   			    JumpFixupArray *fixupArrayPtr));
783 EXTERN void		TclInitAuxDataTypeTable _ANSI_ARGS_((void));
784 EXTERN void		TclInitByteCodeObj _ANSI_ARGS_((Tcl_Obj *objPtr,
785 			    CompileEnv *envPtr));
786 EXTERN void		TclInitCompilation _ANSI_ARGS_((void));
787 EXTERN void		TclInitCompileEnv _ANSI_ARGS_((Tcl_Interp *interp,
788 			    CompileEnv *envPtr, char *string,
789 			    int numBytes));
790 EXTERN void		TclInitJumpFixupArray _ANSI_ARGS_((
791 			    JumpFixupArray *fixupArrayPtr));
792 EXTERN void		TclInitLiteralTable _ANSI_ARGS_((
793 			    LiteralTable *tablePtr));
794 #ifdef TCL_COMPILE_STATS
795 EXTERN char *		TclLiteralStats _ANSI_ARGS_((
796 			    LiteralTable *tablePtr));
797 EXTERN int		TclLog2 _ANSI_ARGS_((int value));
798 #endif
799 #ifdef TCL_COMPILE_DEBUG
800 EXTERN void		TclPrintByteCodeObj _ANSI_ARGS_((Tcl_Interp *interp,
801 		            Tcl_Obj *objPtr));
802 #endif
803 EXTERN int		TclPrintInstruction _ANSI_ARGS_((ByteCode* codePtr,
804 			    unsigned char *pc));
805 EXTERN void		TclPrintObject _ANSI_ARGS_((FILE *outFile,
806 			    Tcl_Obj *objPtr, int maxChars));
807 EXTERN void		TclPrintSource _ANSI_ARGS_((FILE *outFile,
808 			    CONST char *string, int maxChars));
809 EXTERN void		TclRegisterAuxDataType _ANSI_ARGS_((AuxDataType *typePtr));
810 EXTERN int		TclRegisterLiteral _ANSI_ARGS_((CompileEnv *envPtr,
811 			    char *bytes, int length, int onHeap));
812 EXTERN void		TclReleaseLiteral _ANSI_ARGS_((Tcl_Interp *interp,
813 			    Tcl_Obj *objPtr));
814 EXTERN void		TclSetCmdNameObj _ANSI_ARGS_((Tcl_Interp *interp,
815 			    Tcl_Obj *objPtr, Command *cmdPtr));
816 #ifdef TCL_COMPILE_DEBUG
817 EXTERN void		TclVerifyGlobalLiteralTable _ANSI_ARGS_((
818 			    Interp *iPtr));
819 EXTERN void		TclVerifyLocalLiteralTable _ANSI_ARGS_((
820 			    CompileEnv *envPtr));
821 #endif
822 EXTERN int		TclCompileVariableCmd _ANSI_ARGS_((
823 			    Tcl_Interp *interp, Tcl_Parse *parsePtr, CompileEnv *envPtr));
824 
825 /*
826  *----------------------------------------------------------------
827  * Macros used by Tcl bytecode compilation and execution modules
828  * inside the Tcl core but not used outside.
829  *----------------------------------------------------------------
830  */
831 
832 /*
833  * Form of TclRegisterLiteral with onHeap == 0.
834  * In that case, it is safe to cast away CONSTness, and it
835  * is cleanest to do that here, all in one place.
836  */
837 
838 #define TclRegisterNewLiteral(envPtr, bytes, length) \
839 	TclRegisterLiteral(envPtr, (char *)(bytes), length, /*onHeap*/ 0)
840 
841 /*
842  * Macro used to update the stack requirements.
843  * It is called by the macros TclEmitOpCode, TclEmitInst1 and
844  * TclEmitInst4.
845  * Remark that the very last instruction of a bytecode always
846  * reduces the stack level: INST_DONE or INST_POP, so that the
847  * maxStackdepth is always updated.
848  */
849 
850 #define TclUpdateStackReqs(op, i, envPtr) \
851     {\
852 	int delta = tclInstructionTable[(op)].stackEffect;\
853 	if (delta) {\
854 	    if (delta < 0) {\
855 		if((envPtr)->maxStackDepth < (envPtr)->currStackDepth) {\
856 		    (envPtr)->maxStackDepth = (envPtr)->currStackDepth;\
857 		}\
858 		if (delta == INT_MIN) {\
859 		    delta = 1 - (i);\
860 		}\
861 	    }\
862 	    (envPtr)->currStackDepth += delta;\
863 	}\
864     }
865 
866 /*
867  * Macro to emit an opcode byte into a CompileEnv's code array.
868  * The ANSI C "prototype" for this macro is:
869  *
870  * EXTERN void	TclEmitOpcode _ANSI_ARGS_((unsigned char op,
871  *		    CompileEnv *envPtr));
872  */
873 
874 #define TclEmitOpcode(op, envPtr) \
875     if ((envPtr)->codeNext == (envPtr)->codeEnd) \
876         TclExpandCodeArray(envPtr); \
877     *(envPtr)->codeNext++ = (unsigned char) (op);\
878     TclUpdateStackReqs(op, 0, envPtr)
879 
880 /*
881  * Macro to emit an integer operand.
882  * The ANSI C "prototype" for this macro is:
883  *
884  * EXTERN void	TclEmitInt1 _ANSI_ARGS_((int i, CompileEnv *envPtr));
885  */
886 
887 #define TclEmitInt1(i, envPtr) \
888     if ((envPtr)->codeNext == (envPtr)->codeEnd) \
889         TclExpandCodeArray(envPtr); \
890     *(envPtr)->codeNext++ = (unsigned char) ((unsigned int) (i))
891 
892 /*
893  * Macros to emit an instruction with signed or unsigned integer operands.
894  * Four byte integers are stored in "big-endian" order with the high order
895  * byte stored at the lowest address.
896  * The ANSI C "prototypes" for these macros are:
897  *
898  * EXTERN void	TclEmitInstInt1 _ANSI_ARGS_((unsigned char op, int i,
899  *		    CompileEnv *envPtr));
900  * EXTERN void	TclEmitInstInt4 _ANSI_ARGS_((unsigned char op, int i,
901  *		    CompileEnv *envPtr));
902  */
903 
904 
905 #define TclEmitInstInt1(op, i, envPtr) \
906     if (((envPtr)->codeNext + 2) > (envPtr)->codeEnd) { \
907         TclExpandCodeArray(envPtr); \
908     } \
909     *(envPtr)->codeNext++ = (unsigned char) (op); \
910     *(envPtr)->codeNext++ = (unsigned char) ((unsigned int) (i));\
911     TclUpdateStackReqs(op, i, envPtr)
912 
913 #define TclEmitInstInt4(op, i, envPtr) \
914     if (((envPtr)->codeNext + 5) > (envPtr)->codeEnd) { \
915         TclExpandCodeArray(envPtr); \
916     } \
917     *(envPtr)->codeNext++ = (unsigned char) (op); \
918     *(envPtr)->codeNext++ = \
919         (unsigned char) ((unsigned int) (i) >> 24); \
920     *(envPtr)->codeNext++ = \
921         (unsigned char) ((unsigned int) (i) >> 16); \
922     *(envPtr)->codeNext++ = \
923         (unsigned char) ((unsigned int) (i) >>  8); \
924     *(envPtr)->codeNext++ = \
925         (unsigned char) ((unsigned int) (i)      );\
926     TclUpdateStackReqs(op, i, envPtr)
927 
928 /*
929  * Macro to push a Tcl object onto the Tcl evaluation stack. It emits the
930  * object's one or four byte array index into the CompileEnv's code
931  * array. These support, respectively, a maximum of 256 (2**8) and 2**32
932  * objects in a CompileEnv. The ANSI C "prototype" for this macro is:
933  *
934  * EXTERN void	TclEmitPush _ANSI_ARGS_((int objIndex, CompileEnv *envPtr));
935  */
936 
937 #define TclEmitPush(objIndex, envPtr) \
938     {\
939         register int objIndexCopy = (objIndex);\
940         if (objIndexCopy <= 255) { \
941 	    TclEmitInstInt1(INST_PUSH1, objIndexCopy, (envPtr)); \
942         } else { \
943 	    TclEmitInstInt4(INST_PUSH4, objIndexCopy, (envPtr)); \
944 	}\
945     }
946 
947 /*
948  * Macros to update a (signed or unsigned) integer starting at a pointer.
949  * The two variants depend on the number of bytes. The ANSI C "prototypes"
950  * for these macros are:
951  *
952  * EXTERN void	TclStoreInt1AtPtr _ANSI_ARGS_((int i, unsigned char *p));
953  * EXTERN void	TclStoreInt4AtPtr _ANSI_ARGS_((int i, unsigned char *p));
954  */
955 
956 #define TclStoreInt1AtPtr(i, p) \
957     *(p)   = (unsigned char) ((unsigned int) (i))
958 
959 #define TclStoreInt4AtPtr(i, p) \
960     *(p)   = (unsigned char) ((unsigned int) (i) >> 24); \
961     *(p+1) = (unsigned char) ((unsigned int) (i) >> 16); \
962     *(p+2) = (unsigned char) ((unsigned int) (i) >>  8); \
963     *(p+3) = (unsigned char) ((unsigned int) (i)      )
964 
965 /*
966  * Macros to update instructions at a particular pc with a new op code
967  * and a (signed or unsigned) int operand. The ANSI C "prototypes" for
968  * these macros are:
969  *
970  * EXTERN void	TclUpdateInstInt1AtPc _ANSI_ARGS_((unsigned char op, int i,
971  *		    unsigned char *pc));
972  * EXTERN void	TclUpdateInstInt4AtPc _ANSI_ARGS_((unsigned char op, int i,
973  *		    unsigned char *pc));
974  */
975 
976 #define TclUpdateInstInt1AtPc(op, i, pc) \
977     *(pc) = (unsigned char) (op); \
978     TclStoreInt1AtPtr((i), ((pc)+1))
979 
980 #define TclUpdateInstInt4AtPc(op, i, pc) \
981     *(pc) = (unsigned char) (op); \
982     TclStoreInt4AtPtr((i), ((pc)+1))
983 
984 /*
985  * Macros to get a signed integer (GET_INT{1,2}) or an unsigned int
986  * (GET_UINT{1,2}) from a pointer. There are two variants for each
987  * return type that depend on the number of bytes fetched.
988  * The ANSI C "prototypes" for these macros are:
989  *
990  * EXTERN int	        TclGetInt1AtPtr  _ANSI_ARGS_((unsigned char *p));
991  * EXTERN int	        TclGetInt4AtPtr  _ANSI_ARGS_((unsigned char *p));
992  * EXTERN unsigned int	TclGetUInt1AtPtr _ANSI_ARGS_((unsigned char *p));
993  * EXTERN unsigned int	TclGetUInt4AtPtr _ANSI_ARGS_((unsigned char *p));
994  */
995 
996 /*
997  * The TclGetInt1AtPtr macro is tricky because we want to do sign
998  * extension on the 1-byte value. Unfortunately the "char" type isn't
999  * signed on all platforms so sign-extension doesn't always happen
1000  * automatically. Sometimes we can explicitly declare the pointer to be
1001  * signed, but other times we have to explicitly sign-extend the value
1002  * in software.
1003  */
1004 
1005 #ifndef __CHAR_UNSIGNED__
1006 #   define TclGetInt1AtPtr(p) ((int) *((char *) p))
1007 #else
1008 #   ifdef HAVE_SIGNED_CHAR
1009 #	define TclGetInt1AtPtr(p) ((int) *((signed char *) p))
1010 #    else
1011 #	define TclGetInt1AtPtr(p) (((int) *((char *) p)) \
1012 		| ((*(p) & 0200) ? (-256) : 0))
1013 #    endif
1014 #endif
1015 
1016 #define TclGetInt4AtPtr(p) (((int) TclGetInt1AtPtr(p) << 24) | \
1017 		                  	    (*((p)+1) << 16) | \
1018 				  	    (*((p)+2) <<  8) | \
1019 				  	    (*((p)+3)))
1020 
1021 #define TclGetUInt1AtPtr(p) ((unsigned int) *(p))
1022 #define TclGetUInt4AtPtr(p) ((unsigned int) (*(p)     << 24) | \
1023 		                            (*((p)+1) << 16) | \
1024 				            (*((p)+2) <<  8) | \
1025 				            (*((p)+3)))
1026 
1027 /*
1028  * Macros used to compute the minimum and maximum of two integers.
1029  * The ANSI C "prototypes" for these macros are:
1030  *
1031  * EXTERN int  TclMin _ANSI_ARGS_((int i, int j));
1032  * EXTERN int  TclMax _ANSI_ARGS_((int i, int j));
1033  */
1034 
1035 #define TclMin(i, j)   ((((int) i) < ((int) j))? (i) : (j))
1036 #define TclMax(i, j)   ((((int) i) > ((int) j))? (i) : (j))
1037 
1038 # undef TCL_STORAGE_CLASS
1039 # define TCL_STORAGE_CLASS DLLIMPORT
1040 
1041 #endif /* _TCLCOMPILATION */
1042 
1043 
1044 
1045 
1046 
1047