parser.c revision 214490
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1991, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)parser.c	8.7 (Berkeley) 5/16/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD: head/bin/sh/parser.c 214490 2010-10-28 21:51:14Z jilles $");
401556Srgrimes
4117987Speter#include <stdlib.h>
42149017Sstefanf#include <unistd.h>
43209337Sjilles#include <stdio.h>
4417987Speter
451556Srgrimes#include "shell.h"
461556Srgrimes#include "parser.h"
471556Srgrimes#include "nodes.h"
481556Srgrimes#include "expand.h"	/* defines rmescapes() */
491556Srgrimes#include "syntax.h"
501556Srgrimes#include "options.h"
511556Srgrimes#include "input.h"
521556Srgrimes#include "output.h"
531556Srgrimes#include "var.h"
541556Srgrimes#include "error.h"
551556Srgrimes#include "memalloc.h"
561556Srgrimes#include "mystring.h"
571556Srgrimes#include "alias.h"
5817987Speter#include "show.h"
5959436Scracauer#include "eval.h"
60214304Sjilles#include "exec.h"	/* to check for special builtins */
6117987Speter#ifndef NO_HISTORY
621556Srgrimes#include "myhistedit.h"
6317987Speter#endif
641556Srgrimes
651556Srgrimes/*
661556Srgrimes * Shell command parser.
671556Srgrimes */
681556Srgrimes
69142845Sobrien#define	EOFMARKLEN	79
70142845Sobrien#define	PROMPTLEN	128
711556Srgrimes
721556Srgrimes/* values returned by readtoken */
7317987Speter#include "token.h"
741556Srgrimes
751556Srgrimes
761556Srgrimes
771556Srgrimesstruct heredoc {
781556Srgrimes	struct heredoc *next;	/* next here document in list */
791556Srgrimes	union node *here;		/* redirection node */
801556Srgrimes	char *eofmark;		/* string indicating end of input */
811556Srgrimes	int striptabs;		/* if set, strip leading tabs */
821556Srgrimes};
831556Srgrimes
84206145Sjillesstruct parser_temp {
85206145Sjilles	struct parser_temp *next;
86206145Sjilles	void *data;
87206145Sjilles};
881556Srgrimes
891556Srgrimes
90213760Sobrienstatic struct heredoc *heredoclist;	/* list of here documents to read */
91213760Sobrienstatic int doprompt;		/* if set, prompt the user */
92213760Sobrienstatic int needprompt;		/* true if interactive and at start of line */
93213760Sobrienstatic int lasttoken;		/* last token read */
941556SrgrimesMKINIT int tokpushback;		/* last token pushed back */
95213760Sobrienstatic char *wordtext;		/* text of last word returned by readtoken */
961556SrgrimesMKINIT int checkkwd;            /* 1 == check for kwds, 2 == also eat newlines */
97213760Sobrienstatic struct nodelist *backquotelist;
98213760Sobrienstatic union node *redirnode;
99213760Sobrienstatic struct heredoc *heredoc;
100213760Sobrienstatic int quoteflag;		/* set if (part of) last token was quoted */
101213760Sobrienstatic int startlinno;		/* line # where last token started */
102213760Sobrienstatic int funclinno;		/* line # where the current function started */
103213760Sobrienstatic struct parser_temp *parser_temp;
1041556Srgrimes
10518018Speter/* XXX When 'noaliases' is set to one, no alias expansion takes place. */
10618018Speterstatic int noaliases = 0;
1071556Srgrimes
1081556Srgrimes
109213811Sobrienstatic union node *list(int);
110213811Sobrienstatic union node *andor(void);
111213811Sobrienstatic union node *pipeline(void);
112213811Sobrienstatic union node *command(void);
113213811Sobrienstatic union node *simplecmd(union node **, union node *);
114213811Sobrienstatic union node *makename(void);
115213811Sobrienstatic void parsefname(void);
116213811Sobrienstatic void parseheredoc(void);
117213811Sobrienstatic int peektoken(void);
118213811Sobrienstatic int readtoken(void);
119213811Sobrienstatic int xxreadtoken(void);
120213811Sobrienstatic int readtoken1(int, char const *, char *, int);
121213811Sobrienstatic int noexpand(char *);
122213811Sobrienstatic void synexpect(int) __dead2;
123213811Sobrienstatic void synerror(const char *) __dead2;
124213811Sobrienstatic void setprompt(int);
1251556Srgrimes
12617987Speter
127213811Sobrienstatic void *
128206145Sjillesparser_temp_alloc(size_t len)
129206145Sjilles{
130206145Sjilles	struct parser_temp *t;
131206145Sjilles
132206145Sjilles	INTOFF;
133206145Sjilles	t = ckmalloc(sizeof(*t));
134206145Sjilles	t->data = NULL;
135206145Sjilles	t->next = parser_temp;
136206145Sjilles	parser_temp = t;
137206145Sjilles	t->data = ckmalloc(len);
138206145Sjilles	INTON;
139206145Sjilles	return t->data;
140206145Sjilles}
141206145Sjilles
142206145Sjilles
143213811Sobrienstatic void *
144206145Sjillesparser_temp_realloc(void *ptr, size_t len)
145206145Sjilles{
146206145Sjilles	struct parser_temp *t;
147206145Sjilles
148206145Sjilles	INTOFF;
149206145Sjilles	t = parser_temp;
150206145Sjilles	if (ptr != t->data)
151206145Sjilles		error("bug: parser_temp_realloc misused");
152206145Sjilles	t->data = ckrealloc(t->data, len);
153206145Sjilles	INTON;
154206145Sjilles	return t->data;
155206145Sjilles}
156206145Sjilles
157206145Sjilles
158213811Sobrienstatic void
159206145Sjillesparser_temp_free_upto(void *ptr)
160206145Sjilles{
161206145Sjilles	struct parser_temp *t;
162206145Sjilles	int done = 0;
163206145Sjilles
164206145Sjilles	INTOFF;
165206145Sjilles	while (parser_temp != NULL && !done) {
166206145Sjilles		t = parser_temp;
167206145Sjilles		parser_temp = t->next;
168206145Sjilles		done = t->data == ptr;
169206145Sjilles		ckfree(t->data);
170206145Sjilles		ckfree(t);
171206145Sjilles	}
172206145Sjilles	INTON;
173206145Sjilles	if (!done)
174206145Sjilles		error("bug: parser_temp_free_upto misused");
175206145Sjilles}
176206145Sjilles
177206145Sjilles
178213811Sobrienstatic void
179206145Sjillesparser_temp_free_all(void)
180206145Sjilles{
181206145Sjilles	struct parser_temp *t;
182206145Sjilles
183206145Sjilles	INTOFF;
184206145Sjilles	while (parser_temp != NULL) {
185206145Sjilles		t = parser_temp;
186206145Sjilles		parser_temp = t->next;
187206145Sjilles		ckfree(t->data);
188206145Sjilles		ckfree(t);
189206145Sjilles	}
190206145Sjilles	INTON;
191206145Sjilles}
192206145Sjilles
193206145Sjilles
1941556Srgrimes/*
1951556Srgrimes * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
1961556Srgrimes * valid parse tree indicating a blank line.)
1971556Srgrimes */
1981556Srgrimes
1991556Srgrimesunion node *
20090111Simpparsecmd(int interact)
20117987Speter{
2021556Srgrimes	int t;
2031556Srgrimes
204206145Sjilles	/* This assumes the parser is not re-entered,
205206145Sjilles	 * which could happen if we add command substitution on PS1/PS2.
206206145Sjilles	 */
207206145Sjilles	parser_temp_free_all();
208208656Sjilles	heredoclist = NULL;
209206145Sjilles
21060593Scracauer	tokpushback = 0;
2111556Srgrimes	doprompt = interact;
2121556Srgrimes	if (doprompt)
2131556Srgrimes		setprompt(1);
2141556Srgrimes	else
2151556Srgrimes		setprompt(0);
2161556Srgrimes	needprompt = 0;
2171556Srgrimes	t = readtoken();
2181556Srgrimes	if (t == TEOF)
2191556Srgrimes		return NEOF;
2201556Srgrimes	if (t == TNL)
2211556Srgrimes		return NULL;
2221556Srgrimes	tokpushback++;
2231556Srgrimes	return list(1);
2241556Srgrimes}
2251556Srgrimes
2261556Srgrimes
227213811Sobrienstatic union node *
22890111Simplist(int nlflag)
22917987Speter{
2301556Srgrimes	union node *n1, *n2, *n3;
23117987Speter	int tok;
2321556Srgrimes
2331556Srgrimes	checkkwd = 2;
2341556Srgrimes	if (nlflag == 0 && tokendlist[peektoken()])
2351556Srgrimes		return NULL;
23617987Speter	n1 = NULL;
2371556Srgrimes	for (;;) {
23817987Speter		n2 = andor();
23917987Speter		tok = readtoken();
24017987Speter		if (tok == TBACKGND) {
24117987Speter			if (n2->type == NCMD || n2->type == NPIPE) {
24217987Speter				n2->ncmd.backgnd = 1;
24317987Speter			} else if (n2->type == NREDIR) {
24417987Speter				n2->type = NBACKGND;
24517987Speter			} else {
24617987Speter				n3 = (union node *)stalloc(sizeof (struct nredir));
24717987Speter				n3->type = NBACKGND;
24817987Speter				n3->nredir.n = n2;
24917987Speter				n3->nredir.redirect = NULL;
25017987Speter				n2 = n3;
25117987Speter			}
25217987Speter		}
25317987Speter		if (n1 == NULL) {
25417987Speter			n1 = n2;
25517987Speter		}
25617987Speter		else {
25717987Speter			n3 = (union node *)stalloc(sizeof (struct nbinary));
25817987Speter			n3->type = NSEMI;
25917987Speter			n3->nbinary.ch1 = n1;
26017987Speter			n3->nbinary.ch2 = n2;
26117987Speter			n1 = n3;
26217987Speter		}
26317987Speter		switch (tok) {
26413882Sjoerg		case TBACKGND:
26517987Speter		case TSEMI:
26617987Speter			tok = readtoken();
267102410Scharnier			/* FALLTHROUGH */
2681556Srgrimes		case TNL:
26917987Speter			if (tok == TNL) {
27017987Speter				parseheredoc();
27117987Speter				if (nlflag)
27217987Speter					return n1;
273210488Sjilles			} else if (tok == TEOF && nlflag) {
274210488Sjilles				parseheredoc();
275210488Sjilles				return n1;
27617987Speter			} else {
27717987Speter				tokpushback++;
27817987Speter			}
2791556Srgrimes			checkkwd = 2;
2801556Srgrimes			if (tokendlist[peektoken()])
2811556Srgrimes				return n1;
2821556Srgrimes			break;
2831556Srgrimes		case TEOF:
2841556Srgrimes			if (heredoclist)
2851556Srgrimes				parseheredoc();
2861556Srgrimes			else
2871556Srgrimes				pungetc();		/* push back EOF on input */
2881556Srgrimes			return n1;
2891556Srgrimes		default:
2901556Srgrimes			if (nlflag)
2911556Srgrimes				synexpect(-1);
2921556Srgrimes			tokpushback++;
2931556Srgrimes			return n1;
2941556Srgrimes		}
2951556Srgrimes	}
2961556Srgrimes}
2971556Srgrimes
2981556Srgrimes
2991556Srgrimes
300213811Sobrienstatic union node *
30190111Simpandor(void)
30290111Simp{
3031556Srgrimes	union node *n1, *n2, *n3;
3041556Srgrimes	int t;
3051556Srgrimes
3061556Srgrimes	n1 = pipeline();
3071556Srgrimes	for (;;) {
3081556Srgrimes		if ((t = readtoken()) == TAND) {
3091556Srgrimes			t = NAND;
3101556Srgrimes		} else if (t == TOR) {
3111556Srgrimes			t = NOR;
3121556Srgrimes		} else {
3131556Srgrimes			tokpushback++;
3141556Srgrimes			return n1;
3151556Srgrimes		}
3161556Srgrimes		n2 = pipeline();
3171556Srgrimes		n3 = (union node *)stalloc(sizeof (struct nbinary));
3181556Srgrimes		n3->type = t;
3191556Srgrimes		n3->nbinary.ch1 = n1;
3201556Srgrimes		n3->nbinary.ch2 = n2;
3211556Srgrimes		n1 = n3;
3221556Srgrimes	}
3231556Srgrimes}
3241556Srgrimes
3251556Srgrimes
3261556Srgrimes
327213811Sobrienstatic union node *
32890111Simppipeline(void)
32990111Simp{
33075336Sbrian	union node *n1, *n2, *pipenode;
3311556Srgrimes	struct nodelist *lp, *prev;
332214281Sjilles	int negate, t;
3331556Srgrimes
33475336Sbrian	negate = 0;
335191009Sstefanf	checkkwd = 2;
3361556Srgrimes	TRACE(("pipeline: entered\n"));
33775336Sbrian	while (readtoken() == TNOT)
33875336Sbrian		negate = !negate;
33975336Sbrian	tokpushback++;
3401556Srgrimes	n1 = command();
3411556Srgrimes	if (readtoken() == TPIPE) {
3421556Srgrimes		pipenode = (union node *)stalloc(sizeof (struct npipe));
3431556Srgrimes		pipenode->type = NPIPE;
3441556Srgrimes		pipenode->npipe.backgnd = 0;
3451556Srgrimes		lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
3461556Srgrimes		pipenode->npipe.cmdlist = lp;
3471556Srgrimes		lp->n = n1;
3481556Srgrimes		do {
3491556Srgrimes			prev = lp;
3501556Srgrimes			lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
351214281Sjilles			checkkwd = 2;
352214281Sjilles			t = readtoken();
353214281Sjilles			tokpushback++;
354214281Sjilles			if (t == TNOT)
355214281Sjilles				lp->n = pipeline();
356214281Sjilles			else
357214281Sjilles				lp->n = command();
3581556Srgrimes			prev->next = lp;
3591556Srgrimes		} while (readtoken() == TPIPE);
3601556Srgrimes		lp->next = NULL;
3611556Srgrimes		n1 = pipenode;
3621556Srgrimes	}
3631556Srgrimes	tokpushback++;
36475336Sbrian	if (negate) {
36575336Sbrian		n2 = (union node *)stalloc(sizeof (struct nnot));
36675336Sbrian		n2->type = NNOT;
36775336Sbrian		n2->nnot.com = n1;
36875336Sbrian		return n2;
36975336Sbrian	} else
37075336Sbrian		return n1;
3711556Srgrimes}
3721556Srgrimes
3731556Srgrimes
3741556Srgrimes
375213811Sobrienstatic union node *
37690111Simpcommand(void)
37790111Simp{
3781556Srgrimes	union node *n1, *n2;
3791556Srgrimes	union node *ap, **app;
3801556Srgrimes	union node *cp, **cpp;
3811556Srgrimes	union node *redir, **rpp;
382214281Sjilles	int t;
3831556Srgrimes
3841556Srgrimes	checkkwd = 2;
38517987Speter	redir = NULL;
38617987Speter	n1 = NULL;
3871556Srgrimes	rpp = &redir;
38820425Ssteve
3891556Srgrimes	/* Check for redirection which may precede command */
3901556Srgrimes	while (readtoken() == TREDIR) {
3911556Srgrimes		*rpp = n2 = redirnode;
3921556Srgrimes		rpp = &n2->nfile.next;
3931556Srgrimes		parsefname();
3941556Srgrimes	}
3951556Srgrimes	tokpushback++;
3961556Srgrimes
3971556Srgrimes	switch (readtoken()) {
3981556Srgrimes	case TIF:
3991556Srgrimes		n1 = (union node *)stalloc(sizeof (struct nif));
4001556Srgrimes		n1->type = NIF;
401104554Stjr		if ((n1->nif.test = list(0)) == NULL)
402104554Stjr			synexpect(-1);
4031556Srgrimes		if (readtoken() != TTHEN)
4041556Srgrimes			synexpect(TTHEN);
4051556Srgrimes		n1->nif.ifpart = list(0);
4061556Srgrimes		n2 = n1;
4071556Srgrimes		while (readtoken() == TELIF) {
4081556Srgrimes			n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
4091556Srgrimes			n2 = n2->nif.elsepart;
4101556Srgrimes			n2->type = NIF;
411104554Stjr			if ((n2->nif.test = list(0)) == NULL)
412104554Stjr				synexpect(-1);
4131556Srgrimes			if (readtoken() != TTHEN)
4141556Srgrimes				synexpect(TTHEN);
4151556Srgrimes			n2->nif.ifpart = list(0);
4161556Srgrimes		}
4171556Srgrimes		if (lasttoken == TELSE)
4181556Srgrimes			n2->nif.elsepart = list(0);
4191556Srgrimes		else {
4201556Srgrimes			n2->nif.elsepart = NULL;
4211556Srgrimes			tokpushback++;
4221556Srgrimes		}
4231556Srgrimes		if (readtoken() != TFI)
4241556Srgrimes			synexpect(TFI);
4251556Srgrimes		checkkwd = 1;
4261556Srgrimes		break;
4271556Srgrimes	case TWHILE:
4281556Srgrimes	case TUNTIL: {
4291556Srgrimes		int got;
4301556Srgrimes		n1 = (union node *)stalloc(sizeof (struct nbinary));
4311556Srgrimes		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
432104554Stjr		if ((n1->nbinary.ch1 = list(0)) == NULL)
433104554Stjr			synexpect(-1);
4341556Srgrimes		if ((got=readtoken()) != TDO) {
4351556SrgrimesTRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
4361556Srgrimes			synexpect(TDO);
4371556Srgrimes		}
4381556Srgrimes		n1->nbinary.ch2 = list(0);
4391556Srgrimes		if (readtoken() != TDONE)
4401556Srgrimes			synexpect(TDONE);
4411556Srgrimes		checkkwd = 1;
4421556Srgrimes		break;
4431556Srgrimes	}
4441556Srgrimes	case TFOR:
4451556Srgrimes		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
4461556Srgrimes			synerror("Bad for loop variable");
4471556Srgrimes		n1 = (union node *)stalloc(sizeof (struct nfor));
4481556Srgrimes		n1->type = NFOR;
4491556Srgrimes		n1->nfor.var = wordtext;
450199282Sjilles		while (readtoken() == TNL)
451199282Sjilles			;
452199282Sjilles		if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
4531556Srgrimes			app = &ap;
4541556Srgrimes			while (readtoken() == TWORD) {
4551556Srgrimes				n2 = (union node *)stalloc(sizeof (struct narg));
4561556Srgrimes				n2->type = NARG;
4571556Srgrimes				n2->narg.text = wordtext;
4581556Srgrimes				n2->narg.backquote = backquotelist;
4591556Srgrimes				*app = n2;
4601556Srgrimes				app = &n2->narg.next;
4611556Srgrimes			}
4621556Srgrimes			*app = NULL;
4631556Srgrimes			n1->nfor.args = ap;
4641556Srgrimes			if (lasttoken != TNL && lasttoken != TSEMI)
4651556Srgrimes				synexpect(-1);
4661556Srgrimes		} else {
467149096Sstefanf			static char argvars[5] = {
468149096Sstefanf				CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
469149096Sstefanf			};
4701556Srgrimes			n2 = (union node *)stalloc(sizeof (struct narg));
4711556Srgrimes			n2->type = NARG;
472149096Sstefanf			n2->narg.text = argvars;
4731556Srgrimes			n2->narg.backquote = NULL;
4741556Srgrimes			n2->narg.next = NULL;
4751556Srgrimes			n1->nfor.args = n2;
4761556Srgrimes			/*
4771556Srgrimes			 * Newline or semicolon here is optional (but note
4781556Srgrimes			 * that the original Bourne shell only allowed NL).
4791556Srgrimes			 */
4801556Srgrimes			if (lasttoken != TNL && lasttoken != TSEMI)
4811556Srgrimes				tokpushback++;
4821556Srgrimes		}
4831556Srgrimes		checkkwd = 2;
4841556Srgrimes		if ((t = readtoken()) == TDO)
4851556Srgrimes			t = TDONE;
4861556Srgrimes		else if (t == TBEGIN)
4871556Srgrimes			t = TEND;
4881556Srgrimes		else
4891556Srgrimes			synexpect(-1);
4901556Srgrimes		n1->nfor.body = list(0);
4911556Srgrimes		if (readtoken() != t)
4921556Srgrimes			synexpect(t);
4931556Srgrimes		checkkwd = 1;
4941556Srgrimes		break;
4951556Srgrimes	case TCASE:
4961556Srgrimes		n1 = (union node *)stalloc(sizeof (struct ncase));
4971556Srgrimes		n1->type = NCASE;
4981556Srgrimes		if (readtoken() != TWORD)
4991556Srgrimes			synexpect(TWORD);
5001556Srgrimes		n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
5011556Srgrimes		n2->type = NARG;
5021556Srgrimes		n2->narg.text = wordtext;
5031556Srgrimes		n2->narg.backquote = backquotelist;
5041556Srgrimes		n2->narg.next = NULL;
5051556Srgrimes		while (readtoken() == TNL);
5061556Srgrimes		if (lasttoken != TWORD || ! equal(wordtext, "in"))
5071556Srgrimes			synerror("expecting \"in\"");
5081556Srgrimes		cpp = &n1->ncase.cases;
50918018Speter		noaliases = 1;	/* turn off alias expansion */
5102760Ssef		checkkwd = 2, readtoken();
511104202Stjr		while (lasttoken != TESAC) {
5121556Srgrimes			*cpp = cp = (union node *)stalloc(sizeof (struct nclist));
5131556Srgrimes			cp->type = NCLIST;
5141556Srgrimes			app = &cp->nclist.pattern;
515104207Stjr			if (lasttoken == TLP)
516104207Stjr				readtoken();
5171556Srgrimes			for (;;) {
5181556Srgrimes				*app = ap = (union node *)stalloc(sizeof (struct narg));
5191556Srgrimes				ap->type = NARG;
5201556Srgrimes				ap->narg.text = wordtext;
5211556Srgrimes				ap->narg.backquote = backquotelist;
5222760Ssef				if (checkkwd = 2, readtoken() != TPIPE)
5231556Srgrimes					break;
5241556Srgrimes				app = &ap->narg.next;
5252760Ssef				readtoken();
5261556Srgrimes			}
5271556Srgrimes			ap->narg.next = NULL;
5281556Srgrimes			if (lasttoken != TRP)
52918018Speter				noaliases = 0, synexpect(TRP);
5301556Srgrimes			cp->nclist.body = list(0);
5312760Ssef
5322760Ssef			checkkwd = 2;
5332760Ssef			if ((t = readtoken()) != TESAC) {
5342760Ssef				if (t != TENDCASE)
53518018Speter					noaliases = 0, synexpect(TENDCASE);
5362760Ssef				else
5372760Ssef					checkkwd = 2, readtoken();
5382760Ssef			}
5391556Srgrimes			cpp = &cp->nclist.next;
540104202Stjr		}
54118018Speter		noaliases = 0;	/* reset alias expansion */
5421556Srgrimes		*cpp = NULL;
5431556Srgrimes		checkkwd = 1;
5441556Srgrimes		break;
5451556Srgrimes	case TLP:
5461556Srgrimes		n1 = (union node *)stalloc(sizeof (struct nredir));
5471556Srgrimes		n1->type = NSUBSHELL;
5481556Srgrimes		n1->nredir.n = list(0);
5491556Srgrimes		n1->nredir.redirect = NULL;
5501556Srgrimes		if (readtoken() != TRP)
5511556Srgrimes			synexpect(TRP);
5521556Srgrimes		checkkwd = 1;
5531556Srgrimes		break;
5541556Srgrimes	case TBEGIN:
5551556Srgrimes		n1 = list(0);
5561556Srgrimes		if (readtoken() != TEND)
5571556Srgrimes			synexpect(TEND);
5581556Srgrimes		checkkwd = 1;
5591556Srgrimes		break;
5601556Srgrimes	/* Handle an empty command like other simple commands.  */
561210221Sjilles	case TBACKGND:
56217987Speter	case TSEMI:
563101662Stjr	case TAND:
564101662Stjr	case TOR:
56517987Speter		/*
56617987Speter		 * An empty command before a ; doesn't make much sense, and
56717987Speter		 * should certainly be disallowed in the case of `if ;'.
56817987Speter		 */
56917987Speter		if (!redir)
57017987Speter			synexpect(-1);
5711556Srgrimes	case TNL:
57210399Sjoerg	case TEOF:
5731556Srgrimes	case TWORD:
57417987Speter	case TRP:
5751556Srgrimes		tokpushback++;
57675160Sbrian		n1 = simplecmd(rpp, redir);
577214281Sjilles		return n1;
5781556Srgrimes	default:
5791556Srgrimes		synexpect(-1);
5801556Srgrimes	}
5811556Srgrimes
5821556Srgrimes	/* Now check for redirection which may follow command */
5831556Srgrimes	while (readtoken() == TREDIR) {
5841556Srgrimes		*rpp = n2 = redirnode;
5851556Srgrimes		rpp = &n2->nfile.next;
5861556Srgrimes		parsefname();
5871556Srgrimes	}
5881556Srgrimes	tokpushback++;
5891556Srgrimes	*rpp = NULL;
5901556Srgrimes	if (redir) {
5911556Srgrimes		if (n1->type != NSUBSHELL) {
5921556Srgrimes			n2 = (union node *)stalloc(sizeof (struct nredir));
5931556Srgrimes			n2->type = NREDIR;
5941556Srgrimes			n2->nredir.n = n1;
5951556Srgrimes			n1 = n2;
5961556Srgrimes		}
5971556Srgrimes		n1->nredir.redirect = redir;
5981556Srgrimes	}
59975160Sbrian
600214281Sjilles	return n1;
6011556Srgrimes}
6021556Srgrimes
6031556Srgrimes
604213811Sobrienstatic union node *
60590111Simpsimplecmd(union node **rpp, union node *redir)
60690111Simp{
6071556Srgrimes	union node *args, **app;
6081556Srgrimes	union node **orig_rpp = rpp;
609210087Sjilles	union node *n = NULL;
610214304Sjilles	int special;
6111556Srgrimes
6121556Srgrimes	/* If we don't have any redirections already, then we must reset */
6131556Srgrimes	/* rpp to be the address of the local redir variable.  */
6141556Srgrimes	if (redir == 0)
6151556Srgrimes		rpp = &redir;
6161556Srgrimes
6171556Srgrimes	args = NULL;
6181556Srgrimes	app = &args;
6198855Srgrimes	/*
6201556Srgrimes	 * We save the incoming value, because we need this for shell
6211556Srgrimes	 * functions.  There can not be a redirect or an argument between
6228855Srgrimes	 * the function name and the open parenthesis.
6231556Srgrimes	 */
6241556Srgrimes	orig_rpp = rpp;
6251556Srgrimes
6261556Srgrimes	for (;;) {
6271556Srgrimes		if (readtoken() == TWORD) {
6281556Srgrimes			n = (union node *)stalloc(sizeof (struct narg));
6291556Srgrimes			n->type = NARG;
6301556Srgrimes			n->narg.text = wordtext;
6311556Srgrimes			n->narg.backquote = backquotelist;
6321556Srgrimes			*app = n;
6331556Srgrimes			app = &n->narg.next;
6341556Srgrimes		} else if (lasttoken == TREDIR) {
6351556Srgrimes			*rpp = n = redirnode;
6361556Srgrimes			rpp = &n->nfile.next;
6371556Srgrimes			parsefname();	/* read name of redirection file */
6381556Srgrimes		} else if (lasttoken == TLP && app == &args->narg.next
6391556Srgrimes					    && rpp == orig_rpp) {
6401556Srgrimes			/* We have a function */
6411556Srgrimes			if (readtoken() != TRP)
6421556Srgrimes				synexpect(TRP);
643179022Sstefanf			funclinno = plinno;
644214291Sjilles			/*
645214291Sjilles			 * - Require plain text.
646214291Sjilles			 * - Functions with '/' cannot be called.
647214291Sjilles			 */
648214291Sjilles			if (!noexpand(n->narg.text) || quoteflag ||
649214291Sjilles			    strchr(n->narg.text, '/'))
6501556Srgrimes				synerror("Bad function name");
651214291Sjilles			rmescapes(n->narg.text);
652214304Sjilles			if (find_builtin(n->narg.text, &special) >= 0 &&
653214304Sjilles			    special)
654214304Sjilles				synerror("Cannot override a special builtin with a function");
6551556Srgrimes			n->type = NDEFUN;
6561556Srgrimes			n->narg.next = command();
657179022Sstefanf			funclinno = 0;
658210087Sjilles			return n;
6591556Srgrimes		} else {
6601556Srgrimes			tokpushback++;
6611556Srgrimes			break;
6621556Srgrimes		}
6631556Srgrimes	}
6641556Srgrimes	*app = NULL;
6651556Srgrimes	*rpp = NULL;
6661556Srgrimes	n = (union node *)stalloc(sizeof (struct ncmd));
6671556Srgrimes	n->type = NCMD;
6681556Srgrimes	n->ncmd.backgnd = 0;
6691556Srgrimes	n->ncmd.args = args;
6701556Srgrimes	n->ncmd.redirect = redir;
671210087Sjilles	return n;
6721556Srgrimes}
6731556Srgrimes
674213811Sobrienstatic union node *
67590111Simpmakename(void)
67690111Simp{
67717987Speter	union node *n;
6781556Srgrimes
67917987Speter	n = (union node *)stalloc(sizeof (struct narg));
68017987Speter	n->type = NARG;
68117987Speter	n->narg.next = NULL;
68217987Speter	n->narg.text = wordtext;
68317987Speter	n->narg.backquote = backquotelist;
68417987Speter	return n;
68517987Speter}
68617987Speter
687213760Sobrienvoid
688213760Sobrienfixredir(union node *n, const char *text, int err)
68990111Simp{
69017987Speter	TRACE(("Fix redir %s %d\n", text, err));
69117987Speter	if (!err)
69217987Speter		n->ndup.vname = NULL;
69317987Speter
69417987Speter	if (is_digit(text[0]) && text[1] == '\0')
69517987Speter		n->ndup.dupfd = digit_val(text[0]);
69617987Speter	else if (text[0] == '-' && text[1] == '\0')
69717987Speter		n->ndup.dupfd = -1;
69817987Speter	else {
69920425Ssteve
70017987Speter		if (err)
70117987Speter			synerror("Bad fd number");
70217987Speter		else
70317987Speter			n->ndup.vname = makename();
70417987Speter	}
70517987Speter}
70617987Speter
70717987Speter
708213811Sobrienstatic void
70990111Simpparsefname(void)
71090111Simp{
7111556Srgrimes	union node *n = redirnode;
7121556Srgrimes
7131556Srgrimes	if (readtoken() != TWORD)
7141556Srgrimes		synexpect(-1);
7151556Srgrimes	if (n->type == NHERE) {
7161556Srgrimes		struct heredoc *here = heredoc;
7171556Srgrimes		struct heredoc *p;
7181556Srgrimes		int i;
7191556Srgrimes
7201556Srgrimes		if (quoteflag == 0)
7211556Srgrimes			n->type = NXHERE;
7221556Srgrimes		TRACE(("Here document %d\n", n->type));
7231556Srgrimes		if (here->striptabs) {
7241556Srgrimes			while (*wordtext == '\t')
7251556Srgrimes				wordtext++;
7261556Srgrimes		}
7271556Srgrimes		if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
7281556Srgrimes			synerror("Illegal eof marker for << redirection");
7291556Srgrimes		rmescapes(wordtext);
7301556Srgrimes		here->eofmark = wordtext;
7311556Srgrimes		here->next = NULL;
7321556Srgrimes		if (heredoclist == NULL)
7331556Srgrimes			heredoclist = here;
7341556Srgrimes		else {
7351556Srgrimes			for (p = heredoclist ; p->next ; p = p->next);
7361556Srgrimes			p->next = here;
7371556Srgrimes		}
7381556Srgrimes	} else if (n->type == NTOFD || n->type == NFROMFD) {
73917987Speter		fixredir(n, wordtext, 0);
7401556Srgrimes	} else {
74117987Speter		n->nfile.fname = makename();
7421556Srgrimes	}
7431556Srgrimes}
7441556Srgrimes
7451556Srgrimes
7461556Srgrimes/*
7471556Srgrimes * Input any here documents.
7481556Srgrimes */
7491556Srgrimes
750213811Sobrienstatic void
75190111Simpparseheredoc(void)
75290111Simp{
7531556Srgrimes	struct heredoc *here;
7541556Srgrimes	union node *n;
7551556Srgrimes
7561556Srgrimes	while (heredoclist) {
7571556Srgrimes		here = heredoclist;
7581556Srgrimes		heredoclist = here->next;
7591556Srgrimes		if (needprompt) {
7601556Srgrimes			setprompt(2);
7611556Srgrimes			needprompt = 0;
7621556Srgrimes		}
7631556Srgrimes		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
7641556Srgrimes				here->eofmark, here->striptabs);
7651556Srgrimes		n = (union node *)stalloc(sizeof (struct narg));
7661556Srgrimes		n->narg.type = NARG;
7671556Srgrimes		n->narg.next = NULL;
7681556Srgrimes		n->narg.text = wordtext;
7691556Srgrimes		n->narg.backquote = backquotelist;
7701556Srgrimes		here->here->nhere.doc = n;
7711556Srgrimes	}
7721556Srgrimes}
7731556Srgrimes
774213811Sobrienstatic int
77590111Simppeektoken(void)
77690111Simp{
7771556Srgrimes	int t;
7781556Srgrimes
7791556Srgrimes	t = readtoken();
7801556Srgrimes	tokpushback++;
7811556Srgrimes	return (t);
7821556Srgrimes}
7831556Srgrimes
784213811Sobrienstatic int
78590111Simpreadtoken(void)
78690111Simp{
7871556Srgrimes	int t;
7881556Srgrimes	int savecheckkwd = checkkwd;
7891556Srgrimes	struct alias *ap;
7901556Srgrimes#ifdef DEBUG
7911556Srgrimes	int alreadyseen = tokpushback;
7921556Srgrimes#endif
7938855Srgrimes
7941556Srgrimes	top:
7951556Srgrimes	t = xxreadtoken();
7961556Srgrimes
7971556Srgrimes	if (checkkwd) {
7981556Srgrimes		/*
7991556Srgrimes		 * eat newlines
8001556Srgrimes		 */
8011556Srgrimes		if (checkkwd == 2) {
8021556Srgrimes			checkkwd = 0;
8031556Srgrimes			while (t == TNL) {
8041556Srgrimes				parseheredoc();
8051556Srgrimes				t = xxreadtoken();
8061556Srgrimes			}
8071556Srgrimes		} else
8081556Srgrimes			checkkwd = 0;
8091556Srgrimes		/*
8101556Srgrimes		 * check for keywords and aliases
8111556Srgrimes		 */
81220425Ssteve		if (t == TWORD && !quoteflag)
81317987Speter		{
81498463Sjmallett			const char * const *pp;
8151556Srgrimes
81698463Sjmallett			for (pp = parsekwd; *pp; pp++) {
81720425Ssteve				if (**pp == *wordtext && equal(*pp, wordtext))
81817987Speter				{
8191556Srgrimes					lasttoken = t = pp - parsekwd + KWDOFFSET;
8201556Srgrimes					TRACE(("keyword %s recognized\n", tokname[t]));
8211556Srgrimes					goto out;
8221556Srgrimes				}
8231556Srgrimes			}
82418018Speter			if (noaliases == 0 &&
82518018Speter			    (ap = lookupalias(wordtext, 1)) != NULL) {
8261556Srgrimes				pushstring(ap->val, strlen(ap->val), ap);
8271556Srgrimes				checkkwd = savecheckkwd;
8281556Srgrimes				goto top;
8291556Srgrimes			}
8301556Srgrimes		}
8311556Srgrimesout:
83275160Sbrian		checkkwd = (t == TNOT) ? savecheckkwd : 0;
8331556Srgrimes	}
8341556Srgrimes#ifdef DEBUG
8351556Srgrimes	if (!alreadyseen)
8361556Srgrimes	    TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
8371556Srgrimes	else
8381556Srgrimes	    TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
8391556Srgrimes#endif
8401556Srgrimes	return (t);
8411556Srgrimes}
8421556Srgrimes
8431556Srgrimes
8441556Srgrimes/*
8451556Srgrimes * Read the next input token.
8461556Srgrimes * If the token is a word, we set backquotelist to the list of cmds in
8471556Srgrimes *	backquotes.  We set quoteflag to true if any part of the word was
8481556Srgrimes *	quoted.
8491556Srgrimes * If the token is TREDIR, then we set redirnode to a structure containing
8501556Srgrimes *	the redirection.
8511556Srgrimes * In all cases, the variable startlinno is set to the number of the line
8521556Srgrimes *	on which the token starts.
8531556Srgrimes *
8541556Srgrimes * [Change comment:  here documents and internal procedures]
8551556Srgrimes * [Readtoken shouldn't have any arguments.  Perhaps we should make the
8561556Srgrimes *  word parsing code into a separate routine.  In this case, readtoken
8571556Srgrimes *  doesn't need to have any internal procedures, but parseword does.
8581556Srgrimes *  We could also make parseoperator in essence the main routine, and
8591556Srgrimes *  have parseword (readtoken1?) handle both words and redirection.]
8601556Srgrimes */
8611556Srgrimes
8621556Srgrimes#define RETURN(token)	return lasttoken = token
8631556Srgrimes
864213811Sobrienstatic int
86590111Simpxxreadtoken(void)
86690111Simp{
86725230Ssteve	int c;
8681556Srgrimes
8691556Srgrimes	if (tokpushback) {
8701556Srgrimes		tokpushback = 0;
8711556Srgrimes		return lasttoken;
8721556Srgrimes	}
8731556Srgrimes	if (needprompt) {
8741556Srgrimes		setprompt(2);
8751556Srgrimes		needprompt = 0;
8761556Srgrimes	}
8771556Srgrimes	startlinno = plinno;
8781556Srgrimes	for (;;) {	/* until token or start of word found */
8791556Srgrimes		c = pgetc_macro();
8801556Srgrimes		if (c == ' ' || c == '\t')
8811556Srgrimes			continue;		/* quick check for white space first */
8821556Srgrimes		switch (c) {
8831556Srgrimes		case ' ': case '\t':
8841556Srgrimes			continue;
8851556Srgrimes		case '#':
8861556Srgrimes			while ((c = pgetc()) != '\n' && c != PEOF);
8871556Srgrimes			pungetc();
8881556Srgrimes			continue;
8891556Srgrimes		case '\\':
8901556Srgrimes			if (pgetc() == '\n') {
8911556Srgrimes				startlinno = ++plinno;
8921556Srgrimes				if (doprompt)
8931556Srgrimes					setprompt(2);
8941556Srgrimes				else
8951556Srgrimes					setprompt(0);
8961556Srgrimes				continue;
8971556Srgrimes			}
8981556Srgrimes			pungetc();
8991556Srgrimes			goto breakloop;
9001556Srgrimes		case '\n':
9011556Srgrimes			plinno++;
9021556Srgrimes			needprompt = doprompt;
9031556Srgrimes			RETURN(TNL);
9041556Srgrimes		case PEOF:
9051556Srgrimes			RETURN(TEOF);
9061556Srgrimes		case '&':
9071556Srgrimes			if (pgetc() == '&')
9081556Srgrimes				RETURN(TAND);
9091556Srgrimes			pungetc();
9101556Srgrimes			RETURN(TBACKGND);
9111556Srgrimes		case '|':
9121556Srgrimes			if (pgetc() == '|')
9131556Srgrimes				RETURN(TOR);
9141556Srgrimes			pungetc();
9151556Srgrimes			RETURN(TPIPE);
9161556Srgrimes		case ';':
9171556Srgrimes			if (pgetc() == ';')
9181556Srgrimes				RETURN(TENDCASE);
9191556Srgrimes			pungetc();
9201556Srgrimes			RETURN(TSEMI);
9211556Srgrimes		case '(':
9221556Srgrimes			RETURN(TLP);
9231556Srgrimes		case ')':
9241556Srgrimes			RETURN(TRP);
9251556Srgrimes		default:
9261556Srgrimes			goto breakloop;
9271556Srgrimes		}
9281556Srgrimes	}
9291556Srgrimesbreakloop:
9301556Srgrimes	return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
9311556Srgrimes#undef RETURN
9321556Srgrimes}
9331556Srgrimes
9341556Srgrimes
935213811Sobrien#define MAXNEST_static 8
936206145Sjillesstruct tokenstate
937206145Sjilles{
938206145Sjilles	const char *syntax; /* *SYNTAX */
939206145Sjilles	int parenlevel; /* levels of parentheses in arithmetic */
940206145Sjilles	enum tokenstate_category
941206145Sjilles	{
942206145Sjilles		TSTATE_TOP,
943206145Sjilles		TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
944206145Sjilles		TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
945206145Sjilles		TSTATE_ARITH
946206145Sjilles	} category;
947206145Sjilles};
948206145Sjilles
949206145Sjilles
950205130Sjilles/*
951205130Sjilles * Called to parse command substitutions.
952205130Sjilles */
9531556Srgrimes
954213811Sobrienstatic char *
955205130Sjillesparsebackq(char *out, struct nodelist **pbqlist,
956205130Sjilles		int oldstyle, int dblquote, int quoted)
957205130Sjilles{
958205130Sjilles	struct nodelist **nlpp;
959205130Sjilles	union node *n;
960205130Sjilles	char *volatile str;
961205130Sjilles	struct jmploc jmploc;
962205130Sjilles	struct jmploc *const savehandler = handler;
963205130Sjilles	int savelen;
964205130Sjilles	int saveprompt;
965205130Sjilles	const int bq_startlinno = plinno;
966205130Sjilles	char *volatile ostr = NULL;
967205130Sjilles	struct parsefile *const savetopfile = getcurrentfile();
968208655Sjilles	struct heredoc *const saveheredoclist = heredoclist;
969208655Sjilles	struct heredoc *here;
970205130Sjilles
971205130Sjilles	str = NULL;
972205130Sjilles	if (setjmp(jmploc.loc)) {
973205130Sjilles		popfilesupto(savetopfile);
974205130Sjilles		if (str)
975205130Sjilles			ckfree(str);
976205130Sjilles		if (ostr)
977205130Sjilles			ckfree(ostr);
978208655Sjilles		heredoclist = saveheredoclist;
979205130Sjilles		handler = savehandler;
980205130Sjilles		if (exception == EXERROR) {
981205130Sjilles			startlinno = bq_startlinno;
982205130Sjilles			synerror("Error in command substitution");
983205130Sjilles		}
984205130Sjilles		longjmp(handler->loc, 1);
985205130Sjilles	}
986205130Sjilles	INTOFF;
987205130Sjilles	savelen = out - stackblock();
988205130Sjilles	if (savelen > 0) {
989205130Sjilles		str = ckmalloc(savelen);
990205130Sjilles		memcpy(str, stackblock(), savelen);
991205130Sjilles	}
992205130Sjilles	handler = &jmploc;
993208655Sjilles	heredoclist = NULL;
994205130Sjilles	INTON;
995205130Sjilles        if (oldstyle) {
996205130Sjilles                /* We must read until the closing backquote, giving special
997205130Sjilles                   treatment to some slashes, and then push the string and
998205130Sjilles                   reread it as input, interpreting it normally.  */
999205130Sjilles                char *oout;
1000205130Sjilles                int c;
1001205130Sjilles                int olen;
1002205130Sjilles
1003205130Sjilles
1004205130Sjilles                STARTSTACKSTR(oout);
1005205130Sjilles		for (;;) {
1006205130Sjilles			if (needprompt) {
1007205130Sjilles				setprompt(2);
1008205130Sjilles				needprompt = 0;
1009205130Sjilles			}
1010205130Sjilles			switch (c = pgetc()) {
1011205130Sjilles			case '`':
1012205130Sjilles				goto done;
1013205130Sjilles
1014205130Sjilles			case '\\':
1015205130Sjilles                                if ((c = pgetc()) == '\n') {
1016205130Sjilles					plinno++;
1017205130Sjilles					if (doprompt)
1018205130Sjilles						setprompt(2);
1019205130Sjilles					else
1020205130Sjilles						setprompt(0);
1021205130Sjilles					/*
1022205130Sjilles					 * If eating a newline, avoid putting
1023205130Sjilles					 * the newline into the new character
1024205130Sjilles					 * stream (via the STPUTC after the
1025205130Sjilles					 * switch).
1026205130Sjilles					 */
1027205130Sjilles					continue;
1028205130Sjilles				}
1029205130Sjilles                                if (c != '\\' && c != '`' && c != '$'
1030205130Sjilles                                    && (!dblquote || c != '"'))
1031205130Sjilles                                        STPUTC('\\', oout);
1032205130Sjilles				break;
1033205130Sjilles
1034205130Sjilles			case '\n':
1035205130Sjilles				plinno++;
1036205130Sjilles				needprompt = doprompt;
1037205130Sjilles				break;
1038205130Sjilles
1039205130Sjilles			case PEOF:
1040205130Sjilles			        startlinno = plinno;
1041205130Sjilles				synerror("EOF in backquote substitution");
1042205130Sjilles 				break;
1043205130Sjilles
1044205130Sjilles			default:
1045205130Sjilles				break;
1046205130Sjilles			}
1047205130Sjilles			STPUTC(c, oout);
1048205130Sjilles                }
1049205130Sjillesdone:
1050205130Sjilles                STPUTC('\0', oout);
1051205130Sjilles                olen = oout - stackblock();
1052205130Sjilles		INTOFF;
1053205130Sjilles		ostr = ckmalloc(olen);
1054205130Sjilles		memcpy(ostr, stackblock(), olen);
1055205130Sjilles		setinputstring(ostr, 1);
1056205130Sjilles		INTON;
1057205130Sjilles        }
1058205130Sjilles	nlpp = pbqlist;
1059205130Sjilles	while (*nlpp)
1060205130Sjilles		nlpp = &(*nlpp)->next;
1061205130Sjilles	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1062205130Sjilles	(*nlpp)->next = NULL;
1063205130Sjilles
1064205130Sjilles	if (oldstyle) {
1065205130Sjilles		saveprompt = doprompt;
1066205130Sjilles		doprompt = 0;
1067205130Sjilles	}
1068205130Sjilles
1069205130Sjilles	n = list(0);
1070205130Sjilles
1071205130Sjilles	if (oldstyle)
1072205130Sjilles		doprompt = saveprompt;
1073205130Sjilles	else {
1074205130Sjilles		if (readtoken() != TRP)
1075205130Sjilles			synexpect(TRP);
1076205130Sjilles	}
1077205130Sjilles
1078205130Sjilles	(*nlpp)->n = n;
1079205130Sjilles        if (oldstyle) {
1080205130Sjilles		/*
1081205130Sjilles		 * Start reading from old file again, ignoring any pushed back
1082205130Sjilles		 * tokens left from the backquote parsing
1083205130Sjilles		 */
1084205130Sjilles                popfile();
1085205130Sjilles		tokpushback = 0;
1086205130Sjilles	}
1087205130Sjilles	while (stackblocksize() <= savelen)
1088205130Sjilles		growstackblock();
1089205130Sjilles	STARTSTACKSTR(out);
1090208655Sjilles	INTOFF;
1091205130Sjilles	if (str) {
1092205130Sjilles		memcpy(out, str, savelen);
1093205130Sjilles		STADJUST(savelen, out);
1094205130Sjilles		ckfree(str);
1095205130Sjilles		str = NULL;
1096205130Sjilles	}
1097205130Sjilles	if (ostr) {
1098205130Sjilles		ckfree(ostr);
1099205130Sjilles		ostr = NULL;
1100205130Sjilles	}
1101208655Sjilles	here = saveheredoclist;
1102208655Sjilles	if (here != NULL) {
1103208655Sjilles		while (here->next != NULL)
1104208655Sjilles			here = here->next;
1105208655Sjilles		here->next = heredoclist;
1106208655Sjilles		heredoclist = saveheredoclist;
1107208655Sjilles	}
1108205130Sjilles	handler = savehandler;
1109208655Sjilles	INTON;
1110205130Sjilles	if (quoted)
1111205130Sjilles		USTPUTC(CTLBACKQ | CTLQUOTE, out);
1112205130Sjilles	else
1113205130Sjilles		USTPUTC(CTLBACKQ, out);
1114205130Sjilles	return out;
1115205130Sjilles}
1116205130Sjilles
1117205130Sjilles
11181556Srgrimes/*
11191556Srgrimes * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
11201556Srgrimes * is not NULL, read a here document.  In the latter case, eofmark is the
11211556Srgrimes * word which marks the end of the document and striptabs is true if
11221556Srgrimes * leading tabs should be stripped from the document.  The argument firstc
11231556Srgrimes * is the first character of the input token or document.
11241556Srgrimes *
11251556Srgrimes * Because C does not have internal subroutines, I have simulated them
11261556Srgrimes * using goto's to implement the subroutine linkage.  The following macros
11271556Srgrimes * will run code that appears at the end of readtoken1.
11281556Srgrimes */
11291556Srgrimes
11301556Srgrimes#define CHECKEND()	{goto checkend; checkend_return:;}
11311556Srgrimes#define PARSEREDIR()	{goto parseredir; parseredir_return:;}
11321556Srgrimes#define PARSESUB()	{goto parsesub; parsesub_return:;}
11331556Srgrimes#define	PARSEARITH()	{goto parsearith; parsearith_return:;}
11341556Srgrimes
1135213811Sobrienstatic int
1136206145Sjillesreadtoken1(int firstc, char const *initialsyntax, char *eofmark, int striptabs)
113790111Simp{
113817987Speter	int c = firstc;
113917987Speter	char *out;
11401556Srgrimes	int len;
11411556Srgrimes	char line[EOFMARKLEN + 1];
11421556Srgrimes	struct nodelist *bqlist;
11431556Srgrimes	int quotef;
1144206145Sjilles	int newvarnest;
1145206145Sjilles	int level;
114654679Scracauer	int synentry;
1147213811Sobrien	struct tokenstate state_static[MAXNEST_static];
1148213811Sobrien	int maxnest = MAXNEST_static;
1149206145Sjilles	struct tokenstate *state = state_static;
11501556Srgrimes
11511556Srgrimes	startlinno = plinno;
11521556Srgrimes	quotef = 0;
11531556Srgrimes	bqlist = NULL;
1154206145Sjilles	newvarnest = 0;
1155206145Sjilles	level = 0;
1156206145Sjilles	state[level].syntax = initialsyntax;
1157206145Sjilles	state[level].parenlevel = 0;
1158206145Sjilles	state[level].category = TSTATE_TOP;
11591556Srgrimes
11601556Srgrimes	STARTSTACKSTR(out);
11611556Srgrimes	loop: {	/* for each line, until end of word */
11621556Srgrimes		CHECKEND();	/* set c to PEOF if at end of here document */
11631556Srgrimes		for (;;) {	/* until end of line or end of word */
11641556Srgrimes			CHECKSTRSPACE(3, out);	/* permit 3 calls to USTPUTC */
116554679Scracauer
1166206145Sjilles			synentry = state[level].syntax[c];
116754679Scracauer
116854679Scracauer			switch(synentry) {
11691556Srgrimes			case CNL:	/* '\n' */
1170206145Sjilles				if (state[level].syntax == BASESYNTAX)
11711556Srgrimes					goto endword;	/* exit outer loop */
11721556Srgrimes				USTPUTC(c, out);
11731556Srgrimes				plinno++;
11741556Srgrimes				if (doprompt)
11751556Srgrimes					setprompt(2);
11761556Srgrimes				else
11771556Srgrimes					setprompt(0);
11781556Srgrimes				c = pgetc();
11791556Srgrimes				goto loop;		/* continue outer loop */
11801556Srgrimes			case CWORD:
11811556Srgrimes				USTPUTC(c, out);
11821556Srgrimes				break;
11831556Srgrimes			case CCTL:
1184206145Sjilles				if (eofmark == NULL || initialsyntax != SQSYNTAX)
11851556Srgrimes					USTPUTC(CTLESC, out);
11861556Srgrimes				USTPUTC(c, out);
11871556Srgrimes				break;
11881556Srgrimes			case CBACK:	/* backslash */
11891556Srgrimes				c = pgetc();
11901556Srgrimes				if (c == PEOF) {
11911556Srgrimes					USTPUTC('\\', out);
11921556Srgrimes					pungetc();
11931556Srgrimes				} else if (c == '\n') {
1194160849Syar					plinno++;
11951556Srgrimes					if (doprompt)
11961556Srgrimes						setprompt(2);
11971556Srgrimes					else
11981556Srgrimes						setprompt(0);
11991556Srgrimes				} else {
1200206145Sjilles					if (state[level].syntax == DQSYNTAX &&
1201206145Sjilles					    c != '\\' && c != '`' && c != '$' &&
1202206145Sjilles					    (c != '"' || (eofmark != NULL &&
1203206145Sjilles						newvarnest == 0)) &&
1204206145Sjilles					    (c != '}' || state[level].category != TSTATE_VAR_OLD))
12051556Srgrimes						USTPUTC('\\', out);
120683675Stegge					if (SQSYNTAX[c] == CCTL)
12071556Srgrimes						USTPUTC(CTLESC, out);
1208206145Sjilles					else if (eofmark == NULL ||
1209206145Sjilles					    newvarnest > 0)
121038887Stegge						USTPUTC(CTLQUOTEMARK, out);
12111556Srgrimes					USTPUTC(c, out);
12121556Srgrimes					quotef++;
12131556Srgrimes				}
12141556Srgrimes				break;
12151556Srgrimes			case CSQUOTE:
1216206145Sjilles				USTPUTC(CTLQUOTEMARK, out);
1217206145Sjilles				state[level].syntax = SQSYNTAX;
12181556Srgrimes				break;
12191556Srgrimes			case CDQUOTE:
1220206145Sjilles				USTPUTC(CTLQUOTEMARK, out);
1221206145Sjilles				state[level].syntax = DQSYNTAX;
12221556Srgrimes				break;
12231556Srgrimes			case CENDQUOTE:
1224206145Sjilles				if (eofmark != NULL && newvarnest == 0)
12251556Srgrimes					USTPUTC(c, out);
1226206145Sjilles				else {
1227214305Sjilles					state[level].syntax = BASESYNTAX;
12281556Srgrimes					quotef++;
12291556Srgrimes				}
12301556Srgrimes				break;
12311556Srgrimes			case CVAR:	/* '$' */
12321556Srgrimes				PARSESUB();		/* parse substitution */
12331556Srgrimes				break;
12341556Srgrimes			case CENDVAR:	/* '}' */
1235206145Sjilles				if (level > 0 &&
1236206145Sjilles				    (state[level].category == TSTATE_VAR_OLD ||
1237214490Sjilles				    (state[level].category == TSTATE_VAR_NEW &&
1238214490Sjilles				     state[level].syntax == BASESYNTAX))) {
1239206145Sjilles					if (state[level].category == TSTATE_VAR_OLD)
1240206145Sjilles						state[level - 1].syntax = state[level].syntax;
1241206145Sjilles					else
1242206145Sjilles						newvarnest--;
1243206145Sjilles					level--;
12441556Srgrimes					USTPUTC(CTLENDVAR, out);
12451556Srgrimes				} else {
12461556Srgrimes					USTPUTC(c, out);
12471556Srgrimes				}
12481556Srgrimes				break;
12491556Srgrimes			case CLP:	/* '(' in arithmetic */
1250206145Sjilles				state[level].parenlevel++;
12511556Srgrimes				USTPUTC(c, out);
12521556Srgrimes				break;
12531556Srgrimes			case CRP:	/* ')' in arithmetic */
1254206145Sjilles				if (state[level].parenlevel > 0) {
12551556Srgrimes					USTPUTC(c, out);
1256206145Sjilles					--state[level].parenlevel;
12571556Srgrimes				} else {
12581556Srgrimes					if (pgetc() == ')') {
1259206145Sjilles						if (level > 0 &&
1260206145Sjilles						    state[level].category == TSTATE_ARITH) {
1261206145Sjilles							level--;
12621556Srgrimes							USTPUTC(CTLENDARI, out);
12631556Srgrimes						} else
12641556Srgrimes							USTPUTC(')', out);
12651556Srgrimes					} else {
12668855Srgrimes						/*
12671556Srgrimes						 * unbalanced parens
12681556Srgrimes						 *  (don't 2nd guess - no error)
12691556Srgrimes						 */
12701556Srgrimes						pungetc();
12711556Srgrimes						USTPUTC(')', out);
12721556Srgrimes					}
12731556Srgrimes				}
12741556Srgrimes				break;
12751556Srgrimes			case CBQUOTE:	/* '`' */
1276206145Sjilles				out = parsebackq(out, &bqlist, 1,
1277206145Sjilles				    state[level].syntax == DQSYNTAX &&
1278206145Sjilles				    (eofmark == NULL || newvarnest > 0),
1279206145Sjilles				    state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
12801556Srgrimes				break;
12811556Srgrimes			case CEOF:
12821556Srgrimes				goto endword;		/* exit outer loop */
1283214305Sjilles			case CIGN:
1284214305Sjilles				break;
12851556Srgrimes			default:
1286206145Sjilles				if (level == 0)
12871556Srgrimes					goto endword;	/* exit outer loop */
12881556Srgrimes				USTPUTC(c, out);
12891556Srgrimes			}
12901556Srgrimes			c = pgetc_macro();
12911556Srgrimes		}
12921556Srgrimes	}
12931556Srgrimesendword:
1294206145Sjilles	if (state[level].syntax == ARISYNTAX)
12951556Srgrimes		synerror("Missing '))'");
1296206145Sjilles	if (state[level].syntax != BASESYNTAX && eofmark == NULL)
12971556Srgrimes		synerror("Unterminated quoted string");
1298206145Sjilles	if (state[level].category == TSTATE_VAR_OLD ||
1299206145Sjilles	    state[level].category == TSTATE_VAR_NEW) {
13001556Srgrimes		startlinno = plinno;
13011556Srgrimes		synerror("Missing '}'");
13021556Srgrimes	}
1303206145Sjilles	if (state != state_static)
1304206145Sjilles		parser_temp_free_upto(state);
13051556Srgrimes	USTPUTC('\0', out);
13061556Srgrimes	len = out - stackblock();
13071556Srgrimes	out = stackblock();
13081556Srgrimes	if (eofmark == NULL) {
13091556Srgrimes		if ((c == '>' || c == '<')
13101556Srgrimes		 && quotef == 0
13111556Srgrimes		 && len <= 2
13121556Srgrimes		 && (*out == '\0' || is_digit(*out))) {
13131556Srgrimes			PARSEREDIR();
13141556Srgrimes			return lasttoken = TREDIR;
13151556Srgrimes		} else {
13161556Srgrimes			pungetc();
13171556Srgrimes		}
13181556Srgrimes	}
13191556Srgrimes	quoteflag = quotef;
13201556Srgrimes	backquotelist = bqlist;
13211556Srgrimes	grabstackblock(len);
13221556Srgrimes	wordtext = out;
13231556Srgrimes	return lasttoken = TWORD;
13241556Srgrimes/* end of readtoken routine */
13251556Srgrimes
13261556Srgrimes
13271556Srgrimes/*
13281556Srgrimes * Check to see whether we are at the end of the here document.  When this
13291556Srgrimes * is called, c is set to the first character of the next input line.  If
13301556Srgrimes * we are at the end of the here document, this routine sets the c to PEOF.
13311556Srgrimes */
13321556Srgrimes
13331556Srgrimescheckend: {
13341556Srgrimes	if (eofmark) {
13351556Srgrimes		if (striptabs) {
13361556Srgrimes			while (c == '\t')
13371556Srgrimes				c = pgetc();
13381556Srgrimes		}
13391556Srgrimes		if (c == *eofmark) {
13401556Srgrimes			if (pfgets(line, sizeof line) != NULL) {
134125230Ssteve				char *p, *q;
13421556Srgrimes
13431556Srgrimes				p = line;
13441556Srgrimes				for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
13451556Srgrimes				if (*p == '\n' && *q == '\0') {
13461556Srgrimes					c = PEOF;
13471556Srgrimes					plinno++;
13481556Srgrimes					needprompt = doprompt;
13491556Srgrimes				} else {
13501556Srgrimes					pushstring(line, strlen(line), NULL);
13511556Srgrimes				}
13521556Srgrimes			}
13531556Srgrimes		}
13541556Srgrimes	}
13551556Srgrimes	goto checkend_return;
13561556Srgrimes}
13571556Srgrimes
13581556Srgrimes
13591556Srgrimes/*
13601556Srgrimes * Parse a redirection operator.  The variable "out" points to a string
13611556Srgrimes * specifying the fd to be redirected.  The variable "c" contains the
13621556Srgrimes * first character of the redirection operator.
13631556Srgrimes */
13641556Srgrimes
13651556Srgrimesparseredir: {
13661556Srgrimes	char fd = *out;
13671556Srgrimes	union node *np;
13681556Srgrimes
13691556Srgrimes	np = (union node *)stalloc(sizeof (struct nfile));
13701556Srgrimes	if (c == '>') {
13711556Srgrimes		np->nfile.fd = 1;
13721556Srgrimes		c = pgetc();
13731556Srgrimes		if (c == '>')
13741556Srgrimes			np->type = NAPPEND;
13751556Srgrimes		else if (c == '&')
13761556Srgrimes			np->type = NTOFD;
137796922Stjr		else if (c == '|')
137896922Stjr			np->type = NCLOBBER;
13791556Srgrimes		else {
13801556Srgrimes			np->type = NTO;
13811556Srgrimes			pungetc();
13821556Srgrimes		}
13831556Srgrimes	} else {	/* c == '<' */
13841556Srgrimes		np->nfile.fd = 0;
13851556Srgrimes		c = pgetc();
13861556Srgrimes		if (c == '<') {
13871556Srgrimes			if (sizeof (struct nfile) != sizeof (struct nhere)) {
13881556Srgrimes				np = (union node *)stalloc(sizeof (struct nhere));
13891556Srgrimes				np->nfile.fd = 0;
13901556Srgrimes			}
13911556Srgrimes			np->type = NHERE;
13921556Srgrimes			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
13931556Srgrimes			heredoc->here = np;
13941556Srgrimes			if ((c = pgetc()) == '-') {
13951556Srgrimes				heredoc->striptabs = 1;
13961556Srgrimes			} else {
13971556Srgrimes				heredoc->striptabs = 0;
13981556Srgrimes				pungetc();
13991556Srgrimes			}
14001556Srgrimes		} else if (c == '&')
14011556Srgrimes			np->type = NFROMFD;
140266612Sbrian		else if (c == '>')
140366612Sbrian			np->type = NFROMTO;
14041556Srgrimes		else {
14051556Srgrimes			np->type = NFROM;
14061556Srgrimes			pungetc();
14071556Srgrimes		}
14081556Srgrimes	}
14091556Srgrimes	if (fd != '\0')
14101556Srgrimes		np->nfile.fd = digit_val(fd);
14111556Srgrimes	redirnode = np;
14121556Srgrimes	goto parseredir_return;
14131556Srgrimes}
14141556Srgrimes
14151556Srgrimes
14161556Srgrimes/*
14171556Srgrimes * Parse a substitution.  At this point, we have read the dollar sign
14181556Srgrimes * and nothing else.
14191556Srgrimes */
14201556Srgrimes
14211556Srgrimesparsesub: {
1422179022Sstefanf	char buf[10];
14231556Srgrimes	int subtype;
14241556Srgrimes	int typeloc;
14251556Srgrimes	int flags;
14261556Srgrimes	char *p;
14271556Srgrimes	static const char types[] = "}-+?=";
1428179022Sstefanf	int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1429179022Sstefanf	int i;
1430179022Sstefanf	int linno;
1431179387Sstefanf	int length;
14321556Srgrimes
14331556Srgrimes	c = pgetc();
1434149026Sstefanf	if (c != '(' && c != '{' && (is_eof(c) || !is_name(c)) &&
1435149026Sstefanf	    !is_special(c)) {
14361556Srgrimes		USTPUTC('$', out);
14371556Srgrimes		pungetc();
14381556Srgrimes	} else if (c == '(') {	/* $(command) or $((arith)) */
14391556Srgrimes		if (pgetc() == '(') {
14401556Srgrimes			PARSEARITH();
14411556Srgrimes		} else {
14421556Srgrimes			pungetc();
1443206145Sjilles			out = parsebackq(out, &bqlist, 0,
1444206145Sjilles			    state[level].syntax == DQSYNTAX &&
1445206145Sjilles			    (eofmark == NULL || newvarnest > 0),
1446206145Sjilles			    state[level].syntax == DQSYNTAX ||
1447206145Sjilles			    state[level].syntax == ARISYNTAX);
14481556Srgrimes		}
14491556Srgrimes	} else {
14501556Srgrimes		USTPUTC(CTLVAR, out);
14511556Srgrimes		typeloc = out - stackblock();
14521556Srgrimes		USTPUTC(VSNORMAL, out);
14531556Srgrimes		subtype = VSNORMAL;
1454179022Sstefanf		flags = 0;
14551556Srgrimes		if (c == '{') {
145618202Speter			bracketed_name = 1;
14571556Srgrimes			c = pgetc();
145817987Speter			if (c == '#') {
145917987Speter				if ((c = pgetc()) == '}')
146017987Speter					c = '#';
146117987Speter				else
146217987Speter					subtype = VSLENGTH;
146317987Speter			}
146417987Speter			else
146517987Speter				subtype = 0;
14661556Srgrimes		}
1467149026Sstefanf		if (!is_eof(c) && is_name(c)) {
1468179387Sstefanf			length = 0;
14691556Srgrimes			do {
14701556Srgrimes				STPUTC(c, out);
14711556Srgrimes				c = pgetc();
1472179387Sstefanf				length++;
1473149026Sstefanf			} while (!is_eof(c) && is_in_name(c));
1474179387Sstefanf			if (length == 6 &&
1475179387Sstefanf			    strncmp(out - length, "LINENO", length) == 0) {
1476179022Sstefanf				/* Replace the variable name with the
1477179022Sstefanf				 * current line number. */
1478179022Sstefanf				linno = plinno;
1479179022Sstefanf				if (funclinno != 0)
1480179022Sstefanf					linno -= funclinno - 1;
1481179022Sstefanf				snprintf(buf, sizeof(buf), "%d", linno);
1482179022Sstefanf				STADJUST(-6, out);
1483179022Sstefanf				for (i = 0; buf[i] != '\0'; i++)
1484179022Sstefanf					STPUTC(buf[i], out);
1485179022Sstefanf				flags |= VSLINENO;
1486179022Sstefanf			}
148718202Speter		} else if (is_digit(c)) {
148818202Speter			if (bracketed_name) {
148918202Speter				do {
149018202Speter					STPUTC(c, out);
149118202Speter					c = pgetc();
149218202Speter				} while (is_digit(c));
149318202Speter			} else {
149418202Speter				STPUTC(c, out);
149518202Speter				c = pgetc();
149618202Speter			}
14971556Srgrimes		} else {
1498164003Sstefanf			if (! is_special(c)) {
1499164003Sstefanf				subtype = VSERROR;
1500164003Sstefanf				if (c == '}')
1501164003Sstefanf					pungetc();
1502206144Sjilles				else if (c == '\n' || c == PEOF)
1503206144Sjilles					synerror("Unexpected end of line in substitution");
1504164003Sstefanf				else
1505164003Sstefanf					USTPUTC(c, out);
1506164003Sstefanf			} else {
1507164003Sstefanf				USTPUTC(c, out);
1508164003Sstefanf				c = pgetc();
1509164003Sstefanf			}
15101556Srgrimes		}
15111556Srgrimes		if (subtype == 0) {
151217987Speter			switch (c) {
151317987Speter			case ':':
1514179022Sstefanf				flags |= VSNUL;
15151556Srgrimes				c = pgetc();
151617987Speter				/*FALLTHROUGH*/
151717987Speter			default:
151817987Speter				p = strchr(types, c);
1519164003Sstefanf				if (p == NULL) {
1520206144Sjilles					if (c == '\n' || c == PEOF)
1521206144Sjilles						synerror("Unexpected end of line in substitution");
1522164003Sstefanf					if (flags == VSNUL)
1523164003Sstefanf						STPUTC(':', out);
1524164003Sstefanf					STPUTC(c, out);
1525164003Sstefanf					subtype = VSERROR;
1526164003Sstefanf				} else
1527164003Sstefanf					subtype = p - types + VSNORMAL;
152817987Speter				break;
152917987Speter			case '%':
153020425Ssteve			case '#':
153117987Speter				{
153217987Speter					int cc = c;
153317987Speter					subtype = c == '#' ? VSTRIMLEFT :
153417987Speter							     VSTRIMRIGHT;
153517987Speter					c = pgetc();
153617987Speter					if (c == cc)
153717987Speter						subtype++;
153817987Speter					else
153917987Speter						pungetc();
154017987Speter					break;
154117987Speter				}
15421556Srgrimes			}
1543164003Sstefanf		} else if (subtype != VSERROR) {
15441556Srgrimes			pungetc();
15451556Srgrimes		}
1546164003Sstefanf		STPUTC('=', out);
1547206145Sjilles		if (subtype != VSLENGTH && (state[level].syntax == DQSYNTAX ||
1548206145Sjilles		    state[level].syntax == ARISYNTAX))
15491556Srgrimes			flags |= VSQUOTE;
15501556Srgrimes		*(stackblock() + typeloc) = subtype | flags;
1551206145Sjilles		if (subtype != VSNORMAL) {
1552206145Sjilles			if (level + 1 >= maxnest) {
1553206145Sjilles				maxnest *= 2;
1554206145Sjilles				if (state == state_static) {
1555206145Sjilles					state = parser_temp_alloc(
1556206145Sjilles					    maxnest * sizeof(*state));
1557206145Sjilles					memcpy(state, state_static,
1558213811Sobrien					    MAXNEST_static * sizeof(*state));
1559206145Sjilles				} else
1560206145Sjilles					state = parser_temp_realloc(state,
1561206145Sjilles					    maxnest * sizeof(*state));
1562206145Sjilles			}
1563206145Sjilles			level++;
1564206145Sjilles			state[level].parenlevel = 0;
1565206145Sjilles			if (subtype == VSMINUS || subtype == VSPLUS ||
1566206145Sjilles			    subtype == VSQUESTION || subtype == VSASSIGN) {
1567206145Sjilles				/*
1568206145Sjilles				 * For operators that were in the Bourne shell,
1569206145Sjilles				 * inherit the double-quote state.
1570206145Sjilles				 */
1571206145Sjilles				state[level].syntax = state[level - 1].syntax;
1572206145Sjilles				state[level].category = TSTATE_VAR_OLD;
1573206145Sjilles			} else {
1574206145Sjilles				/*
1575206145Sjilles				 * The other operators take a pattern,
1576206145Sjilles				 * so go to BASESYNTAX.
1577206145Sjilles				 * Also, ' and " are now special, even
1578206145Sjilles				 * in here documents.
1579206145Sjilles				 */
1580206145Sjilles				state[level].syntax = BASESYNTAX;
1581206145Sjilles				state[level].category = TSTATE_VAR_NEW;
1582206145Sjilles				newvarnest++;
1583206145Sjilles			}
1584206145Sjilles		}
15851556Srgrimes	}
15861556Srgrimes	goto parsesub_return;
15871556Srgrimes}
15881556Srgrimes
15891556Srgrimes
15901556Srgrimes/*
15911556Srgrimes * Parse an arithmetic expansion (indicate start of one and set state)
15921556Srgrimes */
15931556Srgrimesparsearith: {
15941556Srgrimes
1595206145Sjilles	if (level + 1 >= maxnest) {
1596206145Sjilles		maxnest *= 2;
1597206145Sjilles		if (state == state_static) {
1598206145Sjilles			state = parser_temp_alloc(
1599206145Sjilles			    maxnest * sizeof(*state));
1600206145Sjilles			memcpy(state, state_static,
1601213811Sobrien			    MAXNEST_static * sizeof(*state));
1602206145Sjilles		} else
1603206145Sjilles			state = parser_temp_realloc(state,
1604206145Sjilles			    maxnest * sizeof(*state));
16051556Srgrimes	}
1606206145Sjilles	level++;
1607206145Sjilles	state[level].syntax = ARISYNTAX;
1608206145Sjilles	state[level].parenlevel = 0;
1609206145Sjilles	state[level].category = TSTATE_ARITH;
1610206145Sjilles	USTPUTC(CTLARI, out);
1611206145Sjilles	if (state[level - 1].syntax == DQSYNTAX)
1612206145Sjilles		USTPUTC('"',out);
1613206145Sjilles	else
1614206145Sjilles		USTPUTC(' ',out);
16151556Srgrimes	goto parsearith_return;
16161556Srgrimes}
16171556Srgrimes
16181556Srgrimes} /* end of readtoken */
16191556Srgrimes
16201556Srgrimes
16211556Srgrimes
16221556Srgrimes#ifdef mkinit
16231556SrgrimesRESET {
16241556Srgrimes	tokpushback = 0;
16251556Srgrimes	checkkwd = 0;
16261556Srgrimes}
16271556Srgrimes#endif
16281556Srgrimes
16291556Srgrimes/*
16301556Srgrimes * Returns true if the text contains nothing to expand (no dollar signs
16311556Srgrimes * or backquotes).
16321556Srgrimes */
16331556Srgrimes
1634213811Sobrienstatic int
163590111Simpnoexpand(char *text)
163690111Simp{
163725230Ssteve	char *p;
163825230Ssteve	char c;
16391556Srgrimes
16401556Srgrimes	p = text;
16411556Srgrimes	while ((c = *p++) != '\0') {
164239137Stegge		if ( c == CTLQUOTEMARK)
164339137Stegge			continue;
16441556Srgrimes		if (c == CTLESC)
16451556Srgrimes			p++;
164683675Stegge		else if (BASESYNTAX[(int)c] == CCTL)
16471556Srgrimes			return 0;
16481556Srgrimes	}
16491556Srgrimes	return 1;
16501556Srgrimes}
16511556Srgrimes
16521556Srgrimes
16531556Srgrimes/*
16541556Srgrimes * Return true if the argument is a legal variable name (a letter or
16551556Srgrimes * underscore followed by zero or more letters, underscores, and digits).
16561556Srgrimes */
16571556Srgrimes
16581556Srgrimesint
1659200956Sjillesgoodname(const char *name)
166090111Simp{
1661200956Sjilles	const char *p;
16621556Srgrimes
16631556Srgrimes	p = name;
16641556Srgrimes	if (! is_name(*p))
16651556Srgrimes		return 0;
16661556Srgrimes	while (*++p) {
16671556Srgrimes		if (! is_in_name(*p))
16681556Srgrimes			return 0;
16691556Srgrimes	}
16701556Srgrimes	return 1;
16711556Srgrimes}
16721556Srgrimes
16731556Srgrimes
16741556Srgrimes/*
16751556Srgrimes * Called when an unexpected token is read during the parse.  The argument
16761556Srgrimes * is the token that is expected, or -1 if more than one type of token can
16771556Srgrimes * occur at this point.
16781556Srgrimes */
16791556Srgrimes
1680213811Sobrienstatic void
168190111Simpsynexpect(int token)
168217987Speter{
16831556Srgrimes	char msg[64];
16841556Srgrimes
16851556Srgrimes	if (token >= 0) {
16861556Srgrimes		fmtstr(msg, 64, "%s unexpected (expecting %s)",
16871556Srgrimes			tokname[lasttoken], tokname[token]);
16881556Srgrimes	} else {
16891556Srgrimes		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
16901556Srgrimes	}
16911556Srgrimes	synerror(msg);
16921556Srgrimes}
16931556Srgrimes
16941556Srgrimes
1695213811Sobrienstatic void
1696201053Sjillessynerror(const char *msg)
169790111Simp{
16981556Srgrimes	if (commandname)
1699201366Sjilles		outfmt(out2, "%s: %d: ", commandname, startlinno);
1700201366Sjilles	outfmt(out2, "Syntax error: %s\n", msg);
17011556Srgrimes	error((char *)NULL);
17021556Srgrimes}
17031556Srgrimes
1704213811Sobrienstatic void
170590111Simpsetprompt(int which)
170690111Simp{
17071556Srgrimes	whichprompt = which;
17081556Srgrimes
170917987Speter#ifndef NO_HISTORY
17101556Srgrimes	if (!el)
171117987Speter#endif
1712199629Sjilles	{
17131556Srgrimes		out2str(getprompt(NULL));
1714199629Sjilles		flushout(out2);
1715199629Sjilles	}
17161556Srgrimes}
17171556Srgrimes
17181556Srgrimes/*
17191556Srgrimes * called by editline -- any expansions to the prompt
17201556Srgrimes *    should be added here.
17211556Srgrimes */
17221556Srgrimeschar *
172390111Simpgetprompt(void *unused __unused)
172425905Ssteve{
1725142845Sobrien	static char ps[PROMPTLEN];
1726142845Sobrien	char *fmt;
1727209653Sjilles	const char *pwd;
1728209653Sjilles	int i, trim;
1729201053Sjilles	static char internal_error[] = "<internal prompt error>";
1730142845Sobrien
1731142845Sobrien	/*
1732142845Sobrien	 * Select prompt format.
1733142845Sobrien	 */
17341556Srgrimes	switch (whichprompt) {
17351556Srgrimes	case 0:
1736201053Sjilles		fmt = nullstr;
1737142845Sobrien		break;
17381556Srgrimes	case 1:
1739142845Sobrien		fmt = ps1val();
1740142845Sobrien		break;
17411556Srgrimes	case 2:
1742142845Sobrien		fmt = ps2val();
1743142845Sobrien		break;
17441556Srgrimes	default:
1745201053Sjilles		return internal_error;
17461556Srgrimes	}
1747142845Sobrien
1748142845Sobrien	/*
1749142845Sobrien	 * Format prompt string.
1750142845Sobrien	 */
1751142845Sobrien	for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1752142845Sobrien		if (*fmt == '\\')
1753142845Sobrien			switch (*++fmt) {
1754142845Sobrien
1755142845Sobrien				/*
1756142845Sobrien				 * Hostname.
1757142845Sobrien				 *
1758142845Sobrien				 * \h specifies just the local hostname,
1759142845Sobrien				 * \H specifies fully-qualified hostname.
1760142845Sobrien				 */
1761142845Sobrien			case 'h':
1762142845Sobrien			case 'H':
1763149024Sstefanf				ps[i] = '\0';
1764142845Sobrien				gethostname(&ps[i], PROMPTLEN - i);
1765142845Sobrien				/* Skip to end of hostname. */
1766142845Sobrien				trim = (*fmt == 'h') ? '.' : '\0';
1767142845Sobrien				while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1768142845Sobrien					i++;
1769142845Sobrien				break;
1770142845Sobrien
1771142845Sobrien				/*
1772142845Sobrien				 * Working directory.
1773142845Sobrien				 *
1774142845Sobrien				 * \W specifies just the final component,
1775142845Sobrien				 * \w specifies the entire path.
1776142845Sobrien				 */
1777142845Sobrien			case 'W':
1778142845Sobrien			case 'w':
1779209653Sjilles				pwd = lookupvar("PWD");
1780209653Sjilles				if (pwd == NULL)
1781209653Sjilles					pwd = "?";
1782209653Sjilles				if (*fmt == 'W' &&
1783209653Sjilles				    *pwd == '/' && pwd[1] != '\0')
1784209653Sjilles					strlcpy(&ps[i], strrchr(pwd, '/') + 1,
1785209653Sjilles					    PROMPTLEN - i);
1786209653Sjilles				else
1787209653Sjilles					strlcpy(&ps[i], pwd, PROMPTLEN - i);
1788142845Sobrien				/* Skip to end of path. */
1789142845Sobrien				while (ps[i + 1] != '\0')
1790142845Sobrien					i++;
1791142845Sobrien				break;
1792142845Sobrien
1793142845Sobrien				/*
1794142845Sobrien				 * Superuser status.
1795142845Sobrien				 *
1796142845Sobrien				 * '$' for normal users, '#' for root.
1797142845Sobrien				 */
1798142845Sobrien			case '$':
1799142845Sobrien				ps[i] = (geteuid() != 0) ? '$' : '#';
1800142845Sobrien				break;
1801142845Sobrien
1802142845Sobrien				/*
1803142845Sobrien				 * A literal \.
1804142845Sobrien				 */
1805142845Sobrien			case '\\':
1806142845Sobrien				ps[i] = '\\';
1807142845Sobrien				break;
1808142845Sobrien
1809142845Sobrien				/*
1810142845Sobrien				 * Emit unrecognized formats verbatim.
1811142845Sobrien				 */
1812142845Sobrien			default:
1813142845Sobrien				ps[i++] = '\\';
1814142845Sobrien				ps[i] = *fmt;
1815142845Sobrien				break;
1816142845Sobrien			}
1817142845Sobrien		else
1818142845Sobrien			ps[i] = *fmt;
1819142845Sobrien	ps[i] = '\0';
1820142845Sobrien	return (ps);
18211556Srgrimes}
1822