Home | History | Annotate | Line # | Download | only in sh
parser.c revision 1.122
      1 /*	$NetBSD: parser.c,v 1.122 2017/05/03 21:36:16 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kenneth Almquist.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)parser.c	8.7 (Berkeley) 5/16/95";
     39 #else
     40 __RCSID("$NetBSD: parser.c,v 1.122 2017/05/03 21:36:16 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <stdio.h>
     45 #include <stdlib.h>
     46 #include <limits.h>
     47 
     48 #include "shell.h"
     49 #include "parser.h"
     50 #include "nodes.h"
     51 #include "expand.h"	/* defines rmescapes() */
     52 #include "eval.h"	/* defines commandname */
     53 #include "syntax.h"
     54 #include "options.h"
     55 #include "input.h"
     56 #include "output.h"
     57 #include "var.h"
     58 #include "error.h"
     59 #include "memalloc.h"
     60 #include "mystring.h"
     61 #include "alias.h"
     62 #include "show.h"
     63 #ifndef SMALL
     64 #include "myhistedit.h"
     65 #endif
     66 
     67 /*
     68  * Shell command parser.
     69  */
     70 
     71 /* values returned by readtoken */
     72 #include "token.h"
     73 
     74 #define OPENBRACE '{'
     75 #define CLOSEBRACE '}'
     76 
     77 
     78 struct heredoc {
     79 	struct heredoc *next;	/* next here document in list */
     80 	union node *here;		/* redirection node */
     81 	char *eofmark;		/* string indicating end of input */
     82 	int striptabs;		/* if set, strip leading tabs */
     83 	int startline;		/* line number where << seen */
     84 };
     85 
     86 
     87 
     88 static int noalias = 0;		/* when set, don't handle aliases */
     89 struct heredoc *heredoclist;	/* list of here documents to read */
     90 int parsebackquote;		/* nonzero if we are inside backquotes */
     91 int doprompt;			/* if set, prompt the user */
     92 int needprompt;			/* true if interactive and at start of line */
     93 int lasttoken;			/* last token read */
     94 MKINIT int tokpushback;		/* last token pushed back */
     95 char *wordtext;			/* text of last word returned by readtoken */
     96 MKINIT int checkkwd;		/* 1 == check for kwds, 2 == also eat newlines */
     97 struct nodelist *backquotelist;
     98 union node *redirnode;
     99 struct heredoc *heredoc;
    100 int quoteflag;			/* set if (part of) last token was quoted */
    101 int startlinno;			/* line # where last token started */
    102 int funclinno;			/* line # where the current function started */
    103 
    104 
    105 STATIC union node *list(int, int);
    106 STATIC union node *andor(void);
    107 STATIC union node *pipeline(void);
    108 STATIC union node *command(void);
    109 STATIC union node *simplecmd(union node **, union node *);
    110 STATIC union node *makename(void);
    111 STATIC void parsefname(void);
    112 STATIC void slurp_heredoc(char *const, const int, const int);
    113 STATIC void readheredocs(void);
    114 STATIC int peektoken(void);
    115 STATIC int readtoken(void);
    116 STATIC int xxreadtoken(void);
    117 STATIC int readtoken1(int, char const *, int);
    118 STATIC int noexpand(char *);
    119 STATIC void synexpect(int, const char *) __dead;
    120 STATIC void synerror(const char *) __dead;
    121 STATIC void setprompt(int);
    122 STATIC int pgetc_linecont(void);
    123 
    124 
    125 static const char EOFhere[] = "EOF reading here (<<) document";
    126 
    127 
    128 /*
    129  * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
    130  * valid parse tree indicating a blank line.)
    131  */
    132 
    133 union node *
    134 parsecmd(int interact)
    135 {
    136 	int t;
    137 	union node *n;
    138 
    139 	tokpushback = 0;
    140 	doprompt = interact;
    141 	if (doprompt)
    142 		setprompt(1);
    143 	else
    144 		setprompt(0);
    145 	needprompt = 0;
    146 	t = readtoken();
    147 	if (t == TEOF)
    148 		return NEOF;
    149 	if (t == TNL)
    150 		return NULL;
    151 	tokpushback++;
    152 	n = list(1, 0);
    153 	if (heredoclist)
    154 		error("%d: Here document (<<%s) expected but not present",
    155 			heredoclist->startline, heredoclist->eofmark);
    156 	return n;
    157 }
    158 
    159 
    160 STATIC union node *
    161 list(int nlflag, int erflag)
    162 {
    163 	union node *n1, *n2, *n3;
    164 	int tok;
    165 	TRACE(("list(%d,%d): entered\n", nlflag, erflag));
    166 
    167 	checkkwd = 2;
    168 	if (nlflag == 0 && tokendlist[peektoken()])
    169 		return NULL;
    170 	n1 = NULL;
    171 	for (;;) {
    172 		n2 = andor();
    173 		tok = readtoken();
    174 		if (tok == TBACKGND) {
    175 			if (n2->type == NCMD || n2->type == NPIPE) {
    176 				n2->ncmd.backgnd = 1;
    177 			} else if (n2->type == NREDIR) {
    178 				n2->type = NBACKGND;
    179 			} else {
    180 				n3 = stalloc(sizeof(struct nredir));
    181 				n3->type = NBACKGND;
    182 				n3->nredir.n = n2;
    183 				n3->nredir.redirect = NULL;
    184 				n2 = n3;
    185 			}
    186 		}
    187 		if (n1 == NULL) {
    188 			n1 = n2;
    189 		}
    190 		else {
    191 			n3 = stalloc(sizeof(struct nbinary));
    192 			n3->type = NSEMI;
    193 			n3->nbinary.ch1 = n1;
    194 			n3->nbinary.ch2 = n2;
    195 			n1 = n3;
    196 		}
    197 		switch (tok) {
    198 		case TBACKGND:
    199 		case TSEMI:
    200 			tok = readtoken();
    201 			/* FALLTHROUGH */
    202 		case TNL:
    203 			if (tok == TNL) {
    204 				readheredocs();
    205 				if (nlflag)
    206 					return n1;
    207 			} else {
    208 				tokpushback++;
    209 			}
    210 			checkkwd = 2;
    211 			if (tokendlist[peektoken()])
    212 				return n1;
    213 			break;
    214 		case TEOF:
    215 			pungetc();	/* push back EOF on input */
    216 			return n1;
    217 		default:
    218 			if (nlflag || erflag)
    219 				synexpect(-1, 0);
    220 			tokpushback++;
    221 			return n1;
    222 		}
    223 	}
    224 }
    225 
    226 STATIC union node *
    227 andor(void)
    228 {
    229 	union node *n1, *n2, *n3;
    230 	int t;
    231 
    232 	TRACE(("andor: entered\n"));
    233 	n1 = pipeline();
    234 	for (;;) {
    235 		if ((t = readtoken()) == TAND) {
    236 			t = NAND;
    237 		} else if (t == TOR) {
    238 			t = NOR;
    239 		} else {
    240 			tokpushback++;
    241 			return n1;
    242 		}
    243 		n2 = pipeline();
    244 		n3 = stalloc(sizeof(struct nbinary));
    245 		n3->type = t;
    246 		n3->nbinary.ch1 = n1;
    247 		n3->nbinary.ch2 = n2;
    248 		n1 = n3;
    249 	}
    250 }
    251 
    252 STATIC union node *
    253 pipeline(void)
    254 {
    255 	union node *n1, *n2, *pipenode;
    256 	struct nodelist *lp, *prev;
    257 	int negate;
    258 
    259 	TRACE(("pipeline: entered\n"));
    260 
    261 	negate = 0;
    262 	checkkwd = 2;
    263 	while (readtoken() == TNOT) {
    264 		TRACE(("pipeline: TNOT recognized\n"));
    265 		negate = !negate;
    266 	}
    267 	tokpushback++;
    268 	n1 = command();
    269 	if (readtoken() == TPIPE) {
    270 		pipenode = stalloc(sizeof(struct npipe));
    271 		pipenode->type = NPIPE;
    272 		pipenode->npipe.backgnd = 0;
    273 		lp = stalloc(sizeof(struct nodelist));
    274 		pipenode->npipe.cmdlist = lp;
    275 		lp->n = n1;
    276 		do {
    277 			prev = lp;
    278 			lp = stalloc(sizeof(struct nodelist));
    279 			lp->n = command();
    280 			prev->next = lp;
    281 		} while (readtoken() == TPIPE);
    282 		lp->next = NULL;
    283 		n1 = pipenode;
    284 	}
    285 	tokpushback++;
    286 	if (negate) {
    287 		TRACE(("negate pipeline\n"));
    288 		n2 = stalloc(sizeof(struct nnot));
    289 		n2->type = NNOT;
    290 		n2->nnot.com = n1;
    291 		return n2;
    292 	} else
    293 		return n1;
    294 }
    295 
    296 
    297 
    298 STATIC union node *
    299 command(void)
    300 {
    301 	union node *n1, *n2;
    302 	union node *ap, **app;
    303 	union node *cp, **cpp;
    304 	union node *redir, **rpp;
    305 	int t, negate = 0;
    306 
    307 	TRACE(("command: entered\n"));
    308 
    309 	checkkwd = 2;
    310 	redir = NULL;
    311 	n1 = NULL;
    312 	rpp = &redir;
    313 
    314 	/* Check for redirection which may precede command */
    315 	while (readtoken() == TREDIR) {
    316 		*rpp = n2 = redirnode;
    317 		rpp = &n2->nfile.next;
    318 		parsefname();
    319 	}
    320 	tokpushback++;
    321 
    322 	while (readtoken() == TNOT) {
    323 		TRACE(("command: TNOT recognized\n"));
    324 		negate = !negate;
    325 	}
    326 	tokpushback++;
    327 
    328 	switch (readtoken()) {
    329 	case TIF:
    330 		n1 = stalloc(sizeof(struct nif));
    331 		n1->type = NIF;
    332 		n1->nif.test = list(0, 0);
    333 		if (readtoken() != TTHEN)
    334 			synexpect(TTHEN, 0);
    335 		n1->nif.ifpart = list(0, 0);
    336 		n2 = n1;
    337 		while (readtoken() == TELIF) {
    338 			n2->nif.elsepart = stalloc(sizeof(struct nif));
    339 			n2 = n2->nif.elsepart;
    340 			n2->type = NIF;
    341 			n2->nif.test = list(0, 0);
    342 			if (readtoken() != TTHEN)
    343 				synexpect(TTHEN, 0);
    344 			n2->nif.ifpart = list(0, 0);
    345 		}
    346 		if (lasttoken == TELSE)
    347 			n2->nif.elsepart = list(0, 0);
    348 		else {
    349 			n2->nif.elsepart = NULL;
    350 			tokpushback++;
    351 		}
    352 		if (readtoken() != TFI)
    353 			synexpect(TFI, 0);
    354 		checkkwd = 1;
    355 		break;
    356 	case TWHILE:
    357 	case TUNTIL: {
    358 		int got;
    359 		n1 = stalloc(sizeof(struct nbinary));
    360 		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
    361 		n1->nbinary.ch1 = list(0, 0);
    362 		if ((got=readtoken()) != TDO) {
    363 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
    364 			synexpect(TDO, 0);
    365 		}
    366 		n1->nbinary.ch2 = list(0, 0);
    367 		if (readtoken() != TDONE)
    368 			synexpect(TDONE, 0);
    369 		checkkwd = 1;
    370 		break;
    371 	}
    372 	case TFOR:
    373 		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
    374 			synerror("Bad for loop variable");
    375 		n1 = stalloc(sizeof(struct nfor));
    376 		n1->type = NFOR;
    377 		n1->nfor.var = wordtext;
    378 		if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
    379 			app = &ap;
    380 			while (readtoken() == TWORD) {
    381 				n2 = stalloc(sizeof(struct narg));
    382 				n2->type = NARG;
    383 				n2->narg.text = wordtext;
    384 				n2->narg.backquote = backquotelist;
    385 				*app = n2;
    386 				app = &n2->narg.next;
    387 			}
    388 			*app = NULL;
    389 			n1->nfor.args = ap;
    390 			if (lasttoken != TNL && lasttoken != TSEMI)
    391 				synexpect(-1, 0);
    392 		} else {
    393 			static char argvars[5] = {
    394 			    CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
    395 			};
    396 			n2 = stalloc(sizeof(struct narg));
    397 			n2->type = NARG;
    398 			n2->narg.text = argvars;
    399 			n2->narg.backquote = NULL;
    400 			n2->narg.next = NULL;
    401 			n1->nfor.args = n2;
    402 			/*
    403 			 * Newline or semicolon here is optional (but note
    404 			 * that the original Bourne shell only allowed NL).
    405 			 */
    406 			if (lasttoken != TNL && lasttoken != TSEMI)
    407 				tokpushback++;
    408 		}
    409 		checkkwd = 2;
    410 		if ((t = readtoken()) == TDO)
    411 			t = TDONE;
    412 		else if (t == TBEGIN)
    413 			t = TEND;
    414 		else
    415 			synexpect(-1, 0);
    416 		n1->nfor.body = list(0, 0);
    417 		if (readtoken() != t)
    418 			synexpect(t, 0);
    419 		checkkwd = 1;
    420 		break;
    421 	case TCASE:
    422 		n1 = stalloc(sizeof(struct ncase));
    423 		n1->type = NCASE;
    424 		if (readtoken() != TWORD)
    425 			synexpect(TWORD, 0);
    426 		n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
    427 		n2->type = NARG;
    428 		n2->narg.text = wordtext;
    429 		n2->narg.backquote = backquotelist;
    430 		n2->narg.next = NULL;
    431 		while (readtoken() == TNL);
    432 		if (lasttoken != TWORD || ! equal(wordtext, "in"))
    433 			synexpect(-1, "in");
    434 		cpp = &n1->ncase.cases;
    435 		noalias = 1;
    436 		checkkwd = 2, readtoken();
    437 		/*
    438 		 * Both ksh and bash accept 'case x in esac'
    439 		 * so configure scripts started taking advantage of this.
    440 		 * The page: http://pubs.opengroup.org/onlinepubs/\
    441 		 * 009695399/utilities/xcu_chap02.html contradicts itself,
    442 		 * as to if this is legal; the "Case Conditional Format"
    443 		 * paragraph shows one case is required, but the "Grammar"
    444 		 * section shows a grammar that explicitly allows the no
    445 		 * case option.
    446 		 */
    447 		while (lasttoken != TESAC) {
    448 			*cpp = cp = stalloc(sizeof(struct nclist));
    449 			if (lasttoken == TLP)
    450 				readtoken();
    451 			cp->type = NCLIST;
    452 			app = &cp->nclist.pattern;
    453 			for (;;) {
    454 				*app = ap = stalloc(sizeof(struct narg));
    455 				ap->type = NARG;
    456 				ap->narg.text = wordtext;
    457 				ap->narg.backquote = backquotelist;
    458 				if (checkkwd = 2, readtoken() != TPIPE)
    459 					break;
    460 				app = &ap->narg.next;
    461 				readtoken();
    462 			}
    463 			ap->narg.next = NULL;
    464 			noalias = 0;
    465 			if (lasttoken != TRP) {
    466 				synexpect(TRP, 0);
    467 			}
    468 			cp->nclist.body = list(0, 0);
    469 
    470 			checkkwd = 2;
    471 			if ((t = readtoken()) != TESAC) {
    472 				if (t != TENDCASE) {
    473 					noalias = 0;
    474 					synexpect(TENDCASE, 0);
    475 				} else {
    476 					noalias = 1;
    477 					checkkwd = 2;
    478 					readtoken();
    479 				}
    480 			}
    481 			cpp = &cp->nclist.next;
    482 		}
    483 		noalias = 0;
    484 		*cpp = NULL;
    485 		checkkwd = 1;
    486 		break;
    487 	case TLP:
    488 		n1 = stalloc(sizeof(struct nredir));
    489 		n1->type = NSUBSHELL;
    490 		n1->nredir.n = list(0, 0);
    491 		n1->nredir.redirect = NULL;
    492 		if (n1->nredir.n == NULL)
    493 			synexpect(-1, 0);
    494 		if (readtoken() != TRP)
    495 			synexpect(TRP, 0);
    496 		checkkwd = 1;
    497 		break;
    498 	case TBEGIN:
    499 		n1 = list(0, 0);
    500 		if (posix && n1 == NULL)
    501 			synexpect(-1, 0);
    502 		if (readtoken() != TEND)
    503 			synexpect(TEND, 0);
    504 		checkkwd = 1;
    505 		break;
    506 
    507 	case TSEMI:
    508 	case TAND:
    509 	case TOR:
    510 	case TPIPE:
    511 	case TNL:
    512 	case TEOF:
    513 	case TRP:
    514 		/*
    515 		 * simple commands must have something in them,
    516 		 * either a word (which at this point includes a=b)
    517 		 * or a redirection.  If we reached the end of the
    518 		 * command (which one of these tokens indicates)
    519 		 * when we are just starting, and have not had a
    520 		 * redirect, then ...
    521 		 *
    522 		 * nb: it is still possible to end up with empty
    523 		 * simple commands, if the "command" is a var
    524 		 * expansion that produces nothing
    525 		 *	X= ; $X && $X
    526 		 * -->          &&
    527 		 * I am not sure if this is intended to be legal or not.
    528 		 */
    529 		if (!redir)
    530 			synexpect(-1, 0);
    531 	case TWORD:
    532 		tokpushback++;
    533 		n1 = simplecmd(rpp, redir);
    534 		goto checkneg;
    535 	case TENDCASE:
    536 		if (redir) {
    537 			tokpushback++;
    538 			goto checkneg;
    539 		}
    540 		/* FALLTHROUGH */
    541 	default:
    542 		synexpect(-1, 0);
    543 		/* NOTREACHED */
    544 	}
    545 
    546 	/* Now check for redirection which may follow command */
    547 	while (readtoken() == TREDIR) {
    548 		*rpp = n2 = redirnode;
    549 		rpp = &n2->nfile.next;
    550 		parsefname();
    551 	}
    552 	tokpushback++;
    553 	*rpp = NULL;
    554 	if (redir) {
    555 		if (n1->type != NSUBSHELL) {
    556 			n2 = stalloc(sizeof(struct nredir));
    557 			n2->type = NREDIR;
    558 			n2->nredir.n = n1;
    559 			n1 = n2;
    560 		}
    561 		n1->nredir.redirect = redir;
    562 	}
    563 
    564 checkneg:
    565 	if (negate) {
    566 		TRACE(("negate command\n"));
    567 		n2 = stalloc(sizeof(struct nnot));
    568 		n2->type = NNOT;
    569 		n2->nnot.com = n1;
    570 		return n2;
    571 	}
    572 	else
    573 		return n1;
    574 }
    575 
    576 
    577 STATIC union node *
    578 simplecmd(union node **rpp, union node *redir)
    579 {
    580 	union node *args, **app;
    581 	union node *n = NULL, *n2;
    582 	int negate = 0;
    583 
    584 	/* If we don't have any redirections already, then we must reset */
    585 	/* rpp to be the address of the local redir variable.  */
    586 	if (redir == 0)
    587 		rpp = &redir;
    588 
    589 	args = NULL;
    590 	app = &args;
    591 
    592 	while (readtoken() == TNOT) {
    593 		TRACE(("simplcmd: TNOT recognized\n"));
    594 		negate = !negate;
    595 	}
    596 	tokpushback++;
    597 
    598 	for (;;) {
    599 		if (readtoken() == TWORD) {
    600 			n = stalloc(sizeof(struct narg));
    601 			n->type = NARG;
    602 			n->narg.text = wordtext;
    603 			n->narg.backquote = backquotelist;
    604 			*app = n;
    605 			app = &n->narg.next;
    606 		} else if (lasttoken == TREDIR) {
    607 			*rpp = n = redirnode;
    608 			rpp = &n->nfile.next;
    609 			parsefname();	/* read name of redirection file */
    610 		} else if (lasttoken == TLP && app == &args->narg.next
    611 					    && redir == 0) {
    612 			/* We have a function */
    613 			if (readtoken() != TRP)
    614 				synexpect(TRP, 0);
    615 			funclinno = plinno;
    616 			rmescapes(n->narg.text);
    617 			if (strchr(n->narg.text, '/'))
    618 				synerror("Bad function name");
    619 			n->type = NDEFUN;
    620 			n->narg.next = command();
    621 			funclinno = 0;
    622 			goto checkneg;
    623 		} else {
    624 			tokpushback++;
    625 			break;
    626 		}
    627 	}
    628 
    629 	if (args == NULL && redir == NULL)
    630 		synexpect(-1, 0);
    631 	*app = NULL;
    632 	*rpp = NULL;
    633 	n = stalloc(sizeof(struct ncmd));
    634 	n->type = NCMD;
    635 	n->ncmd.backgnd = 0;
    636 	n->ncmd.args = args;
    637 	n->ncmd.redirect = redir;
    638 
    639 checkneg:
    640 	if (negate) {
    641 		TRACE(("negate simplecmd\n"));
    642 		n2 = stalloc(sizeof(struct nnot));
    643 		n2->type = NNOT;
    644 		n2->nnot.com = n;
    645 		return n2;
    646 	}
    647 	else
    648 		return n;
    649 }
    650 
    651 STATIC union node *
    652 makename(void)
    653 {
    654 	union node *n;
    655 
    656 	n = stalloc(sizeof(struct narg));
    657 	n->type = NARG;
    658 	n->narg.next = NULL;
    659 	n->narg.text = wordtext;
    660 	n->narg.backquote = backquotelist;
    661 	return n;
    662 }
    663 
    664 void
    665 fixredir(union node *n, const char *text, int err)
    666 {
    667 	TRACE(("Fix redir %s %d\n", text, err));
    668 	if (!err)
    669 		n->ndup.vname = NULL;
    670 
    671 	if (is_number(text))
    672 		n->ndup.dupfd = number(text);
    673 	else if (text[0] == '-' && text[1] == '\0')
    674 		n->ndup.dupfd = -1;
    675 	else {
    676 
    677 		if (err)
    678 			synerror("Bad fd number");
    679 		else
    680 			n->ndup.vname = makename();
    681 	}
    682 }
    683 
    684 
    685 STATIC void
    686 parsefname(void)
    687 {
    688 	union node *n = redirnode;
    689 
    690 	if (readtoken() != TWORD)
    691 		synexpect(-1, 0);
    692 	if (n->type == NHERE) {
    693 		struct heredoc *here = heredoc;
    694 		struct heredoc *p;
    695 
    696 		if (quoteflag == 0)
    697 			n->type = NXHERE;
    698 		TRACE(("Here document %d\n", n->type));
    699 		if (here->striptabs) {
    700 			while (*wordtext == '\t')
    701 				wordtext++;
    702 		}
    703 
    704 		/*
    705 		 * this test is not really necessary, we are not
    706 		 * required to expand wordtext, but there's no reason
    707 		 * it cannot be $$ or something like that - that would
    708 		 * not mean the pid, but literally two '$' characters.
    709 		 * There is no need for limits on what the word can be.
    710 		 * However, it needs to stay literal as entered, not
    711 		 * have $ converted to CTLVAR or something, which as
    712 		 * the parser is, at the minute, is impossible to prevent.
    713 		 * So, leave it like this until the rest of the parser is fixed.
    714 		 */
    715 		if (! noexpand(wordtext))
    716 			synerror("Illegal eof marker for << redirection");
    717 
    718 		rmescapes(wordtext);
    719 		here->eofmark = wordtext;
    720 		here->next = NULL;
    721 		if (heredoclist == NULL)
    722 			heredoclist = here;
    723 		else {
    724 			for (p = heredoclist ; p->next ; p = p->next)
    725 				continue;
    726 			p->next = here;
    727 		}
    728 	} else if (n->type == NTOFD || n->type == NFROMFD) {
    729 		fixredir(n, wordtext, 0);
    730 	} else {
    731 		n->nfile.fname = makename();
    732 	}
    733 }
    734 
    735 /*
    736  * Check to see whether we are at the end of the here document.  When this
    737  * is called, c is set to the first character of the next input line.  If
    738  * we are at the end of the here document, this routine sets the c to PEOF.
    739  * The new value of c is returned.
    740  */
    741 
    742 static int
    743 checkend(int c, char * const eofmark, const int striptabs)
    744 {
    745 	if (striptabs) {
    746 		while (c == '\t')
    747 			c = pgetc();
    748 	}
    749 	if (c == PEOF) {
    750 		if (*eofmark == '\0')
    751 			return (c);
    752 		synerror(EOFhere);
    753 	}
    754 	if (c == *eofmark) {
    755 		int c2;
    756 		char *q;
    757 
    758 		for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
    759 			;
    760 		if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
    761 			c = PEOF;
    762 			if (c2 == '\n') {
    763 				plinno++;
    764 				needprompt = doprompt;
    765 			}
    766 		} else {
    767 			pungetc();
    768 			pushstring(eofmark + 1, q - (eofmark + 1), NULL);
    769 		}
    770 	} else if (c == '\n' && *eofmark == '\0') {
    771 		c = PEOF;
    772 		plinno++;
    773 		needprompt = doprompt;
    774 	}
    775 	return (c);
    776 }
    777 
    778 
    779 /*
    780  * Input any here documents.
    781  */
    782 
    783 STATIC void
    784 slurp_heredoc(char *const eofmark, const int striptabs, const int sq)
    785 {
    786 	int c;
    787 	char *out;
    788 
    789 	c = pgetc();
    790 
    791 	/*
    792 	 * If we hit EOF on the input, and the eofmark is a null string ('')
    793 	 * we consider this empty line to be the eofmark, and exit without err.
    794 	 */
    795 	if (c == PEOF && *eofmark != '\0')
    796 		synerror(EOFhere);
    797 
    798 	STARTSTACKSTR(out);
    799 
    800 	while ((c = checkend(c, eofmark, striptabs)) != PEOF) {
    801 		do {
    802 			if (sq) {
    803 				/*
    804 				 * in single quoted mode (eofmark quoted)
    805 				 * all we look for is \n so we can check
    806 				 * for the epfmark - everything saved literally.
    807 				 */
    808 				STPUTC(c, out);
    809 				if (c == '\n') {
    810 					plinno++;
    811 					break;
    812 				}
    813 				continue;
    814 			}
    815 			/*
    816 			 * In double quoted (non-quoted eofmark)
    817 			 * we must handle \ followed by \n here
    818 			 * otherwise we can mismatch the end mark.
    819 			 * All other uses of \ will be handled later
    820 			 * when the here doc is expanded.
    821 			 *
    822 			 * This also makes sure \\ followed by \n does
    823 			 * not suppress the newline (the \ quotes itself)
    824 			 */
    825 			if (c == '\\') {		/* A backslash */
    826 				c = pgetc();		/* followed by */
    827 				if (c == '\n') {	/* a newline?  */
    828 					plinno++;
    829 					continue;	/*    :drop both */
    830 				}
    831 				STPUTC('\\', out);	/* else keep \ */
    832 			}
    833 			STPUTC(c, out);			/* keep the char */
    834 			if (c == '\n') {		/* at end of line */
    835 				plinno++;
    836 				break;			/* look for eofmark */
    837 			}
    838 		} while ((c = pgetc()) != PEOF);
    839 
    840 		/*
    841 		 * If we have read a line, and reached EOF, without
    842 		 * finding the eofmark, whether the EOF comes before
    843 		 * or immediately after the \n, that is an error.
    844 		 */
    845 		if (c == PEOF || (c = pgetc()) == PEOF)
    846 			synerror(EOFhere);
    847 	}
    848 	STPUTC('\0', out);
    849 
    850 	c = out - stackblock();
    851 	out = stackblock();
    852 	grabstackblock(c);
    853 	wordtext = out;
    854 
    855 	TRACE(("Slurped a heredoc (to '%s')%s: len %d, \"%.16s\"...\n",
    856 		eofmark, striptabs ? " tab stripped" : "", c, wordtext));
    857 }
    858 
    859 STATIC void
    860 readheredocs(void)
    861 {
    862 	struct heredoc *here;
    863 	union node *n;
    864 
    865 	while (heredoclist) {
    866 		here = heredoclist;
    867 		heredoclist = here->next;
    868 		if (needprompt) {
    869 			setprompt(2);
    870 			needprompt = 0;
    871 		}
    872 
    873 		slurp_heredoc(here->eofmark, here->striptabs,
    874 		    here->here->nhere.type == NHERE);
    875 
    876 		n = stalloc(sizeof(struct narg));
    877 		n->narg.type = NARG;
    878 		n->narg.next = NULL;
    879 		n->narg.text = wordtext;
    880 		n->narg.backquote = backquotelist;
    881 		here->here->nhere.doc = n;
    882 
    883 		if (here->here->nhere.type == NHERE)
    884 			continue;
    885 
    886 		/*
    887 		 * Now "parse" here docs that have unquoted eofmarkers.
    888 		 */
    889 		setinputstring(wordtext, 1);
    890 		readtoken1(pgetc(), DQSYNTAX, 1);
    891 		n->narg.text = wordtext;
    892 		n->narg.backquote = backquotelist;
    893 		popfile();
    894 	}
    895 }
    896 
    897 STATIC int
    898 peektoken(void)
    899 {
    900 	int t;
    901 
    902 	t = readtoken();
    903 	tokpushback++;
    904 	return (t);
    905 }
    906 
    907 STATIC int
    908 readtoken(void)
    909 {
    910 	int t;
    911 	int savecheckkwd = checkkwd;
    912 #ifdef DEBUG
    913 	int alreadyseen = tokpushback;
    914 #endif
    915 	struct alias *ap;
    916 
    917 	top:
    918 	t = xxreadtoken();
    919 
    920 	if (checkkwd) {
    921 		/*
    922 		 * eat newlines
    923 		 */
    924 		if (checkkwd == 2) {
    925 			checkkwd = 0;
    926 			while (t == TNL) {
    927 				readheredocs();
    928 				t = xxreadtoken();
    929 			}
    930 		} else
    931 			checkkwd = 0;
    932 		/*
    933 		 * check for keywords and aliases
    934 		 */
    935 		if (t == TWORD && !quoteflag) {
    936 			const char *const *pp;
    937 
    938 			for (pp = parsekwd; *pp; pp++) {
    939 				if (**pp == *wordtext && equal(*pp, wordtext)) {
    940 					lasttoken = t = pp -
    941 					    parsekwd + KWDOFFSET;
    942 					TRACE(("keyword %s recognized\n", tokname[t]));
    943 					goto out;
    944 				}
    945 			}
    946 			if (!noalias &&
    947 			    (ap = lookupalias(wordtext, 1)) != NULL) {
    948 				pushstring(ap->val, strlen(ap->val), ap);
    949 				checkkwd = savecheckkwd;
    950 				goto top;
    951 			}
    952 		}
    953 out:
    954 		checkkwd = (t == TNOT) ? savecheckkwd : 0;
    955 	}
    956 	TRACE(("%stoken %s %s\n", alreadyseen ? "reread " : "", tokname[t], t == TWORD ? wordtext : ""));
    957 	return (t);
    958 }
    959 
    960 
    961 /*
    962  * Read the next input token.
    963  * If the token is a word, we set backquotelist to the list of cmds in
    964  *	backquotes.  We set quoteflag to true if any part of the word was
    965  *	quoted.
    966  * If the token is TREDIR, then we set redirnode to a structure containing
    967  *	the redirection.
    968  * In all cases, the variable startlinno is set to the number of the line
    969  *	on which the token starts.
    970  *
    971  * [Change comment:  here documents and internal procedures]
    972  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
    973  *  word parsing code into a separate routine.  In this case, readtoken
    974  *  doesn't need to have any internal procedures, but parseword does.
    975  *  We could also make parseoperator in essence the main routine, and
    976  *  have parseword (readtoken1?) handle both words and redirection.]
    977  */
    978 
    979 #define RETURN(token)	return lasttoken = token
    980 
    981 STATIC int
    982 xxreadtoken(void)
    983 {
    984 	int c;
    985 
    986 	if (tokpushback) {
    987 		tokpushback = 0;
    988 		return lasttoken;
    989 	}
    990 	if (needprompt) {
    991 		setprompt(2);
    992 		needprompt = 0;
    993 	}
    994 	startlinno = plinno;
    995 	for (;;) {	/* until token or start of word found */
    996 		c = pgetc_macro();
    997 		switch (c) {
    998 		case ' ': case '\t':
    999 			continue;
   1000 		case '#':
   1001 			while ((c = pgetc()) != '\n' && c != PEOF)
   1002 				continue;
   1003 			pungetc();
   1004 			continue;
   1005 
   1006 		case '\n':
   1007 			plinno++;
   1008 			needprompt = doprompt;
   1009 			RETURN(TNL);
   1010 		case PEOF:
   1011 			RETURN(TEOF);
   1012 
   1013 		case '&':
   1014 			if (pgetc_linecont() == '&')
   1015 				RETURN(TAND);
   1016 			pungetc();
   1017 			RETURN(TBACKGND);
   1018 		case '|':
   1019 			if (pgetc_linecont() == '|')
   1020 				RETURN(TOR);
   1021 			pungetc();
   1022 			RETURN(TPIPE);
   1023 		case ';':
   1024 			if (pgetc_linecont() == ';')
   1025 				RETURN(TENDCASE);
   1026 			pungetc();
   1027 			RETURN(TSEMI);
   1028 		case '(':
   1029 			RETURN(TLP);
   1030 		case ')':
   1031 			RETURN(TRP);
   1032 
   1033 		case '\\':
   1034 			switch (pgetc()) {
   1035 			case '\n':
   1036 				startlinno = ++plinno;
   1037 				if (doprompt)
   1038 					setprompt(2);
   1039 				else
   1040 					setprompt(0);
   1041 				continue;
   1042 			case PEOF:
   1043 				RETURN(TEOF);
   1044 			default:
   1045 				pungetc();
   1046 				break;
   1047 			}
   1048 			/* FALLTHROUGH */
   1049 		default:
   1050 			return readtoken1(c, BASESYNTAX, 0);
   1051 		}
   1052 	}
   1053 #undef RETURN
   1054 }
   1055 
   1056 
   1057 
   1058 /*
   1059  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
   1060  * is not NULL, read a here document.  In the latter case, eofmark is the
   1061  * word which marks the end of the document and striptabs is true if
   1062  * leading tabs should be stripped from the document.  The argument firstc
   1063  * is the first character of the input token or document.
   1064  *
   1065  * Because C does not have internal subroutines, I have simulated them
   1066  * using goto's to implement the subroutine linkage.  The following macros
   1067  * will run code that appears at the end of readtoken1.
   1068  */
   1069 
   1070 /*
   1071  * We used to remember only the current syntax, variable nesting level,
   1072  * double quote state for each var nesting level, and arith nesting
   1073  * level (unrelated to var nesting) and one prev syntax when in arith
   1074  * syntax.  This worked for simple cases, but can't handle arith inside
   1075  * var expansion inside arith inside var with some quoted and some not.
   1076  *
   1077  * Inspired by FreeBSD's implementation (though it was the obvious way)
   1078  * though implemented differently, we now have a stack that keeps track
   1079  * of what we are doing now, and what we were doing previously.
   1080  * Every time something changes, which will eventually end and should
   1081  * revert to the previous state, we push this stack, and then pop it
   1082  * again later (that is every ${} with an operator (to parse the word
   1083  * or pattern that follows) ${x} and $x are too simple to need it)
   1084  * $(( )) $( ) and "...".   Always.   Really, always!
   1085  *
   1086  * The stack is implemented as one static (on the C stack) base block
   1087  * containing LEVELS_PER_BLOCK (8) stack entries, which should be
   1088  * enough for the vast majority of cases.  For torture tests, we
   1089  * malloc more blocks as needed.  All accesses through the inline
   1090  * functions below.
   1091  */
   1092 
   1093 /*
   1094  * varnest & arinest will typically be 0 or 1
   1095  * (varnest can increment in usages like ${x=${y}} but probably
   1096  *  does not really need to)
   1097  * parenlevel allows balancing parens inside a $(( )), it is reset
   1098  * at each new nesting level ( $(( ( x + 3 ${unset-)} )) does not work.
   1099  * quoted is special - we need to know 2 things ... are we inside "..."
   1100  * (even if inherited from some previous nesting level) and was there
   1101  * an opening '"' at this level (so the next will be closing).
   1102  * "..." can span nesting levels, but cannot be opened in one and
   1103  * closed in a different one.
   1104  * To handle this, "quoted" has two fields, the bottom 4 (really 2)
   1105  * bits are 0, 1, or 2, for un, single, and double quoted (single quoted
   1106  * is really so special that this setting is not very important)
   1107  * and 0x10 that indicates that an opening quote has been seen.
   1108  * The bottom 4 bits are inherited, the 0x10 bit is not.
   1109  */
   1110 struct tokenstate {
   1111 	const char *ts_syntax;
   1112 	unsigned short ts_parenlevel;	/* counters */
   1113 	unsigned short ts_varnest;	/* 64000 levels should be enough! */
   1114 	unsigned short ts_arinest;
   1115 	unsigned short ts_quoted;	/* 1 -> single, 2 -> double */
   1116 };
   1117 
   1118 #define	NQ	0x00	/* Unquoted */
   1119 #define	SQ	0x01	/* Single Quotes */
   1120 #define	DQ	0x02	/* Double Quotes (or equivalent) */
   1121 #define	QF	0x0F		/* Mask to extract previous values */
   1122 #define	QS	0x10	/* Quoting started at this level in stack */
   1123 
   1124 #define	LEVELS_PER_BLOCK	8
   1125 #define	VSS			struct statestack
   1126 
   1127 struct statestack {
   1128 	VSS *prev;		/* previous block in list */
   1129 	int cur;		/* which of our tokenstates is current */
   1130 	struct tokenstate tokenstate[LEVELS_PER_BLOCK];
   1131 };
   1132 
   1133 static inline struct tokenstate *
   1134 currentstate(VSS *stack)
   1135 {
   1136 	return &stack->tokenstate[stack->cur];
   1137 }
   1138 
   1139 static inline struct tokenstate *
   1140 prevstate(VSS *stack)
   1141 {
   1142 	if (stack->cur != 0)
   1143 		return &stack->tokenstate[stack->cur - 1];
   1144 	if (stack->prev == NULL)	/* cannot drop below base */
   1145 		return &stack->tokenstate[0];
   1146 	return &stack->prev->tokenstate[LEVELS_PER_BLOCK - 1];
   1147 }
   1148 
   1149 static inline VSS *
   1150 bump_state_level(VSS *stack)
   1151 {
   1152 	struct tokenstate *os, *ts;
   1153 
   1154 	os = currentstate(stack);
   1155 
   1156 	if (++stack->cur >= LEVELS_PER_BLOCK) {
   1157 		VSS *ss;
   1158 
   1159 		ss = (VSS *)ckmalloc(sizeof (struct statestack));
   1160 		ss->cur = 0;
   1161 		ss->prev = stack;
   1162 		stack = ss;
   1163 	}
   1164 
   1165 	ts = currentstate(stack);
   1166 
   1167 	ts->ts_parenlevel = 0;	/* parens inside never match outside */
   1168 
   1169 	ts->ts_quoted  = os->ts_quoted & QF;	/* these are default settings */
   1170 	ts->ts_varnest = os->ts_varnest;
   1171 	ts->ts_arinest = os->ts_arinest;	/* when appropriate	   */
   1172 	ts->ts_syntax  = os->ts_syntax;		/*    they will be altered */
   1173 
   1174 	return stack;
   1175 }
   1176 
   1177 static inline VSS *
   1178 drop_state_level(VSS *stack)
   1179 {
   1180 	if (stack->cur == 0) {
   1181 		VSS *ss;
   1182 
   1183 		ss = stack;
   1184 		stack = ss->prev;
   1185 		if (stack == NULL)
   1186 			return ss;
   1187 		ckfree(ss);
   1188 	}
   1189 	--stack->cur;
   1190 	return stack;
   1191 }
   1192 
   1193 static inline void
   1194 cleanup_state_stack(VSS *stack)
   1195 {
   1196 	while (stack->prev != NULL) {
   1197 		stack->cur = 0;
   1198 		stack = drop_state_level(stack);
   1199 	}
   1200 }
   1201 
   1202 #define	PARSESUB()	{goto parsesub; parsesub_return:;}
   1203 #define	PARSEARITH()	{goto parsearith; parsearith_return:;}
   1204 
   1205 /*
   1206  * The following macros all assume the existance of a local var "stack"
   1207  * which contains a pointer to the current struct stackstate
   1208  */
   1209 
   1210 /*
   1211  * These are macros rather than inline funcs to avoid code churn as much
   1212  * as possible - they replace macros of the same name used previously.
   1213  */
   1214 #define	ISDBLQUOTE()	(currentstate(stack)->ts_quoted & QS)
   1215 #define	SETDBLQUOTE()	(currentstate(stack)->ts_quoted = QS | DQ)
   1216 #define	CLRDBLQUOTE()	(currentstate(stack)->ts_quoted =		\
   1217 			    stack->cur != 0 || stack->prev ?		\
   1218 				prevstate(stack)->ts_quoted & QF : 0)
   1219 
   1220 /*
   1221  * This set are just to avoid excess typing and line lengths...
   1222  * The ones that "look like" var names must be implemented to be lvalues
   1223  */
   1224 #define	syntax		(currentstate(stack)->ts_syntax)
   1225 #define	parenlevel	(currentstate(stack)->ts_parenlevel)
   1226 #define	varnest		(currentstate(stack)->ts_varnest)
   1227 #define	arinest		(currentstate(stack)->ts_arinest)
   1228 #define	quoted		(currentstate(stack)->ts_quoted)
   1229 #define	TS_PUSH()	(stack = bump_state_level(stack))
   1230 #define	TS_POP()	(stack = drop_state_level(stack))
   1231 
   1232 /*
   1233  * Called to parse command substitutions.  oldstyle is true if the command
   1234  * is enclosed inside `` (otherwise it was enclosed in "$( )")
   1235  *
   1236  * Internally nlpp is a pointer to the head of the linked
   1237  * list of commands (passed by reference), and savelen is the number of
   1238  * characters on the top of the stack which must be preserved.
   1239  */
   1240 static char *
   1241 parsebackq(VSS *const stack, char * const in,
   1242     struct nodelist **const pbqlist, const int oldstyle)
   1243 {
   1244 	struct nodelist **nlpp;
   1245 	const int savepbq = parsebackquote;
   1246 	union node *n;
   1247 	char *out;
   1248 	char *str = NULL;
   1249 	char *volatile sstr = str;
   1250 	struct jmploc jmploc;
   1251 	struct jmploc *const savehandler = handler;
   1252 	const int savelen = in - stackblock();
   1253 	int saveprompt;
   1254 
   1255 	if (setjmp(jmploc.loc)) {
   1256 		if (sstr)
   1257 			ckfree(__UNVOLATILE(sstr));
   1258 		cleanup_state_stack(stack);
   1259 		parsebackquote = 0;
   1260 		handler = savehandler;
   1261 		longjmp(handler->loc, 1);
   1262 	}
   1263 	INTOFF;
   1264 	sstr = str = NULL;
   1265 	if (savelen > 0) {
   1266 		sstr = str = ckmalloc(savelen);
   1267 		memcpy(str, stackblock(), savelen);
   1268 	}
   1269 	handler = &jmploc;
   1270 	INTON;
   1271         if (oldstyle) {
   1272                 /* We must read until the closing backquote, giving special
   1273                    treatment to some slashes, and then push the string and
   1274                    reread it as input, interpreting it normally.  */
   1275                 int pc;
   1276                 int psavelen;
   1277                 char *pstr;
   1278 
   1279 		/*
   1280 		 * Because the entire `...` is read here, we don't
   1281 		 * need to bother the state stack.  That will be used
   1282 		 * (as appropriate) when the processed string is re-read.
   1283 		 */
   1284                 STARTSTACKSTR(out);
   1285 		for (;;) {
   1286 			if (needprompt) {
   1287 				setprompt(2);
   1288 				needprompt = 0;
   1289 			}
   1290 			switch (pc = pgetc_linecont()) {
   1291 			case '`':
   1292 				goto done;
   1293 
   1294 			case '\\':
   1295                                 if ((pc = pgetc()) == '\n') {
   1296 					plinno++;
   1297 					if (doprompt)
   1298 						setprompt(2);
   1299 					else
   1300 						setprompt(0);
   1301 					/*
   1302 					 * If eating a newline, avoid putting
   1303 					 * the newline into the new character
   1304 					 * stream (via the STPUTC after the
   1305 					 * switch).
   1306 					 */
   1307 					continue;
   1308 				}
   1309                                 if (pc != '\\' && pc != '`' && pc != '$'
   1310                                     && (!ISDBLQUOTE() || pc != '"'))
   1311                                         STPUTC('\\', out);
   1312 				break;
   1313 
   1314 			case '\n':
   1315 				plinno++;
   1316 				needprompt = doprompt;
   1317 				break;
   1318 
   1319 			case PEOF:
   1320 			        startlinno = plinno;
   1321 				synerror("EOF in backquote substitution");
   1322  				break;
   1323 
   1324 			default:
   1325 				break;
   1326 			}
   1327 			STPUTC(pc, out);
   1328                 }
   1329 done:
   1330                 STPUTC('\0', out);
   1331                 psavelen = out - stackblock();
   1332                 if (psavelen > 0) {
   1333 			pstr = grabstackstr(out);
   1334 			setinputstring(pstr, 1);
   1335                 }
   1336         }
   1337 	nlpp = pbqlist;
   1338 	while (*nlpp)
   1339 		nlpp = &(*nlpp)->next;
   1340 	*nlpp = stalloc(sizeof(struct nodelist));
   1341 	(*nlpp)->next = NULL;
   1342 	parsebackquote = oldstyle;
   1343 
   1344 	if (oldstyle) {
   1345 		saveprompt = doprompt;
   1346 		doprompt = 0;
   1347 	} else
   1348 		saveprompt = 0;
   1349 
   1350 	n = list(0, oldstyle);
   1351 
   1352 	if (oldstyle)
   1353 		doprompt = saveprompt;
   1354 	else {
   1355 		if (readtoken() != TRP) {
   1356 			cleanup_state_stack(stack);
   1357 			synexpect(TRP, 0);
   1358 		}
   1359 	}
   1360 
   1361 	(*nlpp)->n = n;
   1362         if (oldstyle) {
   1363 		/*
   1364 		 * Start reading from old file again, ignoring any pushed back
   1365 		 * tokens left from the backquote parsing
   1366 		 */
   1367                 popfile();
   1368 		tokpushback = 0;
   1369 	}
   1370 
   1371 	while (stackblocksize() <= savelen)
   1372 		growstackblock();
   1373 	STARTSTACKSTR(out);
   1374 	if (str) {
   1375 		memcpy(out, str, savelen);
   1376 		STADJUST(savelen, out);
   1377 		INTOFF;
   1378 		ckfree(str);
   1379 		sstr = str = NULL;
   1380 		INTON;
   1381 	}
   1382 	parsebackquote = savepbq;
   1383 	handler = savehandler;
   1384 	if (arinest || ISDBLQUOTE())
   1385 		USTPUTC(CTLBACKQ | CTLQUOTE, out);
   1386 	else
   1387 		USTPUTC(CTLBACKQ, out);
   1388 
   1389 	return out;
   1390 }
   1391 
   1392 /*
   1393  * Parse a redirection operator.  The parameter "out" points to a string
   1394  * specifying the fd to be redirected.  It is guaranteed to be either ""
   1395  * or a numeric string (for now anyway).  The parameter "c" contains the
   1396  * first character of the redirection operator.
   1397  *
   1398  * Note the string "out" is on the stack, which we are about to clobber,
   1399  * so process it first...
   1400  */
   1401 
   1402 static void
   1403 parseredir(const char *out,  int c)
   1404 {
   1405 	union node *np;
   1406 	int fd;
   1407 
   1408 	fd = (*out == '\0') ? -1 : atoi(out);
   1409 
   1410 	np = stalloc(sizeof(struct nfile));
   1411 	if (c == '>') {
   1412 		if (fd < 0)
   1413 			fd = 1;
   1414 		c = pgetc_linecont();
   1415 		if (c == '>')
   1416 			np->type = NAPPEND;
   1417 		else if (c == '|')
   1418 			np->type = NCLOBBER;
   1419 		else if (c == '&')
   1420 			np->type = NTOFD;
   1421 		else {
   1422 			np->type = NTO;
   1423 			pungetc();
   1424 		}
   1425 	} else {	/* c == '<' */
   1426 		if (fd < 0)
   1427 			fd = 0;
   1428 		switch (c = pgetc_linecont()) {
   1429 		case '<':
   1430 			if (sizeof (struct nfile) != sizeof (struct nhere)) {
   1431 				np = stalloc(sizeof(struct nhere));
   1432 				np->nfile.fd = 0;
   1433 			}
   1434 			np->type = NHERE;
   1435 			heredoc = stalloc(sizeof(struct heredoc));
   1436 			heredoc->here = np;
   1437 			heredoc->startline = plinno;
   1438 			if ((c = pgetc_linecont()) == '-') {
   1439 				heredoc->striptabs = 1;
   1440 			} else {
   1441 				heredoc->striptabs = 0;
   1442 				pungetc();
   1443 			}
   1444 			break;
   1445 
   1446 		case '&':
   1447 			np->type = NFROMFD;
   1448 			break;
   1449 
   1450 		case '>':
   1451 			np->type = NFROMTO;
   1452 			break;
   1453 
   1454 		default:
   1455 			np->type = NFROM;
   1456 			pungetc();
   1457 			break;
   1458 		}
   1459 	}
   1460 	np->nfile.fd = fd;
   1461 
   1462 	redirnode = np;		/* this is the "value" of TRENODE */
   1463 }
   1464 
   1465 
   1466 /*
   1467  * The lowest level basic tokenizer.
   1468  *
   1469  * The next input byte (character) is in firstc, syn says which
   1470  * syntax tables we are to use (basic, single or double quoted, or arith)
   1471  * and magicq (used with sqsyntax and dqsyntax only) indicates that the
   1472  * quote character itself is not special (used parsing here docs and similar)
   1473  *
   1474  * The result is the type of the next token (its value, when there is one,
   1475  * is saved in the relevant global var - must fix that someday!) which is
   1476  * also saved for re-reading ("lasttoken").
   1477  *
   1478  * Overall, this routine does far more parsing than it is supposed to.
   1479  * That will also need fixing, someday...
   1480  */
   1481 STATIC int
   1482 readtoken1(int firstc, char const *syn, int magicq)
   1483 {
   1484 	int c;
   1485 	char * out;
   1486 	int len;
   1487 	struct nodelist *bqlist;
   1488 	int quotef;
   1489 	VSS static_stack;
   1490 	VSS *stack = &static_stack;
   1491 
   1492 	stack->prev = NULL;
   1493 	stack->cur = 0;
   1494 
   1495 	syntax = syn;
   1496 
   1497 	startlinno = plinno;
   1498 	varnest = 0;
   1499 	quoted = 0;
   1500 	if (syntax == DQSYNTAX)
   1501 		SETDBLQUOTE();
   1502 	quotef = 0;
   1503 	bqlist = NULL;
   1504 	arinest = 0;
   1505 	parenlevel = 0;
   1506 
   1507 	STARTSTACKSTR(out);
   1508 
   1509 	for (c = firstc ;; c = pgetc_macro()) {	/* until of token */
   1510 		CHECKSTRSPACE(4, out);	/* permit 4 calls to USTPUTC */
   1511 		switch (syntax[c]) {
   1512 		case CNL:	/* '\n' */
   1513 			if (syntax == BASESYNTAX)
   1514 				break;	/* exit loop */
   1515 			USTPUTC(c, out);
   1516 			plinno++;
   1517 			if (doprompt)
   1518 				setprompt(2);
   1519 			else
   1520 				setprompt(0);
   1521 			continue;
   1522 
   1523 		case CWORD:
   1524 			USTPUTC(c, out);
   1525 			continue;
   1526 		case CCTL:
   1527 			if (!magicq || ISDBLQUOTE())
   1528 				USTPUTC(CTLESC, out);
   1529 			USTPUTC(c, out);
   1530 			continue;
   1531 		case CBACK:	/* backslash */
   1532 			c = pgetc();
   1533 			if (c == PEOF) {
   1534 				USTPUTC('\\', out);
   1535 				pungetc();
   1536 				continue;
   1537 			}
   1538 			if (c == '\n') {
   1539 				plinno++;
   1540 				if (doprompt)
   1541 					setprompt(2);
   1542 				else
   1543 					setprompt(0);
   1544 				continue;
   1545 			}
   1546 			quotef = 1;	/* current token is quoted */
   1547 			if (ISDBLQUOTE() && c != '\\' && c != '`' &&
   1548 			    c != '$' && (c != '"' || magicq))
   1549 				USTPUTC('\\', out);
   1550 			if (SQSYNTAX[c] == CCTL)
   1551 				USTPUTC(CTLESC, out);
   1552 			else if (!magicq) {
   1553 				USTPUTC(CTLQUOTEMARK, out);
   1554 				USTPUTC(c, out);
   1555 				if (varnest != 0)
   1556 					USTPUTC(CTLQUOTEEND, out);
   1557 				continue;
   1558 			}
   1559 			USTPUTC(c, out);
   1560 			continue;
   1561 		case CSQUOTE:
   1562 			if (syntax != SQSYNTAX) {
   1563 				if (!magicq)
   1564 					USTPUTC(CTLQUOTEMARK, out);
   1565 				quotef = 1;
   1566 				TS_PUSH();
   1567 				syntax = SQSYNTAX;
   1568 				quoted = SQ;
   1569 				continue;
   1570 			}
   1571 			if (magicq && arinest == 0 && varnest == 0) {
   1572 				/* Ignore inside quoted here document */
   1573 				USTPUTC(c, out);
   1574 				continue;
   1575 			}
   1576 			/* End of single quotes... */
   1577 			TS_POP();
   1578 			if (syntax == BASESYNTAX && varnest != 0)
   1579 				USTPUTC(CTLQUOTEEND, out);
   1580 			continue;
   1581 		case CDQUOTE:
   1582 			if (magicq && arinest == 0 && varnest == 0) {
   1583 				/* Ignore inside here document */
   1584 				USTPUTC(c, out);
   1585 				continue;
   1586 			}
   1587 			quotef = 1;
   1588 			if (arinest) {
   1589 				if (ISDBLQUOTE()) {
   1590 					TS_POP();
   1591 				} else {
   1592 					TS_PUSH();
   1593 					syntax = DQSYNTAX;
   1594 					SETDBLQUOTE();
   1595 					USTPUTC(CTLQUOTEMARK, out);
   1596 				}
   1597 				continue;
   1598 			}
   1599 			if (magicq)
   1600 				continue;
   1601 			if (ISDBLQUOTE()) {
   1602 				TS_POP();
   1603 				if (varnest != 0)
   1604 					USTPUTC(CTLQUOTEEND, out);
   1605 			} else {
   1606 				TS_PUSH();
   1607 				syntax = DQSYNTAX;
   1608 				SETDBLQUOTE();
   1609 				USTPUTC(CTLQUOTEMARK, out);
   1610 			}
   1611 			continue;
   1612 		case CVAR:	/* '$' */
   1613 			PARSESUB();		/* parse substitution */
   1614 			continue;
   1615 		case CENDVAR:	/* CLOSEBRACE */
   1616 			if (varnest > 0 && !ISDBLQUOTE()) {
   1617 				TS_POP();
   1618 				USTPUTC(CTLENDVAR, out);
   1619 			} else {
   1620 				USTPUTC(c, out);
   1621 			}
   1622 			continue;
   1623 		case CLP:	/* '(' in arithmetic */
   1624 			parenlevel++;
   1625 			USTPUTC(c, out);
   1626 			continue;;
   1627 		case CRP:	/* ')' in arithmetic */
   1628 			if (parenlevel > 0) {
   1629 				USTPUTC(c, out);
   1630 				--parenlevel;
   1631 			} else {
   1632 				if (pgetc_linecont() == ')') {
   1633 					if (--arinest == 0) {
   1634 						TS_POP();
   1635 						USTPUTC(CTLENDARI, out);
   1636 					} else
   1637 						USTPUTC(')', out);
   1638 				} else {
   1639 					/*
   1640 					 * unbalanced parens
   1641 					 *  (don't 2nd guess - no error)
   1642 					 */
   1643 					pungetc();
   1644 					USTPUTC(')', out);
   1645 				}
   1646 			}
   1647 			continue;
   1648 		case CBQUOTE:	/* '`' */
   1649 			out = parsebackq(stack, out, &bqlist, 1);
   1650 			continue;
   1651 		case CEOF:		/* --> c == PEOF */
   1652 			break;		/* will exit loop */
   1653 		default:
   1654 			if (varnest == 0 && !ISDBLQUOTE())
   1655 				break;	/* exit loop */
   1656 			USTPUTC(c, out);
   1657 			continue;
   1658 		}
   1659 		break;	/* break from switch -> break from for loop too */
   1660 	}
   1661 
   1662 	if (syntax == ARISYNTAX) {
   1663 		cleanup_state_stack(stack);
   1664 		synerror("Missing '))'");
   1665 	}
   1666 	if (syntax != BASESYNTAX && /* ! parsebackquote && */ !magicq) {
   1667 		cleanup_state_stack(stack);
   1668 		synerror("Unterminated quoted string");
   1669 	}
   1670 	if (varnest != 0) {
   1671 		cleanup_state_stack(stack);
   1672 		startlinno = plinno;
   1673 		/* { */
   1674 		synerror("Missing '}'");
   1675 	}
   1676 
   1677 	USTPUTC('\0', out);
   1678 	len = out - stackblock();
   1679 	out = stackblock();
   1680 
   1681 	if (!magicq) {
   1682 		if ((c == '<' || c == '>')
   1683 		 && quotef == 0 && (*out == '\0' || is_number(out))) {
   1684 			parseredir(out, c);
   1685 			cleanup_state_stack(stack);
   1686 			return lasttoken = TREDIR;
   1687 		} else {
   1688 			pungetc();
   1689 		}
   1690 	}
   1691 
   1692 	quoteflag = quotef;
   1693 	backquotelist = bqlist;
   1694 	grabstackblock(len);
   1695 	wordtext = out;
   1696 	cleanup_state_stack(stack);
   1697 	return lasttoken = TWORD;
   1698 /* end of readtoken routine */
   1699 
   1700 
   1701 /*
   1702  * Parse a substitution.  At this point, we have read the dollar sign
   1703  * and nothing else.
   1704  */
   1705 
   1706 parsesub: {
   1707 	char buf[10];
   1708 	int subtype;
   1709 	int typeloc;
   1710 	int flags;
   1711 	char *p;
   1712 	static const char types[] = "}-+?=";
   1713 	int i;
   1714 	int linno;
   1715 
   1716 	c = pgetc_linecont();
   1717 	if (c != '(' && c != OPENBRACE && !is_name(c) && !is_special(c)) {
   1718 		USTPUTC('$', out);
   1719 		pungetc();
   1720 	} else if (c == '(') {	/* $(command) or $((arith)) */
   1721 		if (pgetc_linecont() == '(') {
   1722 			PARSEARITH();
   1723 		} else {
   1724 			pungetc();
   1725 			out = parsebackq(stack, out, &bqlist, 0);
   1726 		}
   1727 	} else {
   1728 		USTPUTC(CTLVAR, out);
   1729 		typeloc = out - stackblock();
   1730 		USTPUTC(VSNORMAL, out);
   1731 		subtype = VSNORMAL;
   1732 		flags = 0;
   1733 		if (c == OPENBRACE) {
   1734 			c = pgetc_linecont();
   1735 			if (c == '#') {
   1736 				if ((c = pgetc()) == CLOSEBRACE)
   1737 					c = '#';
   1738 				else
   1739 					subtype = VSLENGTH;
   1740 			}
   1741 			else
   1742 				subtype = 0;
   1743 		}
   1744 		if (is_name(c)) {
   1745 			p = out;
   1746 			do {
   1747 				STPUTC(c, out);
   1748 				c = pgetc_linecont();
   1749 			} while (is_in_name(c));
   1750 			if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
   1751 				/* Replace the variable name with the
   1752 				 * current line number. */
   1753 				linno = plinno;
   1754 				if (funclinno != 0)
   1755 					linno -= funclinno - 1;
   1756 				snprintf(buf, sizeof(buf), "%d", linno);
   1757 				STADJUST(-6, out);
   1758 				for (i = 0; buf[i] != '\0'; i++)
   1759 					STPUTC(buf[i], out);
   1760 				flags |= VSLINENO;
   1761 			}
   1762 		} else if (is_digit(c)) {
   1763 			do {
   1764 				USTPUTC(c, out);
   1765 				c = pgetc_linecont();
   1766 			} while (subtype != VSNORMAL && is_digit(c));
   1767 		}
   1768 		else if (is_special(c)) {
   1769 			USTPUTC(c, out);
   1770 			c = pgetc_linecont();
   1771 		}
   1772 		else {
   1773 badsub:
   1774 			cleanup_state_stack(stack);
   1775 			synerror("Bad substitution");
   1776 		}
   1777 
   1778 		STPUTC('=', out);
   1779 		if (subtype == 0) {
   1780 			switch (c) {
   1781 			case ':':
   1782 				flags |= VSNUL;
   1783 				c = pgetc_linecont();
   1784 				/*FALLTHROUGH*/
   1785 			default:
   1786 				p = strchr(types, c);
   1787 				if (p == NULL)
   1788 					goto badsub;
   1789 				subtype = p - types + VSNORMAL;
   1790 				break;
   1791 			case '%':
   1792 			case '#':
   1793 				{
   1794 					int cc = c;
   1795 					subtype = c == '#' ? VSTRIMLEFT :
   1796 							     VSTRIMRIGHT;
   1797 					c = pgetc_linecont();
   1798 					if (c == cc)
   1799 						subtype++;
   1800 					else
   1801 						pungetc();
   1802 					break;
   1803 				}
   1804 			}
   1805 		} else {
   1806 			pungetc();
   1807 		}
   1808 		if (ISDBLQUOTE() || arinest)
   1809 			flags |= VSQUOTE;
   1810 		if (subtype >= VSTRIMLEFT && subtype <= VSTRIMRIGHTMAX)
   1811 			flags |= VSPATQ;
   1812 		*(stackblock() + typeloc) = subtype | flags;
   1813 		if (subtype != VSNORMAL) {
   1814 			TS_PUSH();
   1815 			varnest++;
   1816 			arinest = 0;
   1817 			if (subtype > VSASSIGN) {	/* # ## % %% */
   1818 				syntax = BASESYNTAX;
   1819 				CLRDBLQUOTE();
   1820 			}
   1821 		}
   1822 	}
   1823 	goto parsesub_return;
   1824 }
   1825 
   1826 
   1827 /*
   1828  * Parse an arithmetic expansion (indicate start of one and set state)
   1829  */
   1830 parsearith: {
   1831 
   1832 	if (syntax == ARISYNTAX) {
   1833 		/*
   1834 		 * we collapse embedded arithmetic expansion to
   1835 		 * parentheses, which should be equivalent
   1836 		 */
   1837 		USTPUTC('(', out);
   1838 		USTPUTC('(', out);
   1839 		/*
   1840 		 * Need 2 of them because there will (should be)
   1841 		 * two closing ))'s to follow later.
   1842 		 */
   1843 		parenlevel += 2;
   1844 	} else {
   1845 		TS_PUSH();
   1846 		syntax = ARISYNTAX;
   1847 		++arinest;
   1848 		varnest = 0;
   1849 
   1850 		USTPUTC(CTLARI, out);
   1851 		if (ISDBLQUOTE())
   1852 			USTPUTC('"',out);
   1853 		else
   1854 			USTPUTC(' ',out);
   1855 	}
   1856 	goto parsearith_return;
   1857 }
   1858 
   1859 } /* end of readtoken */
   1860 
   1861 
   1862 
   1863 #ifdef mkinit
   1864 RESET {
   1865 	tokpushback = 0;
   1866 	checkkwd = 0;
   1867 }
   1868 #endif
   1869 
   1870 /*
   1871  * Returns true if the text contains nothing to expand (no dollar signs
   1872  * or backquotes).
   1873  */
   1874 
   1875 STATIC int
   1876 noexpand(char *text)
   1877 {
   1878 	char *p;
   1879 	char c;
   1880 
   1881 	p = text;
   1882 	while ((c = *p++) != '\0') {
   1883 		if (c == CTLQUOTEMARK)
   1884 			continue;
   1885 		if (c == CTLESC)
   1886 			p++;
   1887 		else if (BASESYNTAX[(int)c] == CCTL)
   1888 			return 0;
   1889 	}
   1890 	return 1;
   1891 }
   1892 
   1893 
   1894 /*
   1895  * Return true if the argument is a legal variable name (a letter or
   1896  * underscore followed by zero or more letters, underscores, and digits).
   1897  */
   1898 
   1899 int
   1900 goodname(char *name)
   1901 {
   1902 	char *p;
   1903 
   1904 	p = name;
   1905 	if (! is_name(*p))
   1906 		return 0;
   1907 	while (*++p) {
   1908 		if (! is_in_name(*p))
   1909 			return 0;
   1910 	}
   1911 	return 1;
   1912 }
   1913 
   1914 
   1915 /*
   1916  * Called when an unexpected token is read during the parse.  The argument
   1917  * is the token that is expected, or -1 if more than one type of token can
   1918  * occur at this point.
   1919  */
   1920 
   1921 STATIC void
   1922 synexpect(int token, const char *text)
   1923 {
   1924 	char msg[64];
   1925 	char *p;
   1926 
   1927 	if (lasttoken == TWORD) {
   1928 		size_t len = strlen(wordtext);
   1929 
   1930 		if (len <= 13)
   1931 			fmtstr(msg, 34, "Word \"%.13s\" unexpected", wordtext);
   1932 		else
   1933 			fmtstr(msg, 34,
   1934 			    "Word \"%.10s...\" unexpected", wordtext);
   1935 	} else
   1936 		fmtstr(msg, 34, "%s unexpected", tokname[lasttoken]);
   1937 
   1938 	p = strchr(msg, '\0');
   1939 	if (text)
   1940 		fmtstr(p, 30, " (expecting \"%.10s\")", text);
   1941 	else if (token >= 0)
   1942 		fmtstr(p, 30, " (expecting %s)",  tokname[token]);
   1943 
   1944 	synerror(msg);
   1945 	/* NOTREACHED */
   1946 }
   1947 
   1948 
   1949 STATIC void
   1950 synerror(const char *msg)
   1951 {
   1952 	error("%d: Syntax error: %s\n", startlinno, msg);
   1953 	/* NOTREACHED */
   1954 }
   1955 
   1956 STATIC void
   1957 setprompt(int which)
   1958 {
   1959 	whichprompt = which;
   1960 
   1961 #ifndef SMALL
   1962 	if (!el)
   1963 #endif
   1964 		out2str(getprompt(NULL));
   1965 }
   1966 
   1967 /*
   1968  * handle getting the next character, while ignoring \ \n
   1969  * (which is a little tricky as we only have one char of pushback
   1970  * and we need that one elsewhere).
   1971  */
   1972 STATIC int
   1973 pgetc_linecont(void)
   1974 {
   1975 	int c;
   1976 
   1977 	while ((c = pgetc_macro()) == '\\') {
   1978 		c = pgetc();
   1979 		if (c == '\n') {
   1980 			plinno++;
   1981 			if (doprompt)
   1982 				setprompt(2);
   1983 			else
   1984 				setprompt(0);
   1985 		} else {
   1986 			pungetc();
   1987 			/* Allow the backslash to be pushed back. */
   1988 			pushstring("\\", 1, NULL);
   1989 			return (pgetc());
   1990 		}
   1991 	}
   1992 	return (c);
   1993 }
   1994 
   1995 /*
   1996  * called by editline -- any expansions to the prompt
   1997  *    should be added here.
   1998  */
   1999 const char *
   2000 getprompt(void *unused)
   2001 {
   2002 	switch (whichprompt) {
   2003 	case 0:
   2004 		return "";
   2005 	case 1:
   2006 		return ps1val();
   2007 	case 2:
   2008 		return ps2val();
   2009 	default:
   2010 		return "<internal prompt error>";
   2011 	}
   2012 }
   2013