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