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