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