Debian Codegraph @

generic/tclParse.c

raw
1 /*
2 * tclParse.c --
3 *
4 * This file contains functions that parse Tcl scripts. They do so in a
5 * general-purpose fashion that can be used for many different purposes,
6 * including compilation, direct execution, code analysis, etc.
7 *
8 * Copyright (c) 1997 Sun Microsystems, Inc.
9 * Copyright (c) 1998-2000 Ajuba Solutions.
10 * Contributions from Don Porter, NIST, 2002. (not subject to US copyright)
11 *
12 * See the file "license.terms" for information on usage and redistribution of
13 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 */
15
16 #include "tclInt.h"
17 #include "tclParse.h"
18 #include <assert.h>
19
20 /*
21 * The following table provides parsing information about each possible 8-bit
22 * character. The table is designed to be referenced with either signed or
23 * unsigned characters, so it has 384 entries. The first 128 entries
24 * correspond to negative character values, the next 256 correspond to
25 * positive character values. The last 128 entries are identical to the first
26 * 128. The table is always indexed with a 128-byte offset (the 128th entry
27 * corresponds to a character value of 0).
28 *
29 * The macro CHAR_TYPE is used to index into the table and return information
30 * about its character argument. The following return values are defined.
31 *
32 * TYPE_NORMAL - All characters that don't have special significance to
33 * the Tcl parser.
34 * TYPE_SPACE - The character is a whitespace character other than
35 * newline.
36 * TYPE_COMMAND_END - Character is newline or semicolon.
37 * TYPE_SUBS - Character begins a substitution or has other special
38 * meaning in ParseTokens: backslash, dollar sign, or
39 * open bracket.
40 * TYPE_QUOTE - Character is a double quote.
41 * TYPE_CLOSE_PAREN - Character is a right parenthesis.
42 * TYPE_CLOSE_BRACK - Character is a right square bracket.
43 * TYPE_BRACE - Character is a curly brace (either left or right).
44 */
45
46 const char tclCharTypeTable[] = {
47 /*
48 * Negative character values, from -128 to -1:
49 */
50
51 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
52 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
53 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
54 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
55 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
56 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
57 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
58 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
59 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
60 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
61 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
62 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
63 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
64 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
65 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
66 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
67 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
68 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
69 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
70 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
71 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
72 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
73 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
74 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
75 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
76 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
77 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
78 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
79 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
80 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
81 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
82 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
83
84 /*
85 * Positive character values, from 0-127:
86 */
87
88 TYPE_SUBS, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
89 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
90 TYPE_NORMAL, TYPE_SPACE, TYPE_COMMAND_END, TYPE_SPACE,
91 TYPE_SPACE, TYPE_SPACE, TYPE_NORMAL, TYPE_NORMAL,
92 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
93 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
94 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
95 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
96 TYPE_SPACE, TYPE_NORMAL, TYPE_QUOTE, TYPE_NORMAL,
97 TYPE_SUBS, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
98 TYPE_NORMAL, TYPE_CLOSE_PAREN, TYPE_NORMAL, TYPE_NORMAL,
99 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
100 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
101 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
102 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_COMMAND_END,
103 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
104 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
105 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
106 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
107 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
108 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
109 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
110 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_SUBS,
111 TYPE_SUBS, TYPE_CLOSE_BRACK, TYPE_NORMAL, TYPE_NORMAL,
112 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
113 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
114 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
115 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
116 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
117 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
118 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_BRACE,
119 TYPE_NORMAL, TYPE_BRACE, TYPE_NORMAL, TYPE_NORMAL,
120
121 /*
122 * Large unsigned character values, from 128-255:
123 */
124
125 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
126 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
127 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
128 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
129 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
130 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
131 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
132 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
133 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
134 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
135 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
136 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
137 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
138 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
139 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
140 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
141 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
142 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
143 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
144 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
145 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
146 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
147 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
148 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
149 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
150 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
151 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
152 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
153 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
154 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
155 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
156 TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL,
157 };
158
159 /*
160 * Prototypes for local functions defined in this file:
161 */
162
163 static inline int CommandComplete(const char *script, int numBytes);
164 static int ParseComment(const char *src, int numBytes,
165 Tcl_Parse *parsePtr);
166 static int ParseTokens(const char *src, int numBytes, int mask,
167 int flags, Tcl_Parse *parsePtr);
168 static int ParseWhiteSpace(const char *src, int numBytes,
169 int *incompletePtr, char *typePtr);
170 static int ParseHex(const char *src, int numBytes,
171 int *resultPtr);
172
173 /*
174 *----------------------------------------------------------------------
175 *
176 * TclParseInit --
177 *
178 * Initialize the fields of a Tcl_Parse struct.
179 *
180 * Results:
181 * None.
182 *
183 * Side effects:
184 * The Tcl_Parse struct pointed to by parsePtr gets initialized.
185 *
186 *----------------------------------------------------------------------
187 */
188
189 void
190 TclParseInit(
191 Tcl_Interp *interp, /* Interpreter to use for error reporting */
192 const char *start, /* Start of string to be parsed. */
193 int numBytes, /* Total number of bytes in string. If < 0,
194 * the script consists of all bytes up to the
195 * first null character. */
196 Tcl_Parse *parsePtr) /* Points to struct to initialize */
197 {
198 parsePtr->numWords = 0;
199 parsePtr->tokenPtr = parsePtr->staticTokens;
200 parsePtr->numTokens = 0;
201 parsePtr->tokensAvailable = NUM_STATIC_TOKENS;
202 parsePtr->string = start;
203 parsePtr->end = start + numBytes;
204 parsePtr->term = parsePtr->end;
205 parsePtr->interp = interp;
206 parsePtr->incomplete = 0;
207 parsePtr->errorType = TCL_PARSE_SUCCESS;
208 }
209
210 /*
211 *----------------------------------------------------------------------
212 *
213 * Tcl_ParseCommand --
214 *
215 * Given a string, this function parses the first Tcl command in the
216 * string and returns information about the structure of the command.
217 *
218 * Results:
219 * The return value is TCL_OK if the command was parsed successfully and
220 * TCL_ERROR otherwise. If an error occurs and interp isn't NULL then an
221 * error message is left in its result. On a successful return, parsePtr
222 * is filled in with information about the command that was parsed.
223 *
224 * Side effects:
225 * If there is insufficient space in parsePtr to hold all the information
226 * about the command, then additional space is malloc-ed. If the function
227 * returns TCL_OK then the caller must eventually invoke Tcl_FreeParse to
228 * release any additional space that was allocated.
229 *
230 *----------------------------------------------------------------------
231 */
232
233 int
234 Tcl_ParseCommand(
235 Tcl_Interp *interp, /* Interpreter to use for error reporting; if
236 * NULL, then no error message is provided. */
237 const char *start, /* First character of string containing one or
238 * more Tcl commands. */
239 int numBytes, /* Total number of bytes in string. If < 0,
240 * the script consists of all bytes up to the
241 * first null character. */
242 int nested, /* Non-zero means this is a nested command:
243 * close bracket should be considered a
244 * command terminator. If zero, then close
245 * bracket has no special meaning. */
246 Tcl_Parse *parsePtr)
247 /* Structure to fill in with information about
248 * the parsed command; any previous
249 * information in the structure is ignored. */
250 {
251 const char *src; /* Points to current character in the
252 * command. */
253 char type; /* Result returned by CHAR_TYPE(*src). */
254 Tcl_Token *tokenPtr; /* Pointer to token being filled in. */
255 int wordIndex; /* Index of word token for current word. */
256 int terminators; /* CHAR_TYPE bits that indicate the end of a
257 * command. */
258 const char *termPtr; /* Set by Tcl_ParseBraces/QuotedString to
259 * point to char after terminating one. */
260 int scanned;
261
262 if (numBytes < 0 && start) {
263 numBytes = strlen(start);
264 }
265 TclParseInit(interp, start, numBytes, parsePtr);
266 if ((start == NULL) && (numBytes != 0)) {
267 if (interp != NULL) {
268 Tcl_SetObjResult(interp, Tcl_NewStringObj(
269 "can't parse a NULL pointer", -1));
270 }
271 return TCL_ERROR;
272 }
273 parsePtr->commentStart = NULL;
274 parsePtr->commentSize = 0;
275 parsePtr->commandStart = NULL;
276 parsePtr->commandSize = 0;
277 if (nested != 0) {
278 terminators = TYPE_COMMAND_END | TYPE_CLOSE_BRACK;
279 } else {
280 terminators = TYPE_COMMAND_END;
281 }
282
283 /*
284 * Parse any leading space and comments before the first word of the
285 * command.
286 */
287
288 scanned = ParseComment(start, numBytes, parsePtr);
289 src = (start + scanned);
290 numBytes -= scanned;
291 if (numBytes == 0) {
292 if (nested) {
293 parsePtr->incomplete = nested;
294 }
295 }
296
297 /*
298 * The following loop parses the words of the command, one word in each
299 * iteration through the loop.
300 */
301
302 parsePtr->commandStart = src;
303 while (1) {
304 int expandWord = 0;
305
306 /*
307 * Create the token for the word.
308 */
309
310 TclGrowParseTokenArray(parsePtr, 1);
311 wordIndex = parsePtr->numTokens;
312 tokenPtr = &parsePtr->tokenPtr[wordIndex];
313 tokenPtr->type = TCL_TOKEN_WORD;
314
315 /*
316 * Skip white space before the word. Also skip a backslash-newline
317 * sequence: it should be treated just like white space.
318 */
319
320 scanned = ParseWhiteSpace(src,numBytes, &parsePtr->incomplete, &type);
321 src += scanned;
322 numBytes -= scanned;
323 if (numBytes == 0) {
324 parsePtr->term = src;
325 break;
326 }
327 if ((type & terminators) != 0) {
328 parsePtr->term = src;
329 src++;
330 break;
331 }
332 tokenPtr->start = src;
333 parsePtr->numTokens++;
334 parsePtr->numWords++;
335
336 /*
337 * At this point the word can have one of four forms: something
338 * enclosed in quotes, something enclosed in braces, and expanding
339 * word, or an unquoted word (anything else).
340 */
341
342 parseWord:
343 if (*src == '"') {
344 if (Tcl_ParseQuotedString(interp, src, numBytes, parsePtr, 1,
345 &termPtr) != TCL_OK) {
346 goto error;
347 }
348 src = termPtr;
349 numBytes = parsePtr->end - src;
350 } else if (*src == '{') {
351 int expIdx = wordIndex + 1;
352 Tcl_Token *expPtr;
353
354 if (Tcl_ParseBraces(interp, src, numBytes, parsePtr, 1,
355 &termPtr) != TCL_OK) {
356 goto error;
357 }
358 src = termPtr;
359 numBytes = parsePtr->end - src;
360
361 /*
362 * Check whether the braces contained the word expansion prefix
363 * {*}
364 */
365
366 expPtr = &parsePtr->tokenPtr[expIdx];
367 if ((0 == expandWord)
368 /* Haven't seen prefix already */
369 && (1 == parsePtr->numTokens - expIdx)
370 /* Only one token */
371 && (((1 == (size_t) expPtr->size)
372 /* Same length as prefix */
373 && (expPtr->start[0] == '*')))
374 /* Is the prefix */
375 && (numBytes > 0) && (0 == ParseWhiteSpace(termPtr,
376 numBytes, &parsePtr->incomplete, &type))
377 && (type != TYPE_COMMAND_END)
378 /* Non-whitespace follows */) {
379 expandWord = 1;
380 parsePtr->numTokens--;
381 goto parseWord;
382 }
383 } else {
384 /*
385 * This is an unquoted word. Call ParseTokens and let it do all of
386 * the work.
387 */
388
389 if (ParseTokens(src, numBytes, TYPE_SPACE|terminators,
390 TCL_SUBST_ALL, parsePtr) != TCL_OK) {
391 goto error;
392 }
393 src = parsePtr->term;
394 numBytes = parsePtr->end - src;
395 }
396
397 /*
398 * Finish filling in the token for the word and check for the special
399 * case of a word consisting of a single range of literal text.
400 */
401
402 tokenPtr = &parsePtr->tokenPtr[wordIndex];
403 tokenPtr->size = src - tokenPtr->start;
404 tokenPtr->numComponents = parsePtr->numTokens - (wordIndex + 1);
405 if (expandWord) {
406 int i, isLiteral = 1;
407
408 /*
409 * When a command includes a word that is an expanded literal; for
410 * example, {*}{1 2 3}, the parser performs that expansion
411 * immediately, generating several TCL_TOKEN_SIMPLE_WORDs instead
412 * of a single TCL_TOKEN_EXPAND_WORD that the Tcl_ParseCommand()
413 * caller might have to expand. This notably makes it simpler for
414 * those callers that wish to track line endings, such as those
415 * that implement key parts of TIP 280.
416 *
417 * First check whether the thing to be expanded is a literal,
418 * in the sense of being composed entirely of TCL_TOKEN_TEXT
419 * tokens.
420 */
421
422 for (i = 1; i <= tokenPtr->numComponents; i++) {
423 if (tokenPtr[i].type != TCL_TOKEN_TEXT) {
424 isLiteral = 0;
425 break;
426 }
427 }
428
429 if (isLiteral) {
430 int elemCount = 0, code = TCL_OK, literal = 1;
431 const char *nextElem, *listEnd, *elemStart;
432
433 /*
434 * The word to be expanded is a literal, so determine the
435 * boundaries of the literal string to be treated as a list
436 * and expanded. That literal string starts at
437 * tokenPtr[1].start, and includes all bytes up to, but not
438 * including (tokenPtr[tokenPtr->numComponents].start +
439 * tokenPtr[tokenPtr->numComponents].size)
440 */
441
442 listEnd = (tokenPtr[tokenPtr->numComponents].start +
443 tokenPtr[tokenPtr->numComponents].size);
444 nextElem = tokenPtr[1].start;
445
446 /*
447 * Step through the literal string, parsing and counting list
448 * elements.
449 */
450
451 while (nextElem < listEnd) {
452 int size;
453
454 code = TclFindElement(NULL, nextElem, listEnd - nextElem,
455 &elemStart, &nextElem, &size, &literal);
456 if ((code != TCL_OK) || !literal) {
457 break;
458 }
459 if (elemStart < listEnd) {
460 elemCount++;
461 }
462 }
463
464 if ((code != TCL_OK) || !literal) {
465 /*
466 * Some list element could not be parsed, or is not
467 * present as a literal substring of the script. The
468 * compiler cannot handle list elements that get generated
469 * by a call to TclCopyAndCollapse(). Defer the
470 * handling of this to compile/eval time, where code is
471 * already in place to report the "attempt to expand a
472 * non-list" error or expand lists that require
473 * substitution.
474 */
475
476 tokenPtr->type = TCL_TOKEN_EXPAND_WORD;
477 } else if (elemCount == 0) {
478 /*
479 * We are expanding a literal empty list. This means that
480 * the expanding word completely disappears, leaving no
481 * word generated this pass through the loop. Adjust
482 * accounting appropriately.
483 */
484
485 parsePtr->numWords--;
486 parsePtr->numTokens = wordIndex;
487 } else {
488 /*
489 * Recalculate the number of Tcl_Tokens needed to store
490 * tokens representing the expanded list.
491 */
492
493 const char *listStart;
494 int growthNeeded = wordIndex + 2*elemCount
495 - parsePtr->numTokens;
496
497 parsePtr->numWords += elemCount - 1;
498 if (growthNeeded > 0) {
499 TclGrowParseTokenArray(parsePtr, growthNeeded);
500 tokenPtr = &parsePtr->tokenPtr[wordIndex];
501 }
502 parsePtr->numTokens = wordIndex + 2*elemCount;
503
504 /*
505 * Generate a TCL_TOKEN_SIMPLE_WORD token sequence for
506 * each element of the literal list we are expanding in
507 * place. Take care with the start and size fields of each
508 * token so they point to the right literal characters in
509 * the original script to represent the right expanded
510 * word value.
511 */
512
513 listStart = nextElem = tokenPtr[1].start;
514 while (nextElem < listEnd) {
515 int quoted;
516
517 tokenPtr->type = TCL_TOKEN_SIMPLE_WORD;
518 tokenPtr->numComponents = 1;
519
520 tokenPtr++;
521 tokenPtr->type = TCL_TOKEN_TEXT;
522 tokenPtr->numComponents = 0;
523 TclFindElement(NULL, nextElem, listEnd - nextElem,
524 &(tokenPtr->start), &nextElem,
525 &(tokenPtr->size), NULL);
526
527 quoted = (tokenPtr->start[-1] == '{'
528 || tokenPtr->start[-1] == '"')
529 && tokenPtr->start > listStart;
530 tokenPtr[-1].start = tokenPtr->start - quoted;
531 tokenPtr[-1].size = tokenPtr->start + tokenPtr->size
532 - tokenPtr[-1].start + quoted;
533
534 tokenPtr++;
535 }
536 }
537 } else {
538 /*
539 * The word to be expanded is not a literal, so defer
540 * expansion to compile/eval time by marking with a
541 * TCL_TOKEN_EXPAND_WORD token.
542 */
543
544 tokenPtr->type = TCL_TOKEN_EXPAND_WORD;
545 }
546 } else if ((tokenPtr->numComponents == 1)
547 && (tokenPtr[1].type == TCL_TOKEN_TEXT)) {
548 tokenPtr->type = TCL_TOKEN_SIMPLE_WORD;
549 }
550
551 /*
552 * Do two additional checks: (a) make sure we're really at the end of
553 * a word (there might have been garbage left after a quoted or braced
554 * word), and (b) check for the end of the command.
555 */
556
557 scanned = ParseWhiteSpace(src,numBytes, &parsePtr->incomplete, &type);
558 if (scanned) {
559 src += scanned;
560 numBytes -= scanned;
561 continue;
562 }
563
564 if (numBytes == 0) {
565 parsePtr->term = src;
566 break;
567 }
568 if ((type & terminators) != 0) {
569 parsePtr->term = src;
570 src++;
571 break;
572 }
573 if (src[-1] == '"') {
574 if (interp != NULL) {
575 Tcl_SetObjResult(interp, Tcl_NewStringObj(
576 "extra characters after close-quote", -1));
577 }
578 parsePtr->errorType = TCL_PARSE_QUOTE_EXTRA;
579 } else {
580 if (interp != NULL) {
581 Tcl_SetObjResult(interp, Tcl_NewStringObj(
582 "extra characters after close-brace", -1));
583 }
584 parsePtr->errorType = TCL_PARSE_BRACE_EXTRA;
585 }
586 parsePtr->term = src;
587 goto error;
588 }
589
590 parsePtr->commandSize = src - parsePtr->commandStart;
591 return TCL_OK;
592
593 error:
594 Tcl_FreeParse(parsePtr);
595 parsePtr->commandSize = parsePtr->end - parsePtr->commandStart;
596 return TCL_ERROR;
597 }
598
599 /*
600 *----------------------------------------------------------------------
601 *
602 * TclIsSpaceProc --
603 *
604 * Report whether byte is in the set of whitespace characters used by
605 * Tcl to separate words in scripts or elements in lists.
606 *
607 * Results:
608 * Returns 1, if byte is in the set, 0 otherwise.
609 *
610 * Side effects:
611 * None.
612 *
613 *----------------------------------------------------------------------
614 */
615
616 int
617 TclIsSpaceProc(
618 int byte)
619 {
620 return CHAR_TYPE(byte) & (TYPE_SPACE) || byte == '\n';
621 }
622
623 /*
624 *----------------------------------------------------------------------
625 *
626 * TclIsBareword--
627 *
628 * Report whether byte is one that can be part of a "bareword".
629 * This concept is named in expression parsing, where it determines
630 * what can be a legal function name, but is the same definition used
631 * in determining what variable names can be parsed as variable
632 * substitutions without the benefit of enclosing braces. The set of
633 * ASCII chars that are accepted are the numeric chars ('0'-'9'),
634 * the alphabetic chars ('a'-'z', 'A'-'Z') and underscore ('_').
635 *
636 * Results:
637 * Returns 1, if byte is in the accepted set of chars, 0 otherwise.
638 *
639 * Side effects:
640 * None.
641 *
642 *----------------------------------------------------------------------
643 */
644
645 int
646 TclIsBareword(
647 int byte)
648 {
649 if (byte < '0' || byte > 'z') {
650 return 0;
651 }
652 if (byte <= '9' || byte >= 'a') {
653 return 1;
654 }
655 if (byte == '_') {
656 return 1;
657 }
658 if (byte < 'A' || byte > 'Z') {
659 return 0;
660 }
661 return 1;
662 }
663
664 /*
665 *----------------------------------------------------------------------
666 *
667 * ParseWhiteSpace --
668 *
669 * Scans up to numBytes bytes starting at src, consuming white space
670 * between words as defined by Tcl's parsing rules.
671 *
672 * Results:
673 * Returns the number of bytes recognized as white space. Records at
674 * parsePtr, information about the parse. Records at typePtr the
675 * character type of the non-whitespace character that terminated the
676 * scan.
677 *
678 * Side effects:
679 * None.
680 *
681 *----------------------------------------------------------------------
682 */
683
684 static int
685 ParseWhiteSpace(
686 const char *src, /* First character to parse. */
687 int numBytes, /* Max number of bytes to scan. */
688 int *incompletePtr, /* Set this boolean memory to true if parsing
689 * indicates an incomplete command. */
690 char *typePtr) /* Points to location to store character type
691 * of character that ends run of whitespace */
692 {
693 char type = TYPE_NORMAL;
694 const char *p = src;
695
696 while (1) {
697 while (numBytes && ((type = CHAR_TYPE(*p)) & TYPE_SPACE)) {
698 numBytes--;
699 p++;
700 }
701 if (numBytes && (type & TYPE_SUBS)) {
702 if (*p != '\\') {
703 break;
704 }
705 if (--numBytes == 0) {
706 break;
707 }
708 if (p[1] != '\n') {
709 break;
710 }
711 p += 2;
712 if (--numBytes == 0) {
713 *incompletePtr = 1;
714 break;
715 }
716 continue;
717 }
718 break;
719 }
720 *typePtr = type;
721 return (p - src);
722 }
723
724 /*
725 *----------------------------------------------------------------------
726 *
727 * TclParseAllWhiteSpace --
728 *
729 * Scans up to numBytes bytes starting at src, consuming all white space
730 * including the command-terminating newline characters.
731 *
732 * Results:
733 * Returns the number of bytes recognized as white space.
734 *
735 *----------------------------------------------------------------------
736 */
737
738 int
739 TclParseAllWhiteSpace(
740 const char *src, /* First character to parse. */
741 int numBytes) /* Max number of byes to scan */
742 {
743 int dummy;
744 char type;
745 const char *p = src;
746
747 do {
748 int scanned = ParseWhiteSpace(p, numBytes, &dummy, &type);
749
750 p += scanned;
751 numBytes -= scanned;
752 } while (numBytes && (*p == '\n') && (p++, --numBytes));
753 return (p-src);
754 }
755
756 /*
757 *----------------------------------------------------------------------
758 *
759 * ParseHex --
760 *
761 * Scans a hexadecimal number as a Tcl_UniChar value (e.g., for parsing
762 * \x and \u escape sequences). At most numBytes bytes are scanned.
763 *
764 * Results:
765 * The numeric value is stored in *resultPtr. Returns the number of bytes
766 * consumed.
767 *
768 * Notes:
769 * Relies on the following properties of the ASCII character set, with
770 * which UTF-8 is compatible:
771 *
772 * The digits '0' .. '9' and the letters 'A' .. 'Z' and 'a' .. 'z' occupy
773 * consecutive code points, and '0' < 'A' < 'a'.
774 *
775 *----------------------------------------------------------------------
776 */
777
778 int
779 ParseHex(
780 const char *src, /* First character to parse. */
781 int numBytes, /* Max number of byes to scan */
782 int *resultPtr) /* Points to storage provided by caller where
783 * the character resulting from the
784 * conversion is to be written. */
785 {
786 int result = 0;
787 const char *p = src;
788
789 while (numBytes--) {
790 unsigned char digit = UCHAR(*p);
791
792 if (!isxdigit(digit) || (result > 0x10FFF)) {
793 break;
794 }
795
796 p++;
797 result <<= 4;
798
799 if (digit >= 'a') {
800 result |= (10 + digit - 'a');
801 } else if (digit >= 'A') {
802 result |= (10 + digit - 'A');
803 } else {
804 result |= (digit - '0');
805 }
806 }
807
808 *resultPtr = result;
809 return (p - src);
810 }
811
812 /*
813 *----------------------------------------------------------------------
814 *
815 * TclParseBackslash --
816 *
817 * Scans up to numBytes bytes starting at src, consuming a backslash
818 * sequence as defined by Tcl's parsing rules.
819 *
820 * Results:
821 * Records at readPtr the number of bytes making up the backslash
822 * sequence. Records at dst the UTF-8 encoded equivalent of that
823 * backslash sequence. Returns the number of bytes written to dst, at
824 * most TCL_UTF_MAX. Either readPtr or dst may be NULL, if the results
825 * are not needed, but the return value is the same either way.
826 *
827 * Side effects:
828 * None.
829 *
830 *----------------------------------------------------------------------
831 */
832
833 int
834 TclParseBackslash(
835 const char *src, /* Points to the backslash character of a
836 * backslash sequence. */
837 int numBytes, /* Max number of bytes to scan. */
838 int *readPtr, /* NULL, or points to storage where the number
839 * of bytes scanned should be written. */
840 char *dst) /* NULL, or points to buffer where the UTF-8
841 * encoding of the backslash sequence is to be
842 * written. At most TCL_UTF_MAX bytes will be
843 * written there. */
844 {
845 const char *p = src+1;
846 int result;
847 int count;
848 char buf[TCL_UTF_MAX] = "";
849
850 if (numBytes == 0) {
851 if (readPtr != NULL) {
852 *readPtr = 0;
853 }
854 return 0;
855 }
856
857 if (dst == NULL) {
858 dst = buf;
859 }
860
861 if (numBytes == 1) {
862 /*
863 * Can only scan the backslash, so return it.
864 */
865
866 result = '\\';
867 count = 1;
868 goto done;
869 }
870
871 count = 2;
872 switch (*p) {
873 /*
874 * Note: in the conversions below, use absolute values (e.g., 0xA)
875 * rather than symbolic values (e.g. \n) that get converted by the
876 * compiler. It's possible that compilers on some platforms will do
877 * the symbolic conversions differently, which could result in
878 * non-portable Tcl scripts.
879 */
880
881 case 'a':
882 result = 0x7;
883 break;
884 case 'b':
885 result = 0x8;
886 break;
887 case 'f':
888 result = 0xC;
889 break;
890 case 'n':
891 result = 0xA;
892 break;
893 case 'r':
894 result = 0xD;
895 break;
896 case 't':
897 result = 0x9;
898 break;
899 case 'v':
900 result = 0xB;
901 break;
902 case 'x':
903 count += ParseHex(p+1, (numBytes > 3) ? 2 : numBytes-2, &result);
904 if (count == 2) {
905 /*
906 * No hexdigits -> This is just "x".
907 */
908
909 result = 'x';
910 } else {
911 /*
912 * Keep only the last byte (2 hex digits).
913 */
914 result = UCHAR(result);
915 }
916 break;
917 case 'u':
918 count += ParseHex(p+1, (numBytes > 5) ? 4 : numBytes-2, &result);
919 if (count == 2) {
920 /*
921 * No hexdigits -> This is just "u".
922 */
923 result = 'u';
924 #if TCL_UTF_MAX > 3
925 } else if (((result & 0xFC00) == 0xD800) && (count == 6)
926 && (p[5] == '\\') && (p[6] == 'u') && (numBytes >= 10)) {
927 /* If high surrogate is immediately followed by a low surrogate
928 * escape, combine them into one character. */
929 int low;
930 int count2 = ParseHex(p+7, 4, &low);
931 if ((count2 == 4) && ((low & 0xFC00) == 0xDC00)) {
932 result = ((result & 0x3FF)<<10 | (low & 0x3FF)) + 0x10000;
933 count += count2 + 2;
934 }
935 #endif
936 }
937 break;
938 case 'U':
939 count += ParseHex(p+1, (numBytes > 9) ? 8 : numBytes-2, &result);
940 if (count == 2) {
941 /*
942 * No hexdigits -> This is just "U".
943 */
944 result = 'U';
945 #if TCL_UTF_MAX > 3
946 } else if ((result & ~0x7FF) == 0xD800) {
947 /* Upper or lower surrogate, not allowed in this syntax. */
948 result = 0xFFFD;
949 #endif
950 }
951 break;
952 case '\n':
953 count--;
954 do {
955 p++;
956 count++;
957 } while ((count < numBytes) && ((*p == ' ') || (*p == '\t')));
958 result = ' ';
959 break;
960 case 0:
961 result = '\\';
962 count = 1;
963 break;
964 default:
965 /*
966 * Check for an octal number \oo?o?
967 */
968
969 if (isdigit(UCHAR(*p)) && (UCHAR(*p) < '8')) { /* INTL: digit */
970 result = *p - '0';
971 p++;
972 if ((numBytes == 2) || !isdigit(UCHAR(*p)) /* INTL: digit */
973 || (UCHAR(*p) >= '8')) {
974 break;
975 }
976 count = 3;
977 result = (result << 3) + (*p - '0');
978 p++;
979 if ((numBytes == 3) || !isdigit(UCHAR(*p)) /* INTL: digit */
980 || (UCHAR(*p) >= '8') || (result >= 0x20)) {
981 break;
982 }
983 count = 4;
984 result = UCHAR((result << 3) + (*p - '0'));
985 break;
986 }
987
988 /*
989 * We have to convert here in case the user has put a backslash in
990 * front of a multi-byte utf-8 character. While this means nothing
991 * special, we shouldn't break up a correct utf-8 character. [Bug
992 * #217987] test subst-3.2
993 */
994
995 if (TclUCS4Complete(p, numBytes - 1)) {
996 count = TclUtfToUCS4(p, &result) + 1; /* +1 for '\' */
997 } else {
998 char utfBytes[8];
999
1000 memcpy(utfBytes, p, numBytes - 1);
1001 utfBytes[numBytes - 1] = '\0';
1002 count = TclUtfToUCS4(utfBytes, &result) + 1;
1003 }
1004 break;
1005 }
1006
1007 done:
1008 if (readPtr != NULL) {
1009 *readPtr = count;
1010 }
1011 #if TCL_UTF_MAX < 4
1012 if (result > 0xFFFF) {
1013 result = 0xFFFD;
1014 }
1015 #endif
1016 return TclUCS4ToUtf(result, dst);
1017 }
1018
1019 /*
1020 *----------------------------------------------------------------------
1021 *
1022 * ParseComment --
1023 *
1024 * Scans up to numBytes bytes starting at src, consuming a Tcl comment as
1025 * defined by Tcl's parsing rules.
1026 *
1027 * Results:
1028 * Records in parsePtr information about the parse. Returns the number of
1029 * bytes consumed.
1030 *
1031 * Side effects:
1032 * None.
1033 *
1034 *----------------------------------------------------------------------
1035 */
1036
1037 static int
1038 ParseComment(
1039 const char *src, /* First character to parse. */
1040 int numBytes, /* Max number of bytes to scan. */
1041 Tcl_Parse *parsePtr) /* Information about parse in progress.
1042 * Updated if parsing indicates an incomplete
1043 * command. */
1044 {
1045 const char *p = src;
1046
1047 while (numBytes) {
1048 char type;
1049 int scanned;
1050
1051 do {
1052 scanned = ParseWhiteSpace(p, numBytes,
1053 &parsePtr->incomplete, &type);
1054 p += scanned;
1055 numBytes -= scanned;
1056 } while (numBytes && (*p == '\n') && (p++,numBytes--));
1057
1058 if ((numBytes == 0) || (*p != '#')) {
1059 break;
1060 }
1061 if (parsePtr->commentStart == NULL) {
1062 parsePtr->commentStart = p;
1063 }
1064
1065 while (numBytes) {
1066 if (*p == '\\') {
1067 scanned = ParseWhiteSpace(p, numBytes, &parsePtr->incomplete,
1068 &type);
1069 if (scanned) {
1070 p += scanned;
1071 numBytes -= scanned;
1072 } else {
1073 /*
1074 * General backslash substitution in comments isn't part
1075 * of the formal spec, but test parse-15.47 and history
1076 * indicate that it has been the de facto rule. Don't
1077 * change it now.
1078 */
1079
1080 TclParseBackslash(p, numBytes, &scanned, NULL);
1081 p += scanned;
1082 numBytes -= scanned;
1083 }
1084 } else {
1085 p++;
1086 numBytes--;
1087 if (p[-1] == '\n') {
1088 break;
1089 }
1090 }
1091 }
1092 parsePtr->commentSize = p - parsePtr->commentStart;
1093 }
1094 return (p - src);
1095 }
1096
1097 /*
1098 *----------------------------------------------------------------------
1099 *
1100 * ParseTokens --
1101 *
1102 * This function forms the heart of the Tcl parser. It parses one or more
1103 * tokens from a string, up to a termination point specified by the
1104 * caller. This function is used to parse unquoted command words (those
1105 * not in quotes or braces), words in quotes, and array indices for
1106 * variables. No more than numBytes bytes will be scanned.
1107 *
1108 * Results:
1109 * Tokens are added to parsePtr and parsePtr->term is filled in with the
1110 * address of the character that terminated the parse (the first one
1111 * whose CHAR_TYPE matched mask or the character at parsePtr->end). The
1112 * return value is TCL_OK if the parse completed successfully and
1113 * TCL_ERROR otherwise. If a parse error occurs and parsePtr->interp is
1114 * not NULL, then an error message is left in the interpreter's result.
1115 *
1116 * Side effects:
1117 * None.
1118 *
1119 *----------------------------------------------------------------------
1120 */
1121
1122 static int
1123 ParseTokens(
1124 const char *src, /* First character to parse. */
1125 int numBytes, /* Max number of bytes to scan. */
1126 int mask, /* Specifies when to stop parsing. The parse
1127 * stops at the first unquoted character whose
1128 * CHAR_TYPE contains any of the bits in
1129 * mask. */
1130 int flags, /* OR-ed bits indicating what substitutions to
1131 * perform: TCL_SUBST_COMMANDS,
1132 * TCL_SUBST_VARIABLES, and
1133 * TCL_SUBST_BACKSLASHES */
1134 Tcl_Parse *parsePtr) /* Information about parse in progress.
1135 * Updated with additional tokens and
1136 * termination information. */
1137 {
1138 char type;
1139 int originalTokens;
1140 int noSubstCmds = !(flags & TCL_SUBST_COMMANDS);
1141 int noSubstVars = !(flags & TCL_SUBST_VARIABLES);
1142 int noSubstBS = !(flags & TCL_SUBST_BACKSLASHES);
1143 Tcl_Token *tokenPtr;
1144
1145 /*
1146 * Each iteration through the following loop adds one token of type
1147 * TCL_TOKEN_TEXT, TCL_TOKEN_BS, TCL_TOKEN_COMMAND, or TCL_TOKEN_VARIABLE
1148 * to parsePtr. For TCL_TOKEN_VARIABLE tokens, additional tokens are added
1149 * for the parsed variable name.
1150 */
1151
1152 originalTokens = parsePtr->numTokens;
1153 while (numBytes && !((type = CHAR_TYPE(*src)) & mask)) {
1154 TclGrowParseTokenArray(parsePtr, 1);
1155 tokenPtr = &parsePtr->tokenPtr[parsePtr->numTokens];
1156 tokenPtr->start = src;
1157 tokenPtr->numComponents = 0;
1158
1159 if ((type & TYPE_SUBS) == 0) {
1160 /*
1161 * This is a simple range of characters. Scan to find the end of
1162 * the range.
1163 */
1164
1165 while ((++src, --numBytes)
1166 && !(CHAR_TYPE(*src) & (mask | TYPE_SUBS))) {
1167 /* empty loop */
1168 }
1169 tokenPtr->type = TCL_TOKEN_TEXT;
1170 tokenPtr->size = src - tokenPtr->start;
1171 parsePtr->numTokens++;
1172 } else if (*src == '$') {
1173 int varToken;
1174
1175 if (noSubstVars) {
1176 tokenPtr->type = TCL_TOKEN_TEXT;
1177 tokenPtr->size = 1;
1178 parsePtr->numTokens++;
1179 src++;
1180 numBytes--;
1181 continue;
1182 }
1183
1184 /*
1185 * This is a variable reference. Call Tcl_ParseVarName to do all
1186 * the dirty work of parsing the name.
1187 */
1188
1189 varToken = parsePtr->numTokens;
1190 if (Tcl_ParseVarName(parsePtr->interp, src, numBytes, parsePtr,
1191 1) != TCL_OK) {
1192 return TCL_ERROR;
1193 }
1194 src += parsePtr->tokenPtr[varToken].size;
1195 numBytes -= parsePtr->tokenPtr[varToken].size;
1196 } else if (*src == '[') {
1197 Tcl_Parse *nestedPtr;
1198
1199 if (noSubstCmds) {
1200 tokenPtr->type = TCL_TOKEN_TEXT;
1201 tokenPtr->size = 1;
1202 parsePtr->numTokens++;
1203 src++;
1204 numBytes--;
1205 continue;
1206 }
1207
1208 /*
1209 * Command substitution. Call Tcl_ParseCommand recursively (and
1210 * repeatedly) to parse the nested command(s), then throw away the
1211 * parse information.
1212 */
1213
1214 src++;
1215 numBytes--;
1216 nestedPtr = TclStackAlloc(parsePtr->interp, sizeof(Tcl_Parse));
1217 while (1) {
1218 const char *curEnd;
1219
1220 if (Tcl_ParseCommand(parsePtr->interp, src, numBytes, 1,
1221 nestedPtr) != TCL_OK) {
1222 parsePtr->errorType = nestedPtr->errorType;
1223 parsePtr->term = nestedPtr->term;
1224 parsePtr->incomplete = nestedPtr->incomplete;
1225 TclStackFree(parsePtr->interp, nestedPtr);
1226 return TCL_ERROR;
1227 }
1228 curEnd = src + numBytes;
1229 src = nestedPtr->commandStart + nestedPtr->commandSize;
1230 numBytes = curEnd - src;
1231 Tcl_FreeParse(nestedPtr);
1232
1233 /*
1234 * Check for the closing ']' that ends the command
1235 * substitution. It must have been the last character of the
1236 * parsed command.
1237 */
1238
1239 if ((nestedPtr->term < parsePtr->end)
1240 && (*(nestedPtr->term) == ']')
1241 && !(nestedPtr->incomplete)) {
1242 break;
1243 }
1244 if (numBytes == 0) {
1245 if (parsePtr->interp != NULL) {
1246 Tcl_SetObjResult(parsePtr->interp, Tcl_NewStringObj(
1247 "missing close-bracket", -1));
1248 }
1249 parsePtr->errorType = TCL_PARSE_MISSING_BRACKET;
1250 parsePtr->term = tokenPtr->start;
1251 parsePtr->incomplete = 1;
1252 TclStackFree(parsePtr->interp, nestedPtr);
1253 return TCL_ERROR;
1254 }
1255 }
1256 TclStackFree(parsePtr->interp, nestedPtr);
1257 tokenPtr->type = TCL_TOKEN_COMMAND;
1258 tokenPtr->size = src - tokenPtr->start;
1259 parsePtr->numTokens++;
1260 } else if (*src == '\\') {
1261 if (noSubstBS) {
1262 tokenPtr->type = TCL_TOKEN_TEXT;
1263 tokenPtr->size = 1;
1264 parsePtr->numTokens++;
1265 src++;
1266 numBytes--;
1267 continue;
1268 }
1269
1270 /*
1271 * Backslash substitution.
1272 */
1273
1274 TclParseBackslash(src, numBytes, &tokenPtr->size, NULL);
1275
1276 if (tokenPtr->size == 1) {
1277 /*
1278 * Just a backslash, due to end of string.
1279 */
1280
1281 tokenPtr->type = TCL_TOKEN_TEXT;
1282 parsePtr->numTokens++;
1283 src++;
1284 numBytes--;
1285 continue;
1286 }
1287
1288 if (src[1] == '\n') {
1289 if (numBytes == 2) {
1290 parsePtr->incomplete = 1;
1291 }
1292
1293 /*
1294 * Note: backslash-newline is special in that it is treated
1295 * the same as a space character would be. This means that it
1296 * could terminate the token.
1297 */
1298
1299 if (mask & TYPE_SPACE) {
1300 if (parsePtr->numTokens == originalTokens) {
1301 goto finishToken;
1302 }
1303 break;
1304 }
1305 }
1306
1307 tokenPtr->type = TCL_TOKEN_BS;
1308 parsePtr->numTokens++;
1309 src += tokenPtr->size;
1310 numBytes -= tokenPtr->size;
1311 } else if (*src == 0) {
1312 tokenPtr->type = TCL_TOKEN_TEXT;
1313 tokenPtr->size = 1;
1314 parsePtr->numTokens++;
1315 src++;
1316 numBytes--;
1317 } else {
1318 Tcl_Panic("ParseTokens encountered unknown character");
1319 }
1320 }
1321 if (parsePtr->numTokens == originalTokens) {
1322 /*
1323 * There was nothing in this range of text. Add an empty token for the
1324 * empty range, so that there is always at least one token added.
1325 */
1326
1327 TclGrowParseTokenArray(parsePtr, 1);
1328 tokenPtr = &parsePtr->tokenPtr[parsePtr->numTokens];
1329 tokenPtr->start = src;
1330 tokenPtr->numComponents = 0;
1331
1332 finishToken:
1333 tokenPtr->type = TCL_TOKEN_TEXT;
1334 tokenPtr->size = 0;
1335 parsePtr->numTokens++;
1336 }
1337 parsePtr->term = src;
1338 return TCL_OK;
1339 }
1340
1341 /*
1342 *----------------------------------------------------------------------
1343 *
1344 * Tcl_FreeParse --
1345 *
1346 * This function is invoked to free any dynamic storage that may have
1347 * been allocated by a previous call to Tcl_ParseCommand.
1348 *
1349 * Results:
1350 * None.
1351 *
1352 * Side effects:
1353 * If there is any dynamically allocated memory in *parsePtr, it is
1354 * freed.
1355 *
1356 *----------------------------------------------------------------------
1357 */
1358
1359 void
1360 Tcl_FreeParse(
1361 Tcl_Parse *parsePtr) /* Structure that was filled in by a previous
1362 * call to Tcl_ParseCommand. */
1363 {
1364 if (parsePtr->tokenPtr != parsePtr->staticTokens) {
1365 ckfree(parsePtr->tokenPtr);
1366 parsePtr->tokenPtr = parsePtr->staticTokens;
1367 }
1368 }
1369
1370 /*
1371 *----------------------------------------------------------------------
1372 *
1373 * Tcl_ParseVarName --
1374 *
1375 * Given a string starting with a $ sign, parse off a variable name and
1376 * return information about the parse. No more than numBytes bytes will
1377 * be scanned.
1378 *
1379 * Results:
1380 * The return value is TCL_OK if the command was parsed successfully and
1381 * TCL_ERROR otherwise. If an error occurs and interp isn't NULL then an
1382 * error message is left in its result. On a successful return, tokenPtr
1383 * and numTokens fields of parsePtr are filled in with information about
1384 * the variable name that was parsed. The "size" field of the first new
1385 * token gives the total number of bytes in the variable name. Other
1386 * fields in parsePtr are undefined.
1387 *
1388 * Side effects:
1389 * If there is insufficient space in parsePtr to hold all the information
1390 * about the command, then additional space is malloc-ed. If the function
1391 * returns TCL_OK then the caller must eventually invoke Tcl_FreeParse to
1392 * release any additional space that was allocated.
1393 *
1394 *----------------------------------------------------------------------
1395 */
1396
1397 int
1398 Tcl_ParseVarName(
1399 Tcl_Interp *interp, /* Interpreter to use for error reporting; if
1400 * NULL, then no error message is provided. */
1401 const char *start, /* Start of variable substitution string.
1402 * First character must be "$". */
1403 int numBytes, /* Total number of bytes in string. If < 0,
1404 * the string consists of all bytes up to the
1405 * first null character. */
1406 Tcl_Parse *parsePtr, /* Structure to fill in with information about
1407 * the variable name. */
1408 int append) /* Non-zero means append tokens to existing
1409 * information in parsePtr; zero means ignore
1410 * existing tokens in parsePtr and
1411 * reinitialize it. */
1412 {
1413 Tcl_Token *tokenPtr;
1414 const char *src;
1415 int varIndex;
1416 unsigned array;
1417
1418 if (numBytes < 0 && start) {
1419 numBytes = strlen(start);
1420 }
1421 if (!append) {
1422 TclParseInit(interp, start, numBytes, parsePtr);
1423 }
1424 if ((numBytes == 0) || (start == NULL)) {
1425 return TCL_ERROR;
1426 }
1427
1428 /*
1429 * Generate one token for the variable, an additional token for the name,
1430 * plus any number of additional tokens for the index, if there is one.
1431 */
1432
1433 src = start;
1434 TclGrowParseTokenArray(parsePtr, 2);
1435 tokenPtr = &parsePtr->tokenPtr[parsePtr->numTokens];
1436 tokenPtr->type = TCL_TOKEN_VARIABLE;
1437 tokenPtr->start = src;
1438 varIndex = parsePtr->numTokens;
1439 parsePtr->numTokens++;
1440 tokenPtr++;
1441 src++;
1442 numBytes--;
1443 if (numBytes == 0) {
1444 goto justADollarSign;
1445 }
1446 tokenPtr->type = TCL_TOKEN_TEXT;
1447 tokenPtr->start = src;
1448 tokenPtr->numComponents = 0;
1449
1450 /*
1451 * The name of the variable can have three forms:
1452 * 1. The $ sign is followed by an open curly brace. Then the variable
1453 * name is everything up to the next close curly brace, and the
1454 * variable is a scalar variable.
1455 * 2. The $ sign is not followed by an open curly brace. Then the variable
1456 * name is everything up to the next character that isn't a letter,
1457 * digit, or underscore. :: sequences are also considered part of the
1458 * variable name, in order to support namespaces. If the following
1459 * character is an open parenthesis, then the information between
1460 * parentheses is the array element name.
1461 * 3. The $ sign is followed by something that isn't a letter, digit, or
1462 * underscore: in this case, there is no variable name and the token is
1463 * just "$".
1464 */
1465
1466 if (*src == '{') {
1467 src++;
1468 numBytes--;
1469 tokenPtr->type = TCL_TOKEN_TEXT;
1470 tokenPtr->start = src;
1471 tokenPtr->numComponents = 0;
1472
1473 while (numBytes && (*src != '}')) {
1474 numBytes--;
1475 src++;
1476 }
1477 if (numBytes == 0) {
1478 if (parsePtr->interp != NULL) {
1479 Tcl_SetObjResult(parsePtr->interp, Tcl_NewStringObj(
1480 "missing close-brace for variable name", -1));
1481 }
1482 parsePtr->errorType = TCL_PARSE_MISSING_VAR_BRACE;
1483 parsePtr->term = tokenPtr->start-1;
1484 parsePtr->incomplete = 1;
1485 goto error;
1486 }
1487 tokenPtr->size = src - tokenPtr->start;
1488 tokenPtr[-1].size = src - tokenPtr[-1].start;
1489 parsePtr->numTokens++;
1490 src++;
1491 } else {
1492 tokenPtr->type = TCL_TOKEN_TEXT;
1493 tokenPtr->start = src;
1494 tokenPtr->numComponents = 0;
1495
1496 while (numBytes) {
1497 if (TclIsBareword(*src)) {
1498 src += 1;
1499 numBytes -= 1;
1500 continue;
1501 }
1502 if ((src[0] == ':') && (numBytes != 1) && (src[1] == ':')) {
1503 src += 2;
1504 numBytes -= 2;
1505 while (numBytes && (*src == ':')) {
1506 src++;
1507 numBytes--;
1508 }
1509 continue;
1510 }
1511 break;
1512 }
1513
1514 /*
1515 * Support for empty array names here.
1516 */
1517
1518 array = (numBytes && (*src == '('));
1519 tokenPtr->size = src - tokenPtr->start;
1520 if ((tokenPtr->size == 0) && !array) {
1521 goto justADollarSign;
1522 }
1523 parsePtr->numTokens++;
1524 if (array) {
1525 /*
1526 * This is a reference to an array element. Call ParseTokens
1527 * recursively to parse the element name, since it could contain
1528 * any number of substitutions.
1529 */
1530
1531 if (TCL_OK != ParseTokens(src+1, numBytes-1, TYPE_CLOSE_PAREN,
1532 TCL_SUBST_ALL, parsePtr)) {
1533 goto error;
1534 }
1535 if ((parsePtr->term == src+numBytes) || (*parsePtr->term != ')')){
1536 if (parsePtr->interp != NULL) {
1537 Tcl_SetObjResult(parsePtr->interp, Tcl_NewStringObj(
1538 "missing )", -1));
1539 }
1540 parsePtr->errorType = TCL_PARSE_MISSING_PAREN;
1541 parsePtr->term = src;
1542 parsePtr->incomplete = 1;
1543 goto error;
1544 }
1545 src = parsePtr->term + 1;
1546 }
1547 }
1548 tokenPtr = &parsePtr->tokenPtr[varIndex];
1549 tokenPtr->size = src - tokenPtr->start;
1550 tokenPtr->numComponents = parsePtr->numTokens - (varIndex + 1);
1551 return TCL_OK;
1552
1553 /*
1554 * The dollar sign isn't followed by a variable name. Replace the
1555 * TCL_TOKEN_VARIABLE token with a TCL_TOKEN_TEXT token for the dollar
1556 * sign.
1557 */
1558
1559 justADollarSign:
1560 tokenPtr = &parsePtr->tokenPtr[varIndex];
1561 tokenPtr->type = TCL_TOKEN_TEXT;
1562 tokenPtr->size = 1;
1563 tokenPtr->numComponents = 0;
1564 return TCL_OK;
1565
1566 error:
1567 Tcl_FreeParse(parsePtr);
1568 return TCL_ERROR;
1569 }
1570
1571 /*
1572 *----------------------------------------------------------------------
1573 *
1574 * Tcl_ParseVar --
1575 *
1576 * Given a string starting with a $ sign, parse off a variable name and
1577 * return its value.
1578 *
1579 * Results:
1580 * The return value is the contents of the variable given by the leading
1581 * characters of string. If termPtr isn't NULL, *termPtr gets filled in
1582 * with the address of the character just after the last one in the
1583 * variable specifier. If the variable doesn't exist, then the return
1584 * value is NULL and an error message will be left in interp's result.
1585 *
1586 * Side effects:
1587 * None.
1588 *
1589 *----------------------------------------------------------------------
1590 */
1591
1592 const char *
1593 Tcl_ParseVar(
1594 Tcl_Interp *interp, /* Context for looking up variable. */
1595 const char *start, /* Start of variable substitution. First
1596 * character must be "$". */
1597 const char **termPtr) /* If non-NULL, points to word to fill in with
1598 * character just after last one in the
1599 * variable specifier. */
1600 {
1601 Tcl_Obj *objPtr;
1602 int code;
1603 Tcl_Parse *parsePtr = TclStackAlloc(interp, sizeof(Tcl_Parse));
1604
1605 if (Tcl_ParseVarName(interp, start, -1, parsePtr, 0) != TCL_OK) {
1606 TclStackFree(interp, parsePtr);
1607 return NULL;
1608 }
1609
1610 if (termPtr != NULL) {
1611 *termPtr = start + parsePtr->tokenPtr->size;
1612 }
1613 if (parsePtr->numTokens == 1) {
1614 /*
1615 * There isn't a variable name after all: the $ is just a $.
1616 */
1617
1618 TclStackFree(interp, parsePtr);
1619 return "$";
1620 }
1621
1622 code = TclSubstTokens(interp, parsePtr->tokenPtr, parsePtr->numTokens,
1623 NULL, 1, NULL, NULL);
1624 Tcl_FreeParse(parsePtr);
1625 TclStackFree(interp, parsePtr);
1626 if (code != TCL_OK) {
1627 return NULL;
1628 }
1629 objPtr = Tcl_GetObjResult(interp);
1630
1631 /*
1632 * At this point we should have an object containing the value of a
1633 * variable. Just return the string from that object.
1634 *
1635 * Since TclSubstTokens above returned TCL_OK, we know that objPtr
1636 * is shared. It is in both the interp result and the value of the
1637 * variable. Returning the string relies on that to be true.
1638 */
1639
1640 assert( Tcl_IsShared(objPtr) );
1641
1642 Tcl_ResetResult(interp);
1643 return TclGetString(objPtr);
1644 }
1645
1646 /*
1647 *----------------------------------------------------------------------
1648 *
1649 * Tcl_ParseBraces --
1650 *
1651 * Given a string in braces such as a Tcl command argument or a string
1652 * value in a Tcl expression, this function parses the string and returns
1653 * information about the parse. No more than numBytes bytes will be
1654 * scanned.
1655 *
1656 * Results:
1657 * The return value is TCL_OK if the string was parsed successfully and
1658 * TCL_ERROR otherwise. If an error occurs and interp isn't NULL then an
1659 * error message is left in its result. On a successful return, tokenPtr
1660 * and numTokens fields of parsePtr are filled in with information about
1661 * the string that was parsed. Other fields in parsePtr are undefined.
1662 * termPtr is set to point to the character just after the last one in
1663 * the braced string.
1664 *
1665 * Side effects:
1666 * If there is insufficient space in parsePtr to hold all the information
1667 * about the command, then additional space is malloc-ed. If the function
1668 * returns TCL_OK then the caller must eventually invoke Tcl_FreeParse to
1669 * release any additional space that was allocated.
1670 *
1671 *----------------------------------------------------------------------
1672 */
1673
1674 int
1675 Tcl_ParseBraces(
1676 Tcl_Interp *interp, /* Interpreter to use for error reporting; if
1677 * NULL, then no error message is provided. */
1678 const char *start, /* Start of string enclosed in braces. The
1679 * first character must be {'. */
1680 int numBytes, /* Total number of bytes in string. If < 0,
1681 * the string consists of all bytes up to the
1682 * first null character. */
1683 Tcl_Parse *parsePtr,
1684 /* Structure to fill in with information about
1685 * the string. */
1686 int append, /* Non-zero means append tokens to existing
1687 * information in parsePtr; zero means ignore
1688 * existing tokens in parsePtr and
1689 * reinitialize it. */
1690 const char **termPtr) /* If non-NULL, points to word in which to
1691 * store a pointer to the character just after
1692 * the terminating '}' if the parse was
1693 * successful. */
1694 {
1695 Tcl_Token *tokenPtr;
1696 const char *src;
1697 int startIndex, level, length;
1698
1699 if (numBytes < 0 && start) {
1700 numBytes = strlen(start);
1701 }
1702 if (!append) {
1703 TclParseInit(interp, start, numBytes, parsePtr);
1704 }
1705 if ((numBytes == 0) || (start == NULL)) {
1706 return TCL_ERROR;
1707 }
1708
1709 src = start;
1710 startIndex = parsePtr->numTokens;
1711
1712 TclGrowParseTokenArray(parsePtr, 1);
1713 tokenPtr = &parsePtr->tokenPtr[startIndex];
1714 tokenPtr->type = TCL_TOKEN_TEXT;
1715 tokenPtr->start = src+1;
1716 tokenPtr->numComponents = 0;
1717 level = 1;
1718 while (1) {
1719 while (++src, --numBytes) {
1720 if (CHAR_TYPE(*src) != TYPE_NORMAL) {
1721 break;
1722 }
1723 }
1724 if (numBytes == 0) {
1725 goto missingBraceError;
1726 }
1727
1728 switch (*src) {
1729 case '{':
1730 level++;
1731 break;
1732 case '}':
1733 if (--level == 0) {
1734 /*
1735 * Decide if we need to finish emitting a partially-finished
1736 * token. There are 3 cases:
1737 * {abc \newline xyz} or {xyz}
1738 * - finish emitting "xyz" token
1739 * {abc \newline}
1740 * - don't emit token after \newline
1741 * {} - finish emitting zero-sized token
1742 *
1743 * The last case ensures that there is a token (even if empty)
1744 * that describes the braced string.
1745 */
1746
1747 if ((src != tokenPtr->start)
1748 || (parsePtr->numTokens == startIndex)) {
1749 tokenPtr->size = (src - tokenPtr->start);
1750 parsePtr->numTokens++;
1751 }
1752 if (termPtr != NULL) {
1753 *termPtr = src+1;
1754 }
1755 return TCL_OK;
1756 }
1757 break;
1758 case '\\':
1759 TclParseBackslash(src, numBytes, &length, NULL);
1760 if ((length > 1) && (src[1] == '\n')) {
1761 /*
1762 * A backslash-newline sequence must be collapsed, even inside
1763 * braces, so we have to split the word into multiple tokens
1764 * so that the backslash-newline can be represented
1765 * explicitly.
1766 */
1767
1768 if (numBytes == 2) {
1769 parsePtr->incomplete = 1;
1770 }
1771 tokenPtr->size = (src - tokenPtr->start);
1772 if (tokenPtr->size != 0) {
1773 parsePtr->numTokens++;
1774 }
1775 TclGrowParseTokenArray(parsePtr, 2);
1776 tokenPtr = &parsePtr->tokenPtr[parsePtr->numTokens];
1777 tokenPtr->type = TCL_TOKEN_BS;
1778 tokenPtr->start = src;
1779 tokenPtr->size = length;
1780 tokenPtr->numComponents = 0;
1781 parsePtr->numTokens++;
1782
1783 src += length - 1;
1784 numBytes -= length - 1;
1785 tokenPtr++;
1786 tokenPtr->type = TCL_TOKEN_TEXT;
1787 tokenPtr->start = src + 1;
1788 tokenPtr->numComponents = 0;
1789 } else {
1790 src += length - 1;
1791 numBytes -= length - 1;
1792 }
1793 break;
1794 }
1795 }
1796
1797 missingBraceError:
1798 parsePtr->errorType = TCL_PARSE_MISSING_BRACE;
1799 parsePtr->term = start;
1800 parsePtr->incomplete = 1;
1801 if (parsePtr->interp == NULL) {
1802 /*
1803 * Skip straight to the exit code since we have no interpreter to put
1804 * error message in.
1805 */
1806
1807 goto error;
1808 }
1809
1810 Tcl_SetObjResult(parsePtr->interp, Tcl_NewStringObj(
1811 "missing close-brace", -1));
1812
1813 /*
1814 * Guess if the problem is due to comments by searching the source string
1815 * for a possible open brace within the context of a comment. Since we
1816 * aren't performing a full Tcl parse, just look for an open brace
1817 * preceded by a '<whitespace>#' on the same line.
1818 */
1819
1820 {
1821 int openBrace = 0;
1822
1823 while (--src > start) {
1824 switch (*src) {
1825 case '{':
1826 openBrace = 1;
1827 break;
1828 case '\n':
1829 openBrace = 0;
1830 break;
1831 case '#' :
1832 if (openBrace && TclIsSpaceProcM(src[-1])) {
1833 Tcl_AppendToObj(Tcl_GetObjResult(parsePtr->interp),
1834 ": possible unbalanced brace in comment", -1);
1835 goto error;
1836 }
1837 break;
1838 }
1839 }
1840 }
1841
1842 error:
1843 Tcl_FreeParse(parsePtr);
1844 return TCL_ERROR;
1845 }
1846
1847 /*
1848 *----------------------------------------------------------------------
1849 *
1850 * Tcl_ParseQuotedString --
1851 *
1852 * Given a double-quoted string such as a quoted Tcl command argument or
1853 * a quoted value in a Tcl expression, this function parses the string
1854 * and returns information about the parse. No more than numBytes bytes
1855 * will be scanned.
1856 *
1857 * Results:
1858 * The return value is TCL_OK if the string was parsed successfully and
1859 * TCL_ERROR otherwise. If an error occurs and interp isn't NULL then an
1860 * error message is left in its result. On a successful return, tokenPtr
1861 * and numTokens fields of parsePtr are filled in with information about
1862 * the string that was parsed. Other fields in parsePtr are undefined.
1863 * termPtr is set to point to the character just after the quoted
1864 * string's terminating close-quote.
1865 *
1866 * Side effects:
1867 * If there is insufficient space in parsePtr to hold all the information
1868 * about the command, then additional space is malloc-ed. If the function
1869 * returns TCL_OK then the caller must eventually invoke Tcl_FreeParse to
1870 * release any additional space that was allocated.
1871 *
1872 *----------------------------------------------------------------------
1873 */
1874
1875 int
1876 Tcl_ParseQuotedString(
1877 Tcl_Interp *interp, /* Interpreter to use for error reporting; if
1878 * NULL, then no error message is provided. */
1879 const char *start, /* Start of the quoted string. The first
1880 * character must be '"'. */
1881 int numBytes, /* Total number of bytes in string. If < 0,
1882 * the string consists of all bytes up to the
1883 * first null character. */
1884 Tcl_Parse *parsePtr,
1885 /* Structure to fill in with information about
1886 * the string. */
1887 int append, /* Non-zero means append tokens to existing
1888 * information in parsePtr; zero means ignore
1889 * existing tokens in parsePtr and
1890 * reinitialize it. */
1891 const char **termPtr) /* If non-NULL, points to word in which to
1892 * store a pointer to the character just after
1893 * the quoted string's terminating close-quote
1894 * if the parse succeeds. */
1895 {
1896 if (numBytes < 0 && start) {
1897 numBytes = strlen(start);
1898 }
1899 if (!append) {
1900 TclParseInit(interp, start, numBytes, parsePtr);
1901 }
1902 if ((numBytes == 0) || (start == NULL)) {
1903 return TCL_ERROR;
1904 }
1905
1906 if (TCL_OK != ParseTokens(start+1, numBytes-1, TYPE_QUOTE, TCL_SUBST_ALL,
1907 parsePtr)) {
1908 goto error;
1909 }
1910 if (*parsePtr->term != '"') {
1911 if (parsePtr->interp != NULL) {
1912 Tcl_SetObjResult(parsePtr->interp, Tcl_NewStringObj(
1913 "missing \"", -1));
1914 }
1915 parsePtr->errorType = TCL_PARSE_MISSING_QUOTE;
1916 parsePtr->term = start;
1917 parsePtr->incomplete = 1;
1918 goto error;
1919 }
1920 if (termPtr != NULL) {
1921 *termPtr = (parsePtr->term + 1);
1922 }
1923 return TCL_OK;
1924
1925 error:
1926 Tcl_FreeParse(parsePtr);
1927 return TCL_ERROR;
1928 }
1929
1930 /*
1931 *----------------------------------------------------------------------
1932 *
1933 * TclSubstParse --
1934 *
1935 * Token parser used by the [subst] command. Parses the string made up of
1936 * 'numBytes' bytes starting at 'bytes'. Parsing is controlled by the
1937 * flags argument to provide support for the -nobackslashes, -nocommands,
1938 * and -novariables options, as represented by the flag values
1939 * TCL_SUBST_BACKSLASHES, TCL_SUBST_COMMANDS, TCL_SUBST_VARIABLES.
1940 *
1941 * Results:
1942 * None.
1943 *
1944 * Side effects:
1945 * The Tcl_Parse struct '*parsePtr' is filled with parse results.
1946 * The caller is expected to eventually call Tcl_FreeParse() to properly
1947 * cleanup the value written there.
1948 *
1949 * If a parse error occurs, the Tcl_InterpState value '*statePtr' is
1950 * filled with the state created by that error. When *statePtr is written
1951 * to, the caller is expected to make the required calls to either
1952 * Tcl_RestoreInterpState() or Tcl_DiscardInterpState() to dispose of the
1953 * value written there.
1954 *
1955 *----------------------------------------------------------------------
1956 */
1957
1958 void
1959 TclSubstParse(
1960 Tcl_Interp *interp,
1961 const char *bytes,
1962 int numBytes,
1963 int flags,
1964 Tcl_Parse *parsePtr,
1965 Tcl_InterpState *statePtr)
1966 {
1967 int length = numBytes;
1968 const char *p = bytes;
1969
1970 TclParseInit(interp, p, length, parsePtr);
1971
1972 /*
1973 * First parse the string rep of objPtr, as if it were enclosed as a
1974 * "-quoted word in a normal Tcl command. Honor flags that selectively
1975 * inhibit types of substitution.
1976 */
1977
1978 if (TCL_OK != ParseTokens(p, length, /* mask */ 0, flags, parsePtr)) {
1979 /*
1980 * There was a parse error. Save the interpreter state for possible
1981 * error reporting later.
1982 */
1983
1984 *statePtr = Tcl_SaveInterpState(interp, TCL_ERROR);
1985
1986 /*
1987 * We need to re-parse to get the portion of the string we can [subst]
1988 * before the parse error. Sadly, all the Tcl_Token's created by the
1989 * first parse attempt are gone, freed according to the public spec
1990 * for the Tcl_Parse* routines. The only clue we have is parse.term,
1991 * which points to either the unmatched opener, or to characters that
1992 * follow a close brace or close quote.
1993 *
1994 * Call ParseTokens again, working on the string up to parse.term.
1995 * Keep repeating until we get a good parse on a prefix.
1996 */
1997
1998 do {
1999 parsePtr->numTokens = 0;
2000 parsePtr->tokensAvailable = NUM_STATIC_TOKENS;
2001 parsePtr->end = parsePtr->term;
2002 parsePtr->incomplete = 0;
2003 parsePtr->errorType = TCL_PARSE_SUCCESS;
2004 } while (TCL_OK !=
2005 ParseTokens(p, parsePtr->end - p, 0, flags, parsePtr));
2006
2007 /*
2008 * The good parse will have to be followed by {, (, or [.
2009 */
2010
2011 switch (*(parsePtr->term)) {
2012 case '{':
2013 /*
2014 * Parse error was a missing } in a ${varname} variable
2015 * substitution at the toplevel. We will subst everything up to
2016 * that broken variable substitution before reporting the parse
2017 * error. Substituting the leftover '$' will have no side-effects,
2018 * so the current token stream is fine.
2019 */
2020 break;
2021
2022 case '(':
2023 /*
2024 * Parse error was during the parsing of the index part of an
2025 * array variable substitution at the toplevel.
2026 */
2027
2028 if (*(parsePtr->term - 1) == '$') {
2029 /*
2030 * Special case where removing the array index left us with
2031 * just a dollar sign (array variable with name the empty
2032 * string as its name), instead of with a scalar variable
2033 * reference.
2034 *
2035 * As in the previous case, existing token stream is OK.
2036 */
2037 } else {
2038 /*
2039 * The current parse includes a successful parse of a scalar
2040 * variable substitution where there should have been an array
2041 * variable substitution. We remove that mistaken part of the
2042 * parse before moving on. A scalar variable substitution is
2043 * two tokens.
2044 */
2045
2046 Tcl_Token *varTokenPtr =
2047 parsePtr->tokenPtr + parsePtr->numTokens - 2;
2048
2049 if (varTokenPtr->type != TCL_TOKEN_VARIABLE) {
2050 Tcl_Panic("TclSubstParse: programming error");
2051 }
2052 if (varTokenPtr[1].type != TCL_TOKEN_TEXT) {
2053 Tcl_Panic("TclSubstParse: programming error");
2054 }
2055 parsePtr->numTokens -= 2;
2056 }
2057 break;
2058 case '[':
2059 /*
2060 * Parse error occurred during parsing of a toplevel command
2061 * substitution.
2062 */
2063
2064 parsePtr->end = p + length;
2065 p = parsePtr->term + 1;
2066 length = parsePtr->end - p;
2067 if (length == 0) {
2068 /*
2069 * No commands, just an unmatched [. As in previous cases,
2070 * existing token stream is OK.
2071 */
2072 } else {
2073 /*
2074 * We want to add the parsing of as many commands as we can
2075 * within that substitution until we reach the actual parse
2076 * error. We'll do additional parsing to determine what length
2077 * to claim for the final TCL_TOKEN_COMMAND token.
2078 */
2079
2080 Tcl_Token *tokenPtr;
2081 const char *lastTerm = parsePtr->term;
2082 Tcl_Parse *nestedPtr =
2083 TclStackAlloc(interp, sizeof(Tcl_Parse));
2084
2085 while (TCL_OK ==
2086 Tcl_ParseCommand(NULL, p, length, 0, nestedPtr)) {
2087 Tcl_FreeParse(nestedPtr);
2088 p = nestedPtr->term + (nestedPtr->term < nestedPtr->end);
2089 length = nestedPtr->end - p;
2090 if ((length == 0) && (nestedPtr->term == nestedPtr->end)) {
2091 /*
2092 * If we run out of string, blame the missing close
2093 * bracket on the last command, and do not evaluate it
2094 * during substitution.
2095 */
2096
2097 break;
2098 }
2099 lastTerm = nestedPtr->term;
2100 }
2101 TclStackFree(interp, nestedPtr);
2102
2103 if (lastTerm == parsePtr->term) {
2104 /*
2105 * Parse error in first command. No commands to subst, add
2106 * no more tokens.
2107 */
2108 break;
2109 }
2110
2111 /*
2112 * Create a command substitution token for whatever commands
2113 * got parsed.
2114 */
2115
2116 TclGrowParseTokenArray(parsePtr, 1);
2117 tokenPtr = &(parsePtr->tokenPtr[parsePtr->numTokens]);
2118 tokenPtr->start = parsePtr->term;
2119 tokenPtr->numComponents = 0;
2120 tokenPtr->type = TCL_TOKEN_COMMAND;
2121 tokenPtr->size = lastTerm - tokenPtr->start + 1;
2122 parsePtr->numTokens++;
2123 }
2124 break;
2125
2126 default:
2127 Tcl_Panic("bad parse in TclSubstParse: %c", p[length]);
2128 }
2129 }
2130 }
2131
2132 /*
2133 *----------------------------------------------------------------------
2134 *
2135 * TclSubstTokens --
2136 *
2137 * Accepts an array of count Tcl_Token's, and creates a result value in
2138 * the interp from concatenating the results of performing Tcl
2139 * substitution on each Tcl_Token. Substitution is interrupted if any
2140 * non-TCL_OK completion code arises.
2141 *
2142 * Results:
2143 * The return value is a standard Tcl completion code. The result in
2144 * interp is the substituted value, or an error message if TCL_ERROR is
2145 * returned. If tokensLeftPtr is not NULL, then it points to an int where
2146 * the number of tokens remaining to be processed is written.
2147 *
2148 * Side effects:
2149 * Can be anything, depending on the types of substitution done.
2150 *
2151 *----------------------------------------------------------------------
2152 */
2153
2154 int
2155 TclSubstTokens(
2156 Tcl_Interp *interp, /* Interpreter in which to lookup variables,
2157 * execute nested commands, and report
2158 * errors. */
2159 Tcl_Token *tokenPtr, /* Pointer to first in an array of tokens to
2160 * evaluate and concatenate. */
2161 int count, /* Number of tokens to consider at tokenPtr.
2162 * Must be at least 1. */
2163 int *tokensLeftPtr, /* If not NULL, points to memory where an
2164 * integer representing the number of tokens
2165 * left to be substituted will be written */
2166 int line, /* The line the script starts on. */
2167 int *clNextOuter, /* Information about an outer context for */
2168 const char *outerScript) /* continuation line data. This is set by
2169 * EvalEx() to properly handle [...]-nested
2170 * commands. The 'outerScript' refers to the
2171 * most-outer script containing the embedded
2172 * command, which is refered to by 'script'.
2173 * The 'clNextOuter' refers to the current
2174 * entry in the table of continuation lines in
2175 * this "main script", and the character
2176 * offsets are relative to the 'outerScript'
2177 * as well.
2178 *
2179 * If outerScript == script, then this call is
2180 * for words in the outer-most script or
2181 * command. See Tcl_EvalEx and TclEvalObjEx
2182 * for the places generating arguments for
2183 * which this is true. */
2184 {
2185 Tcl_Obj *result;
2186 int code = TCL_OK;
2187 #define NUM_STATIC_POS 20
2188 int isLiteral, maxNumCL, numCL, i, adjust;
2189 int *clPosition = NULL;
2190 Interp *iPtr = (Interp *) interp;
2191 int inFile = iPtr->evalFlags & TCL_EVAL_FILE;
2192
2193 /*
2194 * Each pass through this loop will substitute one token, and its
2195 * components, if any. The only thing tricky here is that we go to some
2196 * effort to pass Tcl_Obj's through untouched, to avoid string copying and
2197 * Tcl_Obj creation if possible, to aid performance and limit shimmering.
2198 *
2199 * Further optimization opportunities might be to check for the equivalent
2200 * of Tcl_SetObjResult(interp, Tcl_GetObjResult(interp)) and omit them.
2201 */
2202
2203 /*
2204 * For the handling of continuation lines in literals, first check if
2205 * this is actually a literal. If not then forego the additional
2206 * processing. Otherwise preallocate a small table to store the
2207 * locations of all continuation lines we find in this literal, if any.
2208 * The table is extended if needed.
2209 */
2210
2211 numCL = 0;
2212 maxNumCL = 0;
2213 isLiteral = 1;
2214 for (i=0 ; i < count; i++) {
2215 if ((tokenPtr[i].type != TCL_TOKEN_TEXT)
2216 && (tokenPtr[i].type != TCL_TOKEN_BS)) {
2217 isLiteral = 0;
2218 break;
2219 }
2220 }
2221
2222 if (isLiteral) {
2223 maxNumCL = NUM_STATIC_POS;
2224 clPosition = ckalloc(maxNumCL * sizeof(int));
2225 }
2226
2227 adjust = 0;
2228 result = NULL;
2229 for (; count>0 && code==TCL_OK ; count--, tokenPtr++) {
2230 Tcl_Obj *appendObj = NULL;
2231 const char *append = NULL;
2232 int appendByteLength = 0;
2233 char utfCharBytes[TCL_UTF_MAX] = "";
2234
2235 switch (tokenPtr->type) {
2236 case TCL_TOKEN_TEXT:
2237 append = tokenPtr->start;
2238 appendByteLength = tokenPtr->size;
2239 break;
2240
2241 case TCL_TOKEN_BS:
2242 appendByteLength = TclParseBackslash(tokenPtr->start,
2243 tokenPtr->size, NULL, utfCharBytes);
2244 append = utfCharBytes;
2245
2246 /*
2247 * If the backslash sequence we found is in a literal, and
2248 * represented a continuation line, we compute and store its
2249 * location (as char offset to the beginning of the _result_
2250 * script). We may have to extend the table of locations.
2251 *
2252 * Note that the continuation line information is relevant even if
2253 * the word we are processing is not a literal, as it can affect
2254 * nested commands. See the branch for TCL_TOKEN_COMMAND below,
2255 * where the adjustment we are tracking here is taken into
2256 * account. The good thing is that we do not need a table of
2257 * everything, just the number of lines we have to add as
2258 * correction.
2259 */
2260
2261 if ((appendByteLength == 1) && (utfCharBytes[0] == ' ')
2262 && (tokenPtr->start[1] == '\n')) {
2263 if (isLiteral) {
2264 int clPos;
2265
2266 if (result == 0) {
2267 clPos = 0;
2268 } else {
2269 Tcl_GetStringFromObj(result, &clPos);
2270 }
2271
2272 if (numCL >= maxNumCL) {
2273 maxNumCL *= 2;
2274 clPosition = ckrealloc(clPosition,
2275 maxNumCL * sizeof(int));
2276 }
2277 clPosition[numCL] = clPos;
2278 numCL++;
2279 }
2280 adjust++;
2281 }
2282 break;
2283
2284 case TCL_TOKEN_COMMAND: {
2285 /* TIP #280: Transfer line information to nested command */
2286 iPtr->numLevels++;
2287 code = TclInterpReady(interp);
2288 if (code == TCL_OK) {
2289 /*
2290 * Test cases: info-30.{6,8,9}
2291 */
2292
2293 int theline;
2294
2295 TclAdvanceContinuations(&line, &clNextOuter,
2296 tokenPtr->start - outerScript);
2297 theline = line + adjust;
2298 code = TclEvalEx(interp, tokenPtr->start+1, tokenPtr->size-2,
2299 0, theline, clNextOuter, outerScript);
2300
2301 TclAdvanceLines(&line, tokenPtr->start+1,
2302 tokenPtr->start + tokenPtr->size - 1);
2303
2304 /*
2305 * Restore flag reset by nested eval for future bracketed
2306 * commands and their cmdframe setup
2307 */
2308
2309 if (inFile) {
2310 iPtr->evalFlags |= TCL_EVAL_FILE;
2311 }
2312 }
2313 iPtr->numLevels--;
2314 TclResetCancellation(interp, 0);
2315 appendObj = Tcl_GetObjResult(interp);
2316 break;
2317 }
2318
2319 case TCL_TOKEN_VARIABLE: {
2320 Tcl_Obj *arrayIndex = NULL;
2321 Tcl_Obj *varName = NULL;
2322
2323 if (tokenPtr->numComponents > 1) {
2324 /*
2325 * Subst the index part of an array variable reference.
2326 */
2327
2328 code = TclSubstTokens(interp, tokenPtr+2,
2329 tokenPtr->numComponents - 1, NULL, line, NULL, NULL);
2330 arrayIndex = Tcl_GetObjResult(interp);
2331 Tcl_IncrRefCount(arrayIndex);
2332 }
2333
2334 if (code == TCL_OK) {
2335 varName = Tcl_NewStringObj(tokenPtr[1].start,
2336 tokenPtr[1].size);
2337 appendObj = Tcl_ObjGetVar2(interp, varName, arrayIndex,
2338 TCL_LEAVE_ERR_MSG);
2339 Tcl_DecrRefCount(varName);
2340 if (appendObj == NULL) {
2341 code = TCL_ERROR;
2342 }
2343 }
2344
2345 switch (code) {
2346 case TCL_OK: /* Got value */
2347 case TCL_ERROR: /* Already have error message */
2348 case TCL_BREAK: /* Will not substitute anyway */
2349 case TCL_CONTINUE: /* Will not substitute anyway */
2350 break;
2351 default:
2352 /*
2353 * All other return codes, we will subst the result from the
2354 * code-throwing evaluation.
2355 */
2356
2357 appendObj = Tcl_GetObjResult(interp);
2358 }
2359
2360 if (arrayIndex != NULL) {
2361 Tcl_DecrRefCount(arrayIndex);
2362 }
2363 count -= tokenPtr->numComponents;
2364 tokenPtr += tokenPtr->numComponents;
2365 break;
2366 }
2367
2368 default:
2369 Tcl_Panic("unexpected token type in TclSubstTokens: %d",
2370 tokenPtr->type);
2371 }
2372
2373 if ((code == TCL_BREAK) || (code == TCL_CONTINUE)) {
2374 /*
2375 * Inhibit substitution.
2376 */
2377 continue;
2378 }
2379
2380 if (result == NULL) {
2381 /*
2382 * First pass through. If we have a Tcl_Obj, just use it. If not,
2383 * create one from our string.
2384 */
2385
2386 if (appendObj != NULL) {
2387 result = appendObj;
2388 } else {
2389 result = Tcl_NewStringObj(append, appendByteLength);
2390 }
2391 Tcl_IncrRefCount(result);
2392 } else {
2393 /*
2394 * Subsequent passes. Append to result.
2395 */
2396
2397 if (Tcl_IsShared(result)) {
2398 Tcl_DecrRefCount(result);
2399 result = Tcl_DuplicateObj(result);
2400 Tcl_IncrRefCount(result);
2401 }
2402 if (appendObj != NULL) {
2403 Tcl_AppendObjToObj(result, appendObj);
2404 } else {
2405 Tcl_AppendToObj(result, append, appendByteLength);
2406 }
2407 }
2408 }
2409
2410 if (code != TCL_ERROR) { /* Keep error message in result! */
2411 if (result != NULL) {
2412 Tcl_SetObjResult(interp, result);
2413
2414 /*
2415 * If the code found continuation lines (which implies that this
2416 * word is a literal), then we store the accumulated table of
2417 * locations in the thread-global data structure for the bytecode
2418 * compiler to find later, assuming that the literal is a script
2419 * which will be compiled.
2420 */
2421
2422 if (numCL) {
2423 TclContinuationsEnter(result, numCL, clPosition);
2424 }
2425
2426 /*
2427 * Release the temp table we used to collect the locations of
2428 * continuation lines, if any.
2429 */
2430
2431 if (maxNumCL) {
2432 ckfree(clPosition);
2433 }
2434 } else {
2435 Tcl_ResetResult(interp);
2436 }
2437 }
2438 if (tokensLeftPtr != NULL) {
2439 *tokensLeftPtr = count;
2440 }
2441 if (result != NULL) {
2442 Tcl_DecrRefCount(result);
2443 }
2444 return code;
2445 }
2446
2447 /*
2448 *----------------------------------------------------------------------
2449 *
2450 * CommandComplete --
2451 *
2452 * This function is shared by TclCommandComplete and
2453 * Tcl_ObjCommandComplete; it does all the real work of seeing whether a
2454 * script is complete
2455 *
2456 * Results:
2457 * 1 is returned if the script is complete, 0 if there are open
2458 * delimiters such as " or (. 1 is also returned if there is a parse
2459 * error in the script other than unmatched delimiters.
2460 *
2461 * Side effects:
2462 * None.
2463 *
2464 *----------------------------------------------------------------------
2465 */
2466
2467 static inline int
2468 CommandComplete(
2469 const char *script, /* Script to check. */
2470 int numBytes) /* Number of bytes in script. */
2471 {
2472 Tcl_Parse parse;
2473 const char *p, *end;
2474 int result;
2475
2476 p = script;
2477 end = p + numBytes;
2478 while (Tcl_ParseCommand(NULL, p, end - p, 0, &parse) == TCL_OK) {
2479 p = parse.commandStart + parse.commandSize;
2480 if (p >= end) {
2481 break;
2482 }
2483 Tcl_FreeParse(&parse);
2484 }
2485 if (parse.incomplete) {
2486 result = 0;
2487 } else {
2488 result = 1;
2489 }
2490 Tcl_FreeParse(&parse);
2491 return result;
2492 }
2493
2494 /*
2495 *----------------------------------------------------------------------
2496 *
2497 * Tcl_CommandComplete --
2498 *
2499 * Given a partial or complete Tcl script, this function determines
2500 * whether the script is complete in the sense of having matched braces
2501 * and quotes and brackets.
2502 *
2503 * Results:
2504 * 1 is returned if the script is complete, 0 otherwise. 1 is also
2505 * returned if there is a parse error in the script other than unmatched
2506 * delimiters.
2507 *
2508 * Side effects:
2509 * None.
2510 *
2511 *----------------------------------------------------------------------
2512 */
2513
2514 int
2515 Tcl_CommandComplete(
2516 const char *script) /* Script to check. */
2517 {
2518 return CommandComplete(script, (int) strlen(script));
2519 }
2520
2521 /*
2522 *----------------------------------------------------------------------
2523 *
2524 * TclObjCommandComplete --
2525 *
2526 * Given a partial or complete Tcl command in a Tcl object, this function
2527 * determines whether the command is complete in the sense of having
2528 * matched braces and quotes and brackets.
2529 *
2530 * Results:
2531 * 1 is returned if the command is complete, 0 otherwise.
2532 *
2533 * Side effects:
2534 * None.
2535 *
2536 *----------------------------------------------------------------------
2537 */
2538
2539 int
2540 TclObjCommandComplete(
2541 Tcl_Obj *objPtr) /* Points to object holding script to
2542 * check. */
2543 {
2544 int length;
2545 const char *script = Tcl_GetStringFromObj(objPtr, &length);
2546
2547 return CommandComplete(script, length);
2548 }
2549
2550 /*
2551 * Local Variables:
2552 * mode: c
2553 * c-basic-offset: 4
2554 * fill-column: 78
2555 * End:
2556 */