parser.c revision 1.111 1 /* $NetBSD: parser.c,v 1.111 2016/03/27 14:39:33 christos Exp $ */
2
3 /*-
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)parser.c 8.7 (Berkeley) 5/16/95";
39 #else
40 __RCSID("$NetBSD: parser.c,v 1.111 2016/03/27 14:39:33 christos Exp $");
41 #endif
42 #endif /* not lint */
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <limits.h>
47
48 #include "shell.h"
49 #include "parser.h"
50 #include "nodes.h"
51 #include "expand.h" /* defines rmescapes() */
52 #include "eval.h" /* defines commandname */
53 #include "redir.h" /* defines copyfd() */
54 #include "syntax.h"
55 #include "options.h"
56 #include "input.h"
57 #include "output.h"
58 #include "var.h"
59 #include "error.h"
60 #include "memalloc.h"
61 #include "mystring.h"
62 #include "alias.h"
63 #include "show.h"
64 #ifndef SMALL
65 #include "myhistedit.h"
66 #endif
67
68 /*
69 * Shell command parser.
70 */
71
72 /* values returned by readtoken */
73 #include "token.h"
74
75 #define OPENBRACE '{'
76 #define CLOSEBRACE '}'
77
78
79 struct heredoc {
80 struct heredoc *next; /* next here document in list */
81 union node *here; /* redirection node */
82 char *eofmark; /* string indicating end of input */
83 int striptabs; /* if set, strip leading tabs */
84 };
85
86
87
88 static int noalias = 0; /* when set, don't handle aliases */
89 struct heredoc *heredoclist; /* list of here documents to read */
90 int parsebackquote; /* nonzero if we are inside backquotes */
91 int doprompt; /* if set, prompt the user */
92 int needprompt; /* true if interactive and at start of line */
93 int lasttoken; /* last token read */
94 MKINIT int tokpushback; /* last token pushed back */
95 char *wordtext; /* text of last word returned by readtoken */
96 MKINIT int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
97 struct nodelist *backquotelist;
98 union node *redirnode;
99 struct heredoc *heredoc;
100 int quoteflag; /* set if (part of) last token was quoted */
101 int startlinno; /* line # where last token started */
102 int funclinno; /* line # where the current function started */
103
104
105 STATIC union node *list(int, int);
106 STATIC union node *andor(void);
107 STATIC union node *pipeline(void);
108 STATIC union node *command(void);
109 STATIC union node *simplecmd(union node **, union node *);
110 STATIC union node *makename(void);
111 STATIC void parsefname(void);
112 STATIC void slurp_heredoc(char *const, int, int);
113 STATIC void readheredocs(void);
114 STATIC int peektoken(void);
115 STATIC int readtoken(void);
116 STATIC int xxreadtoken(void);
117 STATIC int readtoken1(int, char const *, int);
118 STATIC int noexpand(char *);
119 STATIC void synexpect(int, const char *) __dead;
120 STATIC void synerror(const char *) __dead;
121 STATIC void setprompt(int);
122
123
124 static const char EOFhere[] = "EOF reading here (<<) document";
125
126
127 /*
128 * Read and parse a command. Returns NEOF on end of file. (NULL is a
129 * valid parse tree indicating a blank line.)
130 */
131
132 union node *
133 parsecmd(int interact)
134 {
135 int t;
136
137 tokpushback = 0;
138 doprompt = interact;
139 if (doprompt)
140 setprompt(1);
141 else
142 setprompt(0);
143 needprompt = 0;
144 t = readtoken();
145 if (t == TEOF)
146 return NEOF;
147 if (t == TNL)
148 return NULL;
149 tokpushback++;
150 return list(1, 0);
151 }
152
153
154 STATIC union node *
155 list(int nlflag, int erflag)
156 {
157 union node *n1, *n2, *n3;
158 int tok;
159 TRACE(("list(%d,%d): entered\n", nlflag, erflag));
160
161 checkkwd = 2;
162 if (nlflag == 0 && tokendlist[peektoken()])
163 return NULL;
164 n1 = NULL;
165 for (;;) {
166 n2 = andor();
167 tok = readtoken();
168 if (tok == TBACKGND) {
169 if (n2->type == NCMD || n2->type == NPIPE) {
170 n2->ncmd.backgnd = 1;
171 } else if (n2->type == NREDIR) {
172 n2->type = NBACKGND;
173 } else {
174 n3 = stalloc(sizeof(struct nredir));
175 n3->type = NBACKGND;
176 n3->nredir.n = n2;
177 n3->nredir.redirect = NULL;
178 n2 = n3;
179 }
180 }
181 if (n1 == NULL) {
182 n1 = n2;
183 }
184 else {
185 n3 = stalloc(sizeof(struct nbinary));
186 n3->type = NSEMI;
187 n3->nbinary.ch1 = n1;
188 n3->nbinary.ch2 = n2;
189 n1 = n3;
190 }
191 switch (tok) {
192 case TBACKGND:
193 case TSEMI:
194 tok = readtoken();
195 /* FALLTHROUGH */
196 case TNL:
197 if (tok == TNL) {
198 readheredocs();
199 if (nlflag)
200 return n1;
201 } else {
202 tokpushback++;
203 }
204 checkkwd = 2;
205 if (tokendlist[peektoken()])
206 return n1;
207 break;
208 case TEOF:
209 if (heredoclist)
210 readheredocs();
211 else
212 pungetc(); /* push back EOF on input */
213 return n1;
214 default:
215 if (nlflag || erflag)
216 synexpect(-1, 0);
217 tokpushback++;
218 return n1;
219 }
220 }
221 }
222
223 STATIC union node *
224 andor(void)
225 {
226 union node *n1, *n2, *n3;
227 int t;
228
229 TRACE(("andor: entered\n"));
230 n1 = pipeline();
231 for (;;) {
232 if ((t = readtoken()) == TAND) {
233 t = NAND;
234 } else if (t == TOR) {
235 t = NOR;
236 } else {
237 tokpushback++;
238 return n1;
239 }
240 n2 = pipeline();
241 n3 = stalloc(sizeof(struct nbinary));
242 n3->type = t;
243 n3->nbinary.ch1 = n1;
244 n3->nbinary.ch2 = n2;
245 n1 = n3;
246 }
247 }
248
249 STATIC union node *
250 pipeline(void)
251 {
252 union node *n1, *n2, *pipenode;
253 struct nodelist *lp, *prev;
254 int negate;
255
256 TRACE(("pipeline: entered\n"));
257
258 negate = 0;
259 checkkwd = 2;
260 while (readtoken() == TNOT) {
261 TRACE(("pipeline: TNOT recognized\n"));
262 negate = !negate;
263 }
264 tokpushback++;
265 n1 = command();
266 if (readtoken() == TPIPE) {
267 pipenode = stalloc(sizeof(struct npipe));
268 pipenode->type = NPIPE;
269 pipenode->npipe.backgnd = 0;
270 lp = stalloc(sizeof(struct nodelist));
271 pipenode->npipe.cmdlist = lp;
272 lp->n = n1;
273 do {
274 prev = lp;
275 lp = stalloc(sizeof(struct nodelist));
276 lp->n = command();
277 prev->next = lp;
278 } while (readtoken() == TPIPE);
279 lp->next = NULL;
280 n1 = pipenode;
281 }
282 tokpushback++;
283 if (negate) {
284 TRACE(("negate pipeline\n"));
285 n2 = stalloc(sizeof(struct nnot));
286 n2->type = NNOT;
287 n2->nnot.com = n1;
288 return n2;
289 } else
290 return n1;
291 }
292
293
294
295 STATIC union node *
296 command(void)
297 {
298 union node *n1, *n2;
299 union node *ap, **app;
300 union node *cp, **cpp;
301 union node *redir, **rpp;
302 int t, negate = 0;
303
304 TRACE(("command: entered\n"));
305
306 checkkwd = 2;
307 redir = NULL;
308 n1 = NULL;
309 rpp = &redir;
310
311 /* Check for redirection which may precede command */
312 while (readtoken() == TREDIR) {
313 *rpp = n2 = redirnode;
314 rpp = &n2->nfile.next;
315 parsefname();
316 }
317 tokpushback++;
318
319 while (readtoken() == TNOT) {
320 TRACE(("command: TNOT recognized\n"));
321 negate = !negate;
322 }
323 tokpushback++;
324
325 switch (readtoken()) {
326 case TIF:
327 n1 = stalloc(sizeof(struct nif));
328 n1->type = NIF;
329 n1->nif.test = list(0, 0);
330 if (readtoken() != TTHEN)
331 synexpect(TTHEN, 0);
332 n1->nif.ifpart = list(0, 0);
333 n2 = n1;
334 while (readtoken() == TELIF) {
335 n2->nif.elsepart = stalloc(sizeof(struct nif));
336 n2 = n2->nif.elsepart;
337 n2->type = NIF;
338 n2->nif.test = list(0, 0);
339 if (readtoken() != TTHEN)
340 synexpect(TTHEN, 0);
341 n2->nif.ifpart = list(0, 0);
342 }
343 if (lasttoken == TELSE)
344 n2->nif.elsepart = list(0, 0);
345 else {
346 n2->nif.elsepart = NULL;
347 tokpushback++;
348 }
349 if (readtoken() != TFI)
350 synexpect(TFI, 0);
351 checkkwd = 1;
352 break;
353 case TWHILE:
354 case TUNTIL: {
355 int got;
356 n1 = stalloc(sizeof(struct nbinary));
357 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
358 n1->nbinary.ch1 = list(0, 0);
359 if ((got=readtoken()) != TDO) {
360 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
361 synexpect(TDO, 0);
362 }
363 n1->nbinary.ch2 = list(0, 0);
364 if (readtoken() != TDONE)
365 synexpect(TDONE, 0);
366 checkkwd = 1;
367 break;
368 }
369 case TFOR:
370 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
371 synerror("Bad for loop variable");
372 n1 = stalloc(sizeof(struct nfor));
373 n1->type = NFOR;
374 n1->nfor.var = wordtext;
375 if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
376 app = ≈
377 while (readtoken() == TWORD) {
378 n2 = stalloc(sizeof(struct narg));
379 n2->type = NARG;
380 n2->narg.text = wordtext;
381 n2->narg.backquote = backquotelist;
382 *app = n2;
383 app = &n2->narg.next;
384 }
385 *app = NULL;
386 n1->nfor.args = ap;
387 if (lasttoken != TNL && lasttoken != TSEMI)
388 synexpect(-1, 0);
389 } else {
390 static char argvars[5] = {
391 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
392 };
393 n2 = stalloc(sizeof(struct narg));
394 n2->type = NARG;
395 n2->narg.text = argvars;
396 n2->narg.backquote = NULL;
397 n2->narg.next = NULL;
398 n1->nfor.args = n2;
399 /*
400 * Newline or semicolon here is optional (but note
401 * that the original Bourne shell only allowed NL).
402 */
403 if (lasttoken != TNL && lasttoken != TSEMI)
404 tokpushback++;
405 }
406 checkkwd = 2;
407 if ((t = readtoken()) == TDO)
408 t = TDONE;
409 else if (t == TBEGIN)
410 t = TEND;
411 else
412 synexpect(-1, 0);
413 n1->nfor.body = list(0, 0);
414 if (readtoken() != t)
415 synexpect(t, 0);
416 checkkwd = 1;
417 break;
418 case TCASE:
419 n1 = stalloc(sizeof(struct ncase));
420 n1->type = NCASE;
421 if (readtoken() != TWORD)
422 synexpect(TWORD, 0);
423 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
424 n2->type = NARG;
425 n2->narg.text = wordtext;
426 n2->narg.backquote = backquotelist;
427 n2->narg.next = NULL;
428 while (readtoken() == TNL);
429 if (lasttoken != TWORD || ! equal(wordtext, "in"))
430 synexpect(-1, "in");
431 cpp = &n1->ncase.cases;
432 noalias = 1;
433 checkkwd = 2, readtoken();
434 /*
435 * Both ksh and bash accept 'case x in esac'
436 * so configure scripts started taking advantage of this.
437 * The page: http://pubs.opengroup.org/onlinepubs/\
438 * 009695399/utilities/xcu_chap02.html contradicts itself,
439 * as to if this is legal; the "Case Conditional Format"
440 * paragraph shows one case is required, but the "Grammar"
441 * section shows a grammar that explicitly allows the no
442 * case option.
443 */
444 while (lasttoken != TESAC) {
445 *cpp = cp = stalloc(sizeof(struct nclist));
446 if (lasttoken == TLP)
447 readtoken();
448 cp->type = NCLIST;
449 app = &cp->nclist.pattern;
450 for (;;) {
451 *app = ap = stalloc(sizeof(struct narg));
452 ap->type = NARG;
453 ap->narg.text = wordtext;
454 ap->narg.backquote = backquotelist;
455 if (checkkwd = 2, readtoken() != TPIPE)
456 break;
457 app = &ap->narg.next;
458 readtoken();
459 }
460 ap->narg.next = NULL;
461 noalias = 0;
462 if (lasttoken != TRP) {
463 synexpect(TRP, 0);
464 }
465 cp->nclist.body = list(0, 0);
466
467 checkkwd = 2;
468 if ((t = readtoken()) != TESAC) {
469 if (t != TENDCASE) {
470 noalias = 0;
471 synexpect(TENDCASE, 0);
472 } else {
473 noalias = 1;
474 checkkwd = 2;
475 readtoken();
476 }
477 }
478 cpp = &cp->nclist.next;
479 }
480 noalias = 0;
481 *cpp = NULL;
482 checkkwd = 1;
483 break;
484 case TLP:
485 n1 = stalloc(sizeof(struct nredir));
486 n1->type = NSUBSHELL;
487 n1->nredir.n = list(0, 0);
488 n1->nredir.redirect = NULL;
489 if (readtoken() != TRP)
490 synexpect(TRP, 0);
491 checkkwd = 1;
492 break;
493 case TBEGIN:
494 n1 = list(0, 0);
495 if (readtoken() != TEND)
496 synexpect(TEND, 0);
497 checkkwd = 1;
498 break;
499 /* Handle an empty command like other simple commands. */
500 case TSEMI:
501 /*
502 * An empty command before a ; doesn't make much sense, and
503 * should certainly be disallowed in the case of `if ;'.
504 */
505 if (!redir)
506 synexpect(-1, 0);
507 case TAND:
508 case TOR:
509 case TNL:
510 case TEOF:
511 case TWORD:
512 case TRP:
513 tokpushback++;
514 n1 = simplecmd(rpp, redir);
515 goto checkneg;
516 case TENDCASE:
517 if (redir) {
518 tokpushback++;
519 goto checkneg;
520 }
521 /* FALLTHROUGH */
522 default:
523 synexpect(-1, 0);
524 /* NOTREACHED */
525 }
526
527 /* Now check for redirection which may follow command */
528 while (readtoken() == TREDIR) {
529 *rpp = n2 = redirnode;
530 rpp = &n2->nfile.next;
531 parsefname();
532 }
533 tokpushback++;
534 *rpp = NULL;
535 if (redir) {
536 if (n1->type != NSUBSHELL) {
537 n2 = stalloc(sizeof(struct nredir));
538 n2->type = NREDIR;
539 n2->nredir.n = n1;
540 n1 = n2;
541 }
542 n1->nredir.redirect = redir;
543 }
544
545 checkneg:
546 if (negate) {
547 TRACE(("negate command\n"));
548 n2 = stalloc(sizeof(struct nnot));
549 n2->type = NNOT;
550 n2->nnot.com = n1;
551 return n2;
552 }
553 else
554 return n1;
555 }
556
557
558 STATIC union node *
559 simplecmd(union node **rpp, union node *redir)
560 {
561 union node *args, **app;
562 union node *n = NULL, *n2;
563 int negate = 0;
564
565 /* If we don't have any redirections already, then we must reset */
566 /* rpp to be the address of the local redir variable. */
567 if (redir == 0)
568 rpp = &redir;
569
570 args = NULL;
571 app = &args;
572
573 while (readtoken() == TNOT) {
574 TRACE(("simplcmd: TNOT recognized\n"));
575 negate = !negate;
576 }
577 tokpushback++;
578
579 for (;;) {
580 if (readtoken() == TWORD) {
581 n = stalloc(sizeof(struct narg));
582 n->type = NARG;
583 n->narg.text = wordtext;
584 n->narg.backquote = backquotelist;
585 *app = n;
586 app = &n->narg.next;
587 } else if (lasttoken == TREDIR) {
588 *rpp = n = redirnode;
589 rpp = &n->nfile.next;
590 parsefname(); /* read name of redirection file */
591 } else if (lasttoken == TLP && app == &args->narg.next
592 && redir == 0) {
593 /* We have a function */
594 if (readtoken() != TRP)
595 synexpect(TRP, 0);
596 funclinno = plinno;
597 rmescapes(n->narg.text);
598 if (!goodname(n->narg.text))
599 synerror("Bad function name");
600 n->type = NDEFUN;
601 n->narg.next = command();
602 funclinno = 0;
603 goto checkneg;
604 } else {
605 tokpushback++;
606 break;
607 }
608 }
609 *app = NULL;
610 *rpp = NULL;
611 n = stalloc(sizeof(struct ncmd));
612 n->type = NCMD;
613 n->ncmd.backgnd = 0;
614 n->ncmd.args = args;
615 n->ncmd.redirect = redir;
616
617 checkneg:
618 if (negate) {
619 TRACE(("negate simplecmd\n"));
620 n2 = stalloc(sizeof(struct nnot));
621 n2->type = NNOT;
622 n2->nnot.com = n;
623 return n2;
624 }
625 else
626 return n;
627 }
628
629 STATIC union node *
630 makename(void)
631 {
632 union node *n;
633
634 n = stalloc(sizeof(struct narg));
635 n->type = NARG;
636 n->narg.next = NULL;
637 n->narg.text = wordtext;
638 n->narg.backquote = backquotelist;
639 return n;
640 }
641
642 void
643 fixredir(union node *n, const char *text, int err)
644 {
645 TRACE(("Fix redir %s %d\n", text, err));
646 if (!err)
647 n->ndup.vname = NULL;
648
649 if (is_number(text))
650 n->ndup.dupfd = number(text);
651 else if (text[0] == '-' && text[1] == '\0')
652 n->ndup.dupfd = -1;
653 else {
654
655 if (err)
656 synerror("Bad fd number");
657 else
658 n->ndup.vname = makename();
659 }
660 }
661
662
663 STATIC void
664 parsefname(void)
665 {
666 union node *n = redirnode;
667
668 if (readtoken() != TWORD)
669 synexpect(-1, 0);
670 if (n->type == NHERE) {
671 struct heredoc *here = heredoc;
672 struct heredoc *p;
673
674 if (quoteflag == 0)
675 n->type = NXHERE;
676 TRACE(("Here document %d\n", n->type));
677 if (here->striptabs) {
678 while (*wordtext == '\t')
679 wordtext++;
680 }
681
682 /*
683 * this test is not really necessary, we are not
684 * required to expand wordtext, but there's no reason
685 * it cannot be $$ or something like that - that would
686 * not mean the pid, but literally two '$' characters.
687 * There is no need for limits on what the word can be.
688 * However, it needs to stay literal as entered, not
689 * have $ converted to CTLVAR or something, which as
690 * the parser is, at the minute, is impossible to prevent.
691 * So, leave it like this until the rest of the parser is fixed.
692 */
693 if (! noexpand(wordtext))
694 synerror("Illegal eof marker for << redirection");
695
696 rmescapes(wordtext);
697 here->eofmark = wordtext;
698 here->next = NULL;
699 if (heredoclist == NULL)
700 heredoclist = here;
701 else {
702 for (p = heredoclist ; p->next ; p = p->next)
703 continue;
704 p->next = here;
705 }
706 } else if (n->type == NTOFD || n->type == NFROMFD) {
707 fixredir(n, wordtext, 0);
708 } else {
709 n->nfile.fname = makename();
710 }
711 }
712
713 /*
714 * Check to see whether we are at the end of the here document. When this
715 * is called, c is set to the first character of the next input line. If
716 * we are at the end of the here document, this routine sets the c to PEOF.
717 * The new value of c is returned.
718 */
719
720 static int
721 checkend(int c, char * const eofmark, const int striptabs)
722 {
723 if (striptabs) {
724 while (c == '\t')
725 c = pgetc();
726 }
727 if (c == PEOF) {
728 if (*eofmark == '\0')
729 return (c);
730 synerror(EOFhere);
731 }
732 if (c == *eofmark) {
733 int c2;
734 char *q;
735
736 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
737 ;
738 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
739 c = PEOF;
740 if (c2 == '\n') {
741 plinno++;
742 needprompt = doprompt;
743 }
744 } else {
745 pungetc();
746 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
747 }
748 } else if (c == '\n' && *eofmark == '\0') {
749 c = PEOF;
750 plinno++;
751 needprompt = doprompt;
752 }
753 return (c);
754 }
755
756
757 /*
758 * Input any here documents.
759 */
760
761 STATIC void
762 slurp_heredoc(char *const eofmark, int striptabs, int sq)
763 {
764 int c;
765 char *out;
766
767 c = pgetc();
768
769 /*
770 * If we hit EOF on the input, and the eofmark is a null string ('')
771 * we consider this empty line to be the eofmark, and exit without err.
772 */
773 if (c == PEOF && *eofmark != '\0')
774 synerror(EOFhere);
775
776 STARTSTACKSTR(out);
777
778 while ((c = checkend(c, eofmark, striptabs)) != PEOF) {
779 do {
780 if (sq) {
781 /*
782 * in single quoted mode (eofmark quoted)
783 * all we look for is \n so we can check
784 * for the epfmark - everything saved literally.
785 */
786 STPUTC(c, out);
787 if (c == '\n')
788 break;
789 continue;
790 }
791 /*
792 * In double quoted (non-quoted eofmark)
793 * we must handle \ followed by \n here
794 * otherwise we can mismatch the end mark.
795 * All other uses of \ will be handled later
796 * when the here doc is expanded.
797 *
798 * This also makes sure \\ followed by \n does
799 * not suppress the newline (the \ quotes itself)
800 */
801 if (c == '\\') { /* A backslash */
802 c = pgetc(); /* followed by */
803 if (c == '\n') /* a newline? */
804 continue; /* y:drop both */
805 STPUTC('\\', out); /* else keep \ */
806 }
807 STPUTC(c, out); /* keep the char */
808 if (c == '\n') /* at end of line */
809 break; /* look for eofmark */
810
811 } while ((c = pgetc()) != PEOF);
812
813 /*
814 * If we have read a line, and reached EOF, without
815 * finding the eofmark, whether the EOF comes before
816 * or immediately after the \n, that is an error.
817 */
818 if (c == PEOF || (c = pgetc()) == PEOF)
819 synerror(EOFhere);
820 }
821 STPUTC('\0', out);
822
823 c = out - stackblock();
824 out = stackblock();
825 grabstackblock(c);
826 wordtext = out;
827
828 TRACE(("Slurped a heredoc (to '%s')%s: len %d, \"%.16s\"...\n",
829 eofmark, striptabs ? " tab stripped" : "", c, wordtext));
830 }
831
832 STATIC void
833 readheredocs(void)
834 {
835 struct heredoc *here;
836 union node *n;
837
838 while (heredoclist) {
839 here = heredoclist;
840 heredoclist = here->next;
841 if (needprompt) {
842 setprompt(2);
843 needprompt = 0;
844 }
845
846 slurp_heredoc(here->eofmark, here->striptabs,
847 here->here->nhere.type == NHERE);
848
849 n = stalloc(sizeof(struct narg));
850 n->narg.type = NARG;
851 n->narg.next = NULL;
852 n->narg.text = wordtext;
853 n->narg.backquote = backquotelist;
854 here->here->nhere.doc = n;
855 }
856 }
857
858 void
859 parse_heredoc(union node *n)
860 {
861 if (n->narg.type != NARG)
862 abort();
863
864 if (n->narg.text[0] == '\0') /* nothing to do */
865 return;
866
867 setinputstring(n->narg.text, 1);
868
869 readtoken1(pgetc(), DQSYNTAX, 1);
870
871 n->narg.text = wordtext;
872 n->narg.backquote = backquotelist;
873
874 popfile();
875 }
876
877 STATIC int
878 peektoken(void)
879 {
880 int t;
881
882 t = readtoken();
883 tokpushback++;
884 return (t);
885 }
886
887 STATIC int
888 readtoken(void)
889 {
890 int t;
891 int savecheckkwd = checkkwd;
892 #ifdef DEBUG
893 int alreadyseen = tokpushback;
894 #endif
895 struct alias *ap;
896
897 top:
898 t = xxreadtoken();
899
900 if (checkkwd) {
901 /*
902 * eat newlines
903 */
904 if (checkkwd == 2) {
905 checkkwd = 0;
906 while (t == TNL) {
907 readheredocs();
908 t = xxreadtoken();
909 }
910 } else
911 checkkwd = 0;
912 /*
913 * check for keywords and aliases
914 */
915 if (t == TWORD && !quoteflag) {
916 const char *const *pp;
917
918 for (pp = parsekwd; *pp; pp++) {
919 if (**pp == *wordtext && equal(*pp, wordtext)) {
920 lasttoken = t = pp -
921 parsekwd + KWDOFFSET;
922 TRACE(("keyword %s recognized\n", tokname[t]));
923 goto out;
924 }
925 }
926 if (!noalias &&
927 (ap = lookupalias(wordtext, 1)) != NULL) {
928 pushstring(ap->val, strlen(ap->val), ap);
929 checkkwd = savecheckkwd;
930 goto top;
931 }
932 }
933 out:
934 checkkwd = (t == TNOT) ? savecheckkwd : 0;
935 }
936 TRACE(("%stoken %s %s\n", alreadyseen ? "reread " : "", tokname[t], t == TWORD ? wordtext : ""));
937 return (t);
938 }
939
940
941 /*
942 * Read the next input token.
943 * If the token is a word, we set backquotelist to the list of cmds in
944 * backquotes. We set quoteflag to true if any part of the word was
945 * quoted.
946 * If the token is TREDIR, then we set redirnode to a structure containing
947 * the redirection.
948 * In all cases, the variable startlinno is set to the number of the line
949 * on which the token starts.
950 *
951 * [Change comment: here documents and internal procedures]
952 * [Readtoken shouldn't have any arguments. Perhaps we should make the
953 * word parsing code into a separate routine. In this case, readtoken
954 * doesn't need to have any internal procedures, but parseword does.
955 * We could also make parseoperator in essence the main routine, and
956 * have parseword (readtoken1?) handle both words and redirection.]
957 */
958
959 #define RETURN(token) return lasttoken = token
960
961 STATIC int
962 xxreadtoken(void)
963 {
964 int c;
965
966 if (tokpushback) {
967 tokpushback = 0;
968 return lasttoken;
969 }
970 if (needprompt) {
971 setprompt(2);
972 needprompt = 0;
973 }
974 startlinno = plinno;
975 for (;;) { /* until token or start of word found */
976 c = pgetc_macro();
977 switch (c) {
978 case ' ': case '\t':
979 continue;
980 case '#':
981 while ((c = pgetc()) != '\n' && c != PEOF)
982 continue;
983 pungetc();
984 continue;
985
986 case '\n':
987 plinno++;
988 needprompt = doprompt;
989 RETURN(TNL);
990 case PEOF:
991 RETURN(TEOF);
992
993 case '&':
994 if (pgetc() == '&')
995 RETURN(TAND);
996 pungetc();
997 RETURN(TBACKGND);
998 case '|':
999 if (pgetc() == '|')
1000 RETURN(TOR);
1001 pungetc();
1002 RETURN(TPIPE);
1003 case ';':
1004 if (pgetc() == ';')
1005 RETURN(TENDCASE);
1006 pungetc();
1007 RETURN(TSEMI);
1008 case '(':
1009 RETURN(TLP);
1010 case ')':
1011 RETURN(TRP);
1012
1013 case '\\':
1014 switch (pgetc()) {
1015 case '\n':
1016 startlinno = ++plinno;
1017 if (doprompt)
1018 setprompt(2);
1019 else
1020 setprompt(0);
1021 continue;
1022 case PEOF:
1023 RETURN(TEOF);
1024 default:
1025 pungetc();
1026 break;
1027 }
1028 /* FALLTHROUGH */
1029 default:
1030 return readtoken1(c, BASESYNTAX, 0);
1031 }
1032 }
1033 #undef RETURN
1034 }
1035
1036
1037
1038 /*
1039 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1040 * is not NULL, read a here document. In the latter case, eofmark is the
1041 * word which marks the end of the document and striptabs is true if
1042 * leading tabs should be stripped from the document. The argument firstc
1043 * is the first character of the input token or document.
1044 *
1045 * Because C does not have internal subroutines, I have simulated them
1046 * using goto's to implement the subroutine linkage. The following macros
1047 * will run code that appears at the end of readtoken1.
1048 */
1049
1050 /*
1051 * We used to remember only the current syntax, variable nesting level,
1052 * double quote state for each var nesting level, and arith nesting
1053 * level (unrelated to var nesting) and one prev syntax when in arith
1054 * syntax. This worked for simple cases, but can't handle arith inside
1055 * var expansion inside arith inside var with some quoted and some not.
1056 *
1057 * Inspired by FreeBSD's implementation (though it was the obvious way)
1058 * though implemented differently, we now have a stack that keeps track
1059 * of what we are doing now, and what we were doing previously.
1060 * Every time something changes, which will eventually end and should
1061 * revert to the previous state, we push this stack, and then pop it
1062 * again later (that is every ${} with an operator (to parse the word
1063 * or pattern that follows) ${x} and $x are too simple to need it)
1064 * $(( )) $( ) and "...". Always. Really, always!
1065 *
1066 * The stack is implemented as one static (on the C stack) base block
1067 * containing LEVELS_PER_BLOCK (8) stack entries, which should be
1068 * enough for the vast majority of cases. For torture tests, we
1069 * malloc more blocks as needed. All accesses through the inline
1070 * functions below.
1071 */
1072
1073 /*
1074 * varnest & arinest will typically be 0 or 1
1075 * (varnest can increment in usages like ${x=${y}} but probably
1076 * does not really need to)
1077 * parenlevel allows balancing parens inside a $(( )), it is reset
1078 * at each new nesting level ( $(( ( x + 3 ${unset-)} )) does not work.
1079 * quoted is special - we need to know 2 things ... are we inside "..."
1080 * (even if inherited from some previous nesting level) and was there
1081 * an opening '"' at this level (so the next will be closing).
1082 * "..." can span nesting levels, but cannot be opened in one and
1083 * closed in a different one.
1084 * To handle this, "quoted" has two fields, the bottom 4 (really 2)
1085 * bits are 0, 1, or 2, for un, single, and double quoted (single quoted
1086 * is really so special that this setting is not very important)
1087 * and 0x10 that indicates that an opening quote has been seen.
1088 * The bottom 4 bits are inherited, the 0x10 bit is not.
1089 */
1090 struct tokenstate {
1091 const char *ts_syntax;
1092 unsigned short ts_parenlevel; /* counters */
1093 unsigned short ts_varnest; /* 64000 levels should be enough! */
1094 unsigned short ts_arinest;
1095 unsigned short ts_quoted; /* 1 -> single, 2 -> double */
1096 };
1097
1098 #define NQ 0x00 /* Unquoted */
1099 #define SQ 0x01 /* Single Quotes */
1100 #define DQ 0x02 /* Double Quotes (or equivalent) */
1101 #define QF 0x0F /* Mask to extract previous values */
1102 #define QS 0x10 /* Quoting started at this level in stack */
1103
1104 #define LEVELS_PER_BLOCK 8
1105 #define VSS struct statestack
1106
1107 struct statestack {
1108 VSS *prev; /* previous block in list */
1109 int cur; /* which of our tokenstates is current */
1110 struct tokenstate tokenstate[LEVELS_PER_BLOCK];
1111 };
1112
1113 static inline struct tokenstate *
1114 currentstate(VSS *stack)
1115 {
1116 return &stack->tokenstate[stack->cur];
1117 }
1118
1119 static inline struct tokenstate *
1120 prevstate(VSS *stack)
1121 {
1122 if (stack->cur != 0)
1123 return &stack->tokenstate[stack->cur - 1];
1124 if (stack->prev == NULL) /* cannot drop below base */
1125 return &stack->tokenstate[0];
1126 return &stack->prev->tokenstate[LEVELS_PER_BLOCK - 1];
1127 }
1128
1129 static inline VSS *
1130 bump_state_level(VSS *stack)
1131 {
1132 struct tokenstate *os, *ts;
1133
1134 os = currentstate(stack);
1135
1136 if (++stack->cur >= LEVELS_PER_BLOCK) {
1137 VSS *ss;
1138
1139 ss = (VSS *)ckmalloc(sizeof (struct statestack));
1140 ss->cur = 0;
1141 ss->prev = stack;
1142 stack = ss;
1143 }
1144
1145 ts = currentstate(stack);
1146
1147 ts->ts_parenlevel = 0; /* parens inside never match outside */
1148
1149 ts->ts_quoted = os->ts_quoted & QF; /* these are default settings */
1150 ts->ts_varnest = os->ts_varnest;
1151 ts->ts_arinest = os->ts_arinest; /* when appropriate */
1152 ts->ts_syntax = os->ts_syntax; /* they will be altered */
1153
1154 return stack;
1155 }
1156
1157 static inline VSS *
1158 drop_state_level(VSS *stack)
1159 {
1160 if (stack->cur == 0) {
1161 VSS *ss;
1162
1163 ss = stack;
1164 stack = ss->prev;
1165 if (stack == NULL)
1166 return ss;
1167 ckfree(ss);
1168 }
1169 --stack->cur;
1170 return stack;
1171 }
1172
1173 static inline void
1174 cleanup_state_stack(VSS *stack)
1175 {
1176 while (stack->prev != NULL) {
1177 stack->cur = 0;
1178 stack = drop_state_level(stack);
1179 }
1180 }
1181
1182 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
1183 #define PARSESUB() {goto parsesub; parsesub_return:;}
1184 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1185
1186 /*
1187 * The following macros all assume the existance of a local var "stack"
1188 * which contains a pointer to the current struct stackstate
1189 */
1190
1191 /*
1192 * These are macros rather than inline funcs to avoid code churn as much
1193 * as possible - they replace macros of the same name used previously.
1194 */
1195 #define ISDBLQUOTE() (currentstate(stack)->ts_quoted & QS)
1196 #define SETDBLQUOTE() (currentstate(stack)->ts_quoted = QS | DQ)
1197 #define CLRDBLQUOTE() (currentstate(stack)->ts_quoted = \
1198 stack->cur != 0 || stack->prev ? \
1199 prevstate(stack)->ts_quoted & QF : 0)
1200
1201 /*
1202 * This set are just to avoid excess typing and line lengths...
1203 * The ones that "look like" var names must be implemented to be lvalues
1204 */
1205 #define syntax (currentstate(stack)->ts_syntax)
1206 #define parenlevel (currentstate(stack)->ts_parenlevel)
1207 #define varnest (currentstate(stack)->ts_varnest)
1208 #define arinest (currentstate(stack)->ts_arinest)
1209 #define quoted (currentstate(stack)->ts_quoted)
1210 #define TS_PUSH() (stack = bump_state_level(stack))
1211 #define TS_POP() (stack = drop_state_level(stack))
1212
1213 /*
1214 * Called to parse command substitutions. oldstyle is true if the command
1215 * is enclosed inside `` (otherwise it was enclosed in "$( )")
1216 *
1217 * Internally nlpp is a pointer to the head of the linked
1218 * list of commands (passed by reference), and savelen is the number of
1219 * characters on the top of the stack which must be preserved.
1220 */
1221 static char *
1222 parsebackq(VSS *const stack, char * const in,
1223 struct nodelist **const pbqlist, const int oldstyle)
1224 {
1225 struct nodelist **nlpp;
1226 const int savepbq = parsebackquote;
1227 union node *n;
1228 char *out;
1229 char *str = NULL;
1230 char *volatile sstr = str;
1231 struct jmploc jmploc;
1232 struct jmploc *const savehandler = handler;
1233 const int savelen = in - stackblock();
1234 int saveprompt;
1235
1236 if (setjmp(jmploc.loc)) {
1237 if (sstr)
1238 ckfree(__UNVOLATILE(sstr));
1239 cleanup_state_stack(stack);
1240 parsebackquote = 0;
1241 handler = savehandler;
1242 longjmp(handler->loc, 1);
1243 }
1244 INTOFF;
1245 sstr = str = NULL;
1246 if (savelen > 0) {
1247 sstr = str = ckmalloc(savelen);
1248 memcpy(str, stackblock(), savelen);
1249 }
1250 handler = &jmploc;
1251 INTON;
1252 if (oldstyle) {
1253 /* We must read until the closing backquote, giving special
1254 treatment to some slashes, and then push the string and
1255 reread it as input, interpreting it normally. */
1256 int pc;
1257 int psavelen;
1258 char *pstr;
1259
1260 /*
1261 * Because the entire `...` is read here, we don't
1262 * need to bother the state stack. That will be used
1263 * (as appropriate) when the processed string is re-read.
1264 */
1265 STARTSTACKSTR(out);
1266 for (;;) {
1267 if (needprompt) {
1268 setprompt(2);
1269 needprompt = 0;
1270 }
1271 switch (pc = pgetc()) {
1272 case '`':
1273 goto done;
1274
1275 case '\\':
1276 if ((pc = pgetc()) == '\n') {
1277 plinno++;
1278 if (doprompt)
1279 setprompt(2);
1280 else
1281 setprompt(0);
1282 /*
1283 * If eating a newline, avoid putting
1284 * the newline into the new character
1285 * stream (via the STPUTC after the
1286 * switch).
1287 */
1288 continue;
1289 }
1290 if (pc != '\\' && pc != '`' && pc != '$'
1291 && (!ISDBLQUOTE() || pc != '"'))
1292 STPUTC('\\', out);
1293 break;
1294
1295 case '\n':
1296 plinno++;
1297 needprompt = doprompt;
1298 break;
1299
1300 case PEOF:
1301 startlinno = plinno;
1302 synerror("EOF in backquote substitution");
1303 break;
1304
1305 default:
1306 break;
1307 }
1308 STPUTC(pc, out);
1309 }
1310 done:
1311 STPUTC('\0', out);
1312 psavelen = out - stackblock();
1313 if (psavelen > 0) {
1314 pstr = grabstackstr(out);
1315 setinputstring(pstr, 1);
1316 }
1317 }
1318 nlpp = pbqlist;
1319 while (*nlpp)
1320 nlpp = &(*nlpp)->next;
1321 *nlpp = stalloc(sizeof(struct nodelist));
1322 (*nlpp)->next = NULL;
1323 parsebackquote = oldstyle;
1324
1325 if (oldstyle) {
1326 saveprompt = doprompt;
1327 doprompt = 0;
1328 } else
1329 saveprompt = 0;
1330
1331 n = list(0, oldstyle);
1332
1333 if (oldstyle)
1334 doprompt = saveprompt;
1335 else {
1336 if (readtoken() != TRP) {
1337 cleanup_state_stack(stack);
1338 synexpect(TRP, 0);
1339 }
1340 }
1341
1342 (*nlpp)->n = n;
1343 if (oldstyle) {
1344 /*
1345 * Start reading from old file again, ignoring any pushed back
1346 * tokens left from the backquote parsing
1347 */
1348 popfile();
1349 tokpushback = 0;
1350 }
1351
1352 while (stackblocksize() <= savelen)
1353 growstackblock();
1354 STARTSTACKSTR(out);
1355 if (str) {
1356 memcpy(out, str, savelen);
1357 STADJUST(savelen, out);
1358 INTOFF;
1359 ckfree(str);
1360 sstr = str = NULL;
1361 INTON;
1362 }
1363 parsebackquote = savepbq;
1364 handler = savehandler;
1365 if (arinest || ISDBLQUOTE())
1366 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1367 else
1368 USTPUTC(CTLBACKQ, out);
1369
1370 return out;
1371 }
1372
1373 STATIC int
1374 readtoken1(int firstc, char const *syn, int magicq)
1375 {
1376 int c = firstc;
1377 char * out;
1378 int len;
1379 struct nodelist *bqlist;
1380 int quotef;
1381 VSS static_stack;
1382 VSS *stack = &static_stack;
1383
1384 stack->prev = NULL;
1385 stack->cur = 0;
1386
1387 syntax = syn;
1388
1389 startlinno = plinno;
1390 varnest = 0;
1391 quoted = 0;
1392 if (syntax == DQSYNTAX)
1393 SETDBLQUOTE();
1394 quotef = 0;
1395 bqlist = NULL;
1396 arinest = 0;
1397 parenlevel = 0;
1398
1399 STARTSTACKSTR(out);
1400 loop: { /* for each line, until end of word */
1401 for (;;) { /* until end of line or end of word */
1402 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1403 switch(syntax[c]) {
1404 case CNL: /* '\n' */
1405 if (syntax == BASESYNTAX)
1406 goto endword; /* exit outer loop */
1407 USTPUTC(c, out);
1408 plinno++;
1409 if (doprompt)
1410 setprompt(2);
1411 else
1412 setprompt(0);
1413 c = pgetc();
1414 goto loop; /* continue outer loop */
1415 case CWORD:
1416 USTPUTC(c, out);
1417 break;
1418 case CCTL:
1419 if (!magicq || ISDBLQUOTE())
1420 USTPUTC(CTLESC, out);
1421 USTPUTC(c, out);
1422 break;
1423 case CBACK: /* backslash */
1424 c = pgetc();
1425 if (c == PEOF) {
1426 USTPUTC('\\', out);
1427 pungetc();
1428 break;
1429 }
1430 if (c == '\n') {
1431 plinno++;
1432 if (doprompt)
1433 setprompt(2);
1434 else
1435 setprompt(0);
1436 break;
1437 }
1438 quotef = 1;
1439 if (ISDBLQUOTE() && c != '\\' &&
1440 c != '`' && c != '$' &&
1441 (c != '"' || magicq))
1442 USTPUTC('\\', out);
1443 if (SQSYNTAX[c] == CCTL)
1444 USTPUTC(CTLESC, out);
1445 else if (!magicq) {
1446 USTPUTC(CTLQUOTEMARK, out);
1447 USTPUTC(c, out);
1448 if (varnest != 0)
1449 USTPUTC(CTLQUOTEEND, out);
1450 break;
1451 }
1452 USTPUTC(c, out);
1453 break;
1454 case CSQUOTE:
1455 if (syntax != SQSYNTAX) {
1456 if (!magicq)
1457 USTPUTC(CTLQUOTEMARK, out);
1458 quotef = 1;
1459 TS_PUSH();
1460 syntax = SQSYNTAX;
1461 quoted = SQ;
1462 break;
1463 }
1464 if (magicq && arinest == 0 && varnest == 0) {
1465 /* Ignore inside quoted here document */
1466 USTPUTC(c, out);
1467 break;
1468 }
1469 /* End of single quotes... */
1470 TS_POP();
1471 if (syntax == BASESYNTAX && varnest != 0)
1472 USTPUTC(CTLQUOTEEND, out);
1473 break;
1474 case CDQUOTE:
1475 if (magicq && arinest == 0 && varnest == 0) {
1476 /* Ignore inside here document */
1477 USTPUTC(c, out);
1478 break;
1479 }
1480 quotef = 1;
1481 if (arinest) {
1482 if (ISDBLQUOTE()) {
1483 TS_POP();
1484 } else {
1485 TS_PUSH();
1486 syntax = DQSYNTAX;
1487 SETDBLQUOTE();
1488 USTPUTC(CTLQUOTEMARK, out);
1489 }
1490 break;
1491 }
1492 if (magicq)
1493 break;
1494 if (ISDBLQUOTE()) {
1495 TS_POP();
1496 if (varnest != 0)
1497 USTPUTC(CTLQUOTEEND, out);
1498 } else {
1499 TS_PUSH();
1500 syntax = DQSYNTAX;
1501 SETDBLQUOTE();
1502 USTPUTC(CTLQUOTEMARK, out);
1503 }
1504 break;
1505 case CVAR: /* '$' */
1506 PARSESUB(); /* parse substitution */
1507 break;
1508 case CENDVAR: /* CLOSEBRACE */
1509 if (varnest > 0 && !ISDBLQUOTE()) {
1510 TS_POP();
1511 USTPUTC(CTLENDVAR, out);
1512 } else {
1513 USTPUTC(c, out);
1514 }
1515 break;
1516 case CLP: /* '(' in arithmetic */
1517 parenlevel++;
1518 USTPUTC(c, out);
1519 break;
1520 case CRP: /* ')' in arithmetic */
1521 if (parenlevel > 0) {
1522 USTPUTC(c, out);
1523 --parenlevel;
1524 } else {
1525 if (pgetc() == ')') {
1526 if (--arinest == 0) {
1527 TS_POP();
1528 USTPUTC(CTLENDARI, out);
1529 } else
1530 USTPUTC(')', out);
1531 } else {
1532 /*
1533 * unbalanced parens
1534 * (don't 2nd guess - no error)
1535 */
1536 pungetc();
1537 USTPUTC(')', out);
1538 }
1539 }
1540 break;
1541 case CBQUOTE: /* '`' */
1542 out = parsebackq(stack, out, &bqlist, 1);
1543 break;
1544 case CEOF:
1545 goto endword; /* exit outer loop */
1546 default:
1547 if (varnest == 0 && !ISDBLQUOTE())
1548 goto endword; /* exit outer loop */
1549 USTPUTC(c, out);
1550 }
1551 c = pgetc_macro();
1552 }
1553 }
1554 endword:
1555 if (syntax == ARISYNTAX) {
1556 cleanup_state_stack(stack);
1557 synerror("Missing '))'");
1558 }
1559 if (syntax != BASESYNTAX && /* ! parsebackquote && */ !magicq) {
1560 cleanup_state_stack(stack);
1561 synerror("Unterminated quoted string");
1562 }
1563 if (varnest != 0) {
1564 cleanup_state_stack(stack);
1565 startlinno = plinno;
1566 /* { */
1567 synerror("Missing '}'");
1568 }
1569 USTPUTC('\0', out);
1570 len = out - stackblock();
1571 out = stackblock();
1572 if (!magicq) {
1573 if ((c == '<' || c == '>')
1574 && quotef == 0
1575 && (*out == '\0' || is_number(out))) {
1576 PARSEREDIR();
1577 cleanup_state_stack(stack);
1578 return lasttoken = TREDIR;
1579 } else {
1580 pungetc();
1581 }
1582 }
1583 quoteflag = quotef;
1584 backquotelist = bqlist;
1585 grabstackblock(len);
1586 wordtext = out;
1587 cleanup_state_stack(stack);
1588 return lasttoken = TWORD;
1589 /* end of readtoken routine */
1590
1591
1592 /*
1593 * Parse a redirection operator. The variable "out" points to a string
1594 * specifying the fd to be redirected. The variable "c" contains the
1595 * first character of the redirection operator.
1596 */
1597
1598 parseredir: {
1599 char fd[64];
1600 union node *np;
1601 strlcpy(fd, out, sizeof(fd));
1602
1603 np = stalloc(sizeof(struct nfile));
1604 if (c == '>') {
1605 np->nfile.fd = 1;
1606 c = pgetc();
1607 if (c == '>')
1608 np->type = NAPPEND;
1609 else if (c == '|')
1610 np->type = NCLOBBER;
1611 else if (c == '&')
1612 np->type = NTOFD;
1613 else {
1614 np->type = NTO;
1615 pungetc();
1616 }
1617 } else { /* c == '<' */
1618 np->nfile.fd = 0;
1619 switch (c = pgetc()) {
1620 case '<':
1621 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1622 np = stalloc(sizeof(struct nhere));
1623 np->nfile.fd = 0;
1624 }
1625 np->type = NHERE;
1626 heredoc = stalloc(sizeof(struct heredoc));
1627 heredoc->here = np;
1628 if ((c = pgetc()) == '-') {
1629 heredoc->striptabs = 1;
1630 } else {
1631 heredoc->striptabs = 0;
1632 pungetc();
1633 }
1634 break;
1635
1636 case '&':
1637 np->type = NFROMFD;
1638 break;
1639
1640 case '>':
1641 np->type = NFROMTO;
1642 break;
1643
1644 default:
1645 np->type = NFROM;
1646 pungetc();
1647 break;
1648 }
1649 }
1650 if (*fd != '\0')
1651 np->nfile.fd = number(fd);
1652 redirnode = np;
1653 goto parseredir_return;
1654 }
1655
1656
1657 /*
1658 * Parse a substitution. At this point, we have read the dollar sign
1659 * and nothing else.
1660 */
1661
1662 parsesub: {
1663 char buf[10];
1664 int subtype;
1665 int typeloc;
1666 int flags;
1667 char *p;
1668 static const char types[] = "}-+?=";
1669 int i;
1670 int linno;
1671
1672 c = pgetc();
1673 if (c != '(' && c != OPENBRACE && !is_name(c) && !is_special(c)) {
1674 USTPUTC('$', out);
1675 pungetc();
1676 } else if (c == '(') { /* $(command) or $((arith)) */
1677 if (pgetc() == '(') {
1678 PARSEARITH();
1679 } else {
1680 pungetc();
1681 out = parsebackq(stack, out, &bqlist, 0);
1682 }
1683 } else {
1684 USTPUTC(CTLVAR, out);
1685 typeloc = out - stackblock();
1686 USTPUTC(VSNORMAL, out);
1687 subtype = VSNORMAL;
1688 flags = 0;
1689 if (c == OPENBRACE) {
1690 c = pgetc();
1691 if (c == '#') {
1692 if ((c = pgetc()) == CLOSEBRACE)
1693 c = '#';
1694 else
1695 subtype = VSLENGTH;
1696 }
1697 else
1698 subtype = 0;
1699 }
1700 if (is_name(c)) {
1701 p = out;
1702 do {
1703 STPUTC(c, out);
1704 c = pgetc();
1705 } while (is_in_name(c));
1706 if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
1707 /* Replace the variable name with the
1708 * current line number. */
1709 linno = plinno;
1710 if (funclinno != 0)
1711 linno -= funclinno - 1;
1712 snprintf(buf, sizeof(buf), "%d", linno);
1713 STADJUST(-6, out);
1714 for (i = 0; buf[i] != '\0'; i++)
1715 STPUTC(buf[i], out);
1716 flags |= VSLINENO;
1717 }
1718 } else if (is_digit(c)) {
1719 do {
1720 USTPUTC(c, out);
1721 c = pgetc();
1722 } while (is_digit(c));
1723 }
1724 else if (is_special(c)) {
1725 USTPUTC(c, out);
1726 c = pgetc();
1727 }
1728 else {
1729 badsub:
1730 cleanup_state_stack(stack);
1731 synerror("Bad substitution");
1732 }
1733
1734 STPUTC('=', out);
1735 if (subtype == 0) {
1736 switch (c) {
1737 case ':':
1738 flags |= VSNUL;
1739 c = pgetc();
1740 /*FALLTHROUGH*/
1741 default:
1742 p = strchr(types, c);
1743 if (p == NULL)
1744 goto badsub;
1745 subtype = p - types + VSNORMAL;
1746 break;
1747 case '%':
1748 case '#':
1749 {
1750 int cc = c;
1751 subtype = c == '#' ? VSTRIMLEFT :
1752 VSTRIMRIGHT;
1753 c = pgetc();
1754 if (c == cc)
1755 subtype++;
1756 else
1757 pungetc();
1758 break;
1759 }
1760 }
1761 } else {
1762 pungetc();
1763 }
1764 if (ISDBLQUOTE() || arinest)
1765 flags |= VSQUOTE;
1766 if (subtype >= VSTRIMLEFT && subtype <= VSTRIMRIGHTMAX)
1767 flags |= VSPATQ;
1768 *(stackblock() + typeloc) = subtype | flags;
1769 if (subtype != VSNORMAL) {
1770 TS_PUSH();
1771 varnest++;
1772 arinest = 0;
1773 if (subtype > VSASSIGN) { /* # ## % %% */
1774 syntax = BASESYNTAX;
1775 CLRDBLQUOTE();
1776 }
1777 }
1778 }
1779 goto parsesub_return;
1780 }
1781
1782
1783 /*
1784 * Parse an arithmetic expansion (indicate start of one and set state)
1785 */
1786 parsearith: {
1787
1788 if (syntax == ARISYNTAX) {
1789 /*
1790 * we collapse embedded arithmetic expansion to
1791 * parentheses, which should be equivalent
1792 */
1793 USTPUTC('(', out);
1794 USTPUTC('(', out);
1795 /*
1796 * Need 2 of them because there will (should be)
1797 * two closing ))'s to follow later.
1798 */
1799 parenlevel += 2;
1800 } else {
1801 TS_PUSH();
1802 syntax = ARISYNTAX;
1803 ++arinest;
1804 varnest = 0;
1805
1806 USTPUTC(CTLARI, out);
1807 if (ISDBLQUOTE())
1808 USTPUTC('"',out);
1809 else
1810 USTPUTC(' ',out);
1811 }
1812 goto parsearith_return;
1813 }
1814
1815 } /* end of readtoken */
1816
1817
1818
1819 #ifdef mkinit
1820 RESET {
1821 tokpushback = 0;
1822 checkkwd = 0;
1823 }
1824 #endif
1825
1826 /*
1827 * Returns true if the text contains nothing to expand (no dollar signs
1828 * or backquotes).
1829 */
1830
1831 STATIC int
1832 noexpand(char *text)
1833 {
1834 char *p;
1835 char c;
1836
1837 p = text;
1838 while ((c = *p++) != '\0') {
1839 if (c == CTLQUOTEMARK)
1840 continue;
1841 if (c == CTLESC)
1842 p++;
1843 else if (BASESYNTAX[(int)c] == CCTL)
1844 return 0;
1845 }
1846 return 1;
1847 }
1848
1849
1850 /*
1851 * Return true if the argument is a legal variable name (a letter or
1852 * underscore followed by zero or more letters, underscores, and digits).
1853 */
1854
1855 int
1856 goodname(char *name)
1857 {
1858 char *p;
1859
1860 p = name;
1861 if (! is_name(*p))
1862 return 0;
1863 while (*++p) {
1864 if (! is_in_name(*p))
1865 return 0;
1866 }
1867 return 1;
1868 }
1869
1870
1871 /*
1872 * Called when an unexpected token is read during the parse. The argument
1873 * is the token that is expected, or -1 if more than one type of token can
1874 * occur at this point.
1875 */
1876
1877 STATIC void
1878 synexpect(int token, const char *text)
1879 {
1880 char msg[64];
1881 char *p;
1882
1883 if (lasttoken == TWORD) {
1884 size_t len = strlen(wordtext);
1885
1886 if (len <= 13)
1887 fmtstr(msg, 34, "Word \"%.13s\" unexpected", wordtext);
1888 else
1889 fmtstr(msg, 34,
1890 "Word \"%.10s...\" unexpected", wordtext);
1891 } else
1892 fmtstr(msg, 34, "%s unexpected", tokname[lasttoken]);
1893
1894 p = strchr(msg, '\0');
1895 if (text)
1896 fmtstr(p, 30, " (expecting \"%.10s\")", text);
1897 else if (token >= 0)
1898 fmtstr(p, 30, " (expecting %s)", tokname[token]);
1899
1900 synerror(msg);
1901 /* NOTREACHED */
1902 }
1903
1904
1905 STATIC void
1906 synerror(const char *msg)
1907 {
1908 error("%d: Syntax error: %s\n", startlinno, msg);
1909 /* NOTREACHED */
1910 }
1911
1912 STATIC void
1913 setprompt(int which)
1914 {
1915 whichprompt = which;
1916
1917 #ifndef SMALL
1918 if (!el)
1919 #endif
1920 out2str(getprompt(NULL));
1921 }
1922
1923 /*
1924 * called by editline -- any expansions to the prompt
1925 * should be added here.
1926 */
1927 const char *
1928 getprompt(void *unused)
1929 {
1930 switch (whichprompt) {
1931 case 0:
1932 return "";
1933 case 1:
1934 return ps1val();
1935 case 2:
1936 return ps2val();
1937 default:
1938 return "<internal prompt error>";
1939 }
1940 }
1941