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