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