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