parser.c revision 1.64 1 /* $NetBSD: parser.c,v 1.64 2007/01/13 18:58:26 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.64 2007/01/13 18:58:26 christos Exp $");
41 #endif
42 #endif /* not lint */
43
44 #include <stdlib.h>
45
46 #include "shell.h"
47 #include "parser.h"
48 #include "nodes.h"
49 #include "expand.h" /* defines rmescapes() */
50 #include "eval.h" /* defines commandname */
51 #include "redir.h" /* defines copyfd() */
52 #include "syntax.h"
53 #include "options.h"
54 #include "input.h"
55 #include "output.h"
56 #include "var.h"
57 #include "error.h"
58 #include "memalloc.h"
59 #include "mystring.h"
60 #include "alias.h"
61 #include "show.h"
62 #ifndef SMALL
63 #include "myhistedit.h"
64 #endif
65
66 /*
67 * Shell command parser.
68 */
69
70 #define EOFMARKLEN 79
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
103
104 STATIC union node *list(int);
105 STATIC union node *andor(void);
106 STATIC union node *pipeline(void);
107 STATIC union node *command(void);
108 STATIC union node *simplecmd(union node **, union node *);
109 STATIC union node *makename(void);
110 STATIC void parsefname(void);
111 STATIC void parseheredoc(void);
112 STATIC int peektoken(void);
113 STATIC int readtoken(void);
114 STATIC int xxreadtoken(void);
115 STATIC int readtoken1(int, char const *, char *, int);
116 STATIC int noexpand(char *);
117 STATIC void synexpect(int) __attribute__((__noreturn__));
118 STATIC void synerror(const char *) __attribute__((__noreturn__));
119 STATIC void setprompt(int);
120
121
122 /*
123 * Read and parse a command. Returns NEOF on end of file. (NULL is a
124 * valid parse tree indicating a blank line.)
125 */
126
127 union node *
128 parsecmd(int interact)
129 {
130 int t;
131
132 tokpushback = 0;
133 doprompt = interact;
134 if (doprompt)
135 setprompt(1);
136 else
137 setprompt(0);
138 needprompt = 0;
139 t = readtoken();
140 if (t == TEOF)
141 return NEOF;
142 if (t == TNL)
143 return NULL;
144 tokpushback++;
145 return list(1);
146 }
147
148
149 STATIC union node *
150 list(int nlflag)
151 {
152 union node *n1, *n2, *n3;
153 int tok;
154
155 checkkwd = 2;
156 if (nlflag == 0 && tokendlist[peektoken()])
157 return NULL;
158 n1 = NULL;
159 for (;;) {
160 n2 = andor();
161 tok = readtoken();
162 if (tok == TBACKGND) {
163 if (n2->type == NCMD || n2->type == NPIPE) {
164 n2->ncmd.backgnd = 1;
165 } else if (n2->type == NREDIR) {
166 n2->type = NBACKGND;
167 } else {
168 n3 = (union node *)stalloc(sizeof (struct nredir));
169 n3->type = NBACKGND;
170 n3->nredir.n = n2;
171 n3->nredir.redirect = NULL;
172 n2 = n3;
173 }
174 }
175 if (n1 == NULL) {
176 n1 = n2;
177 }
178 else {
179 n3 = (union node *)stalloc(sizeof (struct nbinary));
180 n3->type = NSEMI;
181 n3->nbinary.ch1 = n1;
182 n3->nbinary.ch2 = n2;
183 n1 = n3;
184 }
185 switch (tok) {
186 case TBACKGND:
187 case TSEMI:
188 tok = readtoken();
189 /* fall through */
190 case TNL:
191 if (tok == TNL) {
192 parseheredoc();
193 if (nlflag)
194 return n1;
195 } else {
196 tokpushback++;
197 }
198 checkkwd = 2;
199 if (tokendlist[peektoken()])
200 return n1;
201 break;
202 case TEOF:
203 if (heredoclist)
204 parseheredoc();
205 else
206 pungetc(); /* push back EOF on input */
207 return n1;
208 default:
209 if (nlflag)
210 synexpect(-1);
211 tokpushback++;
212 return n1;
213 }
214 }
215 }
216
217
218
219 STATIC union node *
220 andor(void)
221 {
222 union node *n1, *n2, *n3;
223 int t;
224
225 n1 = pipeline();
226 for (;;) {
227 if ((t = readtoken()) == TAND) {
228 t = NAND;
229 } else if (t == TOR) {
230 t = NOR;
231 } else {
232 tokpushback++;
233 return n1;
234 }
235 n2 = pipeline();
236 n3 = (union node *)stalloc(sizeof (struct nbinary));
237 n3->type = t;
238 n3->nbinary.ch1 = n1;
239 n3->nbinary.ch2 = n2;
240 n1 = n3;
241 }
242 }
243
244
245
246 STATIC union node *
247 pipeline(void)
248 {
249 union node *n1, *n2, *pipenode;
250 struct nodelist *lp, *prev;
251 int negate;
252
253 negate = 0;
254 TRACE(("pipeline: entered\n"));
255 while (readtoken() == TNOT)
256 negate = !negate;
257 tokpushback++;
258 n1 = command();
259 if (readtoken() == TPIPE) {
260 pipenode = (union node *)stalloc(sizeof (struct npipe));
261 pipenode->type = NPIPE;
262 pipenode->npipe.backgnd = 0;
263 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
264 pipenode->npipe.cmdlist = lp;
265 lp->n = n1;
266 do {
267 prev = lp;
268 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
269 lp->n = command();
270 prev->next = lp;
271 } while (readtoken() == TPIPE);
272 lp->next = NULL;
273 n1 = pipenode;
274 }
275 tokpushback++;
276 if (negate) {
277 n2 = (union node *)stalloc(sizeof (struct nnot));
278 n2->type = NNOT;
279 n2->nnot.com = n1;
280 return n2;
281 } else
282 return n1;
283 }
284
285
286
287 STATIC union node *
288 command(void)
289 {
290 union node *n1, *n2;
291 union node *ap, **app;
292 union node *cp, **cpp;
293 union node *redir, **rpp;
294 int t, negate = 0;
295
296 checkkwd = 2;
297 redir = NULL;
298 n1 = NULL;
299 rpp = &redir;
300
301 /* Check for redirection which may precede command */
302 while (readtoken() == TREDIR) {
303 *rpp = n2 = redirnode;
304 rpp = &n2->nfile.next;
305 parsefname();
306 }
307 tokpushback++;
308
309 while (readtoken() == TNOT) {
310 TRACE(("command: TNOT recognized\n"));
311 negate = !negate;
312 }
313 tokpushback++;
314
315 switch (readtoken()) {
316 case TIF:
317 n1 = (union node *)stalloc(sizeof (struct nif));
318 n1->type = NIF;
319 n1->nif.test = list(0);
320 if (readtoken() != TTHEN)
321 synexpect(TTHEN);
322 n1->nif.ifpart = list(0);
323 n2 = n1;
324 while (readtoken() == TELIF) {
325 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
326 n2 = n2->nif.elsepart;
327 n2->type = NIF;
328 n2->nif.test = list(0);
329 if (readtoken() != TTHEN)
330 synexpect(TTHEN);
331 n2->nif.ifpart = list(0);
332 }
333 if (lasttoken == TELSE)
334 n2->nif.elsepart = list(0);
335 else {
336 n2->nif.elsepart = NULL;
337 tokpushback++;
338 }
339 if (readtoken() != TFI)
340 synexpect(TFI);
341 checkkwd = 1;
342 break;
343 case TWHILE:
344 case TUNTIL: {
345 int got;
346 n1 = (union node *)stalloc(sizeof (struct nbinary));
347 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
348 n1->nbinary.ch1 = list(0);
349 if ((got=readtoken()) != TDO) {
350 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
351 synexpect(TDO);
352 }
353 n1->nbinary.ch2 = list(0);
354 if (readtoken() != TDONE)
355 synexpect(TDONE);
356 checkkwd = 1;
357 break;
358 }
359 case TFOR:
360 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
361 synerror("Bad for loop variable");
362 n1 = (union node *)stalloc(sizeof (struct nfor));
363 n1->type = NFOR;
364 n1->nfor.var = wordtext;
365 if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
366 app = ≈
367 while (readtoken() == TWORD) {
368 n2 = (union node *)stalloc(sizeof (struct narg));
369 n2->type = NARG;
370 n2->narg.text = wordtext;
371 n2->narg.backquote = backquotelist;
372 *app = n2;
373 app = &n2->narg.next;
374 }
375 *app = NULL;
376 n1->nfor.args = ap;
377 if (lasttoken != TNL && lasttoken != TSEMI)
378 synexpect(-1);
379 } else {
380 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
381 '@', '=', '\0'};
382 n2 = (union node *)stalloc(sizeof (struct narg));
383 n2->type = NARG;
384 n2->narg.text = argvars;
385 n2->narg.backquote = NULL;
386 n2->narg.next = NULL;
387 n1->nfor.args = n2;
388 /*
389 * Newline or semicolon here is optional (but note
390 * that the original Bourne shell only allowed NL).
391 */
392 if (lasttoken != TNL && lasttoken != TSEMI)
393 tokpushback++;
394 }
395 checkkwd = 2;
396 if ((t = readtoken()) == TDO)
397 t = TDONE;
398 else if (t == TBEGIN)
399 t = TEND;
400 else
401 synexpect(-1);
402 n1->nfor.body = list(0);
403 if (readtoken() != t)
404 synexpect(t);
405 checkkwd = 1;
406 break;
407 case TCASE:
408 n1 = (union node *)stalloc(sizeof (struct ncase));
409 n1->type = NCASE;
410 if (readtoken() != TWORD)
411 synexpect(TWORD);
412 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
413 n2->type = NARG;
414 n2->narg.text = wordtext;
415 n2->narg.backquote = backquotelist;
416 n2->narg.next = NULL;
417 while (readtoken() == TNL);
418 if (lasttoken != TWORD || ! equal(wordtext, "in"))
419 synerror("expecting \"in\"");
420 cpp = &n1->ncase.cases;
421 noalias = 1;
422 checkkwd = 2, readtoken();
423 do {
424 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
425 if (lasttoken == TLP)
426 readtoken();
427 cp->type = NCLIST;
428 app = &cp->nclist.pattern;
429 for (;;) {
430 *app = ap = (union node *)stalloc(sizeof (struct narg));
431 ap->type = NARG;
432 ap->narg.text = wordtext;
433 ap->narg.backquote = backquotelist;
434 if (checkkwd = 2, readtoken() != TPIPE)
435 break;
436 app = &ap->narg.next;
437 readtoken();
438 }
439 ap->narg.next = NULL;
440 noalias = 0;
441 if (lasttoken != TRP) {
442 synexpect(TRP);
443 }
444 cp->nclist.body = list(0);
445
446 checkkwd = 2;
447 if ((t = readtoken()) != TESAC) {
448 if (t != TENDCASE) {
449 noalias = 0;
450 synexpect(TENDCASE);
451 } else {
452 noalias = 1;
453 checkkwd = 2;
454 readtoken();
455 }
456 }
457 cpp = &cp->nclist.next;
458 } while(lasttoken != TESAC);
459 noalias = 0;
460 *cpp = NULL;
461 checkkwd = 1;
462 break;
463 case TLP:
464 n1 = (union node *)stalloc(sizeof (struct nredir));
465 n1->type = NSUBSHELL;
466 n1->nredir.n = list(0);
467 n1->nredir.redirect = NULL;
468 if (readtoken() != TRP)
469 synexpect(TRP);
470 checkkwd = 1;
471 break;
472 case TBEGIN:
473 n1 = list(0);
474 if (readtoken() != TEND)
475 synexpect(TEND);
476 checkkwd = 1;
477 break;
478 /* Handle an empty command like other simple commands. */
479 case TSEMI:
480 /*
481 * An empty command before a ; doesn't make much sense, and
482 * should certainly be disallowed in the case of `if ;'.
483 */
484 if (!redir)
485 synexpect(-1);
486 case TAND:
487 case TOR:
488 case TNL:
489 case TEOF:
490 case TWORD:
491 case TRP:
492 tokpushback++;
493 n1 = simplecmd(rpp, redir);
494 goto checkneg;
495 default:
496 synexpect(-1);
497 /* NOTREACHED */
498 }
499
500 /* Now check for redirection which may follow command */
501 while (readtoken() == TREDIR) {
502 *rpp = n2 = redirnode;
503 rpp = &n2->nfile.next;
504 parsefname();
505 }
506 tokpushback++;
507 *rpp = NULL;
508 if (redir) {
509 if (n1->type != NSUBSHELL) {
510 n2 = (union node *)stalloc(sizeof (struct nredir));
511 n2->type = NREDIR;
512 n2->nredir.n = n1;
513 n1 = n2;
514 }
515 n1->nredir.redirect = redir;
516 }
517
518 checkneg:
519 if (negate) {
520 n2 = (union node *)stalloc(sizeof (struct nnot));
521 n2->type = NNOT;
522 n2->nnot.com = n1;
523 return n2;
524 }
525 else
526 return n1;
527 }
528
529
530 STATIC union node *
531 simplecmd(union node **rpp, union node *redir)
532 {
533 union node *args, **app;
534 union node **orig_rpp = rpp;
535 union node *n = NULL, *n2;
536 int negate = 0;
537
538 /* If we don't have any redirections already, then we must reset */
539 /* rpp to be the address of the local redir variable. */
540 if (redir == 0)
541 rpp = &redir;
542
543 args = NULL;
544 app = &args;
545 /*
546 * We save the incoming value, because we need this for shell
547 * functions. There can not be a redirect or an argument between
548 * the function name and the open parenthesis.
549 */
550 orig_rpp = rpp;
551
552 while (readtoken() == TNOT) {
553 TRACE(("command: TNOT recognized\n"));
554 negate = !negate;
555 }
556 tokpushback++;
557
558 for (;;) {
559 if (readtoken() == TWORD) {
560 n = (union node *)stalloc(sizeof (struct narg));
561 n->type = NARG;
562 n->narg.text = wordtext;
563 n->narg.backquote = backquotelist;
564 *app = n;
565 app = &n->narg.next;
566 } else if (lasttoken == TREDIR) {
567 *rpp = n = redirnode;
568 rpp = &n->nfile.next;
569 parsefname(); /* read name of redirection file */
570 } else if (lasttoken == TLP && app == &args->narg.next
571 && rpp == orig_rpp) {
572 /* We have a function */
573 if (readtoken() != TRP)
574 synexpect(TRP);
575 rmescapes(n->narg.text);
576 if (!goodname(n->narg.text))
577 synerror("Bad function name");
578 n->type = NDEFUN;
579 n->narg.next = command();
580 goto checkneg;
581 } else {
582 tokpushback++;
583 break;
584 }
585 }
586 *app = NULL;
587 *rpp = NULL;
588 n = (union node *)stalloc(sizeof (struct ncmd));
589 n->type = NCMD;
590 n->ncmd.backgnd = 0;
591 n->ncmd.args = args;
592 n->ncmd.redirect = redir;
593
594 checkneg:
595 if (negate) {
596 n2 = (union node *)stalloc(sizeof (struct nnot));
597 n2->type = NNOT;
598 n2->nnot.com = n;
599 return n2;
600 }
601 else
602 return n;
603 }
604
605 STATIC union node *
606 makename(void)
607 {
608 union node *n;
609
610 n = (union node *)stalloc(sizeof (struct narg));
611 n->type = NARG;
612 n->narg.next = NULL;
613 n->narg.text = wordtext;
614 n->narg.backquote = backquotelist;
615 return n;
616 }
617
618 void fixredir(union node *n, const char *text, int err)
619 {
620 TRACE(("Fix redir %s %d\n", text, err));
621 if (!err)
622 n->ndup.vname = NULL;
623
624 if (is_digit(text[0]) && text[1] == '\0')
625 n->ndup.dupfd = digit_val(text[0]);
626 else if (text[0] == '-' && text[1] == '\0')
627 n->ndup.dupfd = -1;
628 else {
629
630 if (err)
631 synerror("Bad fd number");
632 else
633 n->ndup.vname = makename();
634 }
635 }
636
637
638 STATIC void
639 parsefname(void)
640 {
641 union node *n = redirnode;
642
643 if (readtoken() != TWORD)
644 synexpect(-1);
645 if (n->type == NHERE) {
646 struct heredoc *here = heredoc;
647 struct heredoc *p;
648 int i;
649
650 if (quoteflag == 0)
651 n->type = NXHERE;
652 TRACE(("Here document %d\n", n->type));
653 if (here->striptabs) {
654 while (*wordtext == '\t')
655 wordtext++;
656 }
657 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
658 synerror("Illegal eof marker for << redirection");
659 rmescapes(wordtext);
660 here->eofmark = wordtext;
661 here->next = NULL;
662 if (heredoclist == NULL)
663 heredoclist = here;
664 else {
665 for (p = heredoclist ; p->next ; p = p->next);
666 p->next = here;
667 }
668 } else if (n->type == NTOFD || n->type == NFROMFD) {
669 fixredir(n, wordtext, 0);
670 } else {
671 n->nfile.fname = makename();
672 }
673 }
674
675
676 /*
677 * Input any here documents.
678 */
679
680 STATIC void
681 parseheredoc(void)
682 {
683 struct heredoc *here;
684 union node *n;
685
686 while (heredoclist) {
687 here = heredoclist;
688 heredoclist = here->next;
689 if (needprompt) {
690 setprompt(2);
691 needprompt = 0;
692 }
693 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
694 here->eofmark, here->striptabs);
695 n = (union node *)stalloc(sizeof (struct narg));
696 n->narg.type = NARG;
697 n->narg.next = NULL;
698 n->narg.text = wordtext;
699 n->narg.backquote = backquotelist;
700 here->here->nhere.doc = n;
701 }
702 }
703
704 STATIC int
705 peektoken(void)
706 {
707 int t;
708
709 t = readtoken();
710 tokpushback++;
711 return (t);
712 }
713
714 STATIC int
715 readtoken(void)
716 {
717 int t;
718 int savecheckkwd = checkkwd;
719 #ifdef DEBUG
720 int alreadyseen = tokpushback;
721 #endif
722 struct alias *ap;
723
724 top:
725 t = xxreadtoken();
726
727 if (checkkwd) {
728 /*
729 * eat newlines
730 */
731 if (checkkwd == 2) {
732 checkkwd = 0;
733 while (t == TNL) {
734 parseheredoc();
735 t = xxreadtoken();
736 }
737 } else
738 checkkwd = 0;
739 /*
740 * check for keywords and aliases
741 */
742 if (t == TWORD && !quoteflag)
743 {
744 const char *const *pp;
745
746 for (pp = parsekwd; *pp; pp++) {
747 if (**pp == *wordtext && equal(*pp, wordtext))
748 {
749 lasttoken = t = pp -
750 parsekwd + KWDOFFSET;
751 TRACE(("keyword %s recognized\n", tokname[t]));
752 goto out;
753 }
754 }
755 if(!noalias &&
756 (ap = lookupalias(wordtext, 1)) != NULL) {
757 pushstring(ap->val, strlen(ap->val), ap);
758 checkkwd = savecheckkwd;
759 goto top;
760 }
761 }
762 out:
763 checkkwd = (t == TNOT) ? savecheckkwd : 0;
764 }
765 #ifdef DEBUG
766 if (!alreadyseen)
767 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
768 else
769 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
770 #endif
771 return (t);
772 }
773
774
775 /*
776 * Read the next input token.
777 * If the token is a word, we set backquotelist to the list of cmds in
778 * backquotes. We set quoteflag to true if any part of the word was
779 * quoted.
780 * If the token is TREDIR, then we set redirnode to a structure containing
781 * the redirection.
782 * In all cases, the variable startlinno is set to the number of the line
783 * on which the token starts.
784 *
785 * [Change comment: here documents and internal procedures]
786 * [Readtoken shouldn't have any arguments. Perhaps we should make the
787 * word parsing code into a separate routine. In this case, readtoken
788 * doesn't need to have any internal procedures, but parseword does.
789 * We could also make parseoperator in essence the main routine, and
790 * have parseword (readtoken1?) handle both words and redirection.]
791 */
792
793 #define RETURN(token) return lasttoken = token
794
795 STATIC int
796 xxreadtoken(void)
797 {
798 int c;
799
800 if (tokpushback) {
801 tokpushback = 0;
802 return lasttoken;
803 }
804 if (needprompt) {
805 setprompt(2);
806 needprompt = 0;
807 }
808 startlinno = plinno;
809 for (;;) { /* until token or start of word found */
810 c = pgetc_macro();
811 if (c == ' ' || c == '\t')
812 continue; /* quick check for white space first */
813 switch (c) {
814 case ' ': case '\t':
815 continue;
816 case '#':
817 while ((c = pgetc()) != '\n' && c != PEOF);
818 pungetc();
819 continue;
820 case '\\':
821 if (pgetc() == '\n') {
822 startlinno = ++plinno;
823 if (doprompt)
824 setprompt(2);
825 else
826 setprompt(0);
827 continue;
828 }
829 pungetc();
830 goto breakloop;
831 case '\n':
832 plinno++;
833 needprompt = doprompt;
834 RETURN(TNL);
835 case PEOF:
836 RETURN(TEOF);
837 case '&':
838 if (pgetc() == '&')
839 RETURN(TAND);
840 pungetc();
841 RETURN(TBACKGND);
842 case '|':
843 if (pgetc() == '|')
844 RETURN(TOR);
845 pungetc();
846 RETURN(TPIPE);
847 case ';':
848 if (pgetc() == ';')
849 RETURN(TENDCASE);
850 pungetc();
851 RETURN(TSEMI);
852 case '(':
853 RETURN(TLP);
854 case ')':
855 RETURN(TRP);
856 default:
857 goto breakloop;
858 }
859 }
860 breakloop:
861 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
862 #undef RETURN
863 }
864
865
866
867 /*
868 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
869 * is not NULL, read a here document. In the latter case, eofmark is the
870 * word which marks the end of the document and striptabs is true if
871 * leading tabs should be stripped from the document. The argument firstc
872 * is the first character of the input token or document.
873 *
874 * Because C does not have internal subroutines, I have simulated them
875 * using goto's to implement the subroutine linkage. The following macros
876 * will run code that appears at the end of readtoken1.
877 */
878
879 #define CHECKEND() {goto checkend; checkend_return:;}
880 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
881 #define PARSESUB() {goto parsesub; parsesub_return:;}
882 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
883 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
884 #define PARSEARITH() {goto parsearith; parsearith_return:;}
885
886 /*
887 * Keep track of nested doublequotes in dblquote and doublequotep.
888 * We use dblquote for the first 32 levels, and we expand to a malloc'ed
889 * region for levels above that. Usually we never need to malloc.
890 * This code assumes that an int is 32 bits. We don't use uint32_t,
891 * because the rest of the code does not.
892 */
893 #define ISDBLQUOTE() ((varnest < 32) ? (dblquote & (1 << varnest)) : \
894 (dblquotep[(varnest / 32) - 1] & (1 << (varnest % 32))))
895
896 #define SETDBLQUOTE() \
897 if (varnest < 32) \
898 dblquote |= (1 << varnest); \
899 else \
900 dblquotep[(varnest / 32) - 1] |= (1 << (varnest % 32))
901
902 #define CLRDBLQUOTE() \
903 if (varnest < 32) \
904 dblquote &= ~(1 << varnest); \
905 else \
906 dblquotep[(varnest / 32) - 1] &= ~(1 << (varnest % 32))
907
908 STATIC int
909 readtoken1(int firstc, char const *syn, char *eofmark, int striptabs)
910 {
911 char const * volatile syntax = syn;
912 int c = firstc;
913 char * volatile out;
914 int len;
915 char line[EOFMARKLEN + 1];
916 struct nodelist *bqlist;
917 volatile int quotef;
918 int * volatile dblquotep = NULL;
919 volatile size_t maxnest = 32;
920 volatile int dblquote;
921 volatile int varnest; /* levels of variables expansion */
922 volatile int arinest; /* levels of arithmetic expansion */
923 volatile int parenlevel; /* levels of parens in arithmetic */
924 volatile int oldstyle;
925 char const * volatile prevsyntax; /* syntax before arithmetic */
926 #ifdef __GNUC__
927 prevsyntax = NULL; /* XXX gcc4 */
928 #endif
929
930 startlinno = plinno;
931 dblquote = 0;
932 varnest = 0;
933 if (syntax == DQSYNTAX) {
934 SETDBLQUOTE();
935 }
936 quotef = 0;
937 bqlist = NULL;
938 arinest = 0;
939 parenlevel = 0;
940
941 STARTSTACKSTR(out);
942 loop: { /* for each line, until end of word */
943 #if ATTY
944 if (c == '\034' && doprompt
945 && attyset() && ! equal(termval(), "emacs")) {
946 attyline();
947 if (syntax == BASESYNTAX)
948 return readtoken();
949 c = pgetc();
950 goto loop;
951 }
952 #endif
953 CHECKEND(); /* set c to PEOF if at end of here document */
954 for (;;) { /* until end of line or end of word */
955 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
956 switch(syntax[c]) {
957 case CNL: /* '\n' */
958 if (syntax == BASESYNTAX)
959 goto endword; /* exit outer loop */
960 USTPUTC(c, out);
961 plinno++;
962 if (doprompt)
963 setprompt(2);
964 else
965 setprompt(0);
966 c = pgetc();
967 goto loop; /* continue outer loop */
968 case CWORD:
969 USTPUTC(c, out);
970 break;
971 case CCTL:
972 if (eofmark == NULL || ISDBLQUOTE())
973 USTPUTC(CTLESC, out);
974 USTPUTC(c, out);
975 break;
976 case CBACK: /* backslash */
977 c = pgetc();
978 if (c == PEOF) {
979 USTPUTC('\\', out);
980 pungetc();
981 break;
982 }
983 if (c == '\n') {
984 if (doprompt)
985 setprompt(2);
986 else
987 setprompt(0);
988 break;
989 }
990 quotef = 1;
991 if (ISDBLQUOTE() && c != '\\' &&
992 c != '`' && c != '$' &&
993 (c != '"' || eofmark != NULL))
994 USTPUTC('\\', out);
995 if (SQSYNTAX[c] == CCTL)
996 USTPUTC(CTLESC, out);
997 else if (eofmark == NULL) {
998 USTPUTC(CTLQUOTEMARK, out);
999 USTPUTC(c, out);
1000 if (varnest != 0)
1001 USTPUTC(CTLQUOTEEND, out);
1002 break;
1003 }
1004 USTPUTC(c, out);
1005 break;
1006 case CSQUOTE:
1007 if (syntax != SQSYNTAX) {
1008 if (eofmark == NULL)
1009 USTPUTC(CTLQUOTEMARK, out);
1010 quotef = 1;
1011 syntax = SQSYNTAX;
1012 break;
1013 }
1014 if (eofmark != NULL && arinest == 0 &&
1015 varnest == 0) {
1016 /* Ignore inside quoted here document */
1017 USTPUTC(c, out);
1018 break;
1019 }
1020 /* End of single quotes... */
1021 if (arinest)
1022 syntax = ARISYNTAX;
1023 else {
1024 syntax = BASESYNTAX;
1025 if (varnest != 0)
1026 USTPUTC(CTLQUOTEEND, out);
1027 }
1028 break;
1029 case CDQUOTE:
1030 if (eofmark != NULL && arinest == 0 &&
1031 varnest == 0) {
1032 /* Ignore inside here document */
1033 USTPUTC(c, out);
1034 break;
1035 }
1036 quotef = 1;
1037 if (arinest) {
1038 if (ISDBLQUOTE()) {
1039 syntax = ARISYNTAX;
1040 CLRDBLQUOTE();
1041 } else {
1042 syntax = DQSYNTAX;
1043 SETDBLQUOTE();
1044 USTPUTC(CTLQUOTEMARK, out);
1045 }
1046 break;
1047 }
1048 if (eofmark != NULL)
1049 break;
1050 if (ISDBLQUOTE()) {
1051 if (varnest != 0)
1052 USTPUTC(CTLQUOTEEND, out);
1053 syntax = BASESYNTAX;
1054 CLRDBLQUOTE();
1055 } else {
1056 syntax = DQSYNTAX;
1057 SETDBLQUOTE();
1058 USTPUTC(CTLQUOTEMARK, out);
1059 }
1060 break;
1061 case CVAR: /* '$' */
1062 PARSESUB(); /* parse substitution */
1063 break;
1064 case CENDVAR: /* CLOSEBRACE */
1065 if (varnest > 0 && !ISDBLQUOTE()) {
1066 varnest--;
1067 USTPUTC(CTLENDVAR, out);
1068 } else {
1069 USTPUTC(c, out);
1070 }
1071 break;
1072 case CLP: /* '(' in arithmetic */
1073 parenlevel++;
1074 USTPUTC(c, out);
1075 break;
1076 case CRP: /* ')' in arithmetic */
1077 if (parenlevel > 0) {
1078 USTPUTC(c, out);
1079 --parenlevel;
1080 } else {
1081 if (pgetc() == ')') {
1082 if (--arinest == 0) {
1083 USTPUTC(CTLENDARI, out);
1084 syntax = prevsyntax;
1085 if (syntax == DQSYNTAX)
1086 SETDBLQUOTE();
1087 else
1088 CLRDBLQUOTE();
1089 } else
1090 USTPUTC(')', out);
1091 } else {
1092 /*
1093 * unbalanced parens
1094 * (don't 2nd guess - no error)
1095 */
1096 pungetc();
1097 USTPUTC(')', out);
1098 }
1099 }
1100 break;
1101 case CBQUOTE: /* '`' */
1102 PARSEBACKQOLD();
1103 break;
1104 case CEOF:
1105 goto endword; /* exit outer loop */
1106 default:
1107 if (varnest == 0)
1108 goto endword; /* exit outer loop */
1109 USTPUTC(c, out);
1110 }
1111 c = pgetc_macro();
1112 }
1113 }
1114 endword:
1115 if (syntax == ARISYNTAX)
1116 synerror("Missing '))'");
1117 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
1118 synerror("Unterminated quoted string");
1119 if (varnest != 0) {
1120 startlinno = plinno;
1121 /* { */
1122 synerror("Missing '}'");
1123 }
1124 USTPUTC('\0', out);
1125 len = out - stackblock();
1126 out = stackblock();
1127 if (eofmark == NULL) {
1128 if ((c == '>' || c == '<')
1129 && quotef == 0
1130 && len <= 2
1131 && (*out == '\0' || is_digit(*out))) {
1132 PARSEREDIR();
1133 return lasttoken = TREDIR;
1134 } else {
1135 pungetc();
1136 }
1137 }
1138 quoteflag = quotef;
1139 backquotelist = bqlist;
1140 grabstackblock(len);
1141 wordtext = out;
1142 if (dblquotep != NULL)
1143 ckfree(dblquotep);
1144 return lasttoken = TWORD;
1145 /* end of readtoken routine */
1146
1147
1148
1149 /*
1150 * Check to see whether we are at the end of the here document. When this
1151 * is called, c is set to the first character of the next input line. If
1152 * we are at the end of the here document, this routine sets the c to PEOF.
1153 */
1154
1155 checkend: {
1156 if (eofmark) {
1157 if (striptabs) {
1158 while (c == '\t')
1159 c = pgetc();
1160 }
1161 if (c == *eofmark) {
1162 if (pfgets(line, sizeof line) != NULL) {
1163 char *p, *q;
1164
1165 p = line;
1166 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1167 if (*p == '\n' && *q == '\0') {
1168 c = PEOF;
1169 plinno++;
1170 needprompt = doprompt;
1171 } else {
1172 pushstring(line, strlen(line), NULL);
1173 }
1174 }
1175 }
1176 }
1177 goto checkend_return;
1178 }
1179
1180
1181 /*
1182 * Parse a redirection operator. The variable "out" points to a string
1183 * specifying the fd to be redirected. The variable "c" contains the
1184 * first character of the redirection operator.
1185 */
1186
1187 parseredir: {
1188 char fd = *out;
1189 union node *np;
1190
1191 np = (union node *)stalloc(sizeof (struct nfile));
1192 if (c == '>') {
1193 np->nfile.fd = 1;
1194 c = pgetc();
1195 if (c == '>')
1196 np->type = NAPPEND;
1197 else if (c == '|')
1198 np->type = NCLOBBER;
1199 else if (c == '&')
1200 np->type = NTOFD;
1201 else {
1202 np->type = NTO;
1203 pungetc();
1204 }
1205 } else { /* c == '<' */
1206 np->nfile.fd = 0;
1207 switch (c = pgetc()) {
1208 case '<':
1209 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1210 np = (union node *)stalloc(sizeof (struct nhere));
1211 np->nfile.fd = 0;
1212 }
1213 np->type = NHERE;
1214 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1215 heredoc->here = np;
1216 if ((c = pgetc()) == '-') {
1217 heredoc->striptabs = 1;
1218 } else {
1219 heredoc->striptabs = 0;
1220 pungetc();
1221 }
1222 break;
1223
1224 case '&':
1225 np->type = NFROMFD;
1226 break;
1227
1228 case '>':
1229 np->type = NFROMTO;
1230 break;
1231
1232 default:
1233 np->type = NFROM;
1234 pungetc();
1235 break;
1236 }
1237 }
1238 if (fd != '\0')
1239 np->nfile.fd = digit_val(fd);
1240 redirnode = np;
1241 goto parseredir_return;
1242 }
1243
1244
1245 /*
1246 * Parse a substitution. At this point, we have read the dollar sign
1247 * and nothing else.
1248 */
1249
1250 parsesub: {
1251 int subtype;
1252 int typeloc;
1253 int flags;
1254 char *p;
1255 static const char types[] = "}-+?=";
1256
1257 c = pgetc();
1258 if (c != '(' && c != OPENBRACE && !is_name(c) && !is_special(c)) {
1259 USTPUTC('$', out);
1260 pungetc();
1261 } else if (c == '(') { /* $(command) or $((arith)) */
1262 if (pgetc() == '(') {
1263 PARSEARITH();
1264 } else {
1265 pungetc();
1266 PARSEBACKQNEW();
1267 }
1268 } else {
1269 USTPUTC(CTLVAR, out);
1270 typeloc = out - stackblock();
1271 USTPUTC(VSNORMAL, out);
1272 subtype = VSNORMAL;
1273 if (c == OPENBRACE) {
1274 c = pgetc();
1275 if (c == '#') {
1276 if ((c = pgetc()) == CLOSEBRACE)
1277 c = '#';
1278 else
1279 subtype = VSLENGTH;
1280 }
1281 else
1282 subtype = 0;
1283 }
1284 if (is_name(c)) {
1285 do {
1286 STPUTC(c, out);
1287 c = pgetc();
1288 } while (is_in_name(c));
1289 } else if (is_digit(c)) {
1290 do {
1291 USTPUTC(c, out);
1292 c = pgetc();
1293 } while (is_digit(c));
1294 }
1295 else if (is_special(c)) {
1296 USTPUTC(c, out);
1297 c = pgetc();
1298 }
1299 else
1300 badsub: synerror("Bad substitution");
1301
1302 STPUTC('=', out);
1303 flags = 0;
1304 if (subtype == 0) {
1305 switch (c) {
1306 case ':':
1307 flags = VSNUL;
1308 c = pgetc();
1309 /*FALLTHROUGH*/
1310 default:
1311 p = strchr(types, c);
1312 if (p == NULL)
1313 goto badsub;
1314 subtype = p - types + VSNORMAL;
1315 break;
1316 case '%':
1317 case '#':
1318 {
1319 int cc = c;
1320 subtype = c == '#' ? VSTRIMLEFT :
1321 VSTRIMRIGHT;
1322 c = pgetc();
1323 if (c == cc)
1324 subtype++;
1325 else
1326 pungetc();
1327 break;
1328 }
1329 }
1330 } else {
1331 pungetc();
1332 }
1333 if (ISDBLQUOTE() || arinest)
1334 flags |= VSQUOTE;
1335 *(stackblock() + typeloc) = subtype | flags;
1336 if (subtype != VSNORMAL) {
1337 varnest++;
1338 if (varnest >= maxnest) {
1339 dblquotep = ckrealloc(dblquotep, maxnest / 8);
1340 dblquotep[(maxnest / 32) - 1] = 0;
1341 maxnest += 32;
1342 }
1343 }
1344 }
1345 goto parsesub_return;
1346 }
1347
1348
1349 /*
1350 * Called to parse command substitutions. Newstyle is set if the command
1351 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
1352 * list of commands (passed by reference), and savelen is the number of
1353 * characters on the top of the stack which must be preserved.
1354 */
1355
1356 parsebackq: {
1357 struct nodelist **nlpp;
1358 int savepbq;
1359 union node *n;
1360 char *volatile str;
1361 struct jmploc jmploc;
1362 struct jmploc *volatile savehandler;
1363 int savelen;
1364 int saveprompt;
1365
1366 savepbq = parsebackquote;
1367 if (setjmp(jmploc.loc)) {
1368 if (str)
1369 ckfree(str);
1370 parsebackquote = 0;
1371 handler = savehandler;
1372 longjmp(handler->loc, 1);
1373 }
1374 INTOFF;
1375 str = NULL;
1376 savelen = out - stackblock();
1377 if (savelen > 0) {
1378 str = ckmalloc(savelen);
1379 memcpy(str, stackblock(), savelen);
1380 }
1381 savehandler = handler;
1382 handler = &jmploc;
1383 INTON;
1384 if (oldstyle) {
1385 /* We must read until the closing backquote, giving special
1386 treatment to some slashes, and then push the string and
1387 reread it as input, interpreting it normally. */
1388 char *pout;
1389 int pc;
1390 int psavelen;
1391 char *pstr;
1392
1393
1394 STARTSTACKSTR(pout);
1395 for (;;) {
1396 if (needprompt) {
1397 setprompt(2);
1398 needprompt = 0;
1399 }
1400 switch (pc = pgetc()) {
1401 case '`':
1402 goto done;
1403
1404 case '\\':
1405 if ((pc = pgetc()) == '\n') {
1406 plinno++;
1407 if (doprompt)
1408 setprompt(2);
1409 else
1410 setprompt(0);
1411 /*
1412 * If eating a newline, avoid putting
1413 * the newline into the new character
1414 * stream (via the STPUTC after the
1415 * switch).
1416 */
1417 continue;
1418 }
1419 if (pc != '\\' && pc != '`' && pc != '$'
1420 && (!ISDBLQUOTE() || pc != '"'))
1421 STPUTC('\\', pout);
1422 break;
1423
1424 case '\n':
1425 plinno++;
1426 needprompt = doprompt;
1427 break;
1428
1429 case PEOF:
1430 startlinno = plinno;
1431 synerror("EOF in backquote substitution");
1432 break;
1433
1434 default:
1435 break;
1436 }
1437 STPUTC(pc, pout);
1438 }
1439 done:
1440 STPUTC('\0', pout);
1441 psavelen = pout - stackblock();
1442 if (psavelen > 0) {
1443 pstr = grabstackstr(pout);
1444 setinputstring(pstr, 1);
1445 }
1446 }
1447 nlpp = &bqlist;
1448 while (*nlpp)
1449 nlpp = &(*nlpp)->next;
1450 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1451 (*nlpp)->next = NULL;
1452 parsebackquote = oldstyle;
1453
1454 if (oldstyle) {
1455 saveprompt = doprompt;
1456 doprompt = 0;
1457 } else
1458 saveprompt = 0;
1459
1460 n = list(0);
1461
1462 if (oldstyle)
1463 doprompt = saveprompt;
1464 else {
1465 if (readtoken() != TRP)
1466 synexpect(TRP);
1467 }
1468
1469 (*nlpp)->n = n;
1470 if (oldstyle) {
1471 /*
1472 * Start reading from old file again, ignoring any pushed back
1473 * tokens left from the backquote parsing
1474 */
1475 popfile();
1476 tokpushback = 0;
1477 }
1478 while (stackblocksize() <= savelen)
1479 growstackblock();
1480 STARTSTACKSTR(out);
1481 if (str) {
1482 memcpy(out, str, savelen);
1483 STADJUST(savelen, out);
1484 INTOFF;
1485 ckfree(str);
1486 str = NULL;
1487 INTON;
1488 }
1489 parsebackquote = savepbq;
1490 handler = savehandler;
1491 if (arinest || ISDBLQUOTE())
1492 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1493 else
1494 USTPUTC(CTLBACKQ, out);
1495 if (oldstyle)
1496 goto parsebackq_oldreturn;
1497 else
1498 goto parsebackq_newreturn;
1499 }
1500
1501 /*
1502 * Parse an arithmetic expansion (indicate start of one and set state)
1503 */
1504 parsearith: {
1505
1506 if (++arinest == 1) {
1507 prevsyntax = syntax;
1508 syntax = ARISYNTAX;
1509 USTPUTC(CTLARI, out);
1510 if (ISDBLQUOTE())
1511 USTPUTC('"',out);
1512 else
1513 USTPUTC(' ',out);
1514 } else {
1515 /*
1516 * we collapse embedded arithmetic expansion to
1517 * parenthesis, which should be equivalent
1518 */
1519 USTPUTC('(', out);
1520 }
1521 goto parsearith_return;
1522 }
1523
1524 } /* end of readtoken */
1525
1526
1527
1528 #ifdef mkinit
1529 RESET {
1530 tokpushback = 0;
1531 checkkwd = 0;
1532 }
1533 #endif
1534
1535 /*
1536 * Returns true if the text contains nothing to expand (no dollar signs
1537 * or backquotes).
1538 */
1539
1540 STATIC int
1541 noexpand(char *text)
1542 {
1543 char *p;
1544 char c;
1545
1546 p = text;
1547 while ((c = *p++) != '\0') {
1548 if (c == CTLQUOTEMARK)
1549 continue;
1550 if (c == CTLESC)
1551 p++;
1552 else if (BASESYNTAX[(int)c] == CCTL)
1553 return 0;
1554 }
1555 return 1;
1556 }
1557
1558
1559 /*
1560 * Return true if the argument is a legal variable name (a letter or
1561 * underscore followed by zero or more letters, underscores, and digits).
1562 */
1563
1564 int
1565 goodname(char *name)
1566 {
1567 char *p;
1568
1569 p = name;
1570 if (! is_name(*p))
1571 return 0;
1572 while (*++p) {
1573 if (! is_in_name(*p))
1574 return 0;
1575 }
1576 return 1;
1577 }
1578
1579
1580 /*
1581 * Called when an unexpected token is read during the parse. The argument
1582 * is the token that is expected, or -1 if more than one type of token can
1583 * occur at this point.
1584 */
1585
1586 STATIC void
1587 synexpect(int token)
1588 {
1589 char msg[64];
1590
1591 if (token >= 0) {
1592 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1593 tokname[lasttoken], tokname[token]);
1594 } else {
1595 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1596 }
1597 synerror(msg);
1598 /* NOTREACHED */
1599 }
1600
1601
1602 STATIC void
1603 synerror(const char *msg)
1604 {
1605 if (commandname)
1606 outfmt(&errout, "%s: %d: ", commandname, startlinno);
1607 else
1608 outfmt(&errout, "%s: ", getprogname());
1609 outfmt(&errout, "Syntax error: %s\n", msg);
1610 error((char *)NULL);
1611 /* NOTREACHED */
1612 }
1613
1614 STATIC void
1615 setprompt(int which)
1616 {
1617 whichprompt = which;
1618
1619 #ifndef SMALL
1620 if (!el)
1621 #endif
1622 out2str(getprompt(NULL));
1623 }
1624
1625 /*
1626 * called by editline -- any expansions to the prompt
1627 * should be added here.
1628 */
1629 const char *
1630 getprompt(void *unused)
1631 {
1632 switch (whichprompt) {
1633 case 0:
1634 return "";
1635 case 1:
1636 return ps1val();
1637 case 2:
1638 return ps2val();
1639 default:
1640 return "<internal prompt error>";
1641 }
1642 }
1643