parser.c revision 255065
121918Sjkh/*-
221918Sjkh * Copyright (c) 1991, 1993
321918Sjkh *	The Regents of the University of California.  All rights reserved.
421918Sjkh *
521918Sjkh * This code is derived from software contributed to Berkeley by
621918Sjkh * Kenneth Almquist.
721918Sjkh *
821918Sjkh * Redistribution and use in source and binary forms, with or without
921918Sjkh * modification, are permitted provided that the following conditions
1021918Sjkh * are met:
1121918Sjkh * 1. Redistributions of source code must retain the above copyright
1221918Sjkh *    notice, this list of conditions and the following disclaimer.
1321918Sjkh * 2. Redistributions in binary form must reproduce the above copyright
1421918Sjkh *    notice, this list of conditions and the following disclaimer in the
1521918Sjkh *    documentation and/or other materials provided with the distribution.
1621918Sjkh * 4. Neither the name of the University nor the names of its contributors
1721918Sjkh *    may be used to endorse or promote products derived from this software
1821918Sjkh *    without specific prior written permission.
1921918Sjkh *
2021918Sjkh * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2121918Sjkh * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2221918Sjkh * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2321918Sjkh * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2421918Sjkh * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2521918Sjkh * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2621918Sjkh * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2721918Sjkh * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2829449Scharnier * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2929449Scharnier * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3050479Speter * SUCH DAMAGE.
3129449Scharnier */
3229449Scharnier
3321918Sjkh#ifndef lint
3421918Sjkh#if 0
35112213Srobertstatic char sccsid[] = "@(#)parser.c	8.7 (Berkeley) 5/16/95";
3629449Scharnier#endif
3729449Scharnier#endif /* not lint */
3821918Sjkh#include <sys/cdefs.h>
3921918Sjkh__FBSDID("$FreeBSD: stable/9/bin/sh/parser.c 255065 2013-08-30 10:07:10Z jilles $");
4021918Sjkh
4129449Scharnier#include <stdlib.h>
42112213Srobert#include <unistd.h>
4321918Sjkh#include <stdio.h>
4421918Sjkh
4529449Scharnier#include "shell.h"
4621918Sjkh#include "parser.h"
47112213Srobert#include "nodes.h"
4821918Sjkh#include "expand.h"	/* defines rmescapes() */
4921918Sjkh#include "syntax.h"
5021918Sjkh#include "options.h"
5121918Sjkh#include "input.h"
5221918Sjkh#include "output.h"
5321918Sjkh#include "var.h"
5421918Sjkh#include "error.h"
5521918Sjkh#include "memalloc.h"
5621918Sjkh#include "mystring.h"
5721918Sjkh#include "alias.h"
5821918Sjkh#include "show.h"
5921918Sjkh#include "eval.h"
6021918Sjkh#include "exec.h"	/* to check for special builtins */
6121918Sjkh#ifndef NO_HISTORY
6221918Sjkh#include "myhistedit.h"
6321918Sjkh#endif
6421918Sjkh
6521918Sjkh/*
6621918Sjkh * Shell command parser.
6721918Sjkh */
6821918Sjkh
6921918Sjkh#define	EOFMARKLEN	79
7021918Sjkh#define	PROMPTLEN	128
7121918Sjkh
7221918Sjkh/* values of checkkwd variable */
7321918Sjkh#define CHKALIAS	0x1
7421918Sjkh#define CHKKWD		0x2
7521918Sjkh#define CHKNL		0x4
7621918Sjkh
7721918Sjkh/* values returned by readtoken */
7821918Sjkh#include "token.h"
7921918Sjkh
8021918Sjkh
8121918Sjkh
8221918Sjkhstruct heredoc {
83185073Sdelphij	struct heredoc *next;	/* next here document in list */
8421918Sjkh	union node *here;		/* redirection node */
8521918Sjkh	char *eofmark;		/* string indicating end of input */
8621918Sjkh	int striptabs;		/* if set, strip leading tabs */
8721918Sjkh};
8821918Sjkh
8921918Sjkhstruct parser_temp {
9021918Sjkh	struct parser_temp *next;
9121918Sjkh	void *data;
9221918Sjkh};
9321918Sjkh
9421918Sjkh
9521918Sjkhstatic struct heredoc *heredoclist;	/* list of here documents to read */
9621918Sjkhstatic int doprompt;		/* if set, prompt the user */
9721918Sjkhstatic int needprompt;		/* true if interactive and at start of line */
9821918Sjkhstatic int lasttoken;		/* last token read */
9921918SjkhMKINIT int tokpushback;		/* last token pushed back */
10021918Sjkhstatic char *wordtext;		/* text of last word returned by readtoken */
10121918SjkhMKINIT int checkkwd;            /* 1 == check for kwds, 2 == also eat newlines */
10221918Sjkhstatic struct nodelist *backquotelist;
10321918Sjkhstatic union node *redirnode;
10421918Sjkhstatic struct heredoc *heredoc;
10521918Sjkhstatic int quoteflag;		/* set if (part of) last token was quoted */
10621918Sjkhstatic int startlinno;		/* line # where last token started */
10721918Sjkhstatic int funclinno;		/* line # where the current function started */
10821918Sjkhstatic struct parser_temp *parser_temp;
10921918Sjkh
11021918Sjkh
11121918Sjkhstatic union node *list(int, int);
11221918Sjkhstatic union node *andor(void);
11321918Sjkhstatic union node *pipeline(void);
11421918Sjkhstatic union node *command(void);
11521918Sjkhstatic union node *simplecmd(union node **, union node *);
11621918Sjkhstatic union node *makename(void);
11721918Sjkhstatic void parsefname(void);
11821918Sjkhstatic void parseheredoc(void);
11921918Sjkhstatic int peektoken(void);
12021918Sjkhstatic int readtoken(void);
12121918Sjkhstatic int xxreadtoken(void);
12221918Sjkhstatic int readtoken1(int, char const *, char *, int);
12321918Sjkhstatic int noexpand(char *);
12421918Sjkhstatic void synexpect(int) __dead2;
12521918Sjkhstatic void synerror(const char *) __dead2;
12621918Sjkhstatic void setprompt(int);
12721918Sjkh
12821918Sjkh
12921918Sjkhstatic void *
13021918Sjkhparser_temp_alloc(size_t len)
13121918Sjkh{
13221918Sjkh	struct parser_temp *t;
13321918Sjkh
13421918Sjkh	INTOFF;
13521918Sjkh	t = ckmalloc(sizeof(*t));
13661019Scharnier	t->data = NULL;
13721918Sjkh	t->next = parser_temp;
13829449Scharnier	parser_temp = t;
13921918Sjkh	t->data = ckmalloc(len);
14021918Sjkh	INTON;
14121918Sjkh	return t->data;
14221918Sjkh}
14321918Sjkh
14421918Sjkh
14521918Sjkhstatic void *
14621918Sjkhparser_temp_realloc(void *ptr, size_t len)
14721918Sjkh{
14821918Sjkh	struct parser_temp *t;
14921918Sjkh
15021918Sjkh	INTOFF;
15121918Sjkh	t = parser_temp;
15221918Sjkh	if (ptr != t->data)
15321918Sjkh		error("bug: parser_temp_realloc misused");
15421918Sjkh	t->data = ckrealloc(t->data, len);
15521918Sjkh	INTON;
15621918Sjkh	return t->data;
15721918Sjkh}
15821918Sjkh
15921918Sjkh
16021918Sjkhstatic void
16121918Sjkhparser_temp_free_upto(void *ptr)
16221918Sjkh{
16321918Sjkh	struct parser_temp *t;
16421918Sjkh	int done = 0;
16521918Sjkh
16621918Sjkh	INTOFF;
16721918Sjkh	while (parser_temp != NULL && !done) {
16821918Sjkh		t = parser_temp;
16921918Sjkh		parser_temp = t->next;
17021918Sjkh		done = t->data == ptr;
17121918Sjkh		ckfree(t->data);
17221918Sjkh		ckfree(t);
17321918Sjkh	}
17421918Sjkh	INTON;
17521918Sjkh	if (!done)
17621918Sjkh		error("bug: parser_temp_free_upto misused");
17721918Sjkh}
17821918Sjkh
17921918Sjkh
18021918Sjkhstatic void
18121918Sjkhparser_temp_free_all(void)
18221918Sjkh{
18321918Sjkh	struct parser_temp *t;
18421918Sjkh
18521918Sjkh	INTOFF;
18621918Sjkh	while (parser_temp != NULL) {
18721918Sjkh		t = parser_temp;
18821918Sjkh		parser_temp = t->next;
18921918Sjkh		ckfree(t->data);
19021918Sjkh		ckfree(t);
19121918Sjkh	}
19221918Sjkh	INTON;
19321918Sjkh}
19421918Sjkh
19521918Sjkh
19621918Sjkh/*
19721918Sjkh * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
19821918Sjkh * valid parse tree indicating a blank line.)
19921918Sjkh */
20021918Sjkh
20121918Sjkhunion node *
20221918Sjkhparsecmd(int interact)
20321918Sjkh{
20421918Sjkh	int t;
20521918Sjkh
20621918Sjkh	/* This assumes the parser is not re-entered,
20721918Sjkh	 * which could happen if we add command substitution on PS1/PS2.
20821918Sjkh	 */
20921918Sjkh	parser_temp_free_all();
21021918Sjkh	heredoclist = NULL;
21121918Sjkh
21221918Sjkh	tokpushback = 0;
21321918Sjkh	doprompt = interact;
21461019Scharnier	if (doprompt)
21521918Sjkh		setprompt(1);
21661019Scharnier	else
21721918Sjkh		setprompt(0);
21821918Sjkh	needprompt = 0;
21921918Sjkh	t = readtoken();
22021918Sjkh	if (t == TEOF)
22121918Sjkh		return NEOF;
22221918Sjkh	if (t == TNL)
22321918Sjkh		return NULL;
22421918Sjkh	tokpushback++;
22521918Sjkh	return list(1, 1);
22621918Sjkh}
22721918Sjkh
22821918Sjkh
22921918Sjkhstatic union node *
23021918Sjkhlist(int nlflag, int erflag)
23121918Sjkh{
23221918Sjkh	union node *ntop, *n1, *n2, *n3;
23321918Sjkh	int tok;
23421918Sjkh
23521918Sjkh	checkkwd = CHKNL | CHKKWD | CHKALIAS;
23621918Sjkh	if (!nlflag && !erflag && tokendlist[peektoken()])
23721918Sjkh		return NULL;
23821918Sjkh	ntop = n1 = NULL;
23921918Sjkh	for (;;) {
24021918Sjkh		n2 = andor();
24121918Sjkh		tok = readtoken();
24221918Sjkh		if (tok == TBACKGND) {
24321918Sjkh			if (n2 != NULL && n2->type == NPIPE) {
24421918Sjkh				n2->npipe.backgnd = 1;
24521918Sjkh			} else if (n2 != NULL && n2->type == NREDIR) {
24621918Sjkh				n2->type = NBACKGND;
24721918Sjkh			} else {
24821918Sjkh				n3 = (union node *)stalloc(sizeof (struct nredir));
24961019Scharnier				n3->type = NBACKGND;
250185073Sdelphij				n3->nredir.n = n2;
25121918Sjkh				n3->nredir.redirect = NULL;
25221918Sjkh				n2 = n3;
25321918Sjkh			}
25421918Sjkh		}
25521918Sjkh		if (ntop == NULL)
25621918Sjkh			ntop = n2;
25721918Sjkh		else if (n1 == NULL) {
25821918Sjkh			n1 = (union node *)stalloc(sizeof (struct nbinary));
25921918Sjkh			n1->type = NSEMI;
26021918Sjkh			n1->nbinary.ch1 = ntop;
26121918Sjkh			n1->nbinary.ch2 = n2;
26221918Sjkh			ntop = n1;
26321918Sjkh		}
26421918Sjkh		else {
26521918Sjkh			n3 = (union node *)stalloc(sizeof (struct nbinary));
26621918Sjkh			n3->type = NSEMI;
26721918Sjkh			n3->nbinary.ch1 = n1->nbinary.ch2;
26821918Sjkh			n3->nbinary.ch2 = n2;
26921918Sjkh			n1->nbinary.ch2 = n3;
27021918Sjkh			n1 = n3;
27121918Sjkh		}
272112213Srobert		switch (tok) {
273112213Srobert		case TBACKGND:
274112213Srobert		case TSEMI:
275112213Srobert			tok = readtoken();
27621918Sjkh			/* FALLTHROUGH */
27721918Sjkh		case TNL:
27821918Sjkh			if (tok == TNL) {
27921918Sjkh				parseheredoc();
28021918Sjkh				if (nlflag)
28121918Sjkh					return ntop;
28221918Sjkh			} else if (tok == TEOF && nlflag) {
28321918Sjkh				parseheredoc();
28421918Sjkh				return ntop;
28521918Sjkh			} else {
28621918Sjkh				tokpushback++;
28721918Sjkh			}
288112213Srobert			checkkwd = CHKNL | CHKKWD | CHKALIAS;
289112213Srobert			if (!nlflag && !erflag && tokendlist[peektoken()])
29021918Sjkh				return ntop;
29121918Sjkh			break;
29221918Sjkh		case TEOF:
29321918Sjkh			if (heredoclist)
29421918Sjkh				parseheredoc();
29521918Sjkh			else
29621918Sjkh				pungetc();		/* push back EOF on input */
29721918Sjkh			return ntop;
29821918Sjkh		default:
29921918Sjkh			if (nlflag || erflag)
300112213Srobert				synexpect(-1);
30121918Sjkh			tokpushback++;
30221918Sjkh			return ntop;
30321918Sjkh		}
30421918Sjkh	}
30521918Sjkh}
30621918Sjkh
30721918Sjkh
30821918Sjkh
30961019Scharnierstatic union node *
31021918Sjkhandor(void)
31121918Sjkh{
31221918Sjkh	union node *n1, *n2, *n3;
31321918Sjkh	int t;
31421918Sjkh
31521918Sjkh	n1 = pipeline();
31621918Sjkh	for (;;) {
31721918Sjkh		if ((t = readtoken()) == TAND) {
31821918Sjkh			t = NAND;
31921918Sjkh		} else if (t == TOR) {
32021918Sjkh			t = NOR;
32121918Sjkh		} else {
32221918Sjkh			tokpushback++;
32321918Sjkh			return n1;
32421918Sjkh		}
32521918Sjkh		n2 = pipeline();
32621918Sjkh		n3 = (union node *)stalloc(sizeof (struct nbinary));
32721918Sjkh		n3->type = t;
32821918Sjkh		n3->nbinary.ch1 = n1;
32921918Sjkh		n3->nbinary.ch2 = n2;
33021918Sjkh		n1 = n3;
33121918Sjkh	}
33221918Sjkh}
33321918Sjkh
33421918Sjkh
33521918Sjkh
33621918Sjkhstatic union node *
33721918Sjkhpipeline(void)
33821918Sjkh{
33921918Sjkh	union node *n1, *n2, *pipenode;
34021918Sjkh	struct nodelist *lp, *prev;
34121918Sjkh	int negate, t;
34221918Sjkh
34321918Sjkh	negate = 0;
34421918Sjkh	checkkwd = CHKNL | CHKKWD | CHKALIAS;
34521918Sjkh	TRACE(("pipeline: entered\n"));
34621918Sjkh	while (readtoken() == TNOT)
34721918Sjkh		negate = !negate;
34821918Sjkh	tokpushback++;
34921918Sjkh	n1 = command();
35021918Sjkh	if (readtoken() == TPIPE) {
35121918Sjkh		pipenode = (union node *)stalloc(sizeof (struct npipe));
35221918Sjkh		pipenode->type = NPIPE;
35321918Sjkh		pipenode->npipe.backgnd = 0;
35421918Sjkh		lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
35521918Sjkh		pipenode->npipe.cmdlist = lp;
35621918Sjkh		lp->n = n1;
35721918Sjkh		do {
35821918Sjkh			prev = lp;
35921918Sjkh			lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
36021918Sjkh			checkkwd = CHKNL | CHKKWD | CHKALIAS;
36121918Sjkh			t = readtoken();
36221918Sjkh			tokpushback++;
36321918Sjkh			if (t == TNOT)
36421918Sjkh				lp->n = pipeline();
36521918Sjkh			else
36621918Sjkh				lp->n = command();
36721918Sjkh			prev->next = lp;
36821918Sjkh		} while (readtoken() == TPIPE);
36921918Sjkh		lp->next = NULL;
37021918Sjkh		n1 = pipenode;
37121918Sjkh	}
37221918Sjkh	tokpushback++;
37321918Sjkh	if (negate) {
37421918Sjkh		n2 = (union node *)stalloc(sizeof (struct nnot));
37521918Sjkh		n2->type = NNOT;
37621918Sjkh		n2->nnot.com = n1;
37721918Sjkh		return n2;
37821918Sjkh	} else
37921918Sjkh		return n1;
38021918Sjkh}
38121918Sjkh
38221918Sjkh
38321918Sjkh
38421918Sjkhstatic union node *
38521918Sjkhcommand(void)
38621918Sjkh{
38721918Sjkh	union node *n1, *n2;
38821918Sjkh	union node *ap, **app;
38921918Sjkh	union node *cp, **cpp;
39021918Sjkh	union node *redir, **rpp;
39121918Sjkh	int t;
39221918Sjkh	int is_subshell;
39321918Sjkh
39421918Sjkh	checkkwd = CHKNL | CHKKWD | CHKALIAS;
39521918Sjkh	is_subshell = 0;
396185073Sdelphij	redir = NULL;
39721918Sjkh	n1 = NULL;
39821918Sjkh	rpp = &redir;
39921918Sjkh
40021918Sjkh	/* Check for redirection which may precede command */
401185073Sdelphij	while (readtoken() == TREDIR) {
40221918Sjkh		*rpp = n2 = redirnode;
40321918Sjkh		rpp = &n2->nfile.next;
40421918Sjkh		parsefname();
40521918Sjkh	}
40621918Sjkh	tokpushback++;
40721918Sjkh
40821918Sjkh	switch (readtoken()) {
40921918Sjkh	case TIF:
41021918Sjkh		n1 = (union node *)stalloc(sizeof (struct nif));
41121918Sjkh		n1->type = NIF;
41221918Sjkh		if ((n1->nif.test = list(0, 0)) == NULL)
41321918Sjkh			synexpect(-1);
41421918Sjkh		if (readtoken() != TTHEN)
41521918Sjkh			synexpect(TTHEN);
41621918Sjkh		n1->nif.ifpart = list(0, 0);
41721918Sjkh		n2 = n1;
41821918Sjkh		while (readtoken() == TELIF) {
41921918Sjkh			n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
42021918Sjkh			n2 = n2->nif.elsepart;
42121918Sjkh			n2->type = NIF;
42221918Sjkh			if ((n2->nif.test = list(0, 0)) == NULL)
42321918Sjkh				synexpect(-1);
42421918Sjkh			if (readtoken() != TTHEN)
42521918Sjkh				synexpect(TTHEN);
42621918Sjkh			n2->nif.ifpart = list(0, 0);
42721918Sjkh		}
42821918Sjkh		if (lasttoken == TELSE)
42921918Sjkh			n2->nif.elsepart = list(0, 0);
43021918Sjkh		else {
43121918Sjkh			n2->nif.elsepart = NULL;
43221918Sjkh			tokpushback++;
43321918Sjkh		}
43421918Sjkh		if (readtoken() != TFI)
43521918Sjkh			synexpect(TFI);
43621918Sjkh		checkkwd = CHKKWD | CHKALIAS;
43721918Sjkh		break;
43821918Sjkh	case TWHILE:
43921918Sjkh	case TUNTIL: {
44021918Sjkh		int got;
44121918Sjkh		n1 = (union node *)stalloc(sizeof (struct nbinary));
44221918Sjkh		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
44329449Scharnier		if ((n1->nbinary.ch1 = list(0, 0)) == NULL)
44421918Sjkh			synexpect(-1);
44521918Sjkh		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	case TPIPE:
580	case TENDCASE:
581	case TFALLTHRU:
582		/*
583		 * An empty command before a ; doesn't make much sense, and
584		 * should certainly be disallowed in the case of `if ;'.
585		 */
586		if (!redir)
587			synexpect(-1);
588	case TNL:
589	case TEOF:
590	case TWORD:
591	case TRP:
592		tokpushback++;
593		n1 = simplecmd(rpp, redir);
594		return n1;
595	default:
596		synexpect(-1);
597	}
598
599	/* Now check for redirection which may follow command */
600	while (readtoken() == TREDIR) {
601		*rpp = n2 = redirnode;
602		rpp = &n2->nfile.next;
603		parsefname();
604	}
605	tokpushback++;
606	*rpp = NULL;
607	if (redir) {
608		if (!is_subshell) {
609			n2 = (union node *)stalloc(sizeof (struct nredir));
610			n2->type = NREDIR;
611			n2->nredir.n = n1;
612			n1 = n2;
613		}
614		n1->nredir.redirect = redir;
615	}
616
617	return n1;
618}
619
620
621static union node *
622simplecmd(union node **rpp, union node *redir)
623{
624	union node *args, **app;
625	union node **orig_rpp = rpp;
626	union node *n = NULL;
627	int special;
628	int savecheckkwd;
629
630	/* If we don't have any redirections already, then we must reset */
631	/* rpp to be the address of the local redir variable.  */
632	if (redir == 0)
633		rpp = &redir;
634
635	args = NULL;
636	app = &args;
637	/*
638	 * We save the incoming value, because we need this for shell
639	 * functions.  There can not be a redirect or an argument between
640	 * the function name and the open parenthesis.
641	 */
642	orig_rpp = rpp;
643
644	savecheckkwd = CHKALIAS;
645
646	for (;;) {
647		checkkwd = savecheckkwd;
648		if (readtoken() == TWORD) {
649			n = (union node *)stalloc(sizeof (struct narg));
650			n->type = NARG;
651			n->narg.text = wordtext;
652			n->narg.backquote = backquotelist;
653			*app = n;
654			app = &n->narg.next;
655			if (savecheckkwd != 0 && !isassignment(wordtext))
656				savecheckkwd = 0;
657		} else if (lasttoken == TREDIR) {
658			*rpp = n = redirnode;
659			rpp = &n->nfile.next;
660			parsefname();	/* read name of redirection file */
661		} else if (lasttoken == TLP && app == &args->narg.next
662					    && rpp == orig_rpp) {
663			/* We have a function */
664			if (readtoken() != TRP)
665				synexpect(TRP);
666			funclinno = plinno;
667			/*
668			 * - Require plain text.
669			 * - Functions with '/' cannot be called.
670			 * - Reject name=().
671			 * - Reject ksh extended glob patterns.
672			 */
673			if (!noexpand(n->narg.text) || quoteflag ||
674			    strchr(n->narg.text, '/') ||
675			    strchr("!%*+-=?@}~",
676				n->narg.text[strlen(n->narg.text) - 1]))
677				synerror("Bad function name");
678			rmescapes(n->narg.text);
679			if (find_builtin(n->narg.text, &special) >= 0 &&
680			    special)
681				synerror("Cannot override a special builtin with a function");
682			n->type = NDEFUN;
683			n->narg.next = command();
684			funclinno = 0;
685			return n;
686		} else {
687			tokpushback++;
688			break;
689		}
690	}
691	*app = NULL;
692	*rpp = NULL;
693	n = (union node *)stalloc(sizeof (struct ncmd));
694	n->type = NCMD;
695	n->ncmd.args = args;
696	n->ncmd.redirect = redir;
697	return n;
698}
699
700static union node *
701makename(void)
702{
703	union node *n;
704
705	n = (union node *)stalloc(sizeof (struct narg));
706	n->type = NARG;
707	n->narg.next = NULL;
708	n->narg.text = wordtext;
709	n->narg.backquote = backquotelist;
710	return n;
711}
712
713void
714fixredir(union node *n, const char *text, int err)
715{
716	TRACE(("Fix redir %s %d\n", text, err));
717	if (!err)
718		n->ndup.vname = NULL;
719
720	if (is_digit(text[0]) && text[1] == '\0')
721		n->ndup.dupfd = digit_val(text[0]);
722	else if (text[0] == '-' && text[1] == '\0')
723		n->ndup.dupfd = -1;
724	else {
725
726		if (err)
727			synerror("Bad fd number");
728		else
729			n->ndup.vname = makename();
730	}
731}
732
733
734static void
735parsefname(void)
736{
737	union node *n = redirnode;
738
739	if (readtoken() != TWORD)
740		synexpect(-1);
741	if (n->type == NHERE) {
742		struct heredoc *here = heredoc;
743		struct heredoc *p;
744		int i;
745
746		if (quoteflag == 0)
747			n->type = NXHERE;
748		TRACE(("Here document %d\n", n->type));
749		if (here->striptabs) {
750			while (*wordtext == '\t')
751				wordtext++;
752		}
753		if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
754			synerror("Illegal eof marker for << redirection");
755		rmescapes(wordtext);
756		here->eofmark = wordtext;
757		here->next = NULL;
758		if (heredoclist == NULL)
759			heredoclist = here;
760		else {
761			for (p = heredoclist ; p->next ; p = p->next);
762			p->next = here;
763		}
764	} else if (n->type == NTOFD || n->type == NFROMFD) {
765		fixredir(n, wordtext, 0);
766	} else {
767		n->nfile.fname = makename();
768	}
769}
770
771
772/*
773 * Input any here documents.
774 */
775
776static void
777parseheredoc(void)
778{
779	struct heredoc *here;
780	union node *n;
781
782	while (heredoclist) {
783		here = heredoclist;
784		heredoclist = here->next;
785		if (needprompt) {
786			setprompt(2);
787			needprompt = 0;
788		}
789		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
790				here->eofmark, here->striptabs);
791		n = (union node *)stalloc(sizeof (struct narg));
792		n->narg.type = NARG;
793		n->narg.next = NULL;
794		n->narg.text = wordtext;
795		n->narg.backquote = backquotelist;
796		here->here->nhere.doc = n;
797	}
798}
799
800static int
801peektoken(void)
802{
803	int t;
804
805	t = readtoken();
806	tokpushback++;
807	return (t);
808}
809
810static int
811readtoken(void)
812{
813	int t;
814	struct alias *ap;
815#ifdef DEBUG
816	int alreadyseen = tokpushback;
817#endif
818
819	top:
820	t = xxreadtoken();
821
822	/*
823	 * eat newlines
824	 */
825	if (checkkwd & CHKNL) {
826		while (t == TNL) {
827			parseheredoc();
828			t = xxreadtoken();
829		}
830	}
831
832	/*
833	 * check for keywords and aliases
834	 */
835	if (t == TWORD && !quoteflag)
836	{
837		const char * const *pp;
838
839		if (checkkwd & CHKKWD)
840			for (pp = parsekwd; *pp; pp++) {
841				if (**pp == *wordtext && equal(*pp, wordtext))
842				{
843					lasttoken = t = pp - parsekwd + KWDOFFSET;
844					TRACE(("keyword %s recognized\n", tokname[t]));
845					goto out;
846				}
847			}
848		if (checkkwd & CHKALIAS &&
849		    (ap = lookupalias(wordtext, 1)) != NULL) {
850			pushstring(ap->val, strlen(ap->val), ap);
851			goto top;
852		}
853	}
854out:
855	if (t != TNOT)
856		checkkwd = 0;
857
858#ifdef DEBUG
859	if (!alreadyseen)
860	    TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
861	else
862	    TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
863#endif
864	return (t);
865}
866
867
868/*
869 * Read the next input token.
870 * If the token is a word, we set backquotelist to the list of cmds in
871 *	backquotes.  We set quoteflag to true if any part of the word was
872 *	quoted.
873 * If the token is TREDIR, then we set redirnode to a structure containing
874 *	the redirection.
875 * In all cases, the variable startlinno is set to the number of the line
876 *	on which the token starts.
877 *
878 * [Change comment:  here documents and internal procedures]
879 * [Readtoken shouldn't have any arguments.  Perhaps we should make the
880 *  word parsing code into a separate routine.  In this case, readtoken
881 *  doesn't need to have any internal procedures, but parseword does.
882 *  We could also make parseoperator in essence the main routine, and
883 *  have parseword (readtoken1?) handle both words and redirection.]
884 */
885
886#define RETURN(token)	return lasttoken = token
887
888static int
889xxreadtoken(void)
890{
891	int c;
892
893	if (tokpushback) {
894		tokpushback = 0;
895		return lasttoken;
896	}
897	if (needprompt) {
898		setprompt(2);
899		needprompt = 0;
900	}
901	startlinno = plinno;
902	for (;;) {	/* until token or start of word found */
903		c = pgetc_macro();
904		switch (c) {
905		case ' ': case '\t':
906			continue;
907		case '#':
908			while ((c = pgetc()) != '\n' && c != PEOF);
909			pungetc();
910			continue;
911		case '\\':
912			if (pgetc() == '\n') {
913				startlinno = ++plinno;
914				if (doprompt)
915					setprompt(2);
916				else
917					setprompt(0);
918				continue;
919			}
920			pungetc();
921			goto breakloop;
922		case '\n':
923			plinno++;
924			needprompt = doprompt;
925			RETURN(TNL);
926		case PEOF:
927			RETURN(TEOF);
928		case '&':
929			if (pgetc() == '&')
930				RETURN(TAND);
931			pungetc();
932			RETURN(TBACKGND);
933		case '|':
934			if (pgetc() == '|')
935				RETURN(TOR);
936			pungetc();
937			RETURN(TPIPE);
938		case ';':
939			c = pgetc();
940			if (c == ';')
941				RETURN(TENDCASE);
942			else if (c == '&')
943				RETURN(TFALLTHRU);
944			pungetc();
945			RETURN(TSEMI);
946		case '(':
947			RETURN(TLP);
948		case ')':
949			RETURN(TRP);
950		default:
951			goto breakloop;
952		}
953	}
954breakloop:
955	return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
956#undef RETURN
957}
958
959
960#define MAXNEST_static 8
961struct tokenstate
962{
963	const char *syntax; /* *SYNTAX */
964	int parenlevel; /* levels of parentheses in arithmetic */
965	enum tokenstate_category
966	{
967		TSTATE_TOP,
968		TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
969		TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
970		TSTATE_ARITH
971	} category;
972};
973
974
975/*
976 * Called to parse command substitutions.
977 */
978
979static char *
980parsebackq(char *out, struct nodelist **pbqlist,
981		int oldstyle, int dblquote, int quoted)
982{
983	struct nodelist **nlpp;
984	union node *n;
985	char *volatile str;
986	struct jmploc jmploc;
987	struct jmploc *const savehandler = handler;
988	int savelen;
989	int saveprompt;
990	const int bq_startlinno = plinno;
991	char *volatile ostr = NULL;
992	struct parsefile *const savetopfile = getcurrentfile();
993	struct heredoc *const saveheredoclist = heredoclist;
994	struct heredoc *here;
995
996	str = NULL;
997	if (setjmp(jmploc.loc)) {
998		popfilesupto(savetopfile);
999		if (str)
1000			ckfree(str);
1001		if (ostr)
1002			ckfree(ostr);
1003		heredoclist = saveheredoclist;
1004		handler = savehandler;
1005		if (exception == EXERROR) {
1006			startlinno = bq_startlinno;
1007			synerror("Error in command substitution");
1008		}
1009		longjmp(handler->loc, 1);
1010	}
1011	INTOFF;
1012	savelen = out - stackblock();
1013	if (savelen > 0) {
1014		str = ckmalloc(savelen);
1015		memcpy(str, stackblock(), savelen);
1016	}
1017	handler = &jmploc;
1018	heredoclist = NULL;
1019	INTON;
1020        if (oldstyle) {
1021                /* We must read until the closing backquote, giving special
1022                   treatment to some slashes, and then push the string and
1023                   reread it as input, interpreting it normally.  */
1024                char *oout;
1025                int c;
1026                int olen;
1027
1028
1029                STARTSTACKSTR(oout);
1030		for (;;) {
1031			if (needprompt) {
1032				setprompt(2);
1033				needprompt = 0;
1034			}
1035			CHECKSTRSPACE(2, oout);
1036			switch (c = pgetc()) {
1037			case '`':
1038				goto done;
1039
1040			case '\\':
1041                                if ((c = pgetc()) == '\n') {
1042					plinno++;
1043					if (doprompt)
1044						setprompt(2);
1045					else
1046						setprompt(0);
1047					/*
1048					 * If eating a newline, avoid putting
1049					 * the newline into the new character
1050					 * stream (via the USTPUTC after the
1051					 * switch).
1052					 */
1053					continue;
1054				}
1055                                if (c != '\\' && c != '`' && c != '$'
1056                                    && (!dblquote || c != '"'))
1057                                        USTPUTC('\\', oout);
1058				break;
1059
1060			case '\n':
1061				plinno++;
1062				needprompt = doprompt;
1063				break;
1064
1065			case PEOF:
1066			        startlinno = plinno;
1067				synerror("EOF in backquote substitution");
1068 				break;
1069
1070			default:
1071				break;
1072			}
1073			USTPUTC(c, oout);
1074                }
1075done:
1076                USTPUTC('\0', oout);
1077                olen = oout - stackblock();
1078		INTOFF;
1079		ostr = ckmalloc(olen);
1080		memcpy(ostr, stackblock(), olen);
1081		setinputstring(ostr, 1);
1082		INTON;
1083        }
1084	nlpp = pbqlist;
1085	while (*nlpp)
1086		nlpp = &(*nlpp)->next;
1087	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1088	(*nlpp)->next = NULL;
1089
1090	if (oldstyle) {
1091		saveprompt = doprompt;
1092		doprompt = 0;
1093	}
1094
1095	n = list(0, oldstyle);
1096
1097	if (oldstyle)
1098		doprompt = saveprompt;
1099	else {
1100		if (readtoken() != TRP)
1101			synexpect(TRP);
1102	}
1103
1104	(*nlpp)->n = n;
1105        if (oldstyle) {
1106		/*
1107		 * Start reading from old file again, ignoring any pushed back
1108		 * tokens left from the backquote parsing
1109		 */
1110                popfile();
1111		tokpushback = 0;
1112	}
1113	STARTSTACKSTR(out);
1114	CHECKSTRSPACE(savelen + 1, out);
1115	INTOFF;
1116	if (str) {
1117		memcpy(out, str, savelen);
1118		STADJUST(savelen, out);
1119		ckfree(str);
1120		str = NULL;
1121	}
1122	if (ostr) {
1123		ckfree(ostr);
1124		ostr = NULL;
1125	}
1126	here = saveheredoclist;
1127	if (here != NULL) {
1128		while (here->next != NULL)
1129			here = here->next;
1130		here->next = heredoclist;
1131		heredoclist = saveheredoclist;
1132	}
1133	handler = savehandler;
1134	INTON;
1135	if (quoted)
1136		USTPUTC(CTLBACKQ | CTLQUOTE, out);
1137	else
1138		USTPUTC(CTLBACKQ, out);
1139	return out;
1140}
1141
1142
1143/*
1144 * Called to parse a backslash escape sequence inside $'...'.
1145 * The backslash has already been read.
1146 */
1147static char *
1148readcstyleesc(char *out)
1149{
1150	int c, v, i, n;
1151
1152	c = pgetc();
1153	switch (c) {
1154	case '\0':
1155		synerror("Unterminated quoted string");
1156	case '\n':
1157		plinno++;
1158		if (doprompt)
1159			setprompt(2);
1160		else
1161			setprompt(0);
1162		return out;
1163	case '\\':
1164	case '\'':
1165	case '"':
1166		v = c;
1167		break;
1168	case 'a': v = '\a'; break;
1169	case 'b': v = '\b'; break;
1170	case 'e': v = '\033'; break;
1171	case 'f': v = '\f'; break;
1172	case 'n': v = '\n'; break;
1173	case 'r': v = '\r'; break;
1174	case 't': v = '\t'; break;
1175	case 'v': v = '\v'; break;
1176	case 'x':
1177		  v = 0;
1178		  for (;;) {
1179			  c = pgetc();
1180			  if (c >= '0' && c <= '9')
1181				  v = (v << 4) + c - '0';
1182			  else if (c >= 'A' && c <= 'F')
1183				  v = (v << 4) + c - 'A' + 10;
1184			  else if (c >= 'a' && c <= 'f')
1185				  v = (v << 4) + c - 'a' + 10;
1186			  else
1187				  break;
1188		  }
1189		  pungetc();
1190		  break;
1191	case '0': case '1': case '2': case '3':
1192	case '4': case '5': case '6': case '7':
1193		  v = c - '0';
1194		  c = pgetc();
1195		  if (c >= '0' && c <= '7') {
1196			  v <<= 3;
1197			  v += c - '0';
1198			  c = pgetc();
1199			  if (c >= '0' && c <= '7') {
1200				  v <<= 3;
1201				  v += c - '0';
1202			  } else
1203				  pungetc();
1204		  } else
1205			  pungetc();
1206		  break;
1207	case 'c':
1208		  c = pgetc();
1209		  if (c < 0x3f || c > 0x7a || c == 0x60)
1210			  synerror("Bad escape sequence");
1211		  if (c == '\\' && pgetc() != '\\')
1212			  synerror("Bad escape sequence");
1213		  if (c == '?')
1214			  v = 127;
1215		  else
1216			  v = c & 0x1f;
1217		  break;
1218	case 'u':
1219	case 'U':
1220		  n = c == 'U' ? 8 : 4;
1221		  v = 0;
1222		  for (i = 0; i < n; i++) {
1223			  c = pgetc();
1224			  if (c >= '0' && c <= '9')
1225				  v = (v << 4) + c - '0';
1226			  else if (c >= 'A' && c <= 'F')
1227				  v = (v << 4) + c - 'A' + 10;
1228			  else if (c >= 'a' && c <= 'f')
1229				  v = (v << 4) + c - 'a' + 10;
1230			  else
1231				  synerror("Bad escape sequence");
1232		  }
1233		  if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1234			  synerror("Bad escape sequence");
1235		  /* We really need iconv here. */
1236		  if (initial_localeisutf8 && v > 127) {
1237			  CHECKSTRSPACE(4, out);
1238			  /*
1239			   * We cannot use wctomb() as the locale may have
1240			   * changed.
1241			   */
1242			  if (v <= 0x7ff) {
1243				  USTPUTC(0xc0 | v >> 6, out);
1244				  USTPUTC(0x80 | (v & 0x3f), out);
1245				  return out;
1246			  } else if (v <= 0xffff) {
1247				  USTPUTC(0xe0 | v >> 12, out);
1248				  USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1249				  USTPUTC(0x80 | (v & 0x3f), out);
1250				  return out;
1251			  } else if (v <= 0x10ffff) {
1252				  USTPUTC(0xf0 | v >> 18, out);
1253				  USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1254				  USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1255				  USTPUTC(0x80 | (v & 0x3f), out);
1256				  return out;
1257			  }
1258		  }
1259		  if (v > 127)
1260			  v = '?';
1261		  break;
1262	default:
1263		  synerror("Bad escape sequence");
1264	}
1265	v = (char)v;
1266	/*
1267	 * We can't handle NUL bytes.
1268	 * POSIX says we should skip till the closing quote.
1269	 */
1270	if (v == '\0') {
1271		while ((c = pgetc()) != '\'') {
1272			if (c == '\\')
1273				c = pgetc();
1274			if (c == PEOF)
1275				synerror("Unterminated quoted string");
1276		}
1277		pungetc();
1278		return out;
1279	}
1280	if (SQSYNTAX[v] == CCTL)
1281		USTPUTC(CTLESC, out);
1282	USTPUTC(v, out);
1283	return out;
1284}
1285
1286
1287/*
1288 * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
1289 * is not NULL, read a here document.  In the latter case, eofmark is the
1290 * word which marks the end of the document and striptabs is true if
1291 * leading tabs should be stripped from the document.  The argument firstc
1292 * is the first character of the input token or document.
1293 *
1294 * Because C does not have internal subroutines, I have simulated them
1295 * using goto's to implement the subroutine linkage.  The following macros
1296 * will run code that appears at the end of readtoken1.
1297 */
1298
1299#define CHECKEND()	{goto checkend; checkend_return:;}
1300#define PARSEREDIR()	{goto parseredir; parseredir_return:;}
1301#define PARSESUB()	{goto parsesub; parsesub_return:;}
1302#define	PARSEARITH()	{goto parsearith; parsearith_return:;}
1303
1304static int
1305readtoken1(int firstc, char const *initialsyntax, char *eofmark, int striptabs)
1306{
1307	int c = firstc;
1308	char *out;
1309	int len;
1310	char line[EOFMARKLEN + 1];
1311	struct nodelist *bqlist;
1312	int quotef;
1313	int newvarnest;
1314	int level;
1315	int synentry;
1316	struct tokenstate state_static[MAXNEST_static];
1317	int maxnest = MAXNEST_static;
1318	struct tokenstate *state = state_static;
1319	int sqiscstyle = 0;
1320
1321	startlinno = plinno;
1322	quotef = 0;
1323	bqlist = NULL;
1324	newvarnest = 0;
1325	level = 0;
1326	state[level].syntax = initialsyntax;
1327	state[level].parenlevel = 0;
1328	state[level].category = TSTATE_TOP;
1329
1330	STARTSTACKSTR(out);
1331	loop: {	/* for each line, until end of word */
1332		CHECKEND();	/* set c to PEOF if at end of here document */
1333		for (;;) {	/* until end of line or end of word */
1334			CHECKSTRSPACE(4, out);	/* permit 4 calls to USTPUTC */
1335
1336			synentry = state[level].syntax[c];
1337
1338			switch(synentry) {
1339			case CNL:	/* '\n' */
1340				if (state[level].syntax == BASESYNTAX)
1341					goto endword;	/* exit outer loop */
1342				USTPUTC(c, out);
1343				plinno++;
1344				if (doprompt)
1345					setprompt(2);
1346				else
1347					setprompt(0);
1348				c = pgetc();
1349				goto loop;		/* continue outer loop */
1350			case CSBACK:
1351				if (sqiscstyle) {
1352					out = readcstyleesc(out);
1353					break;
1354				}
1355				/* FALLTHROUGH */
1356			case CWORD:
1357				USTPUTC(c, out);
1358				break;
1359			case CCTL:
1360				if (eofmark == NULL || initialsyntax != SQSYNTAX)
1361					USTPUTC(CTLESC, out);
1362				USTPUTC(c, out);
1363				break;
1364			case CBACK:	/* backslash */
1365				c = pgetc();
1366				if (c == PEOF) {
1367					USTPUTC('\\', out);
1368					pungetc();
1369				} else if (c == '\n') {
1370					plinno++;
1371					if (doprompt)
1372						setprompt(2);
1373					else
1374						setprompt(0);
1375				} else {
1376					if (state[level].syntax == DQSYNTAX &&
1377					    c != '\\' && c != '`' && c != '$' &&
1378					    (c != '"' || (eofmark != NULL &&
1379						newvarnest == 0)) &&
1380					    (c != '}' || state[level].category != TSTATE_VAR_OLD))
1381						USTPUTC('\\', out);
1382					if ((eofmark == NULL ||
1383					    newvarnest > 0) &&
1384					    state[level].syntax == BASESYNTAX)
1385						USTPUTC(CTLQUOTEMARK, out);
1386					if (SQSYNTAX[c] == CCTL)
1387						USTPUTC(CTLESC, out);
1388					USTPUTC(c, out);
1389					if ((eofmark == NULL ||
1390					    newvarnest > 0) &&
1391					    state[level].syntax == BASESYNTAX &&
1392					    state[level].category == TSTATE_VAR_OLD)
1393						USTPUTC(CTLQUOTEEND, out);
1394					quotef++;
1395				}
1396				break;
1397			case CSQUOTE:
1398				USTPUTC(CTLQUOTEMARK, out);
1399				state[level].syntax = SQSYNTAX;
1400				sqiscstyle = 0;
1401				break;
1402			case CDQUOTE:
1403				USTPUTC(CTLQUOTEMARK, out);
1404				state[level].syntax = DQSYNTAX;
1405				break;
1406			case CENDQUOTE:
1407				if (eofmark != NULL && newvarnest == 0)
1408					USTPUTC(c, out);
1409				else {
1410					if (state[level].category == TSTATE_VAR_OLD)
1411						USTPUTC(CTLQUOTEEND, out);
1412					state[level].syntax = BASESYNTAX;
1413					quotef++;
1414				}
1415				break;
1416			case CVAR:	/* '$' */
1417				PARSESUB();		/* parse substitution */
1418				break;
1419			case CENDVAR:	/* '}' */
1420				if (level > 0 &&
1421				    ((state[level].category == TSTATE_VAR_OLD &&
1422				      state[level].syntax ==
1423				      state[level - 1].syntax) ||
1424				    (state[level].category == TSTATE_VAR_NEW &&
1425				     state[level].syntax == BASESYNTAX))) {
1426					if (state[level].category == TSTATE_VAR_NEW)
1427						newvarnest--;
1428					level--;
1429					USTPUTC(CTLENDVAR, out);
1430				} else {
1431					USTPUTC(c, out);
1432				}
1433				break;
1434			case CLP:	/* '(' in arithmetic */
1435				state[level].parenlevel++;
1436				USTPUTC(c, out);
1437				break;
1438			case CRP:	/* ')' in arithmetic */
1439				if (state[level].parenlevel > 0) {
1440					USTPUTC(c, out);
1441					--state[level].parenlevel;
1442				} else {
1443					if (pgetc() == ')') {
1444						if (level > 0 &&
1445						    state[level].category == TSTATE_ARITH) {
1446							level--;
1447							USTPUTC(CTLENDARI, out);
1448						} else
1449							USTPUTC(')', out);
1450					} else {
1451						/*
1452						 * unbalanced parens
1453						 *  (don't 2nd guess - no error)
1454						 */
1455						pungetc();
1456						USTPUTC(')', out);
1457					}
1458				}
1459				break;
1460			case CBQUOTE:	/* '`' */
1461				out = parsebackq(out, &bqlist, 1,
1462				    state[level].syntax == DQSYNTAX &&
1463				    (eofmark == NULL || newvarnest > 0),
1464				    state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1465				break;
1466			case CEOF:
1467				goto endword;		/* exit outer loop */
1468			case CIGN:
1469				break;
1470			default:
1471				if (level == 0)
1472					goto endword;	/* exit outer loop */
1473				USTPUTC(c, out);
1474			}
1475			c = pgetc_macro();
1476		}
1477	}
1478endword:
1479	if (state[level].syntax == ARISYNTAX)
1480		synerror("Missing '))'");
1481	if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1482		synerror("Unterminated quoted string");
1483	if (state[level].category == TSTATE_VAR_OLD ||
1484	    state[level].category == TSTATE_VAR_NEW) {
1485		startlinno = plinno;
1486		synerror("Missing '}'");
1487	}
1488	if (state != state_static)
1489		parser_temp_free_upto(state);
1490	USTPUTC('\0', out);
1491	len = out - stackblock();
1492	out = stackblock();
1493	if (eofmark == NULL) {
1494		if ((c == '>' || c == '<')
1495		 && quotef == 0
1496		 && len <= 2
1497		 && (*out == '\0' || is_digit(*out))) {
1498			PARSEREDIR();
1499			return lasttoken = TREDIR;
1500		} else {
1501			pungetc();
1502		}
1503	}
1504	quoteflag = quotef;
1505	backquotelist = bqlist;
1506	grabstackblock(len);
1507	wordtext = out;
1508	return lasttoken = TWORD;
1509/* end of readtoken routine */
1510
1511
1512/*
1513 * Check to see whether we are at the end of the here document.  When this
1514 * is called, c is set to the first character of the next input line.  If
1515 * we are at the end of the here document, this routine sets the c to PEOF.
1516 */
1517
1518checkend: {
1519	if (eofmark) {
1520		if (striptabs) {
1521			while (c == '\t')
1522				c = pgetc();
1523		}
1524		if (c == *eofmark) {
1525			if (pfgets(line, sizeof line) != NULL) {
1526				char *p, *q;
1527
1528				p = line;
1529				for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1530				if ((*p == '\0' || *p == '\n') && *q == '\0') {
1531					c = PEOF;
1532					if (*p == '\n') {
1533						plinno++;
1534						needprompt = doprompt;
1535					}
1536				} else {
1537					pushstring(line, strlen(line), NULL);
1538				}
1539			}
1540		}
1541	}
1542	goto checkend_return;
1543}
1544
1545
1546/*
1547 * Parse a redirection operator.  The variable "out" points to a string
1548 * specifying the fd to be redirected.  The variable "c" contains the
1549 * first character of the redirection operator.
1550 */
1551
1552parseredir: {
1553	char fd = *out;
1554	union node *np;
1555
1556	np = (union node *)stalloc(sizeof (struct nfile));
1557	if (c == '>') {
1558		np->nfile.fd = 1;
1559		c = pgetc();
1560		if (c == '>')
1561			np->type = NAPPEND;
1562		else if (c == '&')
1563			np->type = NTOFD;
1564		else if (c == '|')
1565			np->type = NCLOBBER;
1566		else {
1567			np->type = NTO;
1568			pungetc();
1569		}
1570	} else {	/* c == '<' */
1571		np->nfile.fd = 0;
1572		c = pgetc();
1573		if (c == '<') {
1574			if (sizeof (struct nfile) != sizeof (struct nhere)) {
1575				np = (union node *)stalloc(sizeof (struct nhere));
1576				np->nfile.fd = 0;
1577			}
1578			np->type = NHERE;
1579			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1580			heredoc->here = np;
1581			if ((c = pgetc()) == '-') {
1582				heredoc->striptabs = 1;
1583			} else {
1584				heredoc->striptabs = 0;
1585				pungetc();
1586			}
1587		} else if (c == '&')
1588			np->type = NFROMFD;
1589		else if (c == '>')
1590			np->type = NFROMTO;
1591		else {
1592			np->type = NFROM;
1593			pungetc();
1594		}
1595	}
1596	if (fd != '\0')
1597		np->nfile.fd = digit_val(fd);
1598	redirnode = np;
1599	goto parseredir_return;
1600}
1601
1602
1603/*
1604 * Parse a substitution.  At this point, we have read the dollar sign
1605 * and nothing else.
1606 */
1607
1608parsesub: {
1609	char buf[10];
1610	int subtype;
1611	int typeloc;
1612	int flags;
1613	char *p;
1614	static const char types[] = "}-+?=";
1615	int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1616	int linno;
1617	int length;
1618	int c1;
1619
1620	c = pgetc();
1621	if (c == '(') {	/* $(command) or $((arith)) */
1622		if (pgetc() == '(') {
1623			PARSEARITH();
1624		} else {
1625			pungetc();
1626			out = parsebackq(out, &bqlist, 0,
1627			    state[level].syntax == DQSYNTAX &&
1628			    (eofmark == NULL || newvarnest > 0),
1629			    state[level].syntax == DQSYNTAX ||
1630			    state[level].syntax == ARISYNTAX);
1631		}
1632	} else if (c == '{' || is_name(c) || is_special(c)) {
1633		USTPUTC(CTLVAR, out);
1634		typeloc = out - stackblock();
1635		USTPUTC(VSNORMAL, out);
1636		subtype = VSNORMAL;
1637		flags = 0;
1638		if (c == '{') {
1639			bracketed_name = 1;
1640			c = pgetc();
1641			subtype = 0;
1642		}
1643varname:
1644		if (!is_eof(c) && is_name(c)) {
1645			length = 0;
1646			do {
1647				STPUTC(c, out);
1648				c = pgetc();
1649				length++;
1650			} while (!is_eof(c) && is_in_name(c));
1651			if (length == 6 &&
1652			    strncmp(out - length, "LINENO", length) == 0) {
1653				/* Replace the variable name with the
1654				 * current line number. */
1655				linno = plinno;
1656				if (funclinno != 0)
1657					linno -= funclinno - 1;
1658				snprintf(buf, sizeof(buf), "%d", linno);
1659				STADJUST(-6, out);
1660				STPUTS(buf, out);
1661				flags |= VSLINENO;
1662			}
1663		} else if (is_digit(c)) {
1664			if (bracketed_name) {
1665				do {
1666					STPUTC(c, out);
1667					c = pgetc();
1668				} while (is_digit(c));
1669			} else {
1670				STPUTC(c, out);
1671				c = pgetc();
1672			}
1673		} else if (is_special(c)) {
1674			c1 = c;
1675			c = pgetc();
1676			if (subtype == 0 && c1 == '#') {
1677				subtype = VSLENGTH;
1678				if (strchr(types, c) == NULL && c != ':' &&
1679				    c != '#' && c != '%')
1680					goto varname;
1681				c1 = c;
1682				c = pgetc();
1683				if (c1 != '}' && c == '}') {
1684					pungetc();
1685					c = c1;
1686					goto varname;
1687				}
1688				pungetc();
1689				c = c1;
1690				c1 = '#';
1691				subtype = 0;
1692			}
1693			USTPUTC(c1, out);
1694		} else {
1695			subtype = VSERROR;
1696			if (c == '}')
1697				pungetc();
1698			else if (c == '\n' || c == PEOF)
1699				synerror("Unexpected end of line in substitution");
1700			else
1701				USTPUTC(c, out);
1702		}
1703		if (subtype == 0) {
1704			switch (c) {
1705			case ':':
1706				flags |= VSNUL;
1707				c = pgetc();
1708				/*FALLTHROUGH*/
1709			default:
1710				p = strchr(types, c);
1711				if (p == NULL) {
1712					if (c == '\n' || c == PEOF)
1713						synerror("Unexpected end of line in substitution");
1714					if (flags == VSNUL)
1715						STPUTC(':', out);
1716					STPUTC(c, out);
1717					subtype = VSERROR;
1718				} else
1719					subtype = p - types + VSNORMAL;
1720				break;
1721			case '%':
1722			case '#':
1723				{
1724					int cc = c;
1725					subtype = c == '#' ? VSTRIMLEFT :
1726							     VSTRIMRIGHT;
1727					c = pgetc();
1728					if (c == cc)
1729						subtype++;
1730					else
1731						pungetc();
1732					break;
1733				}
1734			}
1735		} else if (subtype != VSERROR) {
1736			if (subtype == VSLENGTH && c != '}')
1737				subtype = VSERROR;
1738			pungetc();
1739		}
1740		STPUTC('=', out);
1741		if (state[level].syntax == DQSYNTAX ||
1742		    state[level].syntax == ARISYNTAX)
1743			flags |= VSQUOTE;
1744		*(stackblock() + typeloc) = subtype | flags;
1745		if (subtype != VSNORMAL) {
1746			if (level + 1 >= maxnest) {
1747				maxnest *= 2;
1748				if (state == state_static) {
1749					state = parser_temp_alloc(
1750					    maxnest * sizeof(*state));
1751					memcpy(state, state_static,
1752					    MAXNEST_static * sizeof(*state));
1753				} else
1754					state = parser_temp_realloc(state,
1755					    maxnest * sizeof(*state));
1756			}
1757			level++;
1758			state[level].parenlevel = 0;
1759			if (subtype == VSMINUS || subtype == VSPLUS ||
1760			    subtype == VSQUESTION || subtype == VSASSIGN) {
1761				/*
1762				 * For operators that were in the Bourne shell,
1763				 * inherit the double-quote state.
1764				 */
1765				state[level].syntax = state[level - 1].syntax;
1766				state[level].category = TSTATE_VAR_OLD;
1767			} else {
1768				/*
1769				 * The other operators take a pattern,
1770				 * so go to BASESYNTAX.
1771				 * Also, ' and " are now special, even
1772				 * in here documents.
1773				 */
1774				state[level].syntax = BASESYNTAX;
1775				state[level].category = TSTATE_VAR_NEW;
1776				newvarnest++;
1777			}
1778		}
1779	} else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1780		/* $'cstylequotes' */
1781		USTPUTC(CTLQUOTEMARK, out);
1782		state[level].syntax = SQSYNTAX;
1783		sqiscstyle = 1;
1784	} else {
1785		USTPUTC('$', out);
1786		pungetc();
1787	}
1788	goto parsesub_return;
1789}
1790
1791
1792/*
1793 * Parse an arithmetic expansion (indicate start of one and set state)
1794 */
1795parsearith: {
1796
1797	if (level + 1 >= maxnest) {
1798		maxnest *= 2;
1799		if (state == state_static) {
1800			state = parser_temp_alloc(
1801			    maxnest * sizeof(*state));
1802			memcpy(state, state_static,
1803			    MAXNEST_static * sizeof(*state));
1804		} else
1805			state = parser_temp_realloc(state,
1806			    maxnest * sizeof(*state));
1807	}
1808	level++;
1809	state[level].syntax = ARISYNTAX;
1810	state[level].parenlevel = 0;
1811	state[level].category = TSTATE_ARITH;
1812	USTPUTC(CTLARI, out);
1813	if (state[level - 1].syntax == DQSYNTAX)
1814		USTPUTC('"',out);
1815	else
1816		USTPUTC(' ',out);
1817	goto parsearith_return;
1818}
1819
1820} /* end of readtoken */
1821
1822
1823
1824#ifdef mkinit
1825RESET {
1826	tokpushback = 0;
1827	checkkwd = 0;
1828}
1829#endif
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
1892/*
1893 * Called when an unexpected token is read during the parse.  The argument
1894 * is the token that is expected, or -1 if more than one type of token can
1895 * occur at this point.
1896 */
1897
1898static void
1899synexpect(int token)
1900{
1901	char msg[64];
1902
1903	if (token >= 0) {
1904		fmtstr(msg, 64, "%s unexpected (expecting %s)",
1905			tokname[lasttoken], tokname[token]);
1906	} else {
1907		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1908	}
1909	synerror(msg);
1910}
1911
1912
1913static void
1914synerror(const char *msg)
1915{
1916	if (commandname)
1917		outfmt(out2, "%s: %d: ", commandname, startlinno);
1918	outfmt(out2, "Syntax error: %s\n", msg);
1919	error((char *)NULL);
1920}
1921
1922static void
1923setprompt(int which)
1924{
1925	whichprompt = which;
1926
1927#ifndef NO_HISTORY
1928	if (!el)
1929#endif
1930	{
1931		out2str(getprompt(NULL));
1932		flushout(out2);
1933	}
1934}
1935
1936/*
1937 * called by editline -- any expansions to the prompt
1938 *    should be added here.
1939 */
1940char *
1941getprompt(void *unused __unused)
1942{
1943	static char ps[PROMPTLEN];
1944	char *fmt;
1945	const char *pwd;
1946	int i, trim;
1947	static char internal_error[] = "??";
1948
1949	/*
1950	 * Select prompt format.
1951	 */
1952	switch (whichprompt) {
1953	case 0:
1954		fmt = nullstr;
1955		break;
1956	case 1:
1957		fmt = ps1val();
1958		break;
1959	case 2:
1960		fmt = ps2val();
1961		break;
1962	default:
1963		return internal_error;
1964	}
1965
1966	/*
1967	 * Format prompt string.
1968	 */
1969	for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1970		if (*fmt == '\\')
1971			switch (*++fmt) {
1972
1973				/*
1974				 * Hostname.
1975				 *
1976				 * \h specifies just the local hostname,
1977				 * \H specifies fully-qualified hostname.
1978				 */
1979			case 'h':
1980			case 'H':
1981				ps[i] = '\0';
1982				gethostname(&ps[i], PROMPTLEN - i);
1983				/* Skip to end of hostname. */
1984				trim = (*fmt == 'h') ? '.' : '\0';
1985				while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1986					i++;
1987				break;
1988
1989				/*
1990				 * Working directory.
1991				 *
1992				 * \W specifies just the final component,
1993				 * \w specifies the entire path.
1994				 */
1995			case 'W':
1996			case 'w':
1997				pwd = lookupvar("PWD");
1998				if (pwd == NULL)
1999					pwd = "?";
2000				if (*fmt == 'W' &&
2001				    *pwd == '/' && pwd[1] != '\0')
2002					strlcpy(&ps[i], strrchr(pwd, '/') + 1,
2003					    PROMPTLEN - i);
2004				else
2005					strlcpy(&ps[i], pwd, PROMPTLEN - i);
2006				/* Skip to end of path. */
2007				while (ps[i + 1] != '\0')
2008					i++;
2009				break;
2010
2011				/*
2012				 * Superuser status.
2013				 *
2014				 * '$' for normal users, '#' for root.
2015				 */
2016			case '$':
2017				ps[i] = (geteuid() != 0) ? '$' : '#';
2018				break;
2019
2020				/*
2021				 * A literal \.
2022				 */
2023			case '\\':
2024				ps[i] = '\\';
2025				break;
2026
2027				/*
2028				 * Emit unrecognized formats verbatim.
2029				 */
2030			default:
2031				ps[i++] = '\\';
2032				ps[i] = *fmt;
2033				break;
2034			}
2035		else
2036			ps[i] = *fmt;
2037	ps[i] = '\0';
2038	return (ps);
2039}
2040
2041
2042const char *
2043expandstr(char *ps)
2044{
2045	union node n;
2046	struct jmploc jmploc;
2047	struct jmploc *const savehandler = handler;
2048	const int saveprompt = doprompt;
2049	struct parsefile *const savetopfile = getcurrentfile();
2050	struct parser_temp *const saveparser_temp = parser_temp;
2051	const char *result = NULL;
2052
2053	if (!setjmp(jmploc.loc)) {
2054		handler = &jmploc;
2055		parser_temp = NULL;
2056		setinputstring(ps, 1);
2057		doprompt = 0;
2058		readtoken1(pgetc(), DQSYNTAX, "\n\n", 0);
2059		if (backquotelist != NULL)
2060			error("Command substitution not allowed here");
2061
2062		n.narg.type = NARG;
2063		n.narg.next = NULL;
2064		n.narg.text = wordtext;
2065		n.narg.backquote = backquotelist;
2066
2067		expandarg(&n, NULL, 0);
2068		result = stackblock();
2069		INTOFF;
2070	}
2071	handler = savehandler;
2072	doprompt = saveprompt;
2073	popfilesupto(savetopfile);
2074	if (parser_temp != saveparser_temp) {
2075		parser_temp_free_all();
2076		parser_temp = saveparser_temp;
2077	}
2078	if (result != NULL) {
2079		INTON;
2080	} else if (exception == EXINT)
2081		raise(SIGINT);
2082	return result;
2083}
2084