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