parser.c revision 1.55 1 /* $NetBSD: parser.c,v 1.55 2003/08/07 09:05:37 agc 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.55 2003/08/07 09:05:37 agc 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 cp->type = NCLIST;
426 app = &cp->nclist.pattern;
427 for (;;) {
428 *app = ap = (union node *)stalloc(sizeof (struct narg));
429 ap->type = NARG;
430 ap->narg.text = wordtext;
431 ap->narg.backquote = backquotelist;
432 if (checkkwd = 2, readtoken() != TPIPE)
433 break;
434 app = &ap->narg.next;
435 readtoken();
436 }
437 ap->narg.next = NULL;
438 noalias = 0;
439 if (lasttoken != TRP) {
440 synexpect(TRP);
441 }
442 cp->nclist.body = list(0);
443
444 checkkwd = 2;
445 if ((t = readtoken()) != TESAC) {
446 if (t != TENDCASE) {
447 noalias = 0;
448 synexpect(TENDCASE);
449 } else {
450 noalias = 1;
451 checkkwd = 2;
452 readtoken();
453 }
454 }
455 cpp = &cp->nclist.next;
456 } while(lasttoken != TESAC);
457 noalias = 0;
458 *cpp = NULL;
459 checkkwd = 1;
460 break;
461 case TLP:
462 n1 = (union node *)stalloc(sizeof (struct nredir));
463 n1->type = NSUBSHELL;
464 n1->nredir.n = list(0);
465 n1->nredir.redirect = NULL;
466 if (readtoken() != TRP)
467 synexpect(TRP);
468 checkkwd = 1;
469 break;
470 case TBEGIN:
471 n1 = list(0);
472 if (readtoken() != TEND)
473 synexpect(TEND);
474 checkkwd = 1;
475 break;
476 /* Handle an empty command like other simple commands. */
477 case TSEMI:
478 /*
479 * An empty command before a ; doesn't make much sense, and
480 * should certainly be disallowed in the case of `if ;'.
481 */
482 if (!redir)
483 synexpect(-1);
484 case TAND:
485 case TOR:
486 case TNL:
487 case TEOF:
488 case TWORD:
489 case TRP:
490 tokpushback++;
491 n1 = simplecmd(rpp, redir);
492 goto checkneg;
493 default:
494 synexpect(-1);
495 /* NOTREACHED */
496 }
497
498 /* Now check for redirection which may follow command */
499 while (readtoken() == TREDIR) {
500 *rpp = n2 = redirnode;
501 rpp = &n2->nfile.next;
502 parsefname();
503 }
504 tokpushback++;
505 *rpp = NULL;
506 if (redir) {
507 if (n1->type != NSUBSHELL) {
508 n2 = (union node *)stalloc(sizeof (struct nredir));
509 n2->type = NREDIR;
510 n2->nredir.n = n1;
511 n1 = n2;
512 }
513 n1->nredir.redirect = redir;
514 }
515
516 checkneg:
517 if (negate) {
518 n2 = (union node *)stalloc(sizeof (struct nnot));
519 n2->type = NNOT;
520 n2->nnot.com = n1;
521 return n2;
522 }
523 else
524 return n1;
525 }
526
527
528 STATIC union node *
529 simplecmd(union node **rpp, union node *redir)
530 {
531 union node *args, **app;
532 union node **orig_rpp = rpp;
533 union node *n = NULL, *n2;
534 int negate = 0;
535
536 /* If we don't have any redirections already, then we must reset */
537 /* rpp to be the address of the local redir variable. */
538 if (redir == 0)
539 rpp = &redir;
540
541 args = NULL;
542 app = &args;
543 /*
544 * We save the incoming value, because we need this for shell
545 * functions. There can not be a redirect or an argument between
546 * the function name and the open parenthesis.
547 */
548 orig_rpp = rpp;
549
550 while (readtoken() == TNOT) {
551 TRACE(("command: TNOT recognized\n"));
552 negate = !negate;
553 }
554 tokpushback++;
555
556 for (;;) {
557 if (readtoken() == TWORD) {
558 n = (union node *)stalloc(sizeof (struct narg));
559 n->type = NARG;
560 n->narg.text = wordtext;
561 n->narg.backquote = backquotelist;
562 *app = n;
563 app = &n->narg.next;
564 } else if (lasttoken == TREDIR) {
565 *rpp = n = redirnode;
566 rpp = &n->nfile.next;
567 parsefname(); /* read name of redirection file */
568 } else if (lasttoken == TLP && app == &args->narg.next
569 && rpp == orig_rpp) {
570 /* We have a function */
571 if (readtoken() != TRP)
572 synexpect(TRP);
573 #ifdef notdef
574 if (! goodname(n->narg.text))
575 synerror("Bad function name");
576 #endif
577 n->type = NDEFUN;
578 n->narg.next = command();
579 goto checkneg;
580 } else {
581 tokpushback++;
582 break;
583 }
584 }
585 *app = NULL;
586 *rpp = NULL;
587 n = (union node *)stalloc(sizeof (struct ncmd));
588 n->type = NCMD;
589 n->ncmd.backgnd = 0;
590 n->ncmd.args = args;
591 n->ncmd.redirect = redir;
592
593 checkneg:
594 if (negate) {
595 n2 = (union node *)stalloc(sizeof (struct nnot));
596 n2->type = NNOT;
597 n2->nnot.com = n;
598 return n2;
599 }
600 else
601 return n;
602 }
603
604 STATIC union node *
605 makename(void)
606 {
607 union node *n;
608
609 n = (union node *)stalloc(sizeof (struct narg));
610 n->type = NARG;
611 n->narg.next = NULL;
612 n->narg.text = wordtext;
613 n->narg.backquote = backquotelist;
614 return n;
615 }
616
617 void fixredir(union node *n, const char *text, int err)
618 {
619 TRACE(("Fix redir %s %d\n", text, err));
620 if (!err)
621 n->ndup.vname = NULL;
622
623 if (is_digit(text[0]) && text[1] == '\0')
624 n->ndup.dupfd = digit_val(text[0]);
625 else if (text[0] == '-' && text[1] == '\0')
626 n->ndup.dupfd = -1;
627 else {
628
629 if (err)
630 synerror("Bad fd number");
631 else
632 n->ndup.vname = makename();
633 }
634 }
635
636
637 STATIC void
638 parsefname(void)
639 {
640 union node *n = redirnode;
641
642 if (readtoken() != TWORD)
643 synexpect(-1);
644 if (n->type == NHERE) {
645 struct heredoc *here = heredoc;
646 struct heredoc *p;
647 int i;
648
649 if (quoteflag == 0)
650 n->type = NXHERE;
651 TRACE(("Here document %d\n", n->type));
652 if (here->striptabs) {
653 while (*wordtext == '\t')
654 wordtext++;
655 }
656 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
657 synerror("Illegal eof marker for << redirection");
658 rmescapes(wordtext);
659 here->eofmark = wordtext;
660 here->next = NULL;
661 if (heredoclist == NULL)
662 heredoclist = here;
663 else {
664 for (p = heredoclist ; p->next ; p = p->next);
665 p->next = here;
666 }
667 } else if (n->type == NTOFD || n->type == NFROMFD) {
668 fixredir(n, wordtext, 0);
669 } else {
670 n->nfile.fname = makename();
671 }
672 }
673
674
675 /*
676 * Input any here documents.
677 */
678
679 STATIC void
680 parseheredoc(void)
681 {
682 struct heredoc *here;
683 union node *n;
684
685 while (heredoclist) {
686 here = heredoclist;
687 heredoclist = here->next;
688 if (needprompt) {
689 setprompt(2);
690 needprompt = 0;
691 }
692 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
693 here->eofmark, here->striptabs);
694 n = (union node *)stalloc(sizeof (struct narg));
695 n->narg.type = NARG;
696 n->narg.next = NULL;
697 n->narg.text = wordtext;
698 n->narg.backquote = backquotelist;
699 here->here->nhere.doc = n;
700 }
701 }
702
703 STATIC int
704 peektoken(void)
705 {
706 int t;
707
708 t = readtoken();
709 tokpushback++;
710 return (t);
711 }
712
713 STATIC int
714 readtoken(void)
715 {
716 int t;
717 int savecheckkwd = checkkwd;
718 #ifdef DEBUG
719 int alreadyseen = tokpushback;
720 #endif
721 struct alias *ap;
722
723 top:
724 t = xxreadtoken();
725
726 if (checkkwd) {
727 /*
728 * eat newlines
729 */
730 if (checkkwd == 2) {
731 checkkwd = 0;
732 while (t == TNL) {
733 parseheredoc();
734 t = xxreadtoken();
735 }
736 } else
737 checkkwd = 0;
738 /*
739 * check for keywords and aliases
740 */
741 if (t == TWORD && !quoteflag)
742 {
743 const char *const *pp;
744
745 for (pp = parsekwd; *pp; pp++) {
746 if (**pp == *wordtext && equal(*pp, wordtext))
747 {
748 lasttoken = t = pp -
749 parsekwd + KWDOFFSET;
750 TRACE(("keyword %s recognized\n", tokname[t]));
751 goto out;
752 }
753 }
754 if(!noalias &&
755 (ap = lookupalias(wordtext, 1)) != NULL) {
756 pushstring(ap->val, strlen(ap->val), ap);
757 checkkwd = savecheckkwd;
758 goto top;
759 }
760 }
761 out:
762 checkkwd = (t == TNOT) ? savecheckkwd : 0;
763 }
764 #ifdef DEBUG
765 if (!alreadyseen)
766 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
767 else
768 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
769 #endif
770 return (t);
771 }
772
773
774 /*
775 * Read the next input token.
776 * If the token is a word, we set backquotelist to the list of cmds in
777 * backquotes. We set quoteflag to true if any part of the word was
778 * quoted.
779 * If the token is TREDIR, then we set redirnode to a structure containing
780 * the redirection.
781 * In all cases, the variable startlinno is set to the number of the line
782 * on which the token starts.
783 *
784 * [Change comment: here documents and internal procedures]
785 * [Readtoken shouldn't have any arguments. Perhaps we should make the
786 * word parsing code into a separate routine. In this case, readtoken
787 * doesn't need to have any internal procedures, but parseword does.
788 * We could also make parseoperator in essence the main routine, and
789 * have parseword (readtoken1?) handle both words and redirection.]
790 */
791
792 #define RETURN(token) return lasttoken = token
793
794 STATIC int
795 xxreadtoken(void)
796 {
797 int c;
798
799 if (tokpushback) {
800 tokpushback = 0;
801 return lasttoken;
802 }
803 if (needprompt) {
804 setprompt(2);
805 needprompt = 0;
806 }
807 startlinno = plinno;
808 for (;;) { /* until token or start of word found */
809 c = pgetc_macro();
810 if (c == ' ' || c == '\t')
811 continue; /* quick check for white space first */
812 switch (c) {
813 case ' ': case '\t':
814 continue;
815 case '#':
816 while ((c = pgetc()) != '\n' && c != PEOF);
817 pungetc();
818 continue;
819 case '\\':
820 if (pgetc() == '\n') {
821 startlinno = ++plinno;
822 if (doprompt)
823 setprompt(2);
824 else
825 setprompt(0);
826 continue;
827 }
828 pungetc();
829 goto breakloop;
830 case '\n':
831 plinno++;
832 needprompt = doprompt;
833 RETURN(TNL);
834 case PEOF:
835 RETURN(TEOF);
836 case '&':
837 if (pgetc() == '&')
838 RETURN(TAND);
839 pungetc();
840 RETURN(TBACKGND);
841 case '|':
842 if (pgetc() == '|')
843 RETURN(TOR);
844 pungetc();
845 RETURN(TPIPE);
846 case ';':
847 if (pgetc() == ';')
848 RETURN(TENDCASE);
849 pungetc();
850 RETURN(TSEMI);
851 case '(':
852 RETURN(TLP);
853 case ')':
854 RETURN(TRP);
855 default:
856 goto breakloop;
857 }
858 }
859 breakloop:
860 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
861 #undef RETURN
862 }
863
864
865
866 /*
867 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
868 * is not NULL, read a here document. In the latter case, eofmark is the
869 * word which marks the end of the document and striptabs is true if
870 * leading tabs should be stripped from the document. The argument firstc
871 * is the first character of the input token or document.
872 *
873 * Because C does not have internal subroutines, I have simulated them
874 * using goto's to implement the subroutine linkage. The following macros
875 * will run code that appears at the end of readtoken1.
876 */
877
878 #define CHECKEND() {goto checkend; checkend_return:;}
879 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
880 #define PARSESUB() {goto parsesub; parsesub_return:;}
881 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
882 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
883 #define PARSEARITH() {goto parsearith; parsearith_return:;}
884
885 /*
886 * Keep track of nested doublequotes in dblquote and doublequotep.
887 * We use dblquote for the first 32 levels, and we expand to a malloc'ed
888 * region for levels above that. Usually we never need to malloc.
889 * This code assumes that an int is 32 bits. We don't use uint32_t,
890 * because the rest of the code does not.
891 */
892 #define ISDBLQUOTE() ((varnest < 32) ? (dblquote & (1 << varnest)) : \
893 (dblquotep[(varnest / 32) - 1] & (1 << (varnest % 32))))
894
895 #define SETDBLQUOTE() \
896 if (varnest < 32) \
897 dblquote |= (1 << varnest); \
898 else \
899 dblquotep[(varnest / 32) - 1] |= (1 << (varnest % 32))
900
901 #define CLRDBLQUOTE() \
902 if (varnest < 32) \
903 dblquote &= ~(1 << varnest); \
904 else \
905 dblquotep[(varnest / 32) - 1] &= ~(1 << (varnest % 32))
906
907 STATIC int
908 readtoken1(int firstc, char const *syntax, char *eofmark, int striptabs)
909 {
910 int c = firstc;
911 char *out;
912 int len;
913 char line[EOFMARKLEN + 1];
914 struct nodelist *bqlist;
915 int quotef;
916 int *dblquotep = NULL;
917 size_t maxnest = 32;
918 int dblquote;
919 int varnest; /* levels of variables expansion */
920 int arinest; /* levels of arithmetic expansion */
921 int parenlevel; /* levels of parens in arithmetic */
922 int oldstyle;
923 char const *prevsyntax; /* syntax before arithmetic */
924 #if __GNUC__
925 /* Avoid longjmp clobbering */
926 (void) &maxnest;
927 (void) &dblquotep;
928 (void) &out;
929 (void) "ef;
930 (void) &dblquote;
931 (void) &varnest;
932 (void) &arinest;
933 (void) &parenlevel;
934 (void) &oldstyle;
935 (void) &prevsyntax;
936 (void) &syntax;
937 #endif
938
939 startlinno = plinno;
940 dblquote = 0;
941 varnest = 0;
942 if (syntax == DQSYNTAX) {
943 SETDBLQUOTE();
944 }
945 quotef = 0;
946 bqlist = NULL;
947 arinest = 0;
948 parenlevel = 0;
949
950 STARTSTACKSTR(out);
951 loop: { /* for each line, until end of word */
952 #if ATTY
953 if (c == '\034' && doprompt
954 && attyset() && ! equal(termval(), "emacs")) {
955 attyline();
956 if (syntax == BASESYNTAX)
957 return readtoken();
958 c = pgetc();
959 goto loop;
960 }
961 #endif
962 CHECKEND(); /* set c to PEOF if at end of here document */
963 for (;;) { /* until end of line or end of word */
964 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
965 switch(syntax[c]) {
966 case CNL: /* '\n' */
967 if (syntax == BASESYNTAX)
968 goto endword; /* exit outer loop */
969 USTPUTC(c, out);
970 plinno++;
971 if (doprompt)
972 setprompt(2);
973 else
974 setprompt(0);
975 c = pgetc();
976 goto loop; /* continue outer loop */
977 case CWORD:
978 USTPUTC(c, out);
979 break;
980 case CCTL:
981 if (eofmark == NULL || ISDBLQUOTE())
982 USTPUTC(CTLESC, out);
983 USTPUTC(c, out);
984 break;
985 case CBACK: /* backslash */
986 c = pgetc();
987 if (c == PEOF) {
988 USTPUTC('\\', out);
989 pungetc();
990 } else if (c == '\n') {
991 if (doprompt)
992 setprompt(2);
993 else
994 setprompt(0);
995 } else {
996 if (ISDBLQUOTE() && c != '\\' &&
997 c != '`' && c != '$' &&
998 (c != '"' || eofmark != NULL))
999 USTPUTC('\\', out);
1000 if (SQSYNTAX[c] == CCTL)
1001 USTPUTC(CTLESC, out);
1002 else if (eofmark == NULL)
1003 USTPUTC(CTLQUOTEMARK, out);
1004 USTPUTC(c, out);
1005 quotef++;
1006 }
1007 break;
1008 case CSQUOTE:
1009 if (syntax != SQSYNTAX) {
1010 if (eofmark == NULL)
1011 USTPUTC(CTLQUOTEMARK, out);
1012 syntax = SQSYNTAX;
1013 break;
1014 }
1015 /* FALLTHROUGH */
1016 case CDQUOTE:
1017 if (eofmark != NULL && arinest == 0 &&
1018 varnest == 0) {
1019 USTPUTC(c, out);
1020 } else {
1021 if (arinest) {
1022 if (c != '"' || ISDBLQUOTE()) {
1023 syntax = ARISYNTAX;
1024 CLRDBLQUOTE();
1025 } else {
1026 syntax = DQSYNTAX;
1027 SETDBLQUOTE();
1028 USTPUTC(CTLQUOTEMARK, out);
1029 }
1030 } else if (eofmark == NULL) {
1031 if (c != '"' || ISDBLQUOTE()) {
1032 syntax = BASESYNTAX;
1033 CLRDBLQUOTE();
1034 } else {
1035 syntax = DQSYNTAX;
1036 SETDBLQUOTE();
1037 USTPUTC(CTLQUOTEMARK, out);
1038 }
1039 }
1040 quotef++;
1041 }
1042 break;
1043 case CVAR: /* '$' */
1044 PARSESUB(); /* parse substitution */
1045 break;
1046 case CENDVAR: /* CLOSEBRACE */
1047 if (varnest > 0 && !ISDBLQUOTE()) {
1048 varnest--;
1049 USTPUTC(CTLENDVAR, out);
1050 } else {
1051 USTPUTC(c, out);
1052 }
1053 break;
1054 case CLP: /* '(' in arithmetic */
1055 parenlevel++;
1056 USTPUTC(c, out);
1057 break;
1058 case CRP: /* ')' in arithmetic */
1059 if (parenlevel > 0) {
1060 USTPUTC(c, out);
1061 --parenlevel;
1062 } else {
1063 if (pgetc() == ')') {
1064 if (--arinest == 0) {
1065 USTPUTC(CTLENDARI, out);
1066 syntax = prevsyntax;
1067 if (syntax == DQSYNTAX)
1068 SETDBLQUOTE();
1069 else
1070 CLRDBLQUOTE();
1071 } else
1072 USTPUTC(')', out);
1073 } else {
1074 /*
1075 * unbalanced parens
1076 * (don't 2nd guess - no error)
1077 */
1078 pungetc();
1079 USTPUTC(')', out);
1080 }
1081 }
1082 break;
1083 case CBQUOTE: /* '`' */
1084 PARSEBACKQOLD();
1085 break;
1086 case CEOF:
1087 goto endword; /* exit outer loop */
1088 default:
1089 if (varnest == 0)
1090 goto endword; /* exit outer loop */
1091 USTPUTC(c, out);
1092 }
1093 c = pgetc_macro();
1094 }
1095 }
1096 endword:
1097 if (syntax == ARISYNTAX)
1098 synerror("Missing '))'");
1099 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
1100 synerror("Unterminated quoted string");
1101 if (varnest != 0) {
1102 startlinno = plinno;
1103 /* { */
1104 synerror("Missing '}'");
1105 }
1106 USTPUTC('\0', out);
1107 len = out - stackblock();
1108 out = stackblock();
1109 if (eofmark == NULL) {
1110 if ((c == '>' || c == '<')
1111 && quotef == 0
1112 && len <= 2
1113 && (*out == '\0' || is_digit(*out))) {
1114 PARSEREDIR();
1115 return lasttoken = TREDIR;
1116 } else {
1117 pungetc();
1118 }
1119 }
1120 quoteflag = quotef;
1121 backquotelist = bqlist;
1122 grabstackblock(len);
1123 wordtext = out;
1124 if (dblquotep != NULL)
1125 ckfree(dblquotep);
1126 return lasttoken = TWORD;
1127 /* end of readtoken routine */
1128
1129
1130
1131 /*
1132 * Check to see whether we are at the end of the here document. When this
1133 * is called, c is set to the first character of the next input line. If
1134 * we are at the end of the here document, this routine sets the c to PEOF.
1135 */
1136
1137 checkend: {
1138 if (eofmark) {
1139 if (striptabs) {
1140 while (c == '\t')
1141 c = pgetc();
1142 }
1143 if (c == *eofmark) {
1144 if (pfgets(line, sizeof line) != NULL) {
1145 char *p, *q;
1146
1147 p = line;
1148 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1149 if (*p == '\n' && *q == '\0') {
1150 c = PEOF;
1151 plinno++;
1152 needprompt = doprompt;
1153 } else {
1154 pushstring(line, strlen(line), NULL);
1155 }
1156 }
1157 }
1158 }
1159 goto checkend_return;
1160 }
1161
1162
1163 /*
1164 * Parse a redirection operator. The variable "out" points to a string
1165 * specifying the fd to be redirected. The variable "c" contains the
1166 * first character of the redirection operator.
1167 */
1168
1169 parseredir: {
1170 char fd = *out;
1171 union node *np;
1172
1173 np = (union node *)stalloc(sizeof (struct nfile));
1174 if (c == '>') {
1175 np->nfile.fd = 1;
1176 c = pgetc();
1177 if (c == '>')
1178 np->type = NAPPEND;
1179 else if (c == '|')
1180 np->type = NCLOBBER;
1181 else if (c == '&')
1182 np->type = NTOFD;
1183 else {
1184 np->type = NTO;
1185 pungetc();
1186 }
1187 } else { /* c == '<' */
1188 np->nfile.fd = 0;
1189 switch (c = pgetc()) {
1190 case '<':
1191 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1192 np = (union node *)stalloc(sizeof (struct nhere));
1193 np->nfile.fd = 0;
1194 }
1195 np->type = NHERE;
1196 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1197 heredoc->here = np;
1198 if ((c = pgetc()) == '-') {
1199 heredoc->striptabs = 1;
1200 } else {
1201 heredoc->striptabs = 0;
1202 pungetc();
1203 }
1204 break;
1205
1206 case '&':
1207 np->type = NFROMFD;
1208 break;
1209
1210 case '>':
1211 np->type = NFROMTO;
1212 break;
1213
1214 default:
1215 np->type = NFROM;
1216 pungetc();
1217 break;
1218 }
1219 }
1220 if (fd != '\0')
1221 np->nfile.fd = digit_val(fd);
1222 redirnode = np;
1223 goto parseredir_return;
1224 }
1225
1226
1227 /*
1228 * Parse a substitution. At this point, we have read the dollar sign
1229 * and nothing else.
1230 */
1231
1232 parsesub: {
1233 int subtype;
1234 int typeloc;
1235 int flags;
1236 char *p;
1237 static const char types[] = "}-+?=";
1238
1239 c = pgetc();
1240 if (c != '(' && c != OPENBRACE && !is_name(c) && !is_special(c)) {
1241 USTPUTC('$', out);
1242 pungetc();
1243 } else if (c == '(') { /* $(command) or $((arith)) */
1244 if (pgetc() == '(') {
1245 PARSEARITH();
1246 } else {
1247 pungetc();
1248 PARSEBACKQNEW();
1249 }
1250 } else {
1251 USTPUTC(CTLVAR, out);
1252 typeloc = out - stackblock();
1253 USTPUTC(VSNORMAL, out);
1254 subtype = VSNORMAL;
1255 if (c == OPENBRACE) {
1256 c = pgetc();
1257 if (c == '#') {
1258 if ((c = pgetc()) == CLOSEBRACE)
1259 c = '#';
1260 else
1261 subtype = VSLENGTH;
1262 }
1263 else
1264 subtype = 0;
1265 }
1266 if (is_name(c)) {
1267 do {
1268 STPUTC(c, out);
1269 c = pgetc();
1270 } while (is_in_name(c));
1271 } else if (is_digit(c)) {
1272 do {
1273 USTPUTC(c, out);
1274 c = pgetc();
1275 } while (is_digit(c));
1276 }
1277 else if (is_special(c)) {
1278 USTPUTC(c, out);
1279 c = pgetc();
1280 }
1281 else
1282 badsub: synerror("Bad substitution");
1283
1284 STPUTC('=', out);
1285 flags = 0;
1286 if (subtype == 0) {
1287 switch (c) {
1288 case ':':
1289 flags = VSNUL;
1290 c = pgetc();
1291 /*FALLTHROUGH*/
1292 default:
1293 p = strchr(types, c);
1294 if (p == NULL)
1295 goto badsub;
1296 subtype = p - types + VSNORMAL;
1297 break;
1298 case '%':
1299 case '#':
1300 {
1301 int cc = c;
1302 subtype = c == '#' ? VSTRIMLEFT :
1303 VSTRIMRIGHT;
1304 c = pgetc();
1305 if (c == cc)
1306 subtype++;
1307 else
1308 pungetc();
1309 break;
1310 }
1311 }
1312 } else {
1313 pungetc();
1314 }
1315 if (ISDBLQUOTE() || arinest)
1316 flags |= VSQUOTE;
1317 *(stackblock() + typeloc) = subtype | flags;
1318 if (subtype != VSNORMAL) {
1319 varnest++;
1320 if (varnest >= maxnest) {
1321 dblquotep = ckrealloc(dblquotep, maxnest / 8);
1322 dblquotep[(maxnest / 32) - 1] = 0;
1323 maxnest += 32;
1324 }
1325 }
1326 }
1327 goto parsesub_return;
1328 }
1329
1330
1331 /*
1332 * Called to parse command substitutions. Newstyle is set if the command
1333 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
1334 * list of commands (passed by reference), and savelen is the number of
1335 * characters on the top of the stack which must be preserved.
1336 */
1337
1338 parsebackq: {
1339 struct nodelist **nlpp;
1340 int savepbq;
1341 union node *n;
1342 char *volatile str;
1343 struct jmploc jmploc;
1344 struct jmploc *volatile savehandler;
1345 int savelen;
1346 int saveprompt;
1347 #ifdef __GNUC__
1348 (void) &saveprompt;
1349 #endif
1350
1351 savepbq = parsebackquote;
1352 if (setjmp(jmploc.loc)) {
1353 if (str)
1354 ckfree(str);
1355 parsebackquote = 0;
1356 handler = savehandler;
1357 longjmp(handler->loc, 1);
1358 }
1359 INTOFF;
1360 str = NULL;
1361 savelen = out - stackblock();
1362 if (savelen > 0) {
1363 str = ckmalloc(savelen);
1364 memcpy(str, stackblock(), savelen);
1365 }
1366 savehandler = handler;
1367 handler = &jmploc;
1368 INTON;
1369 if (oldstyle) {
1370 /* We must read until the closing backquote, giving special
1371 treatment to some slashes, and then push the string and
1372 reread it as input, interpreting it normally. */
1373 char *pout;
1374 int pc;
1375 int psavelen;
1376 char *pstr;
1377
1378
1379 STARTSTACKSTR(pout);
1380 for (;;) {
1381 if (needprompt) {
1382 setprompt(2);
1383 needprompt = 0;
1384 }
1385 switch (pc = pgetc()) {
1386 case '`':
1387 goto done;
1388
1389 case '\\':
1390 if ((pc = pgetc()) == '\n') {
1391 plinno++;
1392 if (doprompt)
1393 setprompt(2);
1394 else
1395 setprompt(0);
1396 /*
1397 * If eating a newline, avoid putting
1398 * the newline into the new character
1399 * stream (via the STPUTC after the
1400 * switch).
1401 */
1402 continue;
1403 }
1404 if (pc != '\\' && pc != '`' && pc != '$'
1405 && (!ISDBLQUOTE() || pc != '"'))
1406 STPUTC('\\', pout);
1407 break;
1408
1409 case '\n':
1410 plinno++;
1411 needprompt = doprompt;
1412 break;
1413
1414 case PEOF:
1415 startlinno = plinno;
1416 synerror("EOF in backquote substitution");
1417 break;
1418
1419 default:
1420 break;
1421 }
1422 STPUTC(pc, pout);
1423 }
1424 done:
1425 STPUTC('\0', pout);
1426 psavelen = pout - stackblock();
1427 if (psavelen > 0) {
1428 pstr = grabstackstr(pout);
1429 setinputstring(pstr, 1);
1430 }
1431 }
1432 nlpp = &bqlist;
1433 while (*nlpp)
1434 nlpp = &(*nlpp)->next;
1435 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1436 (*nlpp)->next = NULL;
1437 parsebackquote = oldstyle;
1438
1439 if (oldstyle) {
1440 saveprompt = doprompt;
1441 doprompt = 0;
1442 }
1443
1444 n = list(0);
1445
1446 if (oldstyle)
1447 doprompt = saveprompt;
1448 else {
1449 if (readtoken() != TRP)
1450 synexpect(TRP);
1451 }
1452
1453 (*nlpp)->n = n;
1454 if (oldstyle) {
1455 /*
1456 * Start reading from old file again, ignoring any pushed back
1457 * tokens left from the backquote parsing
1458 */
1459 popfile();
1460 tokpushback = 0;
1461 }
1462 while (stackblocksize() <= savelen)
1463 growstackblock();
1464 STARTSTACKSTR(out);
1465 if (str) {
1466 memcpy(out, str, savelen);
1467 STADJUST(savelen, out);
1468 INTOFF;
1469 ckfree(str);
1470 str = NULL;
1471 INTON;
1472 }
1473 parsebackquote = savepbq;
1474 handler = savehandler;
1475 if (arinest || ISDBLQUOTE())
1476 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1477 else
1478 USTPUTC(CTLBACKQ, out);
1479 if (oldstyle)
1480 goto parsebackq_oldreturn;
1481 else
1482 goto parsebackq_newreturn;
1483 }
1484
1485 /*
1486 * Parse an arithmetic expansion (indicate start of one and set state)
1487 */
1488 parsearith: {
1489
1490 if (++arinest == 1) {
1491 prevsyntax = syntax;
1492 syntax = ARISYNTAX;
1493 USTPUTC(CTLARI, out);
1494 if (ISDBLQUOTE())
1495 USTPUTC('"',out);
1496 else
1497 USTPUTC(' ',out);
1498 } else {
1499 /*
1500 * we collapse embedded arithmetic expansion to
1501 * parenthesis, which should be equivalent
1502 */
1503 USTPUTC('(', out);
1504 }
1505 goto parsearith_return;
1506 }
1507
1508 } /* end of readtoken */
1509
1510
1511
1512 #ifdef mkinit
1513 RESET {
1514 tokpushback = 0;
1515 checkkwd = 0;
1516 }
1517 #endif
1518
1519 /*
1520 * Returns true if the text contains nothing to expand (no dollar signs
1521 * or backquotes).
1522 */
1523
1524 STATIC int
1525 noexpand(char *text)
1526 {
1527 char *p;
1528 char c;
1529
1530 p = text;
1531 while ((c = *p++) != '\0') {
1532 if (c == CTLQUOTEMARK)
1533 continue;
1534 if (c == CTLESC)
1535 p++;
1536 else if (BASESYNTAX[(int)c] == CCTL)
1537 return 0;
1538 }
1539 return 1;
1540 }
1541
1542
1543 /*
1544 * Return true if the argument is a legal variable name (a letter or
1545 * underscore followed by zero or more letters, underscores, and digits).
1546 */
1547
1548 int
1549 goodname(char *name)
1550 {
1551 char *p;
1552
1553 p = name;
1554 if (! is_name(*p))
1555 return 0;
1556 while (*++p) {
1557 if (! is_in_name(*p))
1558 return 0;
1559 }
1560 return 1;
1561 }
1562
1563
1564 /*
1565 * Called when an unexpected token is read during the parse. The argument
1566 * is the token that is expected, or -1 if more than one type of token can
1567 * occur at this point.
1568 */
1569
1570 STATIC void
1571 synexpect(int token)
1572 {
1573 char msg[64];
1574
1575 if (token >= 0) {
1576 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1577 tokname[lasttoken], tokname[token]);
1578 } else {
1579 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1580 }
1581 synerror(msg);
1582 /* NOTREACHED */
1583 }
1584
1585
1586 STATIC void
1587 synerror(const char *msg)
1588 {
1589 if (commandname)
1590 outfmt(&errout, "%s: %d: ", commandname, startlinno);
1591 outfmt(&errout, "Syntax error: %s\n", msg);
1592 error((char *)NULL);
1593 /* NOTREACHED */
1594 }
1595
1596 STATIC void
1597 setprompt(int which)
1598 {
1599 whichprompt = which;
1600
1601 #ifndef SMALL
1602 if (!el)
1603 #endif
1604 out2str(getprompt(NULL));
1605 }
1606
1607 /*
1608 * called by editline -- any expansions to the prompt
1609 * should be added here.
1610 */
1611 const char *
1612 getprompt(void *unused)
1613 {
1614 switch (whichprompt) {
1615 case 0:
1616 return "";
1617 case 1:
1618 return ps1val();
1619 case 2:
1620 return ps2val();
1621 default:
1622 return "<internal prompt error>";
1623 }
1624 }
1625