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