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