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