coverity appeasement
[minix.git] / commands / ash / parser.c
blob20d462a886e457fbb3984e94debf5e6366e9da47
1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)parser.c 8.7 (Berkeley) 5/16/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD: src/bin/sh/parser.c,v 1.51.2.1 2005/03/03 03:43:20 obrien Exp $");
43 #include <stdlib.h>
44 #include <unistd.h>
46 #include "shell.h"
47 #include "parser.h"
48 #include "nodes.h"
49 #include "expand.h" /* defines rmescapes() */
50 #include "syntax.h"
51 #include "options.h"
52 #include "input.h"
53 #include "output.h"
54 #include "var.h"
55 #include "error.h"
56 #include "memalloc.h"
57 #include "mystring.h"
58 #include "alias.h"
59 #include "show.h"
60 #include "eval.h"
61 #if !defined(NO_HISTORY) && !defined(EDITLINE)
62 #include "myhistedit.h"
63 #endif
66 * Shell command parser.
69 #define EOFMARKLEN 79
70 #define PROMPTLEN 128
72 /* values returned by readtoken */
73 #include "token.h"
77 struct heredoc {
78 struct heredoc *next; /* next here document in list */
79 union node *here; /* redirection node */
80 char *eofmark; /* string indicating end of input */
81 int striptabs; /* if set, strip leading tabs */
86 STATIC struct heredoc *heredoclist; /* list of here documents to read */
87 STATIC int parsebackquote; /* nonzero if we are inside backquotes */
88 STATIC int doprompt; /* if set, prompt the user */
89 STATIC int needprompt; /* true if interactive and at start of line */
90 STATIC int lasttoken; /* last token read */
91 MKINIT int tokpushback; /* last token pushed back */
92 STATIC char *wordtext; /* text of last word returned by readtoken */
93 MKINIT int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
94 STATIC struct nodelist *backquotelist;
95 STATIC union node *redirnode;
96 STATIC struct heredoc *heredoc;
97 STATIC int quoteflag; /* set if (part of) last token was quoted */
98 STATIC int startlinno; /* line # where last token started */
100 /* XXX When 'noaliases' is set to one, no alias expansion takes place. */
101 static int noaliases = 0;
103 #define GDB_HACK 1 /* avoid local declarations which gdb can't handle */
104 #ifdef GDB_HACK
105 static const char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'};
106 static const char types[] = "}-+?=";
107 #endif
110 STATIC union node *list(int);
111 STATIC union node *andor(void);
112 STATIC union node *pipeline(void);
113 STATIC union node *command(void);
114 STATIC union node *simplecmd(union node **, union node *);
115 STATIC union node *makename(void);
116 STATIC void parsefname(void);
117 STATIC void parseheredoc(void);
118 STATIC int peektoken(void);
119 STATIC int readtoken(void);
120 STATIC int xxreadtoken(void);
121 STATIC int readtoken1(int, char const *, char *, int);
122 STATIC int noexpand(char *);
123 STATIC void synexpect(int);
124 STATIC void synerror(char *);
125 STATIC void setprompt(int);
129 * Read and parse a command. Returns NEOF on end of file. (NULL is a
130 * valid parse tree indicating a blank line.)
133 union node *
134 parsecmd(int interact)
136 int t;
137 extern int exitstatus;
139 tokpushback = 0;
140 doprompt = interact;
141 if (doprompt)
142 setprompt(exitstatus == 0 || (vpse.flags & VUNSET)
143 ? 1 : -1);
144 else
145 setprompt(0);
146 needprompt = 0;
147 t = readtoken();
148 if (t == TEOF)
149 return NEOF;
150 if (t == TNL)
151 return NULL;
152 tokpushback++;
153 return list(1);
157 STATIC union node *
158 list(int nlflag)
160 union node *n1, *n2, *n3;
161 int tok;
163 checkkwd = 2;
164 if (nlflag == 0 && tokendlist[peektoken()])
165 return NULL;
166 n1 = NULL;
167 for (;;) {
168 n2 = andor();
169 tok = readtoken();
170 if (tok == TBACKGND) {
171 if (n2->type == NCMD || n2->type == NPIPE) {
172 n2->ncmd.backgnd = 1;
173 } else if (n2->type == NREDIR) {
174 n2->type = NBACKGND;
175 } else {
176 n3 = (union node *)stalloc(sizeof (struct nredir));
177 n3->type = NBACKGND;
178 n3->nredir.n = n2;
179 n3->nredir.redirect = NULL;
180 n2 = n3;
183 if (n1 == NULL) {
184 n1 = n2;
186 else {
187 n3 = (union node *)stalloc(sizeof (struct nbinary));
188 n3->type = NSEMI;
189 n3->nbinary.ch1 = n1;
190 n3->nbinary.ch2 = n2;
191 n1 = n3;
193 switch (tok) {
194 case TBACKGND:
195 case TSEMI:
196 tok = readtoken();
197 /* FALLTHROUGH */
198 case TNL:
199 if (tok == TNL) {
200 parseheredoc();
201 if (nlflag)
202 return n1;
203 } else {
204 tokpushback++;
206 checkkwd = 2;
207 if (tokendlist[peektoken()])
208 return n1;
209 break;
210 case TEOF:
211 if (heredoclist)
212 parseheredoc();
213 else
214 pungetc(); /* push back EOF on input */
215 return n1;
216 default:
217 if (nlflag)
218 synexpect(-1);
219 tokpushback++;
220 return n1;
227 STATIC union node *
228 andor(void)
230 union node *n1, *n2, *n3;
231 int t;
233 n1 = pipeline();
234 for (;;) {
235 if ((t = readtoken()) == TAND) {
236 t = NAND;
237 } else if (t == TOR) {
238 t = NOR;
239 } else {
240 tokpushback++;
241 return n1;
243 n2 = pipeline();
244 n3 = (union node *)stalloc(sizeof (struct nbinary));
245 n3->type = t;
246 n3->nbinary.ch1 = n1;
247 n3->nbinary.ch2 = n2;
248 n1 = n3;
254 STATIC union node *
255 pipeline(void)
257 union node *n1, *n2, *pipenode;
258 struct nodelist *lp, *prev;
259 int negate;
261 negate = 0;
262 TRACE(("pipeline: entered\n"));
263 while (readtoken() == TNOT)
264 negate = !negate;
265 tokpushback++;
266 n1 = command();
267 if (readtoken() == TPIPE) {
268 pipenode = (union node *)stalloc(sizeof (struct npipe));
269 pipenode->type = NPIPE;
270 pipenode->npipe.backgnd = 0;
271 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
272 pipenode->npipe.cmdlist = lp;
273 lp->n = n1;
274 do {
275 prev = lp;
276 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
277 lp->n = command();
278 prev->next = lp;
279 } while (readtoken() == TPIPE);
280 lp->next = NULL;
281 n1 = pipenode;
283 tokpushback++;
284 if (negate) {
285 n2 = (union node *)stalloc(sizeof (struct nnot));
286 n2->type = NNOT;
287 n2->nnot.com = n1;
288 return n2;
289 } else
290 return n1;
295 STATIC union node *
296 command(void)
298 union node *n1, *n2;
299 union node *ap, **app;
300 union node *cp, **cpp;
301 union node *redir, **rpp;
302 int t, negate = 0;
304 checkkwd = 2;
305 redir = NULL;
306 n1 = NULL;
307 rpp = &redir;
309 /* Check for redirection which may precede command */
310 while (readtoken() == TREDIR) {
311 *rpp = n2 = redirnode;
312 rpp = &n2->nfile.next;
313 parsefname();
315 tokpushback++;
317 while (readtoken() == TNOT) {
318 TRACE(("command: TNOT recognized\n"));
319 negate = !negate;
321 tokpushback++;
323 switch (readtoken()) {
324 case TIF:
325 n1 = (union node *)stalloc(sizeof (struct nif));
326 n1->type = NIF;
327 if ((n1->nif.test = list(0)) == NULL)
328 synexpect(-1);
329 if (readtoken() != TTHEN)
330 synexpect(TTHEN);
331 n1->nif.ifpart = list(0);
332 n2 = n1;
333 while (readtoken() == TELIF) {
334 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
335 n2 = n2->nif.elsepart;
336 n2->type = NIF;
337 if ((n2->nif.test = list(0)) == NULL)
338 synexpect(-1);
339 if (readtoken() != TTHEN)
340 synexpect(TTHEN);
341 n2->nif.ifpart = list(0);
343 if (lasttoken == TELSE)
344 n2->nif.elsepart = list(0);
345 else {
346 n2->nif.elsepart = NULL;
347 tokpushback++;
349 if (readtoken() != TFI)
350 synexpect(TFI);
351 checkkwd = 1;
352 break;
353 case TWHILE:
354 case TUNTIL: {
355 int got;
356 n1 = (union node *)stalloc(sizeof (struct nbinary));
357 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
358 if ((n1->nbinary.ch1 = list(0)) == NULL)
359 synexpect(-1);
360 if ((got=readtoken()) != TDO) {
361 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
362 synexpect(TDO);
364 n1->nbinary.ch2 = list(0);
365 if (readtoken() != TDONE)
366 synexpect(TDONE);
367 checkkwd = 1;
368 break;
370 case TFOR:
371 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
372 synerror("Bad for loop variable");
373 n1 = (union node *)stalloc(sizeof (struct nfor));
374 n1->type = NFOR;
375 n1->nfor.var = wordtext;
376 if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
377 app = &ap;
378 while (readtoken() == TWORD) {
379 n2 = (union node *)stalloc(sizeof (struct narg));
380 n2->type = NARG;
381 n2->narg.text = wordtext;
382 n2->narg.backquote = backquotelist;
383 *app = n2;
384 app = &n2->narg.next;
386 *app = NULL;
387 n1->nfor.args = ap;
388 if (lasttoken != TNL && lasttoken != TSEMI)
389 synexpect(-1);
390 } else {
391 #ifndef GDB_HACK
392 static const char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
393 '@', '=', '\0'};
394 #endif
395 n2 = (union node *)stalloc(sizeof (struct narg));
396 n2->type = NARG;
397 n2->narg.text = (char *)argvars;
398 n2->narg.backquote = NULL;
399 n2->narg.next = NULL;
400 n1->nfor.args = n2;
402 * Newline or semicolon here is optional (but note
403 * that the original Bourne shell only allowed NL).
405 if (lasttoken != TNL && lasttoken != TSEMI)
406 tokpushback++;
408 checkkwd = 2;
409 if ((t = readtoken()) == TDO)
410 t = TDONE;
411 else if (t == TBEGIN)
412 t = TEND;
413 else
414 synexpect(-1);
415 n1->nfor.body = list(0);
416 if (readtoken() != t)
417 synexpect(t);
418 checkkwd = 1;
419 break;
420 case TCASE:
421 n1 = (union node *)stalloc(sizeof (struct ncase));
422 n1->type = NCASE;
423 if (readtoken() != TWORD)
424 synexpect(TWORD);
425 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
426 n2->type = NARG;
427 n2->narg.text = wordtext;
428 n2->narg.backquote = backquotelist;
429 n2->narg.next = NULL;
430 while (readtoken() == TNL);
431 if (lasttoken != TWORD || ! equal(wordtext, "in"))
432 synerror("expecting \"in\"");
433 cpp = &n1->ncase.cases;
434 noaliases = 1; /* turn off alias expansion */
435 checkkwd = 2, readtoken();
436 while (lasttoken != TESAC) {
437 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
438 cp->type = NCLIST;
439 app = &cp->nclist.pattern;
440 if (lasttoken == TLP)
441 readtoken();
442 for (;;) {
443 *app = ap = (union node *)stalloc(sizeof (struct narg));
444 ap->type = NARG;
445 ap->narg.text = wordtext;
446 ap->narg.backquote = backquotelist;
447 if (checkkwd = 2, readtoken() != TPIPE)
448 break;
449 app = &ap->narg.next;
450 readtoken();
452 ap->narg.next = NULL;
453 if (lasttoken != TRP)
454 noaliases = 0, synexpect(TRP);
455 cp->nclist.body = list(0);
457 checkkwd = 2;
458 if ((t = readtoken()) != TESAC) {
459 if (t != TENDCASE)
460 noaliases = 0, synexpect(TENDCASE);
461 else
462 checkkwd = 2, readtoken();
464 cpp = &cp->nclist.next;
466 noaliases = 0; /* reset alias expansion */
467 *cpp = NULL;
468 checkkwd = 1;
469 break;
470 case TLP:
471 n1 = (union node *)stalloc(sizeof (struct nredir));
472 n1->type = NSUBSHELL;
473 n1->nredir.n = list(0);
474 n1->nredir.redirect = NULL;
475 if (readtoken() != TRP)
476 synexpect(TRP);
477 checkkwd = 1;
478 break;
479 case TBEGIN:
480 n1 = list(0);
481 if (readtoken() != TEND)
482 synexpect(TEND);
483 checkkwd = 1;
484 break;
485 /* Handle an empty command like other simple commands. */
486 case TSEMI:
487 case TAND:
488 case TOR:
490 * An empty command before a ; doesn't make much sense, and
491 * should certainly be disallowed in the case of `if ;'.
493 if (!redir)
494 synexpect(-1);
495 case TNL:
496 case TEOF:
497 case TWORD:
498 case TRP:
499 tokpushback++;
500 n1 = simplecmd(rpp, redir);
501 goto checkneg;
502 default:
503 synexpect(-1);
506 /* Now check for redirection which may follow command */
507 while (readtoken() == TREDIR) {
508 *rpp = n2 = redirnode;
509 rpp = &n2->nfile.next;
510 parsefname();
512 tokpushback++;
513 *rpp = NULL;
514 if (redir) {
515 if (n1->type != NSUBSHELL) {
516 n2 = (union node *)stalloc(sizeof (struct nredir));
517 n2->type = NREDIR;
518 n2->nredir.n = n1;
519 n1 = n2;
521 n1->nredir.redirect = redir;
524 checkneg:
525 if (negate) {
526 n2 = (union node *)stalloc(sizeof (struct nnot));
527 n2->type = NNOT;
528 n2->nnot.com = n1;
529 return n2;
531 else
532 return n1;
536 STATIC union node *
537 simplecmd(union node **rpp, union node *redir)
539 union node *args, **app;
540 union node **orig_rpp = rpp;
541 union node *n = NULL, *n2;
542 int negate = 0;
544 /* If we don't have any redirections already, then we must reset */
545 /* rpp to be the address of the local redir variable. */
546 if (redir == 0)
547 rpp = &redir;
549 args = NULL;
550 app = &args;
552 * We save the incoming value, because we need this for shell
553 * functions. There can not be a redirect or an argument between
554 * the function name and the open parenthesis.
556 orig_rpp = rpp;
558 while (readtoken() == TNOT) {
559 TRACE(("command: TNOT recognized\n"));
560 negate = !negate;
562 tokpushback++;
564 for (;;) {
565 if (readtoken() == TWORD) {
566 n = (union node *)stalloc(sizeof (struct narg));
567 n->type = NARG;
568 n->narg.text = wordtext;
569 n->narg.backquote = backquotelist;
570 *app = n;
571 app = &n->narg.next;
572 } else if (lasttoken == TREDIR) {
573 *rpp = n = redirnode;
574 rpp = &n->nfile.next;
575 parsefname(); /* read name of redirection file */
576 } else if (lasttoken == TLP && app == &args->narg.next
577 && rpp == orig_rpp) {
578 /* We have a function */
579 if (readtoken() != TRP)
580 synexpect(TRP);
581 #ifdef notdef
582 if (! goodname(n->narg.text))
583 synerror("Bad function name");
584 #endif
585 n->type = NDEFUN;
586 n->narg.next = command();
587 goto checkneg;
588 } else {
589 tokpushback++;
590 break;
593 *app = NULL;
594 *rpp = NULL;
595 n = (union node *)stalloc(sizeof (struct ncmd));
596 n->type = NCMD;
597 n->ncmd.backgnd = 0;
598 n->ncmd.args = args;
599 n->ncmd.redirect = redir;
601 checkneg:
602 if (negate) {
603 n2 = (union node *)stalloc(sizeof (struct nnot));
604 n2->type = NNOT;
605 n2->nnot.com = n;
606 return n2;
608 else
609 return n;
612 STATIC union node *
613 makename(void)
615 union node *n;
617 n = (union node *)stalloc(sizeof (struct narg));
618 n->type = NARG;
619 n->narg.next = NULL;
620 n->narg.text = wordtext;
621 n->narg.backquote = backquotelist;
622 return n;
625 void fixredir(union node *n, const char *text, int err)
627 TRACE(("Fix redir %s %d\n", text, err));
628 if (!err)
629 n->ndup.vname = NULL;
631 if (is_digit(text[0]) && text[1] == '\0')
632 n->ndup.dupfd = digit_val(text[0]);
633 else if (text[0] == '-' && text[1] == '\0')
634 n->ndup.dupfd = -1;
635 else {
637 if (err)
638 synerror("Bad fd number");
639 else
640 n->ndup.vname = makename();
645 STATIC void
646 parsefname(void)
648 union node *n = redirnode;
650 if (readtoken() != TWORD)
651 synexpect(-1);
652 if (n->type == NHERE) {
653 struct heredoc *here = heredoc;
654 struct heredoc *p;
655 int i;
657 if (quoteflag == 0)
658 n->type = NXHERE;
659 TRACE(("Here document %d\n", n->type));
660 if (here->striptabs) {
661 while (*wordtext == '\t')
662 wordtext++;
664 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
665 synerror("Illegal eof marker for << redirection");
666 rmescapes(wordtext);
667 here->eofmark = wordtext;
668 here->next = NULL;
669 if (heredoclist == NULL)
670 heredoclist = here;
671 else {
672 for (p = heredoclist ; p->next ; p = p->next);
673 p->next = here;
675 } else if (n->type == NTOFD || n->type == NFROMFD) {
676 fixredir(n, wordtext, 0);
677 } else {
678 n->nfile.fname = makename();
684 * Input any here documents.
687 STATIC void
688 parseheredoc(void)
690 struct heredoc *here;
691 union node *n;
693 while (heredoclist) {
694 here = heredoclist;
695 heredoclist = here->next;
696 if (needprompt) {
697 setprompt(2);
698 needprompt = 0;
700 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
701 here->eofmark, here->striptabs);
702 n = (union node *)stalloc(sizeof (struct narg));
703 n->narg.type = NARG;
704 n->narg.next = NULL;
705 n->narg.text = wordtext;
706 n->narg.backquote = backquotelist;
707 here->here->nhere.doc = n;
711 STATIC int
712 peektoken(void)
714 int t;
716 t = readtoken();
717 tokpushback++;
718 return (t);
721 STATIC int
722 readtoken(void)
724 int t;
725 int savecheckkwd = checkkwd;
726 struct alias *ap;
727 #if DEBUG
728 int alreadyseen = tokpushback;
729 #endif
731 top:
732 t = xxreadtoken();
734 if (checkkwd) {
736 * eat newlines
738 if (checkkwd == 2) {
739 checkkwd = 0;
740 while (t == TNL) {
741 parseheredoc();
742 t = xxreadtoken();
744 } else
745 checkkwd = 0;
747 * check for keywords and aliases
749 if (t == TWORD && !quoteflag)
751 const char * const *pp;
753 for (pp = parsekwd; *pp; pp++) {
754 if (**pp == *wordtext && equal(*pp, wordtext))
756 lasttoken = t = pp - parsekwd + KWDOFFSET;
757 TRACE(("keyword %s recognized\n", tokname[t]));
758 goto out;
761 if (noaliases == 0 &&
762 (ap = lookupalias(wordtext, 1)) != NULL) {
763 pushstring(ap->val, strlen(ap->val), ap);
764 checkkwd = savecheckkwd;
765 goto top;
768 out:
769 checkkwd = (t == TNOT) ? savecheckkwd : 0;
771 #if DEBUG
772 if (!alreadyseen)
773 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
774 else
775 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
776 #endif
777 return (t);
782 * Read the next input token.
783 * If the token is a word, we set backquotelist to the list of cmds in
784 * backquotes. We set quoteflag to true if any part of the word was
785 * quoted.
786 * If the token is TREDIR, then we set redirnode to a structure containing
787 * the redirection.
788 * In all cases, the variable startlinno is set to the number of the line
789 * on which the token starts.
791 * [Change comment: here documents and internal procedures]
792 * [Readtoken shouldn't have any arguments. Perhaps we should make the
793 * word parsing code into a separate routine. In this case, readtoken
794 * doesn't need to have any internal procedures, but parseword does.
795 * We could also make parseoperator in essence the main routine, and
796 * have parseword (readtoken1?) handle both words and redirection.]
799 #define RETURN(token) return lasttoken = token
801 STATIC int
802 xxreadtoken(void)
804 int c;
806 if (tokpushback) {
807 tokpushback = 0;
808 return lasttoken;
810 if (needprompt) {
811 setprompt(2);
812 needprompt = 0;
814 startlinno = plinno;
815 for (;;) { /* until token or start of word found */
816 c = pgetc_macro();
817 if (c == ' ' || c == '\t')
818 continue; /* quick check for white space first */
819 switch (c) {
820 case ' ': case '\t':
821 continue;
822 case '#':
823 while ((c = pgetc()) != '\n' && c != PEOF);
824 pungetc();
825 continue;
826 case '\\':
827 if (pgetc() == '\n') {
828 startlinno = ++plinno;
829 if (doprompt)
830 setprompt(2);
831 else
832 setprompt(0);
833 continue;
835 pungetc();
836 goto breakloop;
837 case '\n':
838 plinno++;
839 needprompt = doprompt;
840 RETURN(TNL);
841 case PEOF:
842 RETURN(TEOF);
843 case '&':
844 if (pgetc() == '&')
845 RETURN(TAND);
846 pungetc();
847 RETURN(TBACKGND);
848 case '|':
849 if (pgetc() == '|')
850 RETURN(TOR);
851 pungetc();
852 RETURN(TPIPE);
853 case ';':
854 if (pgetc() == ';')
855 RETURN(TENDCASE);
856 pungetc();
857 RETURN(TSEMI);
858 case '(':
859 RETURN(TLP);
860 case ')':
861 RETURN(TRP);
862 default:
863 goto breakloop;
866 breakloop:
867 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
868 #undef RETURN
874 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
875 * is not NULL, read a here document. In the latter case, eofmark is the
876 * word which marks the end of the document and striptabs is true if
877 * leading tabs should be stripped from the document. The argument firstc
878 * is the first character of the input token or document.
880 * Because C does not have internal subroutines, I have simulated them
881 * using goto's to implement the subroutine linkage. The following macros
882 * will run code that appears at the end of readtoken1.
885 #define CHECKEND() {goto checkend; checkend_return:;}
886 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
887 #define PARSESUB() {goto parsesub; parsesub_return:;}
888 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
889 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
890 #define PARSEARITH() {goto parsearith; parsearith_return:;}
892 STATIC int
893 readtoken1(int firstc, char const *syntax, char *eofmark, int striptabs)
895 int c = firstc;
896 char *out;
897 int len;
898 char line[EOFMARKLEN + 1];
899 struct nodelist *bqlist;
900 int quotef;
901 int dblquote;
902 int varnest; /* levels of variables expansion */
903 int arinest; /* levels of arithmetic expansion */
904 int parenlevel; /* levels of parens in arithmetic */
905 int oldstyle;
906 char const *prevsyntax; /* syntax before arithmetic */
907 int synentry;
908 #if __GNUC__
909 /* Avoid longjmp clobbering */
910 (void) &out;
911 (void) &quotef;
912 (void) &dblquote;
913 (void) &varnest;
914 (void) &arinest;
915 (void) &parenlevel;
916 (void) &oldstyle;
917 (void) &prevsyntax;
918 (void) &syntax;
919 (void) &synentry;
920 #endif
922 startlinno = plinno;
923 dblquote = 0;
924 if (syntax == DQSYNTAX)
925 dblquote = 1;
926 quotef = 0;
927 bqlist = NULL;
928 varnest = 0;
929 arinest = 0;
930 parenlevel = 0;
932 STARTSTACKSTR(out);
933 loop: { /* for each line, until end of word */
934 CHECKEND(); /* set c to PEOF if at end of here document */
935 for (;;) { /* until end of line or end of word */
936 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
938 synentry = syntax[c];
940 switch(synentry) {
941 case CNL: /* '\n' */
942 if (syntax == BASESYNTAX)
943 goto endword; /* exit outer loop */
944 USTPUTC(c, out);
945 plinno++;
946 if (doprompt)
947 setprompt(2);
948 else
949 setprompt(0);
950 c = pgetc();
951 goto loop; /* continue outer loop */
952 case CWORD:
953 USTPUTC(c, out);
954 break;
955 case CCTL:
956 if (eofmark == NULL || dblquote)
957 USTPUTC(CTLESC, out);
958 USTPUTC(c, out);
959 break;
960 case CBACK: /* backslash */
961 c = pgetc();
962 if (c == PEOF) {
963 USTPUTC('\\', out);
964 pungetc();
965 } else if (c == '\n') {
966 if (doprompt)
967 setprompt(2);
968 else
969 setprompt(0);
970 } else {
971 if (dblquote && c != '\\' &&
972 c != '`' && c != '$' &&
973 (c != '"' || eofmark != NULL))
974 USTPUTC('\\', out);
975 if (SQSYNTAX[c] == CCTL)
976 USTPUTC(CTLESC, out);
977 else if (eofmark == NULL)
978 USTPUTC(CTLQUOTEMARK, out);
979 USTPUTC(c, out);
980 quotef++;
982 break;
983 case CSQUOTE:
984 if (eofmark == NULL)
985 USTPUTC(CTLQUOTEMARK, out);
986 syntax = SQSYNTAX;
987 break;
988 case CDQUOTE:
989 if (eofmark == NULL)
990 USTPUTC(CTLQUOTEMARK, out);
991 syntax = DQSYNTAX;
992 dblquote = 1;
993 break;
994 case CENDQUOTE:
995 if (eofmark != NULL && arinest == 0 &&
996 varnest == 0) {
997 USTPUTC(c, out);
998 } else {
999 if (arinest) {
1000 syntax = ARISYNTAX;
1001 dblquote = 0;
1002 } else if (eofmark == NULL) {
1003 syntax = BASESYNTAX;
1004 dblquote = 0;
1006 quotef++;
1008 break;
1009 case CVAR: /* '$' */
1010 PARSESUB(); /* parse substitution */
1011 break;
1012 case CENDVAR: /* '}' */
1013 if (varnest > 0) {
1014 varnest--;
1015 USTPUTC(CTLENDVAR, out);
1016 } else {
1017 USTPUTC(c, out);
1019 break;
1020 case CLP: /* '(' in arithmetic */
1021 parenlevel++;
1022 USTPUTC(c, out);
1023 break;
1024 case CRP: /* ')' in arithmetic */
1025 if (parenlevel > 0) {
1026 USTPUTC(c, out);
1027 --parenlevel;
1028 } else {
1029 if (pgetc() == ')') {
1030 if (--arinest == 0) {
1031 USTPUTC(CTLENDARI, out);
1032 syntax = prevsyntax;
1033 if (syntax == DQSYNTAX)
1034 dblquote = 1;
1035 else
1036 dblquote = 0;
1037 } else
1038 USTPUTC(')', out);
1039 } else {
1041 * unbalanced parens
1042 * (don't 2nd guess - no error)
1044 pungetc();
1045 USTPUTC(')', out);
1048 break;
1049 case CBQUOTE: /* '`' */
1050 PARSEBACKQOLD();
1051 break;
1052 case CEOF:
1053 goto endword; /* exit outer loop */
1054 default:
1055 if (varnest == 0)
1056 goto endword; /* exit outer loop */
1057 USTPUTC(c, out);
1059 c = pgetc_macro();
1062 endword:
1063 if (syntax == ARISYNTAX)
1064 synerror("Missing '))'");
1065 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
1066 synerror("Unterminated quoted string");
1067 if (varnest != 0) {
1068 startlinno = plinno;
1069 synerror("Missing '}'");
1071 USTPUTC('\0', out);
1072 len = out - stackblock();
1073 out = stackblock();
1074 if (eofmark == NULL) {
1075 if ((c == '>' || c == '<')
1076 && quotef == 0
1077 && len <= 2
1078 && (*out == '\0' || is_digit(*out))) {
1079 PARSEREDIR();
1080 return lasttoken = TREDIR;
1081 } else {
1082 pungetc();
1085 quoteflag = quotef;
1086 backquotelist = bqlist;
1087 grabstackblock(len);
1088 wordtext = out;
1089 return lasttoken = TWORD;
1090 /* end of readtoken routine */
1095 * Check to see whether we are at the end of the here document. When this
1096 * is called, c is set to the first character of the next input line. If
1097 * we are at the end of the here document, this routine sets the c to PEOF.
1100 checkend: {
1101 if (eofmark) {
1102 if (striptabs) {
1103 while (c == '\t')
1104 c = pgetc();
1106 if (c == *eofmark) {
1107 if (pfgets(line, sizeof line) != NULL) {
1108 char *p, *q;
1110 p = line;
1111 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1112 if (*p == '\n' && *q == '\0') {
1113 c = PEOF;
1114 plinno++;
1115 needprompt = doprompt;
1116 } else {
1117 pushstring(line, strlen(line), NULL);
1122 goto checkend_return;
1127 * Parse a redirection operator. The variable "out" points to a string
1128 * specifying the fd to be redirected. The variable "c" contains the
1129 * first character of the redirection operator.
1132 parseredir: {
1133 char fd = *out;
1134 union node *np;
1136 np = (union node *)stalloc(sizeof (struct nfile));
1137 if (c == '>') {
1138 np->nfile.fd = 1;
1139 c = pgetc();
1140 if (c == '>')
1141 np->type = NAPPEND;
1142 else if (c == '&')
1143 np->type = NTOFD;
1144 else if (c == '|')
1145 np->type = NCLOBBER;
1146 else {
1147 np->type = NTO;
1148 pungetc();
1150 } else { /* c == '<' */
1151 np->nfile.fd = 0;
1152 c = pgetc();
1153 if (c == '<') {
1154 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1155 np = (union node *)stalloc(sizeof (struct nhere));
1156 np->nfile.fd = 0;
1158 np->type = NHERE;
1159 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1160 heredoc->here = np;
1161 if ((c = pgetc()) == '-') {
1162 heredoc->striptabs = 1;
1163 } else {
1164 heredoc->striptabs = 0;
1165 pungetc();
1167 } else if (c == '&')
1168 np->type = NFROMFD;
1169 else if (c == '>')
1170 np->type = NFROMTO;
1171 else {
1172 np->type = NFROM;
1173 pungetc();
1176 if (fd != '\0')
1177 np->nfile.fd = digit_val(fd);
1178 redirnode = np;
1179 goto parseredir_return;
1184 * Parse a substitution. At this point, we have read the dollar sign
1185 * and nothing else.
1188 parsesub: {
1189 int subtype;
1190 int typeloc;
1191 int flags;
1192 char *p;
1193 #ifndef GDB_HACK
1194 static const char types[] = "}-+?=";
1195 #endif
1196 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1198 c = pgetc();
1199 if (c != '(' && c != '{' && !is_name(c) && !is_special(c)) {
1200 USTPUTC('$', out);
1201 pungetc();
1202 } else if (c == '(') { /* $(command) or $((arith)) */
1203 if (pgetc() == '(') {
1204 PARSEARITH();
1205 } else {
1206 pungetc();
1207 PARSEBACKQNEW();
1209 } else {
1210 USTPUTC(CTLVAR, out);
1211 typeloc = out - stackblock();
1212 USTPUTC(VSNORMAL, out);
1213 subtype = VSNORMAL;
1214 if (c == '{') {
1215 bracketed_name = 1;
1216 c = pgetc();
1217 if (c == '#') {
1218 if ((c = pgetc()) == '}')
1219 c = '#';
1220 else
1221 subtype = VSLENGTH;
1223 else
1224 subtype = 0;
1226 if (is_name(c)) {
1227 do {
1228 STPUTC(c, out);
1229 c = pgetc();
1230 } while (is_in_name(c));
1231 } else if (is_digit(c)) {
1232 if (bracketed_name) {
1233 do {
1234 STPUTC(c, out);
1235 c = pgetc();
1236 } while (is_digit(c));
1237 } else {
1238 STPUTC(c, out);
1239 c = pgetc();
1241 } else {
1242 if (! is_special(c))
1243 badsub: synerror("Bad substitution");
1244 USTPUTC(c, out);
1245 c = pgetc();
1247 STPUTC('=', out);
1248 flags = 0;
1249 if (subtype == 0) {
1250 switch (c) {
1251 case ':':
1252 flags = VSNUL;
1253 c = pgetc();
1254 /*FALLTHROUGH*/
1255 default:
1256 p = strchr(types, c);
1257 if (p == NULL)
1258 goto badsub;
1259 subtype = p - types + VSNORMAL;
1260 break;
1261 case '%':
1262 case '#':
1264 int cc = c;
1265 subtype = c == '#' ? VSTRIMLEFT :
1266 VSTRIMRIGHT;
1267 c = pgetc();
1268 if (c == cc)
1269 subtype++;
1270 else
1271 pungetc();
1272 break;
1275 } else {
1276 pungetc();
1278 if (subtype != VSLENGTH && (dblquote || arinest))
1279 flags |= VSQUOTE;
1280 *(stackblock() + typeloc) = subtype | flags;
1281 if (subtype != VSNORMAL)
1282 varnest++;
1284 goto parsesub_return;
1289 * Called to parse command substitutions. Newstyle is set if the command
1290 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
1291 * list of commands (passed by reference), and savelen is the number of
1292 * characters on the top of the stack which must be preserved.
1295 parsebackq: {
1296 struct nodelist **nlpp;
1297 int savepbq;
1298 union node *n;
1299 char *volatile str;
1300 struct jmploc jmploc;
1301 struct jmploc *volatile savehandler;
1302 int savelen;
1303 int saveprompt;
1304 #if __GNUC__
1305 /* Avoid longjmp clobbering */
1306 (void) &saveprompt;
1307 #endif
1309 savepbq = parsebackquote;
1310 if (setjmp(jmploc.loc)) {
1311 if (str)
1312 ckfree(str);
1313 parsebackquote = 0;
1314 handler = savehandler;
1315 longjmp(handler->loc, 1);
1317 INTOFF;
1318 str = NULL;
1319 savelen = out - stackblock();
1320 if (savelen > 0) {
1321 str = ckmalloc(savelen);
1322 memcpy(str, stackblock(), savelen);
1324 savehandler = handler;
1325 handler = &jmploc;
1326 INTON;
1327 if (oldstyle) {
1328 /* We must read until the closing backquote, giving special
1329 treatment to some slashes, and then push the string and
1330 reread it as input, interpreting it normally. */
1331 char *out;
1332 int c;
1333 int savelen;
1334 char *str;
1337 STARTSTACKSTR(out);
1338 for (;;) {
1339 if (needprompt) {
1340 setprompt(2);
1341 needprompt = 0;
1343 switch (c = pgetc()) {
1344 case '`':
1345 goto done;
1347 case '\\':
1348 if ((c = pgetc()) == '\n') {
1349 plinno++;
1350 if (doprompt)
1351 setprompt(2);
1352 else
1353 setprompt(0);
1355 * If eating a newline, avoid putting
1356 * the newline into the new character
1357 * stream (via the STPUTC after the
1358 * switch).
1360 continue;
1362 if (c != '\\' && c != '`' && c != '$'
1363 && (!dblquote || c != '"'))
1364 STPUTC('\\', out);
1365 break;
1367 case '\n':
1368 plinno++;
1369 needprompt = doprompt;
1370 break;
1372 case PEOF:
1373 startlinno = plinno;
1374 synerror("EOF in backquote substitution");
1375 break;
1377 default:
1378 break;
1380 STPUTC(c, out);
1382 done:
1383 STPUTC('\0', out);
1384 savelen = out - stackblock();
1385 if (savelen > 0) {
1386 str = ckmalloc(savelen);
1387 memcpy(str, stackblock(), savelen);
1388 setinputstring(str, 1);
1391 nlpp = &bqlist;
1392 while (*nlpp)
1393 nlpp = &(*nlpp)->next;
1394 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1395 (*nlpp)->next = NULL;
1396 parsebackquote = oldstyle;
1398 if (oldstyle) {
1399 saveprompt = doprompt;
1400 doprompt = 0;
1403 n = list(0);
1405 if (oldstyle)
1406 doprompt = saveprompt;
1407 else {
1408 if (readtoken() != TRP)
1409 synexpect(TRP);
1412 (*nlpp)->n = n;
1413 if (oldstyle) {
1415 * Start reading from old file again, ignoring any pushed back
1416 * tokens left from the backquote parsing
1418 popfile();
1419 tokpushback = 0;
1421 while (stackblocksize() <= savelen)
1422 growstackblock();
1423 STARTSTACKSTR(out);
1424 if (str) {
1425 memcpy(out, str, savelen);
1426 STADJUST(savelen, out);
1427 INTOFF;
1428 ckfree(str);
1429 str = NULL;
1430 INTON;
1432 parsebackquote = savepbq;
1433 handler = savehandler;
1434 if (arinest || dblquote)
1435 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1436 else
1437 USTPUTC(CTLBACKQ, out);
1438 if (oldstyle)
1439 goto parsebackq_oldreturn;
1440 else
1441 goto parsebackq_newreturn;
1445 * Parse an arithmetic expansion (indicate start of one and set state)
1447 parsearith: {
1449 if (++arinest == 1) {
1450 prevsyntax = syntax;
1451 syntax = ARISYNTAX;
1452 USTPUTC(CTLARI, out);
1453 if (dblquote)
1454 USTPUTC('"',out);
1455 else
1456 USTPUTC(' ',out);
1457 } else {
1459 * we collapse embedded arithmetic expansion to
1460 * parenthesis, which should be equivalent
1462 USTPUTC('(', out);
1464 goto parsearith_return;
1467 } /* end of readtoken */
1471 #ifdef mkinit
1472 RESET {
1473 tokpushback = 0;
1474 checkkwd = 0;
1476 #endif
1479 * Returns true if the text contains nothing to expand (no dollar signs
1480 * or backquotes).
1483 STATIC int
1484 noexpand(char *text)
1486 char *p;
1487 char c;
1489 p = text;
1490 while ((c = *p++) != '\0') {
1491 if ( c == CTLQUOTEMARK)
1492 continue;
1493 if (c == CTLESC)
1494 p++;
1495 else if (BASESYNTAX[(int)c] == CCTL)
1496 return 0;
1498 return 1;
1503 * Return true if the argument is a legal variable name (a letter or
1504 * underscore followed by zero or more letters, underscores, and digits).
1508 goodname(char *name)
1510 char *p;
1512 p = name;
1513 if (! is_name(*p))
1514 return 0;
1515 while (*++p) {
1516 if (! is_in_name(*p))
1517 return 0;
1519 return 1;
1524 * Called when an unexpected token is read during the parse. The argument
1525 * is the token that is expected, or -1 if more than one type of token can
1526 * occur at this point.
1529 STATIC void
1530 synexpect(int token)
1532 char msg[64];
1534 if (token >= 0) {
1535 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1536 tokname[lasttoken], tokname[token]);
1537 } else {
1538 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1540 synerror(msg);
1544 STATIC void
1545 synerror(char *msg)
1547 if (commandname)
1548 outfmt(&errout, "%s: %d: ", commandname, startlinno);
1549 outfmt(&errout, "Syntax error: %s\n", msg);
1550 error((char *)NULL);
1553 STATIC void
1554 setprompt(int which)
1556 whichprompt = which;
1558 #ifndef NO_HISTORY
1559 #ifdef EDITLINE
1560 if (!editable)
1561 #else
1562 if (!el)
1563 #endif /* EDITLINE */
1564 #endif /* !NO_HISTORY */
1565 out2str(getprompt(NULL));
1569 * called by editline -- any expansions to the prompt
1570 * should be added here.
1572 char *
1573 getprompt(void *unused __unused)
1575 static char ps[PROMPTLEN];
1576 char *fmt;
1577 int i, j, trim;
1580 * Select prompt format.
1582 switch (whichprompt) {
1583 case -1:
1584 fmt = pseval();
1585 break;
1586 case 0:
1587 fmt = "";
1588 break;
1589 case 1:
1590 fmt = ps1val();
1591 break;
1592 case 2:
1593 fmt = ps2val();
1594 break;
1595 default:
1596 return "<internal prompt error>";
1600 * Format prompt string.
1602 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1603 if (*fmt == '\\')
1604 switch (*++fmt) {
1607 * Hostname.
1609 * \h specifies just the local hostname,
1610 * \H specifies fully-qualified hostname.
1612 case 'h':
1613 case 'H':
1614 ps[i] == '\0';
1615 gethostname(&ps[i], PROMPTLEN - i);
1616 /* Skip to end of hostname. */
1617 trim = (*fmt == 'h') ? '.' : '\0';
1618 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1619 i++;
1620 break;
1623 * Working directory.
1625 * \W specifies just the final component,
1626 * \w specifies the entire path.
1628 case 'W':
1629 case 'w':
1630 ps[i] == '\0';
1631 getcwd(&ps[i], PROMPTLEN - i);
1632 if (*fmt == 'W') {
1633 /* Final path component only. */
1634 trim = 1;
1635 for (j = i; ps[j] != '\0'; j++)
1636 if (ps[j] == '/')
1637 trim = j + 1;
1638 memmove(&ps[i], &ps[trim],
1639 j - trim + 1);
1641 /* Skip to end of path. */
1642 while (ps[i + 1] != '\0')
1643 i++;
1644 break;
1647 * Superuser status.
1649 * '$' for normal users, '#' for root.
1651 case '$':
1652 ps[i] = (geteuid() != 0) ? '$' : '#';
1653 break;
1656 * A literal \.
1658 case '\\':
1659 ps[i] = '\\';
1660 break;
1663 * Emit unrecognized formats verbatim.
1665 default:
1666 ps[i++] = '\\';
1667 ps[i] = *fmt;
1668 break;
1670 else
1671 ps[i] = *fmt;
1672 ps[i] = '\0';
1673 return (ps);
1677 * $PchId: parser.c,v 1.6 2006/05/29 13:08:11 philip Exp $