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