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