Debian Codegraph @

generic/tclCompExpr.c

raw
1 /*
2 * tclCompExpr.c --
3 *
4 * This file contains the code to parse and compile Tcl expressions and
5 * implementations of the Tcl commands corresponding to expression
6 * operators, such as the command ::tcl::mathop::+ .
7 *
8 * Contributions from Don Porter, NIST, 2006-2007. (not subject to US copyright)
9 *
10 * See the file "license.terms" for information on usage and redistribution of
11 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 */
13
14 #include "tclInt.h"
15 #include "tclCompile.h" /* CompileEnv */
16
17 /*
18 * Expression parsing takes place in the routine ParseExpr(). It takes a
19 * string as input, parses that string, and generates a representation of the
20 * expression in the form of a tree of operators, a list of literals, a list
21 * of function names, and an array of Tcl_Token's within a Tcl_Parse struct.
22 * The tree is composed of OpNodes.
23 */
24
25 typedef struct OpNode {
26 int left; /* "Pointer" to the left operand. */
27 int right; /* "Pointer" to the right operand. */
28 union {
29 int parent; /* "Pointer" to the parent operand. */
30 int prev; /* "Pointer" joining incomplete tree stack */
31 } p;
32 unsigned char lexeme; /* Code that identifies the operator. */
33 unsigned char precedence; /* Precedence of the operator */
34 unsigned char mark; /* Mark used to control traversal. */
35 unsigned char constant; /* Flag marking constant subexpressions. */
36 } OpNode;
37
38 /*
39 * The storage for the tree is dynamically allocated array of OpNodes. The
40 * array is grown as parsing needs dictate according to a scheme similar to
41 * Tcl's string growth algorithm, so that the resizing costs are O(N) and so
42 * that we use at least half the memory allocated as expressions get large.
43 *
44 * Each OpNode in the tree represents an operator in the expression, either
45 * unary or binary. When parsing is completed successfully, a binary operator
46 * OpNode will have its left and right fields filled with "pointers" to its
47 * left and right operands. A unary operator OpNode will have its right field
48 * filled with a pointer to its single operand. When an operand is a
49 * subexpression the "pointer" takes the form of the index -- a non-negative
50 * integer -- into the OpNode storage array where the root of that
51 * subexpression parse tree is found.
52 *
53 * Non-operator elements of the expression do not get stored in the OpNode
54 * tree. They are stored in the other structures according to their type.
55 * Literal values get appended to the literal list. Elements that denote forms
56 * of quoting or substitution known to the Tcl parser get stored as
57 * Tcl_Tokens. These non-operator elements of the expression are the leaves of
58 * the completed parse tree. When an operand of an OpNode is one of these leaf
59 * elements, the following negative integer codes are used to indicate which
60 * kind of elements it is.
61 */
62
63 enum OperandTypes {
64 OT_LITERAL = -3, /* Operand is a literal in the literal list */
65 OT_TOKENS = -2, /* Operand is sequence of Tcl_Tokens */
66 OT_EMPTY = -1 /* "Operand" is an empty string. This is a special
67 * case used only to represent the EMPTY lexeme. See
68 * below. */
69 };
70
71 /*
72 * Readable macros to test whether a "pointer" value points to an operator.
73 * They operate on the "non-negative integer -> operator; negative integer ->
74 * a non-operator OperandType" distinction.
75 */
76
77 #define IsOperator(l) ((l) >= 0)
78 #define NotOperator(l) ((l) < 0)
79
80 /*
81 * Note that it is sufficient to store in the tree just the type of leaf
82 * operand, without any explicit pointer to which leaf. This is true because
83 * the traversals of the completed tree we perform are known to visit the
84 * leaves in the same order as the original parse.
85 *
86 * In a completed parse tree, those OpNodes that are themselves (roots of
87 * subexpression trees that are) operands of some operator store in their
88 * p.parent field a "pointer" to the OpNode of that operator. The p.parent
89 * field permits a traversal of the tree within a non-recursive routine
90 * (ConvertTreeToTokens() and CompileExprTree()). This means that even
91 * expression trees of great depth pose no risk of blowing the C stack.
92 *
93 * While the parse tree is being constructed, the same memory space is used to
94 * hold the p.prev field which chains together a stack of incomplete trees
95 * awaiting their right operands.
96 *
97 * The lexeme field is filled in with the lexeme of the operator that is
98 * returned by the ParseLexeme() routine. Only lexemes for unary and binary
99 * operators get stored in an OpNode. Other lexmes get different treatment.
100 *
101 * The precedence field provides a place to store the precedence of the
102 * operator, so it need not be looked up again and again.
103 *
104 * The mark field is use to control the traversal of the tree, so that it can
105 * be done non-recursively. The mark values are:
106 */
107
108 enum Marks {
109 MARK_LEFT, /* Next step of traversal is to visit left subtree */
110 MARK_RIGHT, /* Next step of traversal is to visit right subtree */
111 MARK_PARENT /* Next step of traversal is to return to parent */
112 };
113
114 /*
115 * The constant field is a boolean flag marking which subexpressions are
116 * completely known at compile time, and are eligible for computing then
117 * rather than waiting until run time.
118 */
119
120 /*
121 * Each lexeme belongs to one of four categories, which determine its place in
122 * the parse tree. We use the two high bits of the (unsigned char) value to
123 * store a NODE_TYPE code.
124 */
125
126 #define NODE_TYPE 0xC0
127
128 /*
129 * The four category values are LEAF, UNARY, and BINARY, explained below, and
130 * "uncategorized", which is used either temporarily, until context determines
131 * which of the other three categories is correct, or for lexemes like
132 * INVALID, which aren't really lexemes at all, but indicators of a parsing
133 * error. Note that the codes must be distinct to distinguish categories, but
134 * need not take the form of a bit array.
135 */
136
137 #define BINARY 0x40 /* This lexeme is a binary operator. An OpNode
138 * representing it should go into the parse
139 * tree, and two operands should be parsed for
140 * it in the expression. */
141 #define UNARY 0x80 /* This lexeme is a unary operator. An OpNode
142 * representing it should go into the parse
143 * tree, and one operand should be parsed for
144 * it in the expression. */
145 #define LEAF 0xC0 /* This lexeme is a leaf operand in the parse
146 * tree. No OpNode will be placed in the tree
147 * for it. Either a literal value will be
148 * appended to the list of literals in this
149 * expression, or appropriate Tcl_Tokens will
150 * be appended in a Tcl_Parse struct to
151 * represent those leaves that require some
152 * form of substitution. */
153
154 /* Uncategorized lexemes */
155
156 #define PLUS 1 /* Ambiguous. Resolves to UNARY_PLUS or
157 * BINARY_PLUS according to context. */
158 #define MINUS 2 /* Ambiguous. Resolves to UNARY_MINUS or
159 * BINARY_MINUS according to context. */
160 #define BAREWORD 3 /* Ambiguous. Resolves to BOOLEAN or to
161 * FUNCTION or a parse error according to
162 * context and value. */
163 #define INCOMPLETE 4 /* A parse error. Used only when the single
164 * "=" is encountered. */
165 #define INVALID 5 /* A parse error. Used when any punctuation
166 * appears that's not a supported operator. */
167
168 /* Leaf lexemes */
169
170 #define NUMBER (LEAF | 1)
171 /* For literal numbers */
172 #define SCRIPT (LEAF | 2)
173 /* Script substitution; [foo] */
174 #define BOOLEAN (LEAF | BAREWORD)
175 /* For literal booleans */
176 #define BRACED (LEAF | 4)
177 /* Braced string; {foo bar} */
178 #define VARIABLE (LEAF | 5)
179 /* Variable substitution; $x */
180 #define QUOTED (LEAF | 6)
181 /* Quoted string; "foo $bar [soom]" */
182 #define EMPTY (LEAF | 7)
183 /* Used only for an empty argument list to a
184 * function. Represents the empty string
185 * within parens in the expression: rand() */
186
187 /* Unary operator lexemes */
188
189 #define UNARY_PLUS (UNARY | PLUS)
190 #define UNARY_MINUS (UNARY | MINUS)
191 #define FUNCTION (UNARY | BAREWORD)
192 /* This is a bit of "creative interpretation"
193 * on the part of the parser. A function call
194 * is parsed into the parse tree according to
195 * the perspective that the function name is a
196 * unary operator and its argument list,
197 * enclosed in parens, is its operand. The
198 * additional requirements not implied
199 * generally by treatment as a unary operator
200 * -- for example, the requirement that the
201 * operand be enclosed in parens -- are hard
202 * coded in the relevant portions of
203 * ParseExpr(). We trade off the need to
204 * include such exceptional handling in the
205 * code against the need we would otherwise
206 * have for more lexeme categories. */
207 #define START (UNARY | 4)
208 /* This lexeme isn't parsed from the
209 * expression text at all. It represents the
210 * start of the expression and sits at the
211 * root of the parse tree where it serves as
212 * the start/end point of traversals. */
213 #define OPEN_PAREN (UNARY | 5)
214 /* Another bit of creative interpretation,
215 * where we treat "(" as a unary operator with
216 * the sub-expression between it and its
217 * matching ")" as its operand. See
218 * CLOSE_PAREN below. */
219 #define NOT (UNARY | 6)
220 #define BIT_NOT (UNARY | 7)
221
222 /* Binary operator lexemes */
223
224 #define BINARY_PLUS (BINARY | PLUS)
225 #define BINARY_MINUS (BINARY | MINUS)
226 #define COMMA (BINARY | 3)
227 /* The "," operator is a low precedence binary
228 * operator that separates the arguments in a
229 * function call. The additional constraint
230 * that this operator can only legally appear
231 * at the right places within a function call
232 * argument list are hard coded within
233 * ParseExpr(). */
234 #define MULT (BINARY | 4)
235 #define DIVIDE (BINARY | 5)
236 #define MOD (BINARY | 6)
237 #define LESS (BINARY | 7)
238 #define GREATER (BINARY | 8)
239 #define BIT_AND (BINARY | 9)
240 #define BIT_XOR (BINARY | 10)
241 #define BIT_OR (BINARY | 11)
242 #define QUESTION (BINARY | 12)
243 /* These two lexemes make up the */
244 #define COLON (BINARY | 13)
245 /* ternary conditional operator, $x ? $y : $z.
246 * We treat them as two binary operators to
247 * avoid another lexeme category, and code the
248 * additional constraints directly in
249 * ParseExpr(). For instance, the right
250 * operand of a "?" operator must be a ":"
251 * operator. */
252 #define LEFT_SHIFT (BINARY | 14)
253 #define RIGHT_SHIFT (BINARY | 15)
254 #define LEQ (BINARY | 16)
255 #define GEQ (BINARY | 17)
256 #define EQUAL (BINARY | 18)
257 #define NEQ (BINARY | 19)
258 #define AND (BINARY | 20)
259 #define OR (BINARY | 21)
260 #define STREQ (BINARY | 22)
261 #define STRNEQ (BINARY | 23)
262 #define EXPON (BINARY | 24)
263 /* Unlike the other binary operators, EXPON is
264 * right associative and this distinction is
265 * coded directly in ParseExpr(). */
266 #define IN_LIST (BINARY | 25)
267 #define NOT_IN_LIST (BINARY | 26)
268 #define CLOSE_PAREN (BINARY | 27)
269 /* By categorizing the CLOSE_PAREN lexeme as a
270 * BINARY operator, the normal parsing rules
271 * for binary operators assure that a close
272 * paren will not directly follow another
273 * operator, and the machinery already in
274 * place to connect operands to operators
275 * according to precedence performs most of
276 * the work of matching open and close parens
277 * for us. In the end though, a close paren is
278 * not really a binary operator, and some
279 * special coding in ParseExpr() make sure we
280 * never put an actual CLOSE_PAREN node in the
281 * parse tree. The sub-expression between
282 * parens becomes the single argument of the
283 * matching OPEN_PAREN unary operator. */
284 #define END (BINARY | 28)
285 /* This lexeme represents the end of the
286 * string being parsed. Treating it as a
287 * binary operator follows the same logic as
288 * the CLOSE_PAREN lexeme and END pairs with
289 * START, in the same way that CLOSE_PAREN
290 * pairs with OPEN_PAREN. */
291
292 /*
293 * When ParseExpr() builds the parse tree it must choose which operands to
294 * connect to which operators. This is done according to operator precedence.
295 * The greater an operator's precedence the greater claim it has to link to an
296 * available operand. The Precedence enumeration lists the precedence values
297 * used by Tcl expression operators, from lowest to highest claim. Each
298 * precedence level is commented with the operators that hold that precedence.
299 */
300
301 enum Precedence {
302 PREC_END = 1, /* END */
303 PREC_START, /* START */
304 PREC_CLOSE_PAREN, /* ")" */
305 PREC_OPEN_PAREN, /* "(" */
306 PREC_COMMA, /* "," */
307 PREC_CONDITIONAL, /* "?", ":" */
308 PREC_OR, /* "||" */
309 PREC_AND, /* "&&" */
310 PREC_BIT_OR, /* "|" */
311 PREC_BIT_XOR, /* "^" */
312 PREC_BIT_AND, /* "&" */
313 PREC_EQUAL, /* "==", "!=", "eq", "ne", "in", "ni" */
314 PREC_COMPARE, /* "<", ">", "<=", ">=" */
315 PREC_SHIFT, /* "<<", ">>" */
316 PREC_ADD, /* "+", "-" */
317 PREC_MULT, /* "*", "/", "%" */
318 PREC_EXPON, /* "**" */
319 PREC_UNARY /* "+", "-", FUNCTION, "!", "~" */
320 };
321
322 /*
323 * Here the same information contained in the comments above is stored in
324 * inverted form, so that given a lexeme, one can quickly look up its
325 * precedence value.
326 */
327
328 static const unsigned char prec[] = {
329 /* Non-operator lexemes */
330 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
331 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
332 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
333 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
334 0,
335 /* Binary operator lexemes */
336 PREC_ADD, /* BINARY_PLUS */
337 PREC_ADD, /* BINARY_MINUS */
338 PREC_COMMA, /* COMMA */
339 PREC_MULT, /* MULT */
340 PREC_MULT, /* DIVIDE */
341 PREC_MULT, /* MOD */
342 PREC_COMPARE, /* LESS */
343 PREC_COMPARE, /* GREATER */
344 PREC_BIT_AND, /* BIT_AND */
345 PREC_BIT_XOR, /* BIT_XOR */
346 PREC_BIT_OR, /* BIT_OR */
347 PREC_CONDITIONAL, /* QUESTION */
348 PREC_CONDITIONAL, /* COLON */
349 PREC_SHIFT, /* LEFT_SHIFT */
350 PREC_SHIFT, /* RIGHT_SHIFT */
351 PREC_COMPARE, /* LEQ */
352 PREC_COMPARE, /* GEQ */
353 PREC_EQUAL, /* EQUAL */
354 PREC_EQUAL, /* NEQ */
355 PREC_AND, /* AND */
356 PREC_OR, /* OR */
357 PREC_EQUAL, /* STREQ */
358 PREC_EQUAL, /* STRNEQ */
359 PREC_EXPON, /* EXPON */
360 PREC_EQUAL, /* IN_LIST */
361 PREC_EQUAL, /* NOT_IN_LIST */
362 PREC_CLOSE_PAREN, /* CLOSE_PAREN */
363 PREC_END, /* END */
364 /* Expansion room for more binary operators */
365 0, 0, 0,
366 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
367 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
368 0,
369 /* Unary operator lexemes */
370 PREC_UNARY, /* UNARY_PLUS */
371 PREC_UNARY, /* UNARY_MINUS */
372 PREC_UNARY, /* FUNCTION */
373 PREC_START, /* START */
374 PREC_OPEN_PAREN, /* OPEN_PAREN */
375 PREC_UNARY, /* NOT*/
376 PREC_UNARY, /* BIT_NOT*/
377 };
378
379 /*
380 * A table mapping lexemes to bytecode instructions, used by CompileExprTree().
381 */
382
383 static const unsigned char instruction[] = {
384 /* Non-operator lexemes */
385 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
386 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
387 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
388 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
389 0,
390 /* Binary operator lexemes */
391 INST_ADD, /* BINARY_PLUS */
392 INST_SUB, /* BINARY_MINUS */
393 0, /* COMMA */
394 INST_MULT, /* MULT */
395 INST_DIV, /* DIVIDE */
396 INST_MOD, /* MOD */
397 INST_LT, /* LESS */
398 INST_GT, /* GREATER */
399 INST_BITAND, /* BIT_AND */
400 INST_BITXOR, /* BIT_XOR */
401 INST_BITOR, /* BIT_OR */
402 0, /* QUESTION */
403 0, /* COLON */
404 INST_LSHIFT, /* LEFT_SHIFT */
405 INST_RSHIFT, /* RIGHT_SHIFT */
406 INST_LE, /* LEQ */
407 INST_GE, /* GEQ */
408 INST_EQ, /* EQUAL */
409 INST_NEQ, /* NEQ */
410 0, /* AND */
411 0, /* OR */
412 INST_STR_EQ, /* STREQ */
413 INST_STR_NEQ, /* STRNEQ */
414 INST_EXPON, /* EXPON */
415 INST_LIST_IN, /* IN_LIST */
416 INST_LIST_NOT_IN, /* NOT_IN_LIST */
417 0, /* CLOSE_PAREN */
418 0, /* END */
419 /* Expansion room for more binary operators */
420 0, 0, 0,
421 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
422 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
423 0,
424 /* Unary operator lexemes */
425 INST_UPLUS, /* UNARY_PLUS */
426 INST_UMINUS, /* UNARY_MINUS */
427 0, /* FUNCTION */
428 0, /* START */
429 0, /* OPEN_PAREN */
430 INST_LNOT, /* NOT*/
431 INST_BITNOT, /* BIT_NOT*/
432 };
433
434 /*
435 * A table mapping a byte value to the corresponding lexeme for use by
436 * ParseLexeme().
437 */
438
439 static const unsigned char Lexeme[] = {
440 INVALID /* NUL */, INVALID /* SOH */,
441 INVALID /* STX */, INVALID /* ETX */,
442 INVALID /* EOT */, INVALID /* ENQ */,
443 INVALID /* ACK */, INVALID /* BEL */,
444 INVALID /* BS */, INVALID /* HT */,
445 INVALID /* LF */, INVALID /* VT */,
446 INVALID /* FF */, INVALID /* CR */,
447 INVALID /* SO */, INVALID /* SI */,
448 INVALID /* DLE */, INVALID /* DC1 */,
449 INVALID /* DC2 */, INVALID /* DC3 */,
450 INVALID /* DC4 */, INVALID /* NAK */,
451 INVALID /* SYN */, INVALID /* ETB */,
452 INVALID /* CAN */, INVALID /* EM */,
453 INVALID /* SUB */, INVALID /* ESC */,
454 INVALID /* FS */, INVALID /* GS */,
455 INVALID /* RS */, INVALID /* US */,
456 INVALID /* SPACE */, 0 /* ! or != */,
457 QUOTED /* " */, INVALID /* # */,
458 VARIABLE /* $ */, MOD /* % */,
459 0 /* & or && */, INVALID /* ' */,
460 OPEN_PAREN /* ( */, CLOSE_PAREN /* ) */,
461 0 /* * or ** */, PLUS /* + */,
462 COMMA /* , */, MINUS /* - */,
463 0 /* . */, DIVIDE /* / */,
464 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0-9 */
465 COLON /* : */, INVALID /* ; */,
466 0 /* < or << or <= */,
467 0 /* == or INVALID */,
468 0 /* > or >> or >= */,
469 QUESTION /* ? */, INVALID /* @ */,
470 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A-M */
471 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* N-Z */
472 SCRIPT /* [ */, INVALID /* \ */,
473 INVALID /* ] */, BIT_XOR /* ^ */,
474 INVALID /* _ */, INVALID /* ` */,
475 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* a-m */
476 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* n-z */
477 BRACED /* { */, 0 /* | or || */,
478 INVALID /* } */, BIT_NOT /* ~ */,
479 INVALID /* DEL */
480 };
481
482 /*
483 * The JumpList struct is used to create a stack of data needed for the
484 * TclEmitForwardJump() and TclFixupForwardJump() calls that are performed
485 * when compiling the short-circuiting operators QUESTION/COLON, AND, and OR.
486 * Keeping a stack permits the CompileExprTree() routine to be non-recursive.
487 */
488
489 typedef struct JumpList {
490 JumpFixup jump; /* Pass this argument to matching calls of
491 * TclEmitForwardJump() and
492 * TclFixupForwardJump(). */
493 struct JumpList *next; /* Point to next item on the stack */
494 } JumpList;
495
496 /*
497 * Declarations for local functions to this file:
498 */
499
500 static void CompileExprTree(Tcl_Interp *interp, OpNode *nodes,
501 int index, Tcl_Obj *const **litObjvPtr,
502 Tcl_Obj *const *funcObjv, Tcl_Token *tokenPtr,
503 CompileEnv *envPtr, int optimize);
504 static void ConvertTreeToTokens(const char *start, int numBytes,
505 OpNode *nodes, Tcl_Token *tokenPtr,
506 Tcl_Parse *parsePtr);
507 static int ExecConstantExprTree(Tcl_Interp *interp, OpNode *nodes,
508 int index, Tcl_Obj * const **litObjvPtr);
509 static int ParseExpr(Tcl_Interp *interp, const char *start,
510 int numBytes, OpNode **opTreePtr,
511 Tcl_Obj *litList, Tcl_Obj *funcList,
512 Tcl_Parse *parsePtr, int parseOnly);
513 static int ParseLexeme(const char *start, int numBytes,
514 unsigned char *lexemePtr, Tcl_Obj **literalPtr);
515
516 /*
517 *----------------------------------------------------------------------
518 *
519 * ParseExpr --
520 *
521 * Given a string, the numBytes bytes starting at start, this function
522 * parses it as a Tcl expression and constructs a tree representing the
523 * structure of the expression. The caller must pass in empty lists as
524 * the funcList and litList arguments. The elements of the parsed
525 * expression are returned to the caller as that tree, a list of literal
526 * values, a list of function names, and in Tcl_Tokens added to a
527 * Tcl_Parse struct passed in by the caller.
528 *
529 * Results:
530 * If the string is successfully parsed as a valid Tcl expression, TCL_OK
531 * is returned, and data about the expression structure is written to the
532 * last four arguments. If the string cannot be parsed as a valid Tcl
533 * expression, TCL_ERROR is returned, and if interp is non-NULL, an error
534 * message is written to interp.
535 *
536 * Side effects:
537 * Memory will be allocated. If TCL_OK is returned, the caller must clean
538 * up the returned data structures. The (OpNode *) value written to
539 * opTreePtr should be passed to ckfree() and the parsePtr argument
540 * should be passed to Tcl_FreeParse(). The elements appended to the
541 * litList and funcList will automatically be freed whenever the refcount
542 * on those lists indicates they can be freed.
543 *
544 *----------------------------------------------------------------------
545 */
546
547 static int
548 ParseExpr(
549 Tcl_Interp *interp, /* Used for error reporting. */
550 const char *start, /* Start of source string to parse. */
551 int numBytes, /* Number of bytes in string. */
552 OpNode **opTreePtr, /* Points to space where a pointer to the
553 * allocated OpNode tree should go. */
554 Tcl_Obj *litList, /* List to append literals to. */
555 Tcl_Obj *funcList, /* List to append function names to. */
556 Tcl_Parse *parsePtr, /* Structure to fill with tokens representing
557 * those operands that require run time
558 * substitutions. */
559 int parseOnly) /* A boolean indicating whether the caller's
560 * aim is just a parse, or whether it will go
561 * on to compile the expression. Different
562 * optimizations are appropriate for the two
563 * scenarios. */
564 {
565 OpNode *nodes = NULL; /* Pointer to the OpNode storage array where
566 * we build the parse tree. */
567 unsigned int nodesAvailable = 64; /* Initial size of the storage array. This
568 * value establishes a minimum tree memory
569 * cost of only about 1 kilobyte, and is large
570 * enough for most expressions to parse with
571 * no need for array growth and
572 * reallocation. */
573 unsigned int nodesUsed = 0; /* Number of OpNodes filled. */
574 int scanned = 0; /* Capture number of byte scanned by parsing
575 * routines. */
576 int lastParsed; /* Stores info about what the lexeme parsed
577 * the previous pass through the parsing loop
578 * was. If it was an operator, lastParsed is
579 * the index of the OpNode for that operator.
580 * If it was not an operator, lastParsed holds
581 * an OperandTypes value encoding what we need
582 * to know about it. */
583 int incomplete; /* Index of the most recent incomplete tree in
584 * the OpNode array. Heads a stack of
585 * incomplete trees linked by p.prev. */
586 int complete = OT_EMPTY; /* "Index" of the complete tree (that is, a
587 * complete subexpression) determined at the
588 * moment. OT_EMPTY is a nonsense value used
589 * only to silence compiler warnings. During a
590 * parse, complete will always hold an index
591 * or an OperandTypes value pointing to an
592 * actual leaf at the time the complete tree
593 * is needed. */
594
595 /*
596 * These variables control generation of the error message.
597 */
598
599 Tcl_Obj *msg = NULL; /* The error message. */
600 Tcl_Obj *post = NULL; /* In a few cases, an additional postscript
601 * for the error message, supplying more
602 * information after the error msg and
603 * location have been reported. */
604 const char *errCode = NULL; /* The detail word of the errorCode list, or
605 * NULL to indicate that no changes to the
606 * errorCode are to be done. */
607 const char *subErrCode = NULL;
608 /* Extra information for use in generating the
609 * errorCode. */
610 const char *mark = "_@_"; /* In the portion of the complete error
611 * message where the error location is
612 * reported, this "mark" substring is inserted
613 * into the string being parsed to aid in
614 * pinpointing the location of the syntax
615 * error in the expression. */
616 int insertMark = 0; /* A boolean controlling whether the "mark"
617 * should be inserted. */
618 const int limit = 25; /* Portions of the error message are
619 * constructed out of substrings of the
620 * original expression. In order to keep the
621 * error message readable, we impose this
622 * limit on the substring size we extract. */
623
624 TclParseInit(interp, start, numBytes, parsePtr);
625
626 nodes = (OpNode *)attemptckalloc(nodesAvailable * sizeof(OpNode));
627 if (nodes == NULL) {
628 TclNewLiteralStringObj(msg, "not enough memory to parse expression");
629 errCode = "NOMEM";
630 goto error;
631 }
632
633 /*
634 * Initialize the parse tree with the special "START" node.
635 */
636
637 nodes->lexeme = START;
638 nodes->precedence = prec[START];
639 nodes->mark = MARK_RIGHT;
640 nodes->constant = 1;
641 incomplete = lastParsed = nodesUsed;
642 nodesUsed++;
643
644 /*
645 * Main parsing loop parses one lexeme per iteration. We exit the loop
646 * only when there's a syntax error with a "goto error" which takes us to
647 * the error handling code following the loop, or when we've successfully
648 * completed the parse and we return to the caller.
649 */
650
651 while (1) {
652 OpNode *nodePtr; /* Points to the OpNode we may fill this pass
653 * through the loop. */
654 unsigned char lexeme; /* The lexeme we parse this iteration. */
655 Tcl_Obj *literal; /* Filled by the ParseLexeme() call when a
656 * literal is parsed that has a Tcl_Obj rep
657 * worth preserving. */
658
659 /*
660 * Each pass through this loop adds up to one more OpNode. Allocate
661 * space for one if required.
662 */
663
664 if (nodesUsed >= nodesAvailable) {
665 unsigned int size = nodesUsed * 2;
666 OpNode *newPtr = NULL;
667
668 do {
669 if (size <= UINT_MAX/sizeof(OpNode)) {
670 newPtr = (OpNode *) attemptckrealloc(nodes,
671 size * sizeof(OpNode));
672 }
673 } while ((newPtr == NULL)
674 && ((size -= (size - nodesUsed) / 2) > nodesUsed));
675 if (newPtr == NULL) {
676 TclNewLiteralStringObj(msg,
677 "not enough memory to parse expression");
678 errCode = "NOMEM";
679 goto error;
680 }
681 nodesAvailable = size;
682 nodes = newPtr;
683 }
684 nodePtr = nodes + nodesUsed;
685
686 /*
687 * Skip white space between lexemes.
688 */
689
690 scanned = TclParseAllWhiteSpace(start, numBytes);
691 start += scanned;
692 numBytes -= scanned;
693
694 scanned = ParseLexeme(start, numBytes, &lexeme, &literal);
695
696 /*
697 * Use context to categorize the lexemes that are ambiguous.
698 */
699
700 if ((NODE_TYPE & lexeme) == 0) {
701 int b;
702
703 switch (lexeme) {
704 case INVALID:
705 msg = Tcl_ObjPrintf("invalid character \"%.*s\"",
706 scanned, start);
707 errCode = "BADCHAR";
708 goto error;
709 case INCOMPLETE:
710 msg = Tcl_ObjPrintf("incomplete operator \"%.*s\"",
711 scanned, start);
712 errCode = "PARTOP";
713 goto error;
714 case BAREWORD:
715
716 /*
717 * Most barewords in an expression are a syntax error. The
718 * exceptions are that when a bareword is followed by an open
719 * paren, it might be a function call, and when the bareword
720 * is a legal literal boolean value, we accept that as well.
721 */
722
723 if (start[scanned+TclParseAllWhiteSpace(
724 start+scanned, numBytes-scanned)] == '(') {
725 lexeme = FUNCTION;
726
727 /*
728 * When we compile the expression we'll need the function
729 * name, and there's no place in the parse tree to store
730 * it, so we keep a separate list of all the function
731 * names we've parsed in the order we found them.
732 */
733
734 Tcl_ListObjAppendElement(NULL, funcList, literal);
735 } else if (Tcl_GetBooleanFromObj(NULL,literal,&b) == TCL_OK) {
736 lexeme = BOOLEAN;
737 } else {
738 Tcl_DecrRefCount(literal);
739 msg = Tcl_ObjPrintf("invalid bareword \"%.*s%s\"",
740 (scanned < limit) ? scanned : limit - 3, start,
741 (scanned < limit) ? "" : "...");
742 post = Tcl_ObjPrintf(
743 "should be \"$%.*s%s\" or \"{%.*s%s}\"",
744 (scanned < limit) ? scanned : limit - 3,
745 start, (scanned < limit) ? "" : "...",
746 (scanned < limit) ? scanned : limit - 3,
747 start, (scanned < limit) ? "" : "...");
748 Tcl_AppendPrintfToObj(post, " or \"%.*s%s(...)\" or ...",
749 (scanned < limit) ? scanned : limit - 3,
750 start, (scanned < limit) ? "" : "...");
751 errCode = "BAREWORD";
752 if (start[0] == '0') {
753 const char *stop;
754 TclParseNumber(NULL, NULL, NULL, start, scanned,
755 &stop, TCL_PARSE_NO_WHITESPACE);
756
757 if (isdigit(UCHAR(*stop)) || (stop == start + 1)) {
758 switch (start[1]) {
759 case 'b':
760 Tcl_AppendToObj(post,
761 " (invalid binary number?)", -1);
762 parsePtr->errorType = TCL_PARSE_BAD_NUMBER;
763 errCode = "BADNUMBER";
764 subErrCode = "BINARY";
765 break;
766 case 'o':
767 Tcl_AppendToObj(post,
768 " (invalid octal number?)", -1);
769 parsePtr->errorType = TCL_PARSE_BAD_NUMBER;
770 errCode = "BADNUMBER";
771 subErrCode = "OCTAL";
772 break;
773 default:
774 if (isdigit(UCHAR(start[1]))) {
775 Tcl_AppendToObj(post,
776 " (invalid octal number?)", -1);
777 parsePtr->errorType = TCL_PARSE_BAD_NUMBER;
778 errCode = "BADNUMBER";
779 subErrCode = "OCTAL";
780 }
781 break;
782 }
783 }
784 }
785 goto error;
786 }
787 break;
788 case PLUS:
789 case MINUS:
790 if (IsOperator(lastParsed)) {
791 /*
792 * A "+" or "-" coming just after another operator must be
793 * interpreted as a unary operator.
794 */
795
796 lexeme |= UNARY;
797 } else {
798 lexeme |= BINARY;
799 }
800 }
801 } /* Uncategorized lexemes */
802
803 /*
804 * Handle lexeme based on its category.
805 */
806
807 switch (NODE_TYPE & lexeme) {
808 case LEAF: {
809 /*
810 * Each LEAF results in either a literal getting appended to the
811 * litList, or a sequence of Tcl_Tokens representing a Tcl word
812 * getting appended to the parsePtr->tokens. No OpNode is filled
813 * for this lexeme.
814 */
815
816 Tcl_Token *tokenPtr;
817 const char *end = start;
818 int wordIndex;
819 int code = TCL_OK;
820
821 /*
822 * A leaf operand appearing just after something that's not an
823 * operator is a syntax error.
824 */
825
826 if (NotOperator(lastParsed)) {
827 msg = Tcl_ObjPrintf("missing operator at %s", mark);
828 errCode = "MISSING";
829 scanned = 0;
830 insertMark = 1;
831
832 /*
833 * Free any literal to avoid a memleak.
834 */
835
836 if ((lexeme == NUMBER) || (lexeme == BOOLEAN)) {
837 Tcl_DecrRefCount(literal);
838 }
839 goto error;
840 }
841
842 switch (lexeme) {
843 case NUMBER:
844 case BOOLEAN:
845 /*
846 * TODO: Consider using a dict or hash to collapse all
847 * duplicate literals into a single representative value.
848 * (Like what is done with [split $s {}]).
849 * Pro: ~75% memory saving on expressions like
850 * {1+1+1+1+1+.....+1} (Convert "pointer + Tcl_Obj" cost
851 * to "pointer" cost only)
852 * Con: Cost of the dict store/retrieve on every literal in
853 * every expression when expressions like the above tend
854 * to be uncommon.
855 * The memory savings is temporary; Compiling to bytecode
856 * will collapse things as literals are registered
857 * anyway, so the savings applies only to the time
858 * between parsing and compiling. Possibly important due
859 * to high-water mark nature of memory allocation.
860 */
861
862 Tcl_ListObjAppendElement(NULL, litList, literal);
863 complete = lastParsed = OT_LITERAL;
864 start += scanned;
865 numBytes -= scanned;
866 continue;
867
868 default:
869 break;
870 }
871
872 /*
873 * Remaining LEAF cases may involve filling Tcl_Tokens, so make
874 * room for at least 2 more tokens.
875 */
876
877 TclGrowParseTokenArray(parsePtr, 2);
878 wordIndex = parsePtr->numTokens;
879 tokenPtr = parsePtr->tokenPtr + wordIndex;
880 tokenPtr->type = TCL_TOKEN_WORD;
881 tokenPtr->start = start;
882 parsePtr->numTokens++;
883
884 switch (lexeme) {
885 case QUOTED:
886 code = Tcl_ParseQuotedString(NULL, start, numBytes,
887 parsePtr, 1, &end);
888 scanned = end - start;
889 break;
890
891 case BRACED:
892 code = Tcl_ParseBraces(NULL, start, numBytes,
893 parsePtr, 1, &end);
894 scanned = end - start;
895 break;
896
897 case VARIABLE:
898 code = Tcl_ParseVarName(NULL, start, numBytes, parsePtr, 1);
899
900 /*
901 * Handle the quirk that Tcl_ParseVarName reports a successful
902 * parse even when it gets only a "$" with no variable name.
903 */
904
905 tokenPtr = parsePtr->tokenPtr + wordIndex + 1;
906 if (code == TCL_OK && tokenPtr->type != TCL_TOKEN_VARIABLE) {
907 TclNewLiteralStringObj(msg, "invalid character \"$\"");
908 errCode = "BADCHAR";
909 goto error;
910 }
911 scanned = tokenPtr->size;
912 break;
913
914 case SCRIPT: {
915 Tcl_Parse *nestedPtr = (Tcl_Parse *)
916 TclStackAlloc(interp, sizeof(Tcl_Parse));
917
918 tokenPtr = parsePtr->tokenPtr + parsePtr->numTokens;
919 tokenPtr->type = TCL_TOKEN_COMMAND;
920 tokenPtr->start = start;
921 tokenPtr->numComponents = 0;
922
923 end = start + numBytes;
924 start++;
925 while (1) {
926 code = Tcl_ParseCommand(interp, start, end - start, 1,
927 nestedPtr);
928 if (code != TCL_OK) {
929 parsePtr->term = nestedPtr->term;
930 parsePtr->errorType = nestedPtr->errorType;
931 parsePtr->incomplete = nestedPtr->incomplete;
932 break;
933 }
934 start = nestedPtr->commandStart + nestedPtr->commandSize;
935 Tcl_FreeParse(nestedPtr);
936 if ((nestedPtr->term < end) && (nestedPtr->term[0] == ']')
937 && !nestedPtr->incomplete) {
938 break;
939 }
940
941 if (start == end) {
942 TclNewLiteralStringObj(msg, "missing close-bracket");
943 parsePtr->term = tokenPtr->start;
944 parsePtr->errorType = TCL_PARSE_MISSING_BRACKET;
945 parsePtr->incomplete = 1;
946 code = TCL_ERROR;
947 errCode = "UNBALANCED";
948 break;
949 }
950 }
951 TclStackFree(interp, nestedPtr);
952 end = start;
953 start = tokenPtr->start;
954 scanned = end - start;
955 tokenPtr->size = scanned;
956 parsePtr->numTokens++;
957 break;
958 } /* SCRIPT case */
959 }
960 if (code != TCL_OK) {
961 /*
962 * Here we handle all the syntax errors generated by the
963 * Tcl_Token generating parsing routines called in the switch
964 * just above. If the value of parsePtr->incomplete is 1, then
965 * the error was an unbalanced '[', '(', '{', or '"' and
966 * parsePtr->term is pointing to that unbalanced character. If
967 * the value of parsePtr->incomplete is 0, then the error is
968 * one of lacking whitespace following a quoted word, for
969 * example: expr {[an error {foo}bar]}, and parsePtr->term
970 * points to where the whitespace is missing. We reset our
971 * values of start and scanned so that when our error message
972 * is constructed, the location of the syntax error is sure to
973 * appear in it, even if the quoted expression is truncated.
974 */
975
976 start = parsePtr->term;
977 scanned = parsePtr->incomplete;
978 if (parsePtr->incomplete) {
979 errCode = "UNBALANCED";
980 }
981 goto error;
982 }
983
984 tokenPtr = parsePtr->tokenPtr + wordIndex;
985 tokenPtr->size = scanned;
986 tokenPtr->numComponents = parsePtr->numTokens - wordIndex - 1;
987 if (!parseOnly && ((lexeme == QUOTED) || (lexeme == BRACED))) {
988 /*
989 * When this expression is destined to be compiled, and a
990 * braced or quoted word within an expression is known at
991 * compile time (no runtime substitutions in it), we can store
992 * it as a literal rather than in its tokenized form. This is
993 * an advantage since the compiled bytecode is going to need
994 * the argument in Tcl_Obj form eventually, so it's just as
995 * well to get there now. Another advantage is that with this
996 * conversion, larger constant expressions might be grown and
997 * optimized.
998 *
999 * On the contrary, if the end goal of this parse is to fill a
1000 * Tcl_Parse for a caller of Tcl_ParseExpr(), then it's
1001 * wasteful to convert to a literal only to convert back again
1002 * later.
1003 */
1004
1005 TclNewObj(literal);
1006 if (TclWordKnownAtCompileTime(tokenPtr, literal)) {
1007 Tcl_ListObjAppendElement(NULL, litList, literal);
1008 complete = lastParsed = OT_LITERAL;
1009 parsePtr->numTokens = wordIndex;
1010 break;
1011 }
1012 Tcl_DecrRefCount(literal);
1013 }
1014 complete = lastParsed = OT_TOKENS;
1015 break;
1016 } /* case LEAF */
1017
1018 case UNARY:
1019
1020 /*
1021 * A unary operator appearing just after something that's not an
1022 * operator is a syntax error -- something trying to be the left
1023 * operand of an operator that doesn't take one.
1024 */
1025
1026 if (NotOperator(lastParsed)) {
1027 msg = Tcl_ObjPrintf("missing operator at %s", mark);
1028 scanned = 0;
1029 insertMark = 1;
1030 errCode = "MISSING";
1031 goto error;
1032 }
1033
1034 /*
1035 * Create an OpNode for the unary operator.
1036 */
1037
1038 nodePtr->lexeme = lexeme;
1039 nodePtr->precedence = prec[lexeme];
1040 nodePtr->mark = MARK_RIGHT;
1041
1042 /*
1043 * A FUNCTION cannot be a constant expression, because Tcl allows
1044 * functions to return variable results with the same arguments;
1045 * for example, rand(). Other unary operators can root a constant
1046 * expression, so long as the argument is a constant expression.
1047 */
1048
1049 nodePtr->constant = (lexeme != FUNCTION);
1050
1051 /*
1052 * This unary operator is a new incomplete tree, so push it onto
1053 * our stack of incomplete trees. Also remember it as the last
1054 * lexeme we parsed.
1055 */
1056
1057 nodePtr->p.prev = incomplete;
1058 incomplete = lastParsed = nodesUsed;
1059 nodesUsed++;
1060 break;
1061
1062 case BINARY: {
1063 OpNode *incompletePtr;
1064 unsigned char precedence = prec[lexeme];
1065
1066 /*
1067 * A binary operator appearing just after another operator is a
1068 * syntax error -- one of the two operators is missing an operand.
1069 */
1070
1071 if (IsOperator(lastParsed)) {
1072 if ((lexeme == CLOSE_PAREN)
1073 && (nodePtr[-1].lexeme == OPEN_PAREN)) {
1074 if (nodePtr[-2].lexeme == FUNCTION) {
1075 /*
1076 * Normally, "()" is a syntax error, but as a special
1077 * case accept it as an argument list for a function.
1078 * Treat this as a special LEAF lexeme, and restart
1079 * the parsing loop with zero characters scanned. We
1080 * will parse the ")" again the next time through, but
1081 * with the OT_EMPTY leaf as the subexpression between
1082 * the parens.
1083 */
1084
1085 scanned = 0;
1086 complete = lastParsed = OT_EMPTY;
1087 break;
1088 }
1089 msg = Tcl_ObjPrintf("empty subexpression at %s", mark);
1090 scanned = 0;
1091 insertMark = 1;
1092 errCode = "EMPTY";
1093 goto error;
1094 }
1095
1096 if (nodePtr[-1].precedence > precedence) {
1097 if (nodePtr[-1].lexeme == OPEN_PAREN) {
1098 TclNewLiteralStringObj(msg, "unbalanced open paren");
1099 parsePtr->errorType = TCL_PARSE_MISSING_PAREN;
1100 errCode = "UNBALANCED";
1101 } else if (nodePtr[-1].lexeme == COMMA) {
1102 msg = Tcl_ObjPrintf(
1103 "missing function argument at %s", mark);
1104 scanned = 0;
1105 insertMark = 1;
1106 errCode = "MISSING";
1107 } else if (nodePtr[-1].lexeme == START) {
1108 TclNewLiteralStringObj(msg, "empty expression");
1109 errCode = "EMPTY";
1110 }
1111 } else if (lexeme == CLOSE_PAREN) {
1112 TclNewLiteralStringObj(msg, "unbalanced close paren");
1113 errCode = "UNBALANCED";
1114 } else if ((lexeme == COMMA)
1115 && (nodePtr[-1].lexeme == OPEN_PAREN)
1116 && (nodePtr[-2].lexeme == FUNCTION)) {
1117 msg = Tcl_ObjPrintf("missing function argument at %s",
1118 mark);
1119 scanned = 0;
1120 insertMark = 1;
1121 errCode = "UNBALANCED";
1122 }
1123 if (msg == NULL) {
1124 msg = Tcl_ObjPrintf("missing operand at %s", mark);
1125 scanned = 0;
1126 insertMark = 1;
1127 errCode = "MISSING";
1128 }
1129 goto error;
1130 }
1131
1132 /*
1133 * Here is where the tree comes together. At this point, we have a
1134 * stack of incomplete trees corresponding to substrings that are
1135 * incomplete expressions, followed by a complete tree
1136 * corresponding to a substring that is itself a complete
1137 * expression, followed by the binary operator we have just
1138 * parsed. The incomplete trees can each be completed by adding a
1139 * right operand.
1140 *
1141 * To illustrate with an example, when we parse the expression
1142 * "1+2*3-4" and we reach this point having just parsed the "-"
1143 * operator, we have these incomplete trees: START, "1+", and
1144 * "2*". Next we have the complete subexpression "3". Last is the
1145 * "-" we've just parsed.
1146 *
1147 * The next step is to join our complete tree to an operator. The
1148 * choice is governed by the precedence and associativity of the
1149 * competing operators. If we connect it as the right operand of
1150 * our most recent incomplete tree, we get a new complete tree,
1151 * and we can repeat the process. The while loop following repeats
1152 * this until precedence indicates it is time to join the complete
1153 * tree as the left operand of the just parsed binary operator.
1154 *
1155 * Continuing the example, the first pass through the loop will
1156 * join "3" to "2*"; the next pass will join "2*3" to "1+". Then
1157 * we'll exit the loop and join "1+2*3" to "-". When we return to
1158 * parse another lexeme, our stack of incomplete trees is START
1159 * and "1+2*3-".
1160 */
1161
1162 while (1) {
1163 incompletePtr = nodes + incomplete;
1164
1165 if (incompletePtr->precedence < precedence) {
1166 break;
1167 }
1168
1169 if (incompletePtr->precedence == precedence) {
1170 /*
1171 * Right association rules for exponentiation.
1172 */
1173
1174 if (lexeme == EXPON) {
1175 break;
1176 }
1177
1178 /*
1179 * Special association rules for the conditional
1180 * operators. The "?" and ":" operators have equal
1181 * precedence, but must be linked up in sensible pairs.
1182 */
1183
1184 if ((incompletePtr->lexeme == QUESTION)
1185 && (NotOperator(complete)
1186 || (nodes[complete].lexeme != COLON))) {
1187 break;
1188 }
1189 if ((incompletePtr->lexeme == COLON)
1190 && (lexeme == QUESTION)) {
1191 break;
1192 }
1193 }
1194
1195 /*
1196 * Some special syntax checks...
1197 */
1198
1199 /* Parens must balance */
1200 if ((incompletePtr->lexeme == OPEN_PAREN)
1201 && (lexeme != CLOSE_PAREN)) {
1202 TclNewLiteralStringObj(msg, "unbalanced open paren");
1203 parsePtr->errorType = TCL_PARSE_MISSING_PAREN;
1204 errCode = "UNBALANCED";
1205 goto error;
1206 }
1207
1208 /* Right operand of "?" must be ":" */
1209 if ((incompletePtr->lexeme == QUESTION)
1210 && (NotOperator(complete)
1211 || (nodes[complete].lexeme != COLON))) {
1212 msg = Tcl_ObjPrintf("missing operator \":\" at %s", mark);
1213 scanned = 0;
1214 insertMark = 1;
1215 errCode = "MISSING";
1216 goto error;
1217 }
1218
1219 /* Operator ":" may only be right operand of "?" */
1220 if (IsOperator(complete)
1221 && (nodes[complete].lexeme == COLON)
1222 && (incompletePtr->lexeme != QUESTION)) {
1223 TclNewLiteralStringObj(msg,
1224 "unexpected operator \":\" "
1225 "without preceding \"?\"");
1226 errCode = "SURPRISE";
1227 goto error;
1228 }
1229
1230 /*
1231 * Attach complete tree as right operand of most recent
1232 * incomplete tree.
1233 */
1234
1235 incompletePtr->right = complete;
1236 if (IsOperator(complete)) {
1237 nodes[complete].p.parent = incomplete;
1238 incompletePtr->constant = incompletePtr->constant
1239 && nodes[complete].constant;
1240 } else {
1241 incompletePtr->constant = incompletePtr->constant
1242 && (complete == OT_LITERAL);
1243 }
1244
1245 /*
1246 * The QUESTION/COLON and FUNCTION/OPEN_PAREN combinations
1247 * each make up a single operator. Force them to agree whether
1248 * they have a constant expression.
1249 */
1250
1251 if ((incompletePtr->lexeme == QUESTION)
1252 || (incompletePtr->lexeme == FUNCTION)) {
1253 nodes[complete].constant = incompletePtr->constant;
1254 }
1255
1256 if (incompletePtr->lexeme == START) {
1257 /*
1258 * Completing the START tree indicates we're done.
1259 * Transfer the parse tree to the caller and return.
1260 */
1261
1262 *opTreePtr = nodes;
1263 return TCL_OK;
1264 }
1265
1266 /*
1267 * With a right operand attached, last incomplete tree has
1268 * become the complete tree. Pop it from the incomplete tree
1269 * stack.
1270 */
1271
1272 complete = incomplete;
1273 incomplete = incompletePtr->p.prev;
1274
1275 /* CLOSE_PAREN can only close one OPEN_PAREN. */
1276 if (incompletePtr->lexeme == OPEN_PAREN) {
1277 break;
1278 }
1279 }
1280
1281 /*
1282 * More syntax checks...
1283 */
1284
1285 /* Parens must balance. */
1286 if (lexeme == CLOSE_PAREN) {
1287 if (incompletePtr->lexeme != OPEN_PAREN) {
1288 TclNewLiteralStringObj(msg, "unbalanced close paren");
1289 errCode = "UNBALANCED";
1290 goto error;
1291 }
1292 }
1293
1294 /* Commas must appear only in function argument lists. */
1295 if (lexeme == COMMA) {
1296 if ((incompletePtr->lexeme != OPEN_PAREN)
1297 || (incompletePtr[-1].lexeme != FUNCTION)) {
1298 TclNewLiteralStringObj(msg,
1299 "unexpected \",\" outside function argument list");
1300 errCode = "SURPRISE";
1301 goto error;
1302 }
1303 }
1304
1305 /* Operator ":" may only be right operand of "?" */
1306 if (IsOperator(complete) && (nodes[complete].lexeme == COLON)) {
1307 TclNewLiteralStringObj(msg,
1308 "unexpected operator \":\" without preceding \"?\"");
1309 errCode = "SURPRISE";
1310 goto error;
1311 }
1312
1313 /*
1314 * Create no node for a CLOSE_PAREN lexeme.
1315 */
1316
1317 if (lexeme == CLOSE_PAREN) {
1318 break;
1319 }
1320
1321 /*
1322 * Link complete tree as left operand of new node.
1323 */
1324
1325 nodePtr->lexeme = lexeme;
1326 nodePtr->precedence = precedence;
1327 nodePtr->mark = MARK_LEFT;
1328 nodePtr->left = complete;
1329
1330 /*
1331 * The COMMA operator cannot be optimized, since the function
1332 * needs all of its arguments, and optimization would reduce the
1333 * number. Other binary operators root constant expressions when
1334 * both arguments are constant expressions.
1335 */
1336
1337 nodePtr->constant = (lexeme != COMMA);
1338
1339 if (IsOperator(complete)) {
1340 nodes[complete].p.parent = nodesUsed;
1341 nodePtr->constant = nodePtr->constant
1342 && nodes[complete].constant;
1343 } else {
1344 nodePtr->constant = nodePtr->constant
1345 && (complete == OT_LITERAL);
1346 }
1347
1348 /*
1349 * With a left operand attached and a right operand missing, the
1350 * just-parsed binary operator is root of a new incomplete tree.
1351 * Push it onto the stack of incomplete trees.
1352 */
1353
1354 nodePtr->p.prev = incomplete;
1355 incomplete = lastParsed = nodesUsed;
1356 nodesUsed++;
1357 break;
1358 } /* case BINARY */
1359 } /* lexeme handler */
1360
1361 /* Advance past the just-parsed lexeme */
1362 start += scanned;
1363 numBytes -= scanned;
1364 } /* main parsing loop */
1365
1366 /*
1367 * We only get here if there's been an error. Any errors that didn't get a
1368 * suitable parsePtr->errorType, get recorded as syntax errors.
1369 */
1370
1371 error:
1372 if (parsePtr->errorType == TCL_PARSE_SUCCESS) {
1373 parsePtr->errorType = TCL_PARSE_SYNTAX;
1374 }
1375
1376 /*
1377 * Free any partial parse tree we've built.
1378 */
1379
1380 if (nodes != NULL) {
1381 ckfree(nodes);
1382 }
1383
1384 if (interp == NULL) {
1385 /*
1386 * Nowhere to report an error message, so just free it.
1387 */
1388
1389 if (msg) {
1390 Tcl_DecrRefCount(msg);
1391 }
1392 } else {
1393 /*
1394 * Construct the complete error message. Start with the simple error
1395 * message, pulled from the interp result if necessary...
1396 */
1397
1398 if (msg == NULL) {
1399 msg = Tcl_GetObjResult(interp);
1400 }
1401
1402 /*
1403 * Add a detailed quote from the bad expression, displaying and
1404 * sometimes marking the precise location of the syntax error.
1405 */
1406
1407 Tcl_AppendPrintfToObj(msg, "\nin expression \"%s%.*s%.*s%s%s%.*s%s\"",
1408 ((start - limit) < parsePtr->string) ? "" : "...",
1409 ((start - limit) < parsePtr->string)
1410 ? (int) (start - parsePtr->string) : limit - 3,
1411 ((start - limit) < parsePtr->string)
1412 ? parsePtr->string : start - limit + 3,
1413 (scanned < limit) ? scanned : limit - 3, start,
1414 (scanned < limit) ? "" : "...", insertMark ? mark : "",
1415 (start + scanned + limit > parsePtr->end)
1416 ? (int) (parsePtr->end - start) - scanned : limit-3,
1417 start + scanned,
1418 (start + scanned + limit > parsePtr->end) ? "" : "...");
1419
1420 /*
1421 * Next, append any postscript message.
1422 */
1423
1424 if (post != NULL) {
1425 Tcl_AppendToObj(msg, ";\n", -1);
1426 Tcl_AppendObjToObj(msg, post);
1427 Tcl_DecrRefCount(post);
1428 }
1429 Tcl_SetObjResult(interp, msg);
1430
1431 /*
1432 * Finally, place context information in the errorInfo.
1433 */
1434
1435 numBytes = parsePtr->end - parsePtr->string;
1436 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
1437 "\n (parsing expression \"%.*s%s\")",
1438 (numBytes < limit) ? numBytes : limit - 3,
1439 parsePtr->string, (numBytes < limit) ? "" : "..."));
1440 if (errCode) {
1441 Tcl_SetErrorCode(interp, "TCL", "PARSE", "EXPR", errCode,
1442 subErrCode, (char *)NULL);
1443 }
1444 }
1445
1446 return TCL_ERROR;
1447 }
1448
1449 /*
1450 *----------------------------------------------------------------------
1451 *
1452 * ConvertTreeToTokens --
1453 *
1454 * Given a string, the numBytes bytes starting at start, and an OpNode
1455 * tree and Tcl_Token array created by passing that same string to
1456 * ParseExpr(), this function writes into *parsePtr the sequence of
1457 * Tcl_Tokens needed so to satisfy the historical interface provided by
1458 * Tcl_ParseExpr(). Note that this routine exists only for the sake of
1459 * the public Tcl_ParseExpr() routine. It is not used by Tcl itself at
1460 * all.
1461 *
1462 * Results:
1463 * None.
1464 *
1465 * Side effects:
1466 * The Tcl_Parse *parsePtr is filled with Tcl_Tokens representing the
1467 * parsed expression.
1468 *
1469 *----------------------------------------------------------------------
1470 */
1471
1472 static void
1473 ConvertTreeToTokens(
1474 const char *start,
1475 int numBytes,
1476 OpNode *nodes,
1477 Tcl_Token *tokenPtr,
1478 Tcl_Parse *parsePtr)
1479 {
1480 int subExprTokenIdx = 0;
1481 OpNode *nodePtr = nodes;
1482 int next = nodePtr->right;
1483
1484 while (1) {
1485 Tcl_Token *subExprTokenPtr;
1486 int scanned, parentIdx;
1487 unsigned char lexeme;
1488
1489 /*
1490 * Advance the mark so the next exit from this node won't retrace
1491 * steps over ground already covered.
1492 */
1493
1494 nodePtr->mark++;
1495
1496 /*
1497 * Handle next child node or leaf.
1498 */
1499
1500 switch (next) {
1501 case OT_EMPTY:
1502
1503 /* No tokens and no characters for the OT_EMPTY leaf. */
1504 break;
1505
1506 case OT_LITERAL:
1507
1508 /*
1509 * Skip any white space that comes before the literal.
1510 */
1511
1512 scanned = TclParseAllWhiteSpace(start, numBytes);
1513 start += scanned;
1514 numBytes -= scanned;
1515
1516 /*
1517 * Reparse the literal to get pointers into source string.
1518 */
1519
1520 scanned = ParseLexeme(start, numBytes, &lexeme, NULL);
1521
1522 TclGrowParseTokenArray(parsePtr, 2);
1523 subExprTokenPtr = parsePtr->tokenPtr + parsePtr->numTokens;
1524 subExprTokenPtr->type = TCL_TOKEN_SUB_EXPR;
1525 subExprTokenPtr->start = start;
1526 subExprTokenPtr->size = scanned;
1527 subExprTokenPtr->numComponents = 1;
1528 subExprTokenPtr[1].type = TCL_TOKEN_TEXT;
1529 subExprTokenPtr[1].start = start;
1530 subExprTokenPtr[1].size = scanned;
1531 subExprTokenPtr[1].numComponents = 0;
1532
1533 parsePtr->numTokens += 2;
1534 start += scanned;
1535 numBytes -= scanned;
1536 break;
1537
1538 case OT_TOKENS: {
1539 /*
1540 * tokenPtr points to a token sequence that came from parsing a
1541 * Tcl word. A Tcl word is made up of a sequence of one or more
1542 * elements. When the word is only a single element, it's been the
1543 * historical practice to replace the TCL_TOKEN_WORD token
1544 * directly with a TCL_TOKEN_SUB_EXPR token. However, when the
1545 * word has multiple elements, a TCL_TOKEN_WORD token is kept as a
1546 * grouping device so that TCL_TOKEN_SUB_EXPR always has only one
1547 * element. Wise or not, these are the rules the Tcl expr parser
1548 * has followed, and for the sake of those few callers of
1549 * Tcl_ParseExpr() we do not change them now. Internally, we can
1550 * do better.
1551 */
1552
1553 int toCopy = tokenPtr->numComponents + 1;
1554
1555 if (tokenPtr->numComponents == tokenPtr[1].numComponents + 1) {
1556 /*
1557 * Single element word. Copy tokens and convert the leading
1558 * token to TCL_TOKEN_SUB_EXPR.
1559 */
1560
1561 TclGrowParseTokenArray(parsePtr, toCopy);
1562 subExprTokenPtr = parsePtr->tokenPtr + parsePtr->numTokens;
1563 memcpy(subExprTokenPtr, tokenPtr,
1564 (size_t) toCopy * sizeof(Tcl_Token));
1565 subExprTokenPtr->type = TCL_TOKEN_SUB_EXPR;
1566 parsePtr->numTokens += toCopy;
1567 } else {
1568 /*
1569 * Multiple element word. Create a TCL_TOKEN_SUB_EXPR token to
1570 * lead, with fields initialized from the leading token, then
1571 * copy entire set of word tokens.
1572 */
1573
1574 TclGrowParseTokenArray(parsePtr, toCopy+1);
1575 subExprTokenPtr = parsePtr->tokenPtr + parsePtr->numTokens;
1576 *subExprTokenPtr = *tokenPtr;
1577 subExprTokenPtr->type = TCL_TOKEN_SUB_EXPR;
1578 subExprTokenPtr->numComponents++;
1579 subExprTokenPtr++;
1580 memcpy(subExprTokenPtr, tokenPtr,
1581 (size_t) toCopy * sizeof(Tcl_Token));
1582 parsePtr->numTokens += toCopy + 1;
1583 }
1584
1585 scanned = tokenPtr->start + tokenPtr->size - start;
1586 start += scanned;
1587 numBytes -= scanned;
1588 tokenPtr += toCopy;
1589 break;
1590 }
1591
1592 default:
1593
1594 /*
1595 * Advance to the child node, which is an operator.
1596 */
1597
1598 nodePtr = nodes + next;
1599
1600 /*
1601 * Skip any white space that comes before the subexpression.
1602 */
1603
1604 scanned = TclParseAllWhiteSpace(start, numBytes);
1605 start += scanned;
1606 numBytes -= scanned;
1607
1608 /*
1609 * Generate tokens for the operator / subexpression...
1610 */
1611
1612 switch (nodePtr->lexeme) {
1613 case OPEN_PAREN:
1614 case COMMA:
1615 case COLON:
1616
1617 /*
1618 * Historical practice has been to have no Tcl_Tokens for
1619 * these operators.
1620 */
1621
1622 break;
1623
1624 default: {
1625
1626 /*
1627 * Remember the index of the last subexpression we were
1628 * working on -- that of our parent. We'll stack it later.
1629 */
1630
1631 parentIdx = subExprTokenIdx;
1632
1633 /*
1634 * Verify space for the two leading Tcl_Tokens representing
1635 * the subexpression rooted by this operator. The first
1636 * Tcl_Token will be of type TCL_TOKEN_SUB_EXPR; the second of
1637 * type TCL_TOKEN_OPERATOR.
1638 */
1639
1640 TclGrowParseTokenArray(parsePtr, 2);
1641 subExprTokenIdx = parsePtr->numTokens;
1642 subExprTokenPtr = parsePtr->tokenPtr + subExprTokenIdx;
1643 parsePtr->numTokens += 2;
1644 subExprTokenPtr->type = TCL_TOKEN_SUB_EXPR;
1645 subExprTokenPtr[1].type = TCL_TOKEN_OPERATOR;
1646
1647 /*
1648 * Our current position scanning the string is the starting
1649 * point for this subexpression.
1650 */
1651
1652 subExprTokenPtr->start = start;
1653
1654 /*
1655 * Eventually, we know that the numComponents field of the
1656 * Tcl_Token of type TCL_TOKEN_OPERATOR will be 0. This means
1657 * we can make other use of this field for now to track the
1658 * stack of subexpressions we have pending.
1659 */
1660
1661 subExprTokenPtr[1].numComponents = parentIdx;
1662 break;
1663 }
1664 }
1665 break;
1666 }
1667
1668 /* Determine which way to exit the node on this pass. */
1669 router:
1670 switch (nodePtr->mark) {
1671 case MARK_LEFT:
1672 next = nodePtr->left;
1673 break;
1674
1675 case MARK_RIGHT:
1676 next = nodePtr->right;
1677
1678 /*
1679 * Skip any white space that comes before the operator.
1680 */
1681
1682 scanned = TclParseAllWhiteSpace(start, numBytes);
1683 start += scanned;
1684 numBytes -= scanned;
1685
1686 /*
1687 * Here we scan from the string the operator corresponding to
1688 * nodePtr->lexeme.
1689 */
1690
1691 scanned = ParseLexeme(start, numBytes, &lexeme, NULL);
1692
1693 switch(nodePtr->lexeme) {
1694 case OPEN_PAREN:
1695 case COMMA:
1696 case COLON:
1697
1698 /*
1699 * No tokens for these lexemes -> nothing to do.
1700 */
1701
1702 break;
1703
1704 default:
1705
1706 /*
1707 * Record in the TCL_TOKEN_OPERATOR token the pointers into
1708 * the string marking where the operator is.
1709 */
1710
1711 subExprTokenPtr = parsePtr->tokenPtr + subExprTokenIdx;
1712 subExprTokenPtr[1].start = start;
1713 subExprTokenPtr[1].size = scanned;
1714 break;
1715 }
1716
1717 start += scanned;
1718 numBytes -= scanned;
1719 break;
1720
1721 case MARK_PARENT:
1722 switch (nodePtr->lexeme) {
1723 case START:
1724
1725 /* When we get back to the START node, we're done. */
1726 return;
1727
1728 case COMMA:
1729 case COLON:
1730
1731 /* No tokens for these lexemes -> nothing to do. */
1732 break;
1733
1734 case OPEN_PAREN:
1735
1736 /*
1737 * Skip past matching close paren.
1738 */
1739
1740 scanned = TclParseAllWhiteSpace(start, numBytes);
1741 start += scanned;
1742 numBytes -= scanned;
1743 scanned = ParseLexeme(start, numBytes, &lexeme, NULL);
1744 start += scanned;
1745 numBytes -= scanned;
1746 break;
1747
1748 default:
1749
1750 /*
1751 * Before we leave this node/operator/subexpression for the
1752 * last time, finish up its tokens....
1753 *
1754 * Our current position scanning the string is where the
1755 * substring for the subexpression ends.
1756 */
1757
1758 subExprTokenPtr = parsePtr->tokenPtr + subExprTokenIdx;
1759 subExprTokenPtr->size = start - subExprTokenPtr->start;
1760
1761 /*
1762 * All the Tcl_Tokens allocated and filled belong to
1763 * this subexpression. The first token is the leading
1764 * TCL_TOKEN_SUB_EXPR token, and all the rest (one fewer)
1765 * are its components.
1766 */
1767
1768 subExprTokenPtr->numComponents =
1769 (parsePtr->numTokens - subExprTokenIdx) - 1;
1770
1771 /*
1772 * Finally, as we return up the tree to our parent, pop the
1773 * parent subexpression off our subexpression stack, and
1774 * fill in the zero numComponents for the operator Tcl_Token.
1775 */
1776
1777 parentIdx = subExprTokenPtr[1].numComponents;
1778 subExprTokenPtr[1].numComponents = 0;
1779 subExprTokenIdx = parentIdx;
1780 break;
1781 }
1782
1783 /*
1784 * Since we're returning to parent, skip child handling code.
1785 */
1786
1787 nodePtr = nodes + nodePtr->p.parent;
1788 goto router;
1789 }
1790 }
1791 }
1792
1793 /*
1794 *----------------------------------------------------------------------
1795 *
1796 * Tcl_ParseExpr --
1797 *
1798 * Given a string, the numBytes bytes starting at start, this function
1799 * parses it as a Tcl expression and stores information about the
1800 * structure of the expression in the Tcl_Parse struct indicated by the
1801 * caller.
1802 *
1803 * Results:
1804 * If the string is successfully parsed as a valid Tcl expression, TCL_OK
1805 * is returned, and data about the expression structure is written to
1806 * *parsePtr. If the string cannot be parsed as a valid Tcl expression,
1807 * TCL_ERROR is returned, and if interp is non-NULL, an error message is
1808 * written to interp.
1809 *
1810 * Side effects:
1811 * If there is insufficient space in parsePtr to hold all the information
1812 * about the expression, then additional space is malloc-ed. If the
1813 * function returns TCL_OK then the caller must eventually invoke
1814 * Tcl_FreeParse to release any additional space that was allocated.
1815 *
1816 *----------------------------------------------------------------------
1817 */
1818
1819 int
1820 Tcl_ParseExpr(
1821 Tcl_Interp *interp, /* Used for error reporting. */
1822 const char *start, /* Start of source string to parse. */
1823 int numBytes, /* Number of bytes in string. If < 0, the
1824 * string consists of all bytes up to the
1825 * first null character. */
1826 Tcl_Parse *parsePtr) /* Structure to fill with information about
1827 * the parsed expression; any previous
1828 * information in the structure is ignored. */
1829 {
1830 int code;
1831 OpNode *opTree = NULL; /* Will point to the tree of operators. */
1832 Tcl_Obj *litList; /* List to hold the literals. */
1833 Tcl_Obj *funcList; /* List to hold the functon names. */
1834 Tcl_Parse *exprParsePtr = (Tcl_Parse *)TclStackAlloc(interp, sizeof(Tcl_Parse));
1835 /* Holds the Tcl_Tokens of substitutions. */
1836
1837 TclNewObj(litList);
1838 TclNewObj(funcList);
1839 if (numBytes < 0) {
1840 numBytes = (start ? strlen(start) : 0);
1841 }
1842
1843 code = ParseExpr(interp, start, numBytes, &opTree, litList, funcList,
1844 exprParsePtr, 1 /* parseOnly */);
1845 Tcl_DecrRefCount(funcList);
1846 Tcl_DecrRefCount(litList);
1847
1848 TclParseInit(interp, start, numBytes, parsePtr);
1849 if (code == TCL_OK) {
1850 ConvertTreeToTokens(start, numBytes,
1851 opTree, exprParsePtr->tokenPtr, parsePtr);
1852 } else {
1853 parsePtr->term = exprParsePtr->term;
1854 parsePtr->errorType = exprParsePtr->errorType;
1855 }
1856
1857 Tcl_FreeParse(exprParsePtr);
1858 TclStackFree(interp, exprParsePtr);
1859 ckfree(opTree);
1860 return code;
1861 }
1862
1863 /*
1864 *----------------------------------------------------------------------
1865 *
1866 * ParseLexeme --
1867 *
1868 * Parse a single lexeme from the start of a string, scanning no more
1869 * than numBytes bytes.
1870 *
1871 * Results:
1872 * Returns the number of bytes scanned to produce the lexeme.
1873 *
1874 * Side effects:
1875 * Code identifying lexeme parsed is written to *lexemePtr.
1876 *
1877 *----------------------------------------------------------------------
1878 */
1879
1880 static int
1881 ParseLexeme(
1882 const char *start, /* Start of lexeme to parse. */
1883 int numBytes, /* Number of bytes in string. */
1884 unsigned char *lexemePtr, /* Write code of parsed lexeme to this
1885 * storage. */
1886 Tcl_Obj **literalPtr) /* Write corresponding literal value to this
1887 storage, if non-NULL. */
1888 {
1889 const char *end;
1890 int scanned;
1891 Tcl_UniChar ch = 0;
1892 Tcl_Obj *literal = NULL;
1893 unsigned char byte;
1894
1895 if (numBytes == 0) {
1896 *lexemePtr = END;
1897 return 0;
1898 }
1899 byte = UCHAR(*start);
1900 if (byte < sizeof(Lexeme) && Lexeme[byte] != 0) {
1901 *lexemePtr = Lexeme[byte];
1902 return 1;
1903 }
1904 switch (byte) {
1905 case '*':
1906 if ((numBytes > 1) && (start[1] == '*')) {
1907 *lexemePtr = EXPON;
1908 return 2;
1909 }
1910 *lexemePtr = MULT;
1911 return 1;
1912
1913 case '=':
1914 if ((numBytes > 1) && (start[1] == '=')) {
1915 *lexemePtr = EQUAL;
1916 return 2;
1917 }
1918 *lexemePtr = INCOMPLETE;
1919 return 1;
1920
1921 case '!':
1922 if ((numBytes > 1) && (start[1] == '=')) {
1923 *lexemePtr = NEQ;
1924 return 2;
1925 }
1926 *lexemePtr = NOT;
1927 return 1;
1928
1929 case '&':
1930 if ((numBytes > 1) && (start[1] == '&')) {
1931 *lexemePtr = AND;
1932 return 2;
1933 }
1934 *lexemePtr = BIT_AND;
1935 return 1;
1936
1937 case '|':
1938 if ((numBytes > 1) && (start[1] == '|')) {
1939 *lexemePtr = OR;
1940 return 2;
1941 }
1942 *lexemePtr = BIT_OR;
1943 return 1;
1944
1945 case '<':
1946 if (numBytes > 1) {
1947 switch (start[1]) {
1948 case '<':
1949 *lexemePtr = LEFT_SHIFT;
1950 return 2;
1951 case '=':
1952 *lexemePtr = LEQ;
1953 return 2;
1954 }
1955 }
1956 *lexemePtr = LESS;
1957 return 1;
1958
1959 case '>':
1960 if (numBytes > 1) {
1961 switch (start[1]) {
1962 case '>':
1963 *lexemePtr = RIGHT_SHIFT;
1964 return 2;
1965 case '=':
1966 *lexemePtr = GEQ;
1967 return 2;
1968 }
1969 }
1970 *lexemePtr = GREATER;
1971 return 1;
1972
1973 case 'i':
1974 if ((numBytes > 1) && (start[1] == 'n')
1975 && ((numBytes == 2) || start[2] & 0x80 || !isalpha(UCHAR(start[2])))) {
1976 /*
1977 * Must make this check so we can tell the difference between the
1978 * "in" operator and the "int" function name and the "infinity"
1979 * numeric value.
1980 */
1981
1982 *lexemePtr = IN_LIST;
1983 return 2;
1984 }
1985 break;
1986
1987 case 'e':
1988 if ((numBytes > 1) && (start[1] == 'q')
1989 && ((numBytes == 2) || start[2] & 0x80 || !isalpha(UCHAR(start[2])))) {
1990 *lexemePtr = STREQ;
1991 return 2;
1992 }
1993 break;
1994
1995 case 'n':
1996 if ((numBytes > 1)
1997 && ((numBytes == 2) || start[2] & 0x80 || !isalpha(UCHAR(start[2])))) {
1998 switch (start[1]) {
1999 case 'e':
2000 *lexemePtr = STRNEQ;
2001 return 2;
2002 case 'i':
2003 *lexemePtr = NOT_IN_LIST;
2004 return 2;
2005 }
2006 }
2007 }
2008
2009 TclNewObj(literal);
2010 if (TclParseNumber(NULL, literal, NULL, start, numBytes, &end,
2011 TCL_PARSE_NO_WHITESPACE) == TCL_OK) {
2012 if (end < start + numBytes && !TclIsBareword(*end)) {
2013
2014 number:
2015 TclInitStringRep(literal, start, end-start);
2016 *lexemePtr = NUMBER;
2017 if (literalPtr) {
2018 *literalPtr = literal;
2019 } else {
2020 Tcl_DecrRefCount(literal);
2021 }
2022 return (end-start);
2023 } else {
2024 unsigned char lexeme;
2025
2026 /*
2027 * We have a number followed directly by bareword characters
2028 * (alpha, digit, underscore). Is this a number followed by
2029 * bareword syntax error? Or should we join into one bareword?
2030 * Example: Inf + luence + () becomes a valid function call.
2031 * [Bug 3401704]
2032 */
2033 if (literal->typePtr == &tclDoubleType) {
2034 const char *p = start;
2035
2036 while (p < end) {
2037 if (!TclIsBareword(*p++)) {
2038 /*
2039 * The number has non-bareword characters, so we
2040 * must treat it as a number.
2041 */
2042 goto number;
2043 }
2044 }
2045 }
2046 ParseLexeme(end, numBytes-(end-start), &lexeme, NULL);
2047 if ((NODE_TYPE & lexeme) == BINARY) {
2048 /*
2049 * The bareword characters following the number take the
2050 * form of an operator (eq, ne, in, ni, ...) so we treat
2051 * as number + operator.
2052 */
2053 goto number;
2054 }
2055
2056 /*
2057 * Otherwise, fall through and parse the whole as a bareword.
2058 */
2059 }
2060 }
2061
2062 /*
2063 * We reject leading underscores in bareword. No sensible reason why.
2064 * Might be inspired by reserved identifier rules in C, which of course
2065 * have no direct relevance here.
2066 */
2067
2068 if (!TclIsBareword(*start) || *start == '_') {
2069 if (Tcl_UtfCharComplete(start, numBytes)) {
2070 scanned = TclUtfToUniChar(start, &ch);
2071 } else {
2072 char utfBytes[TCL_UTF_MAX];
2073
2074 memcpy(utfBytes, start, numBytes);
2075 utfBytes[numBytes] = '\0';
2076 scanned = TclUtfToUniChar(utfBytes, &ch);
2077 }
2078 *lexemePtr = INVALID;
2079 Tcl_DecrRefCount(literal);
2080 return scanned;
2081 }
2082 end = start;
2083 while (numBytes && TclIsBareword(*end)) {
2084 end += 1;
2085 numBytes -= 1;
2086 }
2087 *lexemePtr = BAREWORD;
2088 if (literalPtr) {
2089 Tcl_SetStringObj(literal, start, (int) (end-start));
2090 *literalPtr = literal;
2091 } else {
2092 Tcl_DecrRefCount(literal);
2093 }
2094 return (end-start);
2095 }
2096
2097 /*
2098 *----------------------------------------------------------------------
2099 *
2100 * TclCompileExpr --
2101 *
2102 * This procedure compiles a string containing a Tcl expression into Tcl
2103 * bytecodes.
2104 *
2105 * Results:
2106 * None.
2107 *
2108 * Side effects:
2109 * Adds instructions to envPtr to evaluate the expression at runtime.
2110 *
2111 *----------------------------------------------------------------------
2112 */
2113
2114 void
2115 TclCompileExpr(
2116 Tcl_Interp *interp, /* Used for error reporting. */
2117 const char *script, /* The source script to compile. */
2118 int numBytes, /* Number of bytes in script. */
2119 CompileEnv *envPtr, /* Holds resulting instructions. */
2120 int optimize) /* 0 for one-off expressions. */
2121 {
2122 OpNode *opTree = NULL; /* Will point to the tree of operators */
2123 Tcl_Obj *litList; /* List to hold the literals */
2124 Tcl_Obj *funcList; /* List to hold the functon names*/
2125 Tcl_Parse *parsePtr = (Tcl_Parse *)TclStackAlloc(interp, sizeof(Tcl_Parse));
2126 /* Holds the Tcl_Tokens of substitutions */
2127 int code;
2128
2129 TclNewObj(litList);
2130 TclNewObj(funcList);
2131 code = ParseExpr(interp, script, numBytes, &opTree, litList,
2132 funcList, parsePtr, 0 /* parseOnly */);
2133
2134 if (code == TCL_OK) {
2135 /*
2136 * Valid parse; compile the tree.
2137 */
2138
2139 int objc;
2140 Tcl_Obj *const *litObjv;
2141 Tcl_Obj **funcObjv;
2142
2143 /* TIP #280 : Track Lines within the expression */
2144 TclAdvanceLines(&envPtr->line, script,
2145 script + TclParseAllWhiteSpace(script, numBytes));
2146
2147 TclListObjGetElements(NULL, litList, &objc, (Tcl_Obj ***)&litObjv);
2148 TclListObjGetElements(NULL, funcList, &objc, &funcObjv);
2149 CompileExprTree(interp, opTree, 0, &litObjv, funcObjv,
2150 parsePtr->tokenPtr, envPtr, optimize);
2151 } else {
2152 TclCompileSyntaxError(interp, envPtr);
2153 }
2154
2155 Tcl_FreeParse(parsePtr);
2156 TclStackFree(interp, parsePtr);
2157 Tcl_DecrRefCount(funcList);
2158 Tcl_DecrRefCount(litList);
2159 ckfree(opTree);
2160 }
2161
2162 /*
2163 *----------------------------------------------------------------------
2164 *
2165 * ExecConstantExprTree --
2166 * Compiles and executes bytecode for the subexpression tree at index
2167 * in the nodes array. This subexpression must be constant, made up
2168 * of only constant operators (not functions) and literals.
2169 *
2170 * Results:
2171 * A standard Tcl return code and result left in interp.
2172 *
2173 * Side effects:
2174 * Consumes subtree of nodes rooted at index. Advances the pointer
2175 * *litObjvPtr.
2176 *
2177 *----------------------------------------------------------------------
2178 */
2179
2180 static int
2181 ExecConstantExprTree(
2182 Tcl_Interp *interp,
2183 OpNode *nodes,
2184 int index,
2185 Tcl_Obj *const **litObjvPtr)
2186 {
2187 CompileEnv *envPtr;
2188 ByteCode *byteCodePtr;
2189 int code;
2190 Tcl_Obj *byteCodeObj;
2191 NRE_callback *rootPtr = TOP_CB(interp);
2192
2193 TclNewObj(byteCodeObj);
2194 /*
2195 * Note we are compiling an expression with literal arguments. This means
2196 * there can be no [info frame] calls when we execute the resulting
2197 * bytecode, so there's no need to tend to TIP 280 issues.
2198 */
2199
2200 envPtr = (CompileEnv *)TclStackAlloc(interp, sizeof(CompileEnv));
2201 TclInitCompileEnv(interp, envPtr, NULL, 0, NULL, 0);
2202 CompileExprTree(interp, nodes, index, litObjvPtr, NULL, NULL, envPtr,
2203 0 /* optimize */);
2204 TclEmitOpcode(INST_DONE, envPtr);
2205 Tcl_IncrRefCount(byteCodeObj);
2206 TclInitByteCodeObj(byteCodeObj, envPtr);
2207 TclFreeCompileEnv(envPtr);
2208 TclStackFree(interp, envPtr);
2209 byteCodePtr = (ByteCode *)byteCodeObj->internalRep.twoPtrValue.ptr1;
2210 TclNRExecuteByteCode(interp, byteCodePtr);
2211 code = TclNRRunCallbacks(interp, TCL_OK, rootPtr);
2212 Tcl_DecrRefCount(byteCodeObj);
2213 return code;
2214 }
2215
2216 /*
2217 *----------------------------------------------------------------------
2218 *
2219 * CompileExprTree --
2220 *
2221 * Compiles and writes to envPtr instructions for the subexpression tree
2222 * at index in the nodes array. (*litObjvPtr) must point to the proper
2223 * location in a corresponding literals list. Likewise, when non-NULL,
2224 * funcObjv and tokenPtr must point into matching arrays of function
2225 * names and Tcl_Token's derived from earlier call to ParseExpr(). When
2226 * optimize is true, any constant subexpressions will be precomputed.
2227 *
2228 * Results:
2229 * None.
2230 *
2231 * Side effects:
2232 * Adds instructions to envPtr to evaluate the expression at runtime.
2233 * Consumes subtree of nodes rooted at index. Advances the pointer
2234 * *litObjvPtr.
2235 *
2236 *----------------------------------------------------------------------
2237 */
2238
2239 static void
2240 CompileExprTree(
2241 Tcl_Interp *interp,
2242 OpNode *nodes,
2243 int index,
2244 Tcl_Obj *const **litObjvPtr,
2245 Tcl_Obj *const *funcObjv,
2246 Tcl_Token *tokenPtr,
2247 CompileEnv *envPtr,
2248 int optimize)
2249 {
2250 OpNode *nodePtr = nodes + index;
2251 OpNode *rootPtr = nodePtr;
2252 int numWords = 0;
2253 JumpList *jumpPtr = NULL;
2254 int convert = 1;
2255
2256 while (1) {
2257 int next;
2258 JumpList *freePtr, *newJump;
2259
2260 if (nodePtr->mark == MARK_LEFT) {
2261 next = nodePtr->left;
2262
2263 if (nodePtr->lexeme == QUESTION) {
2264 convert = 1;
2265 }
2266 } else if (nodePtr->mark == MARK_RIGHT) {
2267 next = nodePtr->right;
2268
2269 switch (nodePtr->lexeme) {
2270 case FUNCTION: {
2271 Tcl_DString cmdName;
2272 const char *p;
2273 int length;
2274
2275 Tcl_DStringInit(&cmdName);
2276 TclDStringAppendLiteral(&cmdName, "tcl::mathfunc::");
2277 p = TclGetStringFromObj(*funcObjv, &length);
2278 funcObjv++;
2279 Tcl_DStringAppend(&cmdName, p, length);
2280 TclEmitPush(TclRegisterNewCmdLiteral(envPtr,
2281 Tcl_DStringValue(&cmdName),
2282 Tcl_DStringLength(&cmdName)), envPtr);
2283 Tcl_DStringFree(&cmdName);
2284
2285 /*
2286 * Start a count of the number of words in this function
2287 * command invocation. In case there's already a count in
2288 * progress (nested functions), save it in our unused "left"
2289 * field for restoring later.
2290 */
2291
2292 nodePtr->left = numWords;
2293 numWords = 2; /* Command plus one argument */
2294 break;
2295 }
2296 case QUESTION:
2297 newJump = (JumpList *)TclStackAlloc(interp, sizeof(JumpList));
2298 newJump->next = jumpPtr;
2299 jumpPtr = newJump;
2300 TclEmitForwardJump(envPtr, TCL_FALSE_JUMP, &jumpPtr->jump);
2301 break;
2302 case COLON:
2303 newJump = (JumpList *)TclStackAlloc(interp, sizeof(JumpList));
2304 newJump->next = jumpPtr;
2305 jumpPtr = newJump;
2306 TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP,
2307 &jumpPtr->jump);
2308 TclAdjustStackDepth(-1, envPtr);
2309 if (convert) {
2310 jumpPtr->jump.jumpType = TCL_TRUE_JUMP;
2311 }
2312 convert = 1;
2313 break;
2314 case AND:
2315 case OR:
2316 newJump = (JumpList *)TclStackAlloc(interp, sizeof(JumpList));
2317 newJump->next = jumpPtr;
2318 jumpPtr = newJump;
2319 TclEmitForwardJump(envPtr, (nodePtr->lexeme == AND)
2320 ? TCL_FALSE_JUMP : TCL_TRUE_JUMP, &jumpPtr->jump);
2321 break;
2322 }
2323 } else {
2324 int pc1, pc2, target;
2325
2326 switch (nodePtr->lexeme) {
2327 case START:
2328 case QUESTION:
2329 if (convert && (nodePtr == rootPtr)) {
2330 TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr);
2331 }
2332 break;
2333 case OPEN_PAREN:
2334
2335 /* do nothing */
2336 break;
2337 case FUNCTION:
2338 /*
2339 * Use the numWords count we've kept to invoke the function
2340 * command with the correct number of arguments.
2341 */
2342
2343 if (numWords < 255) {
2344 TclEmitInvoke(envPtr, INST_INVOKE_STK1, numWords);
2345 } else {
2346 TclEmitInvoke(envPtr, INST_INVOKE_STK4, numWords);
2347 }
2348
2349 /*
2350 * Restore any saved numWords value.
2351 */
2352
2353 numWords = nodePtr->left;
2354 convert = 1;
2355 break;
2356 case COMMA:
2357 /*
2358 * Each comma implies another function argument.
2359 */
2360
2361 numWords++;
2362 break;
2363 case COLON:
2364 CLANG_ASSERT(jumpPtr);
2365 if (jumpPtr->jump.jumpType == TCL_TRUE_JUMP) {
2366 jumpPtr->jump.jumpType = TCL_UNCONDITIONAL_JUMP;
2367 convert = 1;
2368 }
2369 target = jumpPtr->jump.codeOffset + 2;
2370 if (TclFixupForwardJumpToHere(envPtr, &jumpPtr->jump, 127)) {
2371 target += 3;
2372 }
2373 freePtr = jumpPtr;
2374 jumpPtr = jumpPtr->next;
2375 TclStackFree(interp, freePtr);
2376 TclFixupForwardJump(envPtr, &jumpPtr->jump,
2377 target - jumpPtr->jump.codeOffset, 127);
2378
2379 freePtr = jumpPtr;
2380 jumpPtr = jumpPtr->next;
2381 TclStackFree(interp, freePtr);
2382 break;
2383 case AND:
2384 case OR:
2385 CLANG_ASSERT(jumpPtr);
2386 pc1 = CurrentOffset(envPtr);
2387 TclEmitInstInt1((nodePtr->lexeme == AND) ? INST_JUMP_FALSE1
2388 : INST_JUMP_TRUE1, 0, envPtr);
2389 TclEmitPush(TclRegisterNewLiteral(envPtr,
2390 (nodePtr->lexeme == AND) ? "1" : "0", 1), envPtr);
2391 pc2 = CurrentOffset(envPtr);
2392 TclEmitInstInt1(INST_JUMP1, 0, envPtr);
2393 TclAdjustStackDepth(-1, envPtr);
2394 TclStoreInt1AtPtr(CurrentOffset(envPtr) - pc1,
2395 envPtr->codeStart + pc1 + 1);
2396 if (TclFixupForwardJumpToHere(envPtr, &jumpPtr->jump, 127)) {
2397 pc2 += 3;
2398 }
2399 TclEmitPush(TclRegisterNewLiteral(envPtr,
2400 (nodePtr->lexeme == AND) ? "0" : "1", 1), envPtr);
2401 TclStoreInt1AtPtr(CurrentOffset(envPtr) - pc2,
2402 envPtr->codeStart + pc2 + 1);
2403 convert = 0;
2404 freePtr = jumpPtr;
2405 jumpPtr = jumpPtr->next;
2406 TclStackFree(interp, freePtr);
2407 break;
2408 default:
2409 TclEmitOpcode(instruction[nodePtr->lexeme], envPtr);
2410 convert = 0;
2411 break;
2412 }
2413 if (nodePtr == rootPtr) {
2414 /* We're done */
2415
2416 return;
2417 }
2418 nodePtr = nodes + nodePtr->p.parent;
2419 continue;
2420 }
2421
2422 nodePtr->mark++;
2423 switch (next) {
2424 case OT_EMPTY:
2425 numWords = 1; /* No arguments, so just the command */
2426 break;
2427 case OT_LITERAL: {
2428 Tcl_Obj *const *litObjv = *litObjvPtr;
2429 Tcl_Obj *literal = *litObjv;
2430
2431 if (optimize) {
2432 int length;
2433 const char *bytes = TclGetStringFromObj(literal, &length);
2434 int idx = TclRegisterNewLiteral(envPtr, bytes, length);
2435 Tcl_Obj *objPtr = TclFetchLiteral(envPtr, idx);
2436
2437 if ((objPtr->typePtr == NULL) && (literal->typePtr != NULL)) {
2438 /*
2439 * Would like to do this:
2440 *
2441 * lePtr->objPtr = literal;
2442 * Tcl_IncrRefCount(literal);
2443 * Tcl_DecrRefCount(objPtr);
2444 *
2445 * However, the design of the "global" and "local"
2446 * LiteralTable does not permit the value of lePtr->objPtr
2447 * to change. So rather than replace lePtr->objPtr, we do
2448 * surgery to transfer our desired internalrep into it.
2449 */
2450
2451 objPtr->typePtr = literal->typePtr;
2452 objPtr->internalRep = literal->internalRep;
2453 literal->typePtr = NULL;
2454 }
2455 TclEmitPush(idx, envPtr);
2456 } else {
2457 /*
2458 * When optimize==0, we know the expression is a one-off and
2459 * there's nothing to be gained from sharing literals when
2460 * they won't live long, and the copies we have already have
2461 * an appropriate internalrep. In this case, skip literal
2462 * registration that would enable sharing, and use the routine
2463 * that preserves internalreps.
2464 */
2465
2466 TclEmitPush(TclAddLiteralObj(envPtr, literal, NULL), envPtr);
2467 }
2468 (*litObjvPtr)++;
2469 break;
2470 }
2471 case OT_TOKENS:
2472 CompileTokens(envPtr, tokenPtr, interp);
2473 tokenPtr += tokenPtr->numComponents + 1;
2474 break;
2475 default:
2476 if (optimize && nodes[next].constant) {
2477 Tcl_InterpState save = Tcl_SaveInterpState(interp, TCL_OK);
2478
2479 if (ExecConstantExprTree(interp, nodes, next, litObjvPtr)
2480 == TCL_OK) {
2481 int idx;
2482 Tcl_Obj *objPtr = Tcl_GetObjResult(interp);
2483
2484 /*
2485 * Don't generate a string rep, but if we have one
2486 * already, then use it to share via the literal table.
2487 */
2488
2489 if (objPtr->bytes) {
2490 Tcl_Obj *tableValue;
2491
2492 idx = TclRegisterNewLiteral(envPtr, objPtr->bytes,
2493 objPtr->length);
2494 tableValue = TclFetchLiteral(envPtr, idx);
2495 if ((tableValue->typePtr == NULL) &&
2496 (objPtr->typePtr != NULL)) {
2497 /*
2498 * Same internalrep surgery as for OT_LITERAL.
2499 */
2500
2501 tableValue->typePtr = objPtr->typePtr;
2502 tableValue->internalRep = objPtr->internalRep;
2503 objPtr->typePtr = NULL;
2504 }
2505 } else {
2506 idx = TclAddLiteralObj(envPtr, objPtr, NULL);
2507 }
2508 TclEmitPush(idx, envPtr);
2509 } else {
2510 TclCompileSyntaxError(interp, envPtr);
2511 }
2512 Tcl_RestoreInterpState(interp, save);
2513 convert = 0;
2514 } else {
2515 nodePtr = nodes + next;
2516 }
2517 }
2518 }
2519 }
2520
2521 /*
2522 *----------------------------------------------------------------------
2523 *
2524 * TclSingleOpCmd --
2525 *
2526 * Implements the commands: ~, !, <<, >>, %, !=, ne, in, ni
2527 * in the ::tcl::mathop namespace. These commands have no
2528 * extension to arbitrary arguments; they accept only exactly one
2529 * or exactly two arguments as suitable for the operator.
2530 *
2531 * Results:
2532 * A standard Tcl return code and result left in interp.
2533 *
2534 * Side effects:
2535 * None.
2536 *
2537 *----------------------------------------------------------------------
2538 */
2539
2540 int
2541 TclSingleOpCmd(
2542 ClientData clientData,
2543 Tcl_Interp *interp,
2544 int objc,
2545 Tcl_Obj *const objv[])
2546 {
2547 TclOpCmdClientData *occdPtr = (TclOpCmdClientData *)clientData;
2548 unsigned char lexeme;
2549 OpNode nodes[2];
2550 Tcl_Obj *const *litObjv = objv + 1;
2551
2552 if (objc != 1 + occdPtr->i.numArgs) {
2553 Tcl_WrongNumArgs(interp, 1, objv, occdPtr->expected);
2554 return TCL_ERROR;
2555 }
2556
2557 ParseLexeme(occdPtr->op, strlen(occdPtr->op), &lexeme, NULL);
2558 nodes[0].lexeme = START;
2559 nodes[0].mark = MARK_RIGHT;
2560 nodes[0].right = 1;
2561 nodes[1].lexeme = lexeme;
2562 if (objc == 2) {
2563 nodes[1].mark = MARK_RIGHT;
2564 } else {
2565 nodes[1].mark = MARK_LEFT;
2566 nodes[1].left = OT_LITERAL;
2567 }
2568 nodes[1].right = OT_LITERAL;
2569 nodes[1].p.parent = 0;
2570
2571 return ExecConstantExprTree(interp, nodes, 0, &litObjv);
2572 }
2573
2574 /*
2575 *----------------------------------------------------------------------
2576 *
2577 * TclSortingOpCmd --
2578 * Implements the commands:
2579 * <, <=, >, >=, ==, eq
2580 * in the ::tcl::mathop namespace. These commands are defined for
2581 * arbitrary number of arguments by computing the AND of the base
2582 * operator applied to all neighbor argument pairs.
2583 *
2584 * Results:
2585 * A standard Tcl return code and result left in interp.
2586 *
2587 * Side effects:
2588 * None.
2589 *
2590 *----------------------------------------------------------------------
2591 */
2592
2593 int
2594 TclSortingOpCmd(
2595 ClientData clientData,
2596 Tcl_Interp *interp,
2597 int objc,
2598 Tcl_Obj *const objv[])
2599 {
2600 int code = TCL_OK;
2601
2602 if (objc < 3) {
2603 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1));
2604 } else {
2605 TclOpCmdClientData *occdPtr = (TclOpCmdClientData *)clientData;
2606 Tcl_Obj **litObjv = (Tcl_Obj **)TclStackAlloc(interp,
2607 2 * (objc-2) * sizeof(Tcl_Obj *));
2608 OpNode *nodes = (OpNode *)TclStackAlloc(interp, 2 * (objc-2) * sizeof(OpNode));
2609 unsigned char lexeme;
2610 int i, lastAnd = 1;
2611 Tcl_Obj *const *litObjPtrPtr = litObjv;
2612
2613 ParseLexeme(occdPtr->op, strlen(occdPtr->op), &lexeme, NULL);
2614
2615 litObjv[0] = objv[1];
2616 nodes[0].lexeme = START;
2617 nodes[0].mark = MARK_RIGHT;
2618 for (i=2; i<objc-1; i++) {
2619 litObjv[2*(i-1)-1] = objv[i];
2620 nodes[2*(i-1)-1].lexeme = lexeme;
2621 nodes[2*(i-1)-1].mark = MARK_LEFT;
2622 nodes[2*(i-1)-1].left = OT_LITERAL;
2623 nodes[2*(i-1)-1].right = OT_LITERAL;
2624
2625 litObjv[2*(i-1)] = objv[i];
2626 nodes[2*(i-1)].lexeme = AND;
2627 nodes[2*(i-1)].mark = MARK_LEFT;
2628 nodes[2*(i-1)].left = lastAnd;
2629 nodes[lastAnd].p.parent = 2*(i-1);
2630
2631 nodes[2*(i-1)].right = 2*(i-1)+1;
2632 nodes[2*(i-1)+1].p.parent= 2*(i-1);
2633
2634 lastAnd = 2*(i-1);
2635 }
2636 litObjv[2*(objc-2)-1] = objv[objc-1];
2637
2638 nodes[2*(objc-2)-1].lexeme = lexeme;
2639 nodes[2*(objc-2)-1].mark = MARK_LEFT;
2640 nodes[2*(objc-2)-1].left = OT_LITERAL;
2641 nodes[2*(objc-2)-1].right = OT_LITERAL;
2642
2643 nodes[0].right = lastAnd;
2644 nodes[lastAnd].p.parent = 0;
2645
2646 code = ExecConstantExprTree(interp, nodes, 0, &litObjPtrPtr);
2647
2648 TclStackFree(interp, nodes);
2649 TclStackFree(interp, litObjv);
2650 }
2651 return code;
2652 }
2653
2654 /*
2655 *----------------------------------------------------------------------
2656 *
2657 * TclVariadicOpCmd --
2658 * Implements the commands: +, *, &, |, ^, **
2659 * in the ::tcl::mathop namespace. These commands are defined for
2660 * arbitrary number of arguments by repeatedly applying the base
2661 * operator with suitable associative rules. When fewer than two
2662 * arguments are provided, suitable identity values are returned.
2663 *
2664 * Results:
2665 * A standard Tcl return code and result left in interp.
2666 *
2667 * Side effects:
2668 * None.
2669 *
2670 *----------------------------------------------------------------------
2671 */
2672
2673 int
2674 TclVariadicOpCmd(
2675 ClientData clientData,
2676 Tcl_Interp *interp,
2677 int objc,
2678 Tcl_Obj *const objv[])
2679 {
2680 TclOpCmdClientData *occdPtr = (TclOpCmdClientData *)clientData;
2681 unsigned char lexeme;
2682 int code;
2683
2684 if (objc < 2) {
2685 Tcl_SetObjResult(interp, Tcl_NewIntObj(occdPtr->i.identity));
2686 return TCL_OK;
2687 }
2688
2689 ParseLexeme(occdPtr->op, strlen(occdPtr->op), &lexeme, NULL);
2690 lexeme |= BINARY;
2691
2692 if (objc == 2) {
2693 Tcl_Obj *litObjv[2];
2694 OpNode nodes[2];
2695 int decrMe = 0;
2696 Tcl_Obj *const *litObjPtrPtr = litObjv;
2697
2698 if (lexeme == EXPON) {
2699 TclNewIntObj(litObjv[1], occdPtr->i.identity);
2700 Tcl_IncrRefCount(litObjv[1]);
2701 decrMe = 1;
2702 litObjv[0] = objv[1];
2703 nodes[0].lexeme = START;
2704 nodes[0].mark = MARK_RIGHT;
2705 nodes[0].right = 1;
2706 nodes[1].lexeme = lexeme;
2707 nodes[1].mark = MARK_LEFT;
2708 nodes[1].left = OT_LITERAL;
2709 nodes[1].right = OT_LITERAL;
2710 nodes[1].p.parent = 0;
2711 } else {
2712 if (lexeme == DIVIDE) {
2713 litObjv[0] = Tcl_NewDoubleObj(1.0);
2714 } else {
2715 TclNewIntObj(litObjv[0], occdPtr->i.identity);
2716 }
2717 Tcl_IncrRefCount(litObjv[0]);
2718 litObjv[1] = objv[1];
2719 nodes[0].lexeme = START;
2720 nodes[0].mark = MARK_RIGHT;
2721 nodes[0].right = 1;
2722 nodes[1].lexeme = lexeme;
2723 nodes[1].mark = MARK_LEFT;
2724 nodes[1].left = OT_LITERAL;
2725 nodes[1].right = OT_LITERAL;
2726 nodes[1].p.parent = 0;
2727 }
2728
2729 code = ExecConstantExprTree(interp, nodes, 0, &litObjPtrPtr);
2730
2731 Tcl_DecrRefCount(litObjv[decrMe]);
2732 return code;
2733 } else {
2734 Tcl_Obj *const *litObjv = objv + 1;
2735 OpNode *nodes = (OpNode *)TclStackAlloc(interp, (objc-1) * sizeof(OpNode));
2736 int i, lastOp = OT_LITERAL;
2737
2738 nodes[0].lexeme = START;
2739 nodes[0].mark = MARK_RIGHT;
2740 if (lexeme == EXPON) {
2741 for (i=objc-2; i>0; i--) {
2742 nodes[i].lexeme = lexeme;
2743 nodes[i].mark = MARK_LEFT;
2744 nodes[i].left = OT_LITERAL;
2745 nodes[i].right = lastOp;
2746 if (lastOp >= 0) {
2747 nodes[lastOp].p.parent = i;
2748 }
2749 lastOp = i;
2750 }
2751 } else {
2752 for (i=1; i<objc-1; i++) {
2753 nodes[i].lexeme = lexeme;
2754 nodes[i].mark = MARK_LEFT;
2755 nodes[i].left = lastOp;
2756 if (lastOp >= 0) {
2757 nodes[lastOp].p.parent = i;
2758 }
2759 nodes[i].right = OT_LITERAL;
2760 lastOp = i;
2761 }
2762 }
2763 nodes[0].right = lastOp;
2764 nodes[lastOp].p.parent = 0;
2765
2766 code = ExecConstantExprTree(interp, nodes, 0, &litObjv);
2767
2768 TclStackFree(interp, nodes);
2769 return code;
2770 }
2771 }
2772
2773 /*
2774 *----------------------------------------------------------------------
2775 *
2776 * TclNoIdentOpCmd --
2777 * Implements the commands: -, /
2778 * in the ::tcl::mathop namespace. These commands are defined for
2779 * arbitrary non-zero number of arguments by repeatedly applying the base
2780 * operator with suitable associative rules. When no arguments are
2781 * provided, an error is raised.
2782 *
2783 * Results:
2784 * A standard Tcl return code and result left in interp.
2785 *
2786 * Side effects:
2787 * None.
2788 *
2789 *----------------------------------------------------------------------
2790 */
2791
2792 int
2793 TclNoIdentOpCmd(
2794 ClientData clientData,
2795 Tcl_Interp *interp,
2796 int objc,
2797 Tcl_Obj *const objv[])
2798 {
2799 TclOpCmdClientData *occdPtr = (TclOpCmdClientData *)clientData;
2800
2801 if (objc < 2) {
2802 Tcl_WrongNumArgs(interp, 1, objv, occdPtr->expected);
2803 return TCL_ERROR;
2804 }
2805 return TclVariadicOpCmd(clientData, interp, objc, objv);
2806 }
2807 /*
2808 * Local Variables:
2809 * mode: c
2810 * c-basic-offset: 4
2811 * fill-column: 78
2812 * End:
2813 */