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