Debian Codegraph @

pTk/mTk/tclGeneric/tclCompExpr.c

raw symbols SCIP
1 /*
2 * tclCompExpr.c --
3 *
4 * This file contains the code to compile Tcl expressions.
5 *
6 * Copyright (c) 1997 Sun Microsystems, Inc.
7 * Copyright (c) 1998-2000 by Scriptics Corporation.
8 *
9 * See the file "license.terms" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 *
12 * RCS: @(#) $Id: tclCompExpr.c,v 1.13 2003/02/16 01:36:32 msofer Exp $
13 */
14
15 #include "tclInt.h"
16 #include "tclCompile.h"
17
18 /*
19 * The stuff below is a bit of a hack so that this file can be used in
20 * environments that include no UNIX, i.e. no errno: just arrange to use
21 * the errno from tclExecute.c here.
22 */
23
24 #ifndef TCL_GENERIC_ONLY
25 #include "tclPort.h"
26 #else
27 #define NO_ERRNO_H
28 #endif
29
30 #ifdef NO_ERRNO_H
31 extern int errno; /* Use errno from tclExecute.c. */
32 #define ERANGE 34
33 #endif
34
35 /*
36 * Boolean variable that controls whether expression compilation tracing
37 * is enabled.
38 */
39
40 #ifdef TCL_COMPILE_DEBUG
41 static int traceExprComp = 0;
42 #endif /* TCL_COMPILE_DEBUG */
43
44 /*
45 * The ExprInfo structure describes the state of compiling an expression.
46 * A pointer to an ExprInfo record is passed among the routines in
47 * this module.
48 */
49
50 typedef struct ExprInfo {
51 Tcl_Interp *interp; /* Used for error reporting. */
52 Tcl_Parse *parsePtr; /* Structure filled with information about
53 * the parsed expression. */
54 CONST char *expr; /* The expression that was originally passed
55 * to TclCompileExpr. */
56 CONST char *lastChar; /* Points just after last byte of expr. */
57 int hasOperators; /* Set 1 if the expr has operators; 0 if
58 * expr is only a primary. If 1 after
59 * compiling an expr, a tryCvtToNumeric
60 * instruction is emitted to convert the
61 * primary to a number if possible. */
62 } ExprInfo;
63
64 /*
65 * Definitions of numeric codes representing each expression operator.
66 * The order of these must match the entries in the operatorTable below.
67 * Also the codes for the relational operators (OP_LESS, OP_GREATER,
68 * OP_LE, OP_GE, OP_EQ, and OP_NE) must be consecutive and in that order.
69 * Note that OP_PLUS and OP_MINUS represent both unary and binary operators.
70 */
71
72 #define OP_MULT 0
73 #define OP_DIVIDE 1
74 #define OP_MOD 2
75 #define OP_PLUS 3
76 #define OP_MINUS 4
77 #define OP_LSHIFT 5
78 #define OP_RSHIFT 6
79 #define OP_LESS 7
80 #define OP_GREATER 8
81 #define OP_LE 9
82 #define OP_GE 10
83 #define OP_EQ 11
84 #define OP_NEQ 12
85 #define OP_BITAND 13
86 #define OP_BITXOR 14
87 #define OP_BITOR 15
88 #define OP_LAND 16
89 #define OP_LOR 17
90 #define OP_QUESTY 18
91 #define OP_LNOT 19
92 #define OP_BITNOT 20
93 #define OP_STREQ 21
94 #define OP_STRNEQ 22
95
96 /*
97 * Table describing the expression operators. Entries in this table must
98 * correspond to the definitions of numeric codes for operators just above.
99 */
100
101 static int opTableInitialized = 0; /* 0 means not yet initialized. */
102
103 TCL_DECLARE_MUTEX(opMutex)
104
105 typedef struct OperatorDesc {
106 char *name; /* Name of the operator. */
107 int numOperands; /* Number of operands. 0 if the operator
108 * requires special handling. */
109 int instruction; /* Instruction opcode for the operator.
110 * Ignored if numOperands is 0. */
111 } OperatorDesc;
112
113 static OperatorDesc operatorTable[] = {
114 {"*", 2, INST_MULT},
115 {"/", 2, INST_DIV},
116 {"%", 2, INST_MOD},
117 {"+", 0},
118 {"-", 0},
119 {"<<", 2, INST_LSHIFT},
120 {">>", 2, INST_RSHIFT},
121 {"<", 2, INST_LT},
122 {">", 2, INST_GT},
123 {"<=", 2, INST_LE},
124 {">=", 2, INST_GE},
125 {"==", 2, INST_EQ},
126 {"!=", 2, INST_NEQ},
127 {"&", 2, INST_BITAND},
128 {"^", 2, INST_BITXOR},
129 {"|", 2, INST_BITOR},
130 {"&&", 0},
131 {"||", 0},
132 {"?", 0},
133 {"!", 1, INST_LNOT},
134 {"~", 1, INST_BITNOT},
135 {"eq", 2, INST_STR_EQ},
136 {"ne", 2, INST_STR_NEQ},
137 {NULL}
138 };
139
140 /*
141 * Hashtable used to map the names of expression operators to the index
142 * of their OperatorDesc description.
143 */
144
145 static Tcl_HashTable opHashTable;
146
147 /*
148 * Declarations for local procedures to this file:
149 */
150
151 static int CompileCondExpr _ANSI_ARGS_((
152 Tcl_Token *exprTokenPtr, ExprInfo *infoPtr,
153 CompileEnv *envPtr, Tcl_Token **endPtrPtr));
154 static int CompileLandOrLorExpr _ANSI_ARGS_((
155 Tcl_Token *exprTokenPtr, int opIndex,
156 ExprInfo *infoPtr, CompileEnv *envPtr,
157 Tcl_Token **endPtrPtr));
158 static int CompileMathFuncCall _ANSI_ARGS_((
159 Tcl_Token *exprTokenPtr, CONST char *funcName,
160 ExprInfo *infoPtr, CompileEnv *envPtr,
161 Tcl_Token **endPtrPtr));
162 static int CompileSubExpr _ANSI_ARGS_((
163 Tcl_Token *exprTokenPtr, ExprInfo *infoPtr,
164 CompileEnv *envPtr));
165 static void LogSyntaxError _ANSI_ARGS_((ExprInfo *infoPtr));
166
167 /*
168 * Macro used to debug the execution of the expression compiler.
169 */
170
171 #ifdef TCL_COMPILE_DEBUG
172 #define TRACE(exprBytes, exprLength, tokenBytes, tokenLength) \
173 if (traceExprComp) { \
174 fprintf(stderr, "CompileSubExpr: \"%.*s\", token \"%.*s\"\n", \
175 (exprLength), (exprBytes), (tokenLength), (tokenBytes)); \
176 }
177 #else
178 #define TRACE(exprBytes, exprLength, tokenBytes, tokenLength)
179 #endif /* TCL_COMPILE_DEBUG */
180
181 /*
182 *----------------------------------------------------------------------
183 *
184 * TclCompileExpr --
185 *
186 * This procedure compiles a string containing a Tcl expression into
187 * Tcl bytecodes. This procedure is the top-level interface to the
188 * the expression compilation module, and is used by such public
189 * procedures as Tcl_ExprString, Tcl_ExprStringObj, Tcl_ExprLong,
190 * Tcl_ExprDouble, Tcl_ExprBoolean, and Tcl_ExprBooleanObj.
191 *
192 * Results:
193 * The return value is TCL_OK on a successful compilation and TCL_ERROR
194 * on failure. If TCL_ERROR is returned, then the interpreter's result
195 * contains an error message.
196 *
197 * Side effects:
198 * Adds instructions to envPtr to evaluate the expression at runtime.
199 *
200 *----------------------------------------------------------------------
201 */
202
203 int
204 TclCompileExpr(interp, script, numBytes, envPtr)
205 Tcl_Interp *interp; /* Used for error reporting. */
206 CONST char *script; /* The source script to compile. */
207 int numBytes; /* Number of bytes in script. If < 0, the
208 * string consists of all bytes up to the
209 * first null character. */
210 CompileEnv *envPtr; /* Holds resulting instructions. */
211 {
212 ExprInfo info;
213 Tcl_Parse parse;
214 Tcl_HashEntry *hPtr;
215 int new, i, code;
216
217 /*
218 * If this is the first time we've been called, initialize the table
219 * of expression operators.
220 */
221
222 if (numBytes < 0) {
223 numBytes = (script? strlen(script) : 0);
224 }
225 if (!opTableInitialized) {
226 Tcl_MutexLock(&opMutex);
227 if (!opTableInitialized) {
228 Tcl_InitHashTable(&opHashTable, TCL_STRING_KEYS);
229 for (i = 0; operatorTable[i].name != NULL; i++) {
230 hPtr = Tcl_CreateHashEntry(&opHashTable,
231 operatorTable[i].name, &new);
232 if (new) {
233 Tcl_SetHashValue(hPtr, (ClientData) i);
234 }
235 }
236 opTableInitialized = 1;
237 }
238 Tcl_MutexUnlock(&opMutex);
239 }
240
241 /*
242 * Initialize the structure containing information abvout this
243 * expression compilation.
244 */
245
246 info.interp = interp;
247 info.parsePtr = &parse;
248 info.expr = script;
249 info.lastChar = (script + numBytes);
250 info.hasOperators = 0;
251
252 /*
253 * Parse the expression then compile it.
254 */
255
256 code = Tcl_ParseExpr(interp, script, numBytes, &parse);
257 if (code != TCL_OK) {
258 goto done;
259 }
260
261 code = CompileSubExpr(parse.tokenPtr, &info, envPtr);
262 if (code != TCL_OK) {
263 Tcl_FreeParse(&parse);
264 goto done;
265 }
266
267 if (!info.hasOperators) {
268 /*
269 * Attempt to convert the primary's object to an int or double.
270 * This is done in order to support Tcl's policy of interpreting
271 * operands if at all possible as first integers, else
272 * floating-point numbers.
273 */
274
275 TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr);
276 }
277 Tcl_FreeParse(&parse);
278
279 done:
280 return code;
281 }
282
283 /*
284 *----------------------------------------------------------------------
285 *
286 * TclFinalizeCompilation --
287 *
288 * Clean up the compilation environment so it can later be
289 * properly reinitialized. This procedure is called by
290 * TclFinalizeCompExecEnv() in tclObj.c, which in turn is called
291 * by Tcl_Finalize().
292 *
293 * Results:
294 * None.
295 *
296 * Side effects:
297 * Cleans up the compilation environment. At the moment, just the
298 * table of expression operators is freed.
299 *
300 *----------------------------------------------------------------------
301 */
302
303 void
304 TclFinalizeCompilation()
305 {
306 Tcl_MutexLock(&opMutex);
307 if (opTableInitialized) {
308 Tcl_DeleteHashTable(&opHashTable);
309 opTableInitialized = 0;
310 }
311 Tcl_MutexUnlock(&opMutex);
312 }
313
314 /*
315 *----------------------------------------------------------------------
316 *
317 * CompileSubExpr --
318 *
319 * Given a pointer to a TCL_TOKEN_SUB_EXPR token describing a
320 * subexpression, this procedure emits instructions to evaluate the
321 * subexpression at runtime.
322 *
323 * Results:
324 * The return value is TCL_OK on a successful compilation and TCL_ERROR
325 * on failure. If TCL_ERROR is returned, then the interpreter's result
326 * contains an error message.
327 *
328 * Side effects:
329 * Adds instructions to envPtr to evaluate the subexpression.
330 *
331 *----------------------------------------------------------------------
332 */
333
334 static int
335 CompileSubExpr(exprTokenPtr, infoPtr, envPtr)
336 Tcl_Token *exprTokenPtr; /* Points to TCL_TOKEN_SUB_EXPR token
337 * to compile. */
338 ExprInfo *infoPtr; /* Describes the compilation state for the
339 * expression being compiled. */
340 CompileEnv *envPtr; /* Holds resulting instructions. */
341 {
342 Tcl_Interp *interp = infoPtr->interp;
343 Tcl_Token *tokenPtr, *endPtr, *afterSubexprPtr;
344 OperatorDesc *opDescPtr;
345 Tcl_HashEntry *hPtr;
346 CONST char *operator;
347 Tcl_DString opBuf;
348 int objIndex, opIndex, length, code;
349 char buffer[TCL_UTF_MAX];
350
351 if (exprTokenPtr->type != TCL_TOKEN_SUB_EXPR) {
352 panic("CompileSubExpr: token type %d not TCL_TOKEN_SUB_EXPR\n",
353 exprTokenPtr->type);
354 }
355 code = TCL_OK;
356
357 /*
358 * Switch on the type of the first token after the subexpression token.
359 * After processing it, advance tokenPtr to point just after the
360 * subexpression's last token.
361 */
362
363 tokenPtr = exprTokenPtr+1;
364 TRACE(exprTokenPtr->start, exprTokenPtr->size,
365 tokenPtr->start, tokenPtr->size);
366 switch (tokenPtr->type) {
367 case TCL_TOKEN_WORD:
368 code = TclCompileTokens(interp, tokenPtr+1,
369 tokenPtr->numComponents, envPtr);
370 if (code != TCL_OK) {
371 goto done;
372 }
373 tokenPtr += (tokenPtr->numComponents + 1);
374 break;
375
376 case TCL_TOKEN_TEXT:
377 if (tokenPtr->size > 0) {
378 objIndex = TclRegisterNewLiteral(envPtr, tokenPtr->start,
379 tokenPtr->size);
380 } else {
381 objIndex = TclRegisterNewLiteral(envPtr, "", 0);
382 }
383 TclEmitPush(objIndex, envPtr);
384 tokenPtr += 1;
385 break;
386
387 case TCL_TOKEN_BS:
388 length = Tcl_UtfBackslash(tokenPtr->start, (int *) NULL,
389 buffer);
390 if (length > 0) {
391 objIndex = TclRegisterNewLiteral(envPtr, buffer, length);
392 } else {
393 objIndex = TclRegisterNewLiteral(envPtr, "", 0);
394 }
395 TclEmitPush(objIndex, envPtr);
396 tokenPtr += 1;
397 break;
398
399 case TCL_TOKEN_COMMAND:
400 code = TclCompileScript(interp, tokenPtr->start+1,
401 tokenPtr->size-2, /*nested*/ 0, envPtr);
402 if (code != TCL_OK) {
403 goto done;
404 }
405 tokenPtr += 1;
406 break;
407
408 case TCL_TOKEN_VARIABLE:
409 code = TclCompileTokens(interp, tokenPtr, 1, envPtr);
410 if (code != TCL_OK) {
411 goto done;
412 }
413 tokenPtr += (tokenPtr->numComponents + 1);
414 break;
415
416 case TCL_TOKEN_SUB_EXPR:
417 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
418 if (code != TCL_OK) {
419 goto done;
420 }
421 tokenPtr += (tokenPtr->numComponents + 1);
422 break;
423
424 case TCL_TOKEN_OPERATOR:
425 /*
426 * Look up the operator. If the operator isn't found, treat it
427 * as a math function.
428 */
429 Tcl_DStringInit(&opBuf);
430 operator = Tcl_DStringAppend(&opBuf,
431 tokenPtr->start, tokenPtr->size);
432 hPtr = Tcl_FindHashEntry(&opHashTable, operator);
433 if (hPtr == NULL) {
434 code = CompileMathFuncCall(exprTokenPtr, operator, infoPtr,
435 envPtr, &endPtr);
436 Tcl_DStringFree(&opBuf);
437 if (code != TCL_OK) {
438 goto done;
439 }
440 tokenPtr = endPtr;
441 break;
442 }
443 Tcl_DStringFree(&opBuf);
444 opIndex = (int) Tcl_GetHashValue(hPtr);
445 opDescPtr = &(operatorTable[opIndex]);
446
447 /*
448 * If the operator is "normal", compile it using information
449 * from the operator table.
450 */
451
452 if (opDescPtr->numOperands > 0) {
453 tokenPtr++;
454 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
455 if (code != TCL_OK) {
456 goto done;
457 }
458 tokenPtr += (tokenPtr->numComponents + 1);
459
460 if (opDescPtr->numOperands == 2) {
461 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
462 if (code != TCL_OK) {
463 goto done;
464 }
465 tokenPtr += (tokenPtr->numComponents + 1);
466 }
467 TclEmitOpcode(opDescPtr->instruction, envPtr);
468 infoPtr->hasOperators = 1;
469 break;
470 }
471
472 /*
473 * The operator requires special treatment, and is either
474 * "+" or "-", or one of "&&", "||" or "?".
475 */
476
477 switch (opIndex) {
478 case OP_PLUS:
479 case OP_MINUS:
480 tokenPtr++;
481 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
482 if (code != TCL_OK) {
483 goto done;
484 }
485 tokenPtr += (tokenPtr->numComponents + 1);
486
487 /*
488 * Check whether the "+" or "-" is unary.
489 */
490
491 afterSubexprPtr = exprTokenPtr
492 + exprTokenPtr->numComponents+1;
493 if (tokenPtr == afterSubexprPtr) {
494 TclEmitOpcode(((opIndex==OP_PLUS)?
495 INST_UPLUS : INST_UMINUS),
496 envPtr);
497 break;
498 }
499
500 /*
501 * The "+" or "-" is binary.
502 */
503
504 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
505 if (code != TCL_OK) {
506 goto done;
507 }
508 tokenPtr += (tokenPtr->numComponents + 1);
509 TclEmitOpcode(((opIndex==OP_PLUS)? INST_ADD : INST_SUB),
510 envPtr);
511 break;
512
513 case OP_LAND:
514 case OP_LOR:
515 code = CompileLandOrLorExpr(exprTokenPtr, opIndex,
516 infoPtr, envPtr, &endPtr);
517 if (code != TCL_OK) {
518 goto done;
519 }
520 tokenPtr = endPtr;
521 break;
522
523 case OP_QUESTY:
524 code = CompileCondExpr(exprTokenPtr, infoPtr,
525 envPtr, &endPtr);
526 if (code != TCL_OK) {
527 goto done;
528 }
529 tokenPtr = endPtr;
530 break;
531
532 default:
533 panic("CompileSubExpr: unexpected operator %d requiring special treatment\n",
534 opIndex);
535 } /* end switch on operator requiring special treatment */
536 infoPtr->hasOperators = 1;
537 break;
538
539 default:
540 panic("CompileSubExpr: unexpected token type %d\n",
541 tokenPtr->type);
542 }
543
544 /*
545 * Verify that the subexpression token had the required number of
546 * subtokens: that we've advanced tokenPtr just beyond the
547 * subexpression's last token. For example, a "*" subexpression must
548 * contain the tokens for exactly two operands.
549 */
550
551 if (tokenPtr != (exprTokenPtr + exprTokenPtr->numComponents+1)) {
552 LogSyntaxError(infoPtr);
553 code = TCL_ERROR;
554 }
555
556 done:
557 return code;
558 }
559
560 /*
561 *----------------------------------------------------------------------
562 *
563 * CompileLandOrLorExpr --
564 *
565 * This procedure compiles a Tcl logical and ("&&") or logical or
566 * ("||") subexpression.
567 *
568 * Results:
569 * The return value is TCL_OK on a successful compilation and TCL_ERROR
570 * on failure. If TCL_OK is returned, a pointer to the token just after
571 * the last one in the subexpression is stored at the address in
572 * endPtrPtr. If TCL_ERROR is returned, then the interpreter's result
573 * contains an error message.
574 *
575 * Side effects:
576 * Adds instructions to envPtr to evaluate the expression at runtime.
577 *
578 *----------------------------------------------------------------------
579 */
580
581 static int
582 CompileLandOrLorExpr(exprTokenPtr, opIndex, infoPtr, envPtr, endPtrPtr)
583 Tcl_Token *exprTokenPtr; /* Points to TCL_TOKEN_SUB_EXPR token
584 * containing the "&&" or "||" operator. */
585 int opIndex; /* A code describing the expression
586 * operator: either OP_LAND or OP_LOR. */
587 ExprInfo *infoPtr; /* Describes the compilation state for the
588 * expression being compiled. */
589 CompileEnv *envPtr; /* Holds resulting instructions. */
590 Tcl_Token **endPtrPtr; /* If successful, a pointer to the token
591 * just after the last token in the
592 * subexpression is stored here. */
593 {
594 JumpFixup shortCircuitFixup; /* Used to fix up the short circuit jump
595 * after the first subexpression. */
596 JumpFixup lhsTrueFixup, lhsEndFixup;
597 /* Used to fix up jumps used to convert the
598 * first operand to 0 or 1. */
599 Tcl_Token *tokenPtr;
600 int dist, code;
601 int savedStackDepth = envPtr->currStackDepth;
602
603 /*
604 * Emit code for the first operand.
605 */
606
607 tokenPtr = exprTokenPtr+2;
608 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
609 if (code != TCL_OK) {
610 goto done;
611 }
612 tokenPtr += (tokenPtr->numComponents + 1);
613
614 /*
615 * Convert the first operand to the result that Tcl requires:
616 * "0" or "1". Eventually we'll use a new instruction for this.
617 */
618
619 TclEmitForwardJump(envPtr, TCL_TRUE_JUMP, &lhsTrueFixup);
620 TclEmitPush(TclRegisterNewLiteral(envPtr, "0", 1), envPtr);
621 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &lhsEndFixup);
622 dist = (envPtr->codeNext - envPtr->codeStart) - lhsTrueFixup.codeOffset;
623 if (TclFixupForwardJump(envPtr, &lhsTrueFixup, dist, 127)) {
624 badDist:
625 panic("CompileLandOrLorExpr: bad jump distance %d\n", dist);
626 }
627 envPtr->currStackDepth = savedStackDepth;
628 TclEmitPush(TclRegisterNewLiteral(envPtr, "1", 1), envPtr);
629 dist = (envPtr->codeNext - envPtr->codeStart) - lhsEndFixup.codeOffset;
630 if (TclFixupForwardJump(envPtr, &lhsEndFixup, dist, 127)) {
631 goto badDist;
632 }
633
634 /*
635 * Emit the "short circuit" jump around the rest of the expression.
636 * Duplicate the "0" or "1" on top of the stack first to keep the
637 * jump from consuming it.
638 */
639
640 TclEmitOpcode(INST_DUP, envPtr);
641 TclEmitForwardJump(envPtr,
642 ((opIndex==OP_LAND)? TCL_FALSE_JUMP : TCL_TRUE_JUMP),
643 &shortCircuitFixup);
644
645 /*
646 * Emit code for the second operand.
647 */
648
649 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
650 if (code != TCL_OK) {
651 goto done;
652 }
653 tokenPtr += (tokenPtr->numComponents + 1);
654
655 /*
656 * Emit a "logical and" or "logical or" instruction. This does not try
657 * to "short- circuit" the evaluation of both operands, but instead
658 * ensures that we either have a "1" or a "0" result.
659 */
660
661 TclEmitOpcode(((opIndex==OP_LAND)? INST_LAND : INST_LOR), envPtr);
662
663 /*
664 * Now that we know the target of the forward jump, update it with the
665 * correct distance.
666 */
667
668 dist = (envPtr->codeNext - envPtr->codeStart)
669 - shortCircuitFixup.codeOffset;
670 TclFixupForwardJump(envPtr, &shortCircuitFixup, dist, 127);
671 *endPtrPtr = tokenPtr;
672
673 done:
674 envPtr->currStackDepth = savedStackDepth + 1;
675 return code;
676 }
677
678 /*
679 *----------------------------------------------------------------------
680 *
681 * CompileCondExpr --
682 *
683 * This procedure compiles a Tcl conditional expression:
684 * condExpr ::= lorExpr ['?' condExpr ':' condExpr]
685 *
686 * Results:
687 * The return value is TCL_OK on a successful compilation and TCL_ERROR
688 * on failure. If TCL_OK is returned, a pointer to the token just after
689 * the last one in the subexpression is stored at the address in
690 * endPtrPtr. If TCL_ERROR is returned, then the interpreter's result
691 * contains an error message.
692 *
693 * Side effects:
694 * Adds instructions to envPtr to evaluate the expression at runtime.
695 *
696 *----------------------------------------------------------------------
697 */
698
699 static int
700 CompileCondExpr(exprTokenPtr, infoPtr, envPtr, endPtrPtr)
701 Tcl_Token *exprTokenPtr; /* Points to TCL_TOKEN_SUB_EXPR token
702 * containing the "?" operator. */
703 ExprInfo *infoPtr; /* Describes the compilation state for the
704 * expression being compiled. */
705 CompileEnv *envPtr; /* Holds resulting instructions. */
706 Tcl_Token **endPtrPtr; /* If successful, a pointer to the token
707 * just after the last token in the
708 * subexpression is stored here. */
709 {
710 JumpFixup jumpAroundThenFixup, jumpAroundElseFixup;
711 /* Used to update or replace one-byte jumps
712 * around the then and else expressions when
713 * their target PCs are determined. */
714 Tcl_Token *tokenPtr;
715 int elseCodeOffset, dist, code;
716 int savedStackDepth = envPtr->currStackDepth;
717
718 /*
719 * Emit code for the test.
720 */
721
722 tokenPtr = exprTokenPtr+2;
723 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
724 if (code != TCL_OK) {
725 goto done;
726 }
727 tokenPtr += (tokenPtr->numComponents + 1);
728
729 /*
730 * Emit the jump to the "else" expression if the test was false.
731 */
732
733 TclEmitForwardJump(envPtr, TCL_FALSE_JUMP, &jumpAroundThenFixup);
734
735 /*
736 * Compile the "then" expression. Note that if a subexpression is only
737 * a primary, we need to try to convert it to numeric. We do this to
738 * support Tcl's policy of interpreting operands if at all possible as
739 * first integers, else floating-point numbers.
740 */
741
742 infoPtr->hasOperators = 0;
743 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
744 if (code != TCL_OK) {
745 goto done;
746 }
747 tokenPtr += (tokenPtr->numComponents + 1);
748 if (!infoPtr->hasOperators) {
749 TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr);
750 }
751
752 /*
753 * Emit an unconditional jump around the "else" condExpr.
754 */
755
756 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP,
757 &jumpAroundElseFixup);
758
759 /*
760 * Compile the "else" expression.
761 */
762
763 envPtr->currStackDepth = savedStackDepth;
764 elseCodeOffset = (envPtr->codeNext - envPtr->codeStart);
765 infoPtr->hasOperators = 0;
766 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
767 if (code != TCL_OK) {
768 goto done;
769 }
770 tokenPtr += (tokenPtr->numComponents + 1);
771 if (!infoPtr->hasOperators) {
772 TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr);
773 }
774
775 /*
776 * Fix up the second jump around the "else" expression.
777 */
778
779 dist = (envPtr->codeNext - envPtr->codeStart)
780 - jumpAroundElseFixup.codeOffset;
781 if (TclFixupForwardJump(envPtr, &jumpAroundElseFixup, dist, 127)) {
782 /*
783 * Update the else expression's starting code offset since it
784 * moved down 3 bytes too.
785 */
786
787 elseCodeOffset += 3;
788 }
789
790 /*
791 * Fix up the first jump to the "else" expression if the test was false.
792 */
793
794 dist = (elseCodeOffset - jumpAroundThenFixup.codeOffset);
795 TclFixupForwardJump(envPtr, &jumpAroundThenFixup, dist, 127);
796 *endPtrPtr = tokenPtr;
797
798 done:
799 envPtr->currStackDepth = savedStackDepth + 1;
800 return code;
801 }
802
803 /*
804 *----------------------------------------------------------------------
805 *
806 * CompileMathFuncCall --
807 *
808 * This procedure compiles a call on a math function in an expression:
809 * mathFuncCall ::= funcName '(' [condExpr {',' condExpr}] ')'
810 *
811 * Results:
812 * The return value is TCL_OK on a successful compilation and TCL_ERROR
813 * on failure. If TCL_OK is returned, a pointer to the token just after
814 * the last one in the subexpression is stored at the address in
815 * endPtrPtr. If TCL_ERROR is returned, then the interpreter's result
816 * contains an error message.
817 *
818 * Side effects:
819 * Adds instructions to envPtr to evaluate the math function at
820 * runtime.
821 *
822 *----------------------------------------------------------------------
823 */
824
825 static int
826 CompileMathFuncCall(exprTokenPtr, funcName, infoPtr, envPtr, endPtrPtr)
827 Tcl_Token *exprTokenPtr; /* Points to TCL_TOKEN_SUB_EXPR token
828 * containing the math function call. */
829 CONST char *funcName; /* Name of the math function. */
830 ExprInfo *infoPtr; /* Describes the compilation state for the
831 * expression being compiled. */
832 CompileEnv *envPtr; /* Holds resulting instructions. */
833 Tcl_Token **endPtrPtr; /* If successful, a pointer to the token
834 * just after the last token in the
835 * subexpression is stored here. */
836 {
837 Tcl_Interp *interp = infoPtr->interp;
838 Interp *iPtr = (Interp *) interp;
839 MathFunc *mathFuncPtr;
840 Tcl_HashEntry *hPtr;
841 Tcl_Token *tokenPtr, *afterSubexprPtr;
842 int code, i;
843
844 /*
845 * Look up the MathFunc record for the function.
846 */
847
848 code = TCL_OK;
849 hPtr = Tcl_FindHashEntry(&iPtr->mathFuncTable, funcName);
850 if (hPtr == NULL) {
851 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
852 "unknown math function \"", funcName, "\"", (char *) NULL);
853 code = TCL_ERROR;
854 goto done;
855 }
856 mathFuncPtr = (MathFunc *) Tcl_GetHashValue(hPtr);
857
858 /*
859 * If not a builtin function, push an object with the function's name.
860 */
861
862 if (mathFuncPtr->builtinFuncIndex < 0) {
863 TclEmitPush(TclRegisterNewLiteral(envPtr, funcName, -1), envPtr);
864 }
865
866 /*
867 * Compile any arguments for the function.
868 */
869
870 tokenPtr = exprTokenPtr+2;
871 afterSubexprPtr = exprTokenPtr + (exprTokenPtr->numComponents + 1);
872 if (mathFuncPtr->numArgs > 0) {
873 for (i = 0; i < mathFuncPtr->numArgs; i++) {
874 if (tokenPtr == afterSubexprPtr) {
875 Tcl_ResetResult(interp);
876 Tcl_AppendToObj(Tcl_GetObjResult(interp),
877 "too few arguments for math function", -1);
878 code = TCL_ERROR;
879 goto done;
880 }
881 code = CompileSubExpr(tokenPtr, infoPtr, envPtr);
882 if (code != TCL_OK) {
883 goto done;
884 }
885 tokenPtr += (tokenPtr->numComponents + 1);
886 }
887 if (tokenPtr != afterSubexprPtr) {
888 Tcl_ResetResult(interp);
889 Tcl_AppendToObj(Tcl_GetObjResult(interp),
890 "too many arguments for math function", -1);
891 code = TCL_ERROR;
892 goto done;
893 }
894 } else if (tokenPtr != afterSubexprPtr) {
895 Tcl_ResetResult(interp);
896 Tcl_AppendToObj(Tcl_GetObjResult(interp),
897 "too many arguments for math function", -1);
898 code = TCL_ERROR;
899 goto done;
900 }
901
902 /*
903 * Compile the call on the math function. Note that the "objc" argument
904 * count for non-builtin functions is incremented by 1 to include the
905 * function name itself.
906 */
907
908 if (mathFuncPtr->builtinFuncIndex >= 0) { /* a builtin function */
909 /*
910 * Adjust the current stack depth by the number of arguments
911 * of the builtin function. This cannot be handled by the
912 * TclEmitInstInt1 macro as the number of arguments is not
913 * passed as an operand.
914 */
915
916 if (envPtr->maxStackDepth < envPtr->currStackDepth) {
917 envPtr->maxStackDepth = envPtr->currStackDepth;
918 }
919 TclEmitInstInt1(INST_CALL_BUILTIN_FUNC1,
920 mathFuncPtr->builtinFuncIndex, envPtr);
921 envPtr->currStackDepth -= mathFuncPtr->numArgs;
922 } else {
923 TclEmitInstInt1(INST_CALL_FUNC1, (mathFuncPtr->numArgs+1), envPtr);
924 }
925 *endPtrPtr = afterSubexprPtr;
926
927 done:
928 return code;
929 }
930
931 /*
932 *----------------------------------------------------------------------
933 *
934 * LogSyntaxError --
935 *
936 * This procedure is invoked after an error occurs when compiling an
937 * expression. It sets the interpreter result to an error message
938 * describing the error.
939 *
940 * Results:
941 * None.
942 *
943 * Side effects:
944 * Sets the interpreter result to an error message describing the
945 * expression that was being compiled when the error occurred.
946 *
947 *----------------------------------------------------------------------
948 */
949
950 static void
951 LogSyntaxError(infoPtr)
952 ExprInfo *infoPtr; /* Describes the compilation state for the
953 * expression being compiled. */
954 {
955 int numBytes = (infoPtr->lastChar - infoPtr->expr);
956 char buffer[100];
957
958 sprintf(buffer, "syntax error in expression \"%.*s\"",
959 ((numBytes > 60)? 60 : numBytes), infoPtr->expr);
960 Tcl_ResetResult(infoPtr->interp);
961 Tcl_AppendStringsToObj(Tcl_GetObjResult(infoPtr->interp),
962 buffer, (char *) NULL);
963 }