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