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