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