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