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