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