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