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