Home | History | Annotate | Line # | Download | only in sh
parser.c revision 1.153
      1 /*	$NetBSD: parser.c,v 1.153 2018/11/18 17:23:37 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.153 2018/11/18 17:23:37 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 struct HereDoc {
     78 	struct HereDoc *next;	/* next here document in list */
     79 	union node *here;		/* redirection node */
     80 	char *eofmark;		/* string indicating end of input */
     81 	int striptabs;		/* if set, strip leading tabs */
     82 	int startline;		/* line number where << seen */
     83 };
     84 
     85 MKINIT struct parse_state parse_state;
     86 union parse_state_p psp = { .c_current_parser = &parse_state };
     87 
     88 static const struct parse_state init_parse_state = {	/* all 0's ... */
     89 	.ps_noalias = 0,
     90 	.ps_heredoclist = NULL,
     91 	.ps_parsebackquote = 0,
     92 	.ps_doprompt = 0,
     93 	.ps_needprompt = 0,
     94 	.ps_lasttoken = 0,
     95 	.ps_tokpushback = 0,
     96 	.ps_wordtext = NULL,
     97 	.ps_checkkwd = 0,
     98 	.ps_redirnode = NULL,
     99 	.ps_heredoc = NULL,
    100 	.ps_quoteflag = 0,
    101 	.ps_startlinno = 0,
    102 	.ps_funclinno = 0,
    103 	.ps_elided_nl = 0,
    104 };
    105 
    106 STATIC union node *list(int);
    107 STATIC union node *andor(void);
    108 STATIC union node *pipeline(void);
    109 STATIC union node *command(void);
    110 STATIC union node *simplecmd(union node **, union node *);
    111 STATIC union node *makename(int);
    112 STATIC void parsefname(void);
    113 STATIC int slurp_heredoc(char *const, const int, const int);
    114 STATIC void readheredocs(void);
    115 STATIC int peektoken(void);
    116 STATIC int readtoken(void);
    117 STATIC int xxreadtoken(void);
    118 STATIC int readtoken1(int, char const *, int);
    119 STATIC int noexpand(char *);
    120 STATIC void linebreak(void);
    121 STATIC void consumetoken(int);
    122 STATIC void synexpect(int, const char *) __dead;
    123 STATIC void synerror(const char *) __dead;
    124 STATIC void setprompt(int);
    125 STATIC int pgetc_linecont(void);
    126 
    127 static const char EOFhere[] = "EOF reading here (<<) document";
    128 
    129 #ifdef DEBUG
    130 int parsing = 0;
    131 #endif
    132 
    133 /*
    134  * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
    135  * valid parse tree indicating a blank line.)
    136  */
    137 
    138 union node *
    139 parsecmd(int interact)
    140 {
    141 	int t;
    142 	union node *n;
    143 
    144 #ifdef DEBUG
    145 	parsing++;
    146 #endif
    147 	tokpushback = 0;
    148 	checkkwd = 0;
    149 	doprompt = interact;
    150 	if (doprompt)
    151 		setprompt(1);
    152 	else
    153 		setprompt(0);
    154 	needprompt = 0;
    155 	t = readtoken();
    156 #ifdef DEBUG
    157 	parsing--;
    158 #endif
    159 	if (t == TEOF)
    160 		return NEOF;
    161 	if (t == TNL)
    162 		return NULL;
    163 
    164 #ifdef DEBUG
    165 	parsing++;
    166 #endif
    167 	tokpushback++;
    168 	n = list(1);
    169 #ifdef DEBUG
    170 	parsing--;
    171 #endif
    172 	if (heredoclist)
    173 		error("%d: Here document (<<%s) expected but not present",
    174 			heredoclist->startline, heredoclist->eofmark);
    175 	return n;
    176 }
    177 
    178 
    179 STATIC union node *
    180 list(int nlflag)
    181 {
    182 	union node *ntop, *n1, *n2, *n3;
    183 	int tok;
    184 
    185 	CTRACE(DBG_PARSE, ("list(%d): entered @%d\n",nlflag,plinno));
    186 
    187 	checkkwd = 2;
    188 	if (nlflag == 0 && tokendlist[peektoken()])
    189 		return NULL;
    190 	ntop = n1 = NULL;
    191 	for (;;) {
    192 		n2 = andor();
    193 		tok = readtoken();
    194 		if (tok == TBACKGND) {
    195 			if (n2->type == NCMD || n2->type == NPIPE)
    196 				n2->ncmd.backgnd = 1;
    197 			else if (n2->type == NREDIR)
    198 				n2->type = NBACKGND;
    199 			else {
    200 				n3 = stalloc(sizeof(struct nredir));
    201 				n3->type = NBACKGND;
    202 				n3->nredir.n = n2;
    203 				n3->nredir.redirect = NULL;
    204 				n2 = n3;
    205 			}
    206 		}
    207 
    208 		if (ntop == NULL)
    209 			ntop = n2;
    210 		else if (n1 == NULL) {
    211 			n1 = stalloc(sizeof(struct nbinary));
    212 			n1->type = NSEMI;
    213 			n1->nbinary.ch1 = ntop;
    214 			n1->nbinary.ch2 = n2;
    215 			ntop = n1;
    216 		} else {
    217 			n3 = stalloc(sizeof(struct nbinary));
    218 			n3->type = NSEMI;
    219 			n3->nbinary.ch1 = n1->nbinary.ch2;
    220 			n3->nbinary.ch2 = n2;
    221 			n1->nbinary.ch2 = n3;
    222 			n1 = n3;
    223 		}
    224 
    225 		switch (tok) {
    226 		case TBACKGND:
    227 		case TSEMI:
    228 			tok = readtoken();
    229 			/* FALLTHROUGH */
    230 		case TNL:
    231 			if (tok == TNL) {
    232 				readheredocs();
    233 				if (nlflag)
    234 					return ntop;
    235 			} else if (tok == TEOF && nlflag)
    236 				return ntop;
    237 			else
    238 				tokpushback++;
    239 
    240 			checkkwd = 2;
    241 			if (!nlflag && tokendlist[peektoken()])
    242 				return ntop;
    243 			break;
    244 		case TEOF:
    245 			pungetc();	/* push back EOF on input */
    246 			return ntop;
    247 		default:
    248 			if (nlflag)
    249 				synexpect(-1, 0);
    250 			tokpushback++;
    251 			return ntop;
    252 		}
    253 	}
    254 }
    255 
    256 STATIC union node *
    257 andor(void)
    258 {
    259 	union node *n1, *n2, *n3;
    260 	int t;
    261 
    262 	CTRACE(DBG_PARSE, ("andor: entered @%d\n", plinno));
    263 
    264 	n1 = pipeline();
    265 	for (;;) {
    266 		if ((t = readtoken()) == TAND) {
    267 			t = NAND;
    268 		} else if (t == TOR) {
    269 			t = NOR;
    270 		} else {
    271 			tokpushback++;
    272 			return n1;
    273 		}
    274 		n2 = pipeline();
    275 		n3 = stalloc(sizeof(struct nbinary));
    276 		n3->type = t;
    277 		n3->nbinary.ch1 = n1;
    278 		n3->nbinary.ch2 = n2;
    279 		n1 = n3;
    280 	}
    281 }
    282 
    283 STATIC union node *
    284 pipeline(void)
    285 {
    286 	union node *n1, *n2, *pipenode;
    287 	struct nodelist *lp, *prev;
    288 	int negate;
    289 
    290 	CTRACE(DBG_PARSE, ("pipeline: entered @%d\n", plinno));
    291 
    292 	negate = 0;
    293 	checkkwd = 2;
    294 	while (readtoken() == TNOT) {
    295 		CTRACE(DBG_PARSE, ("pipeline: TNOT recognized\n"));
    296 #ifndef BOGUS_NOT_COMMAND
    297 		if (posix && negate)
    298 			synerror("2nd \"!\" unexpected");
    299 #endif
    300 		negate++;
    301 	}
    302 	tokpushback++;
    303 	n1 = command();
    304 	if (readtoken() == TPIPE) {
    305 		pipenode = stalloc(sizeof(struct npipe));
    306 		pipenode->type = NPIPE;
    307 		pipenode->npipe.backgnd = 0;
    308 		lp = stalloc(sizeof(struct nodelist));
    309 		pipenode->npipe.cmdlist = lp;
    310 		lp->n = n1;
    311 		do {
    312 			prev = lp;
    313 			lp = stalloc(sizeof(struct nodelist));
    314 			lp->n = command();
    315 			prev->next = lp;
    316 		} while (readtoken() == TPIPE);
    317 		lp->next = NULL;
    318 		n1 = pipenode;
    319 	}
    320 	tokpushback++;
    321 	if (negate) {
    322 		CTRACE(DBG_PARSE, ("%snegate pipeline\n",
    323 		    (negate&1) ? "" : "double "));
    324 		n2 = stalloc(sizeof(struct nnot));
    325 		n2->type = (negate & 1) ? NNOT : NDNOT;
    326 		n2->nnot.com = n1;
    327 		return n2;
    328 	} else
    329 		return n1;
    330 }
    331 
    332 
    333 
    334 STATIC union node *
    335 command(void)
    336 {
    337 	union node *n1, *n2;
    338 	union node *ap, **app;
    339 	union node *cp, **cpp;
    340 	union node *redir, **rpp;
    341 	int t;
    342 #ifdef BOGUS_NOT_COMMAND
    343 	int negate = 0;
    344 #endif
    345 
    346 	CTRACE(DBG_PARSE, ("command: entered @%d\n", plinno));
    347 
    348 	checkkwd = 2;
    349 	redir = NULL;
    350 	n1 = NULL;
    351 	rpp = &redir;
    352 
    353 	/* Check for redirection which may precede command */
    354 	while (readtoken() == TREDIR) {
    355 		*rpp = n2 = redirnode;
    356 		rpp = &n2->nfile.next;
    357 		parsefname();
    358 	}
    359 	tokpushback++;
    360 
    361 #ifdef BOGUS_NOT_COMMAND		/* only in pileline() */
    362 	while (readtoken() == TNOT) {
    363 		CTRACE(DBG_PARSE, ("command: TNOT (bogus) recognized\n"));
    364 		negate++;
    365 	}
    366 	tokpushback++;
    367 #endif
    368 
    369 	switch (readtoken()) {
    370 	case TIF:
    371 		n1 = stalloc(sizeof(struct nif));
    372 		n1->type = NIF;
    373 		n1->nif.test = list(0);
    374 		consumetoken(TTHEN);
    375 		n1->nif.ifpart = list(0);
    376 		n2 = n1;
    377 		while (readtoken() == TELIF) {
    378 			n2->nif.elsepart = stalloc(sizeof(struct nif));
    379 			n2 = n2->nif.elsepart;
    380 			n2->type = NIF;
    381 			n2->nif.test = list(0);
    382 			consumetoken(TTHEN);
    383 			n2->nif.ifpart = list(0);
    384 		}
    385 		if (lasttoken == TELSE)
    386 			n2->nif.elsepart = list(0);
    387 		else {
    388 			n2->nif.elsepart = NULL;
    389 			tokpushback++;
    390 		}
    391 		consumetoken(TFI);
    392 		checkkwd = 1;
    393 		break;
    394 	case TWHILE:
    395 	case TUNTIL:
    396 		n1 = stalloc(sizeof(struct nbinary));
    397 		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
    398 		n1->nbinary.ch1 = list(0);
    399 		consumetoken(TDO);
    400 		n1->nbinary.ch2 = list(0);
    401 		consumetoken(TDONE);
    402 		checkkwd = 1;
    403 		break;
    404 	case TFOR:
    405 		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
    406 			synerror("Bad for loop variable");
    407 		n1 = stalloc(sizeof(struct nfor));
    408 		n1->type = NFOR;
    409 		n1->nfor.var = wordtext;
    410 		linebreak();
    411 		if (lasttoken==TWORD && !quoteflag && equal(wordtext,"in")) {
    412 			app = &ap;
    413 			while (readtoken() == TWORD) {
    414 				n2 = makename(startlinno);
    415 				*app = n2;
    416 				app = &n2->narg.next;
    417 			}
    418 			*app = NULL;
    419 			n1->nfor.args = ap;
    420 			if (lasttoken != TNL && lasttoken != TSEMI)
    421 				synexpect(TSEMI, 0);
    422 		} else {
    423 			static char argvars[5] = {
    424 			    CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
    425 			};
    426 
    427 			n2 = stalloc(sizeof(struct narg));
    428 			n2->type = NARG;
    429 			n2->narg.text = argvars;
    430 			n2->narg.backquote = NULL;
    431 			n2->narg.next = NULL;
    432 			n2->narg.lineno = startlinno;
    433 			n1->nfor.args = n2;
    434 			/*
    435 			 * Newline or semicolon here is optional (but note
    436 			 * that the original Bourne shell only allowed NL).
    437 			 */
    438 			if (lasttoken != TNL && lasttoken != TSEMI)
    439 				tokpushback++;
    440 		}
    441 		checkkwd = 2;
    442 		if ((t = readtoken()) == TDO)
    443 			t = TDONE;
    444 		else if (t == TBEGIN)
    445 			t = TEND;
    446 		else
    447 			synexpect(TDO, 0);
    448 		n1->nfor.body = list(0);
    449 		consumetoken(t);
    450 		checkkwd = 1;
    451 		break;
    452 	case TCASE:
    453 		n1 = stalloc(sizeof(struct ncase));
    454 		n1->type = NCASE;
    455 		n1->ncase.lineno = startlinno - elided_nl;
    456 		consumetoken(TWORD);
    457 		n1->ncase.expr = makename(startlinno);
    458 		linebreak();
    459 		if (lasttoken != TWORD || !equal(wordtext, "in"))
    460 			synexpect(-1, "in");
    461 		cpp = &n1->ncase.cases;
    462 		noalias = 1;
    463 		checkkwd = 2;
    464 		readtoken();
    465 		/*
    466 		 * Both ksh and bash accept 'case x in esac'
    467 		 * so configure scripts started taking advantage of this.
    468 		 * The page: http://pubs.opengroup.org/onlinepubs/\
    469 		 * 009695399/utilities/xcu_chap02.html contradicts itself,
    470 		 * as to if this is legal; the "Case Conditional Format"
    471 		 * paragraph shows one case is required, but the "Grammar"
    472 		 * section shows a grammar that explicitly allows the no
    473 		 * case option.
    474 		 *
    475 		 * The standard also says (section 2.10):
    476 		 *   This formal syntax shall take precedence over the
    477 		 *   preceding text syntax description.
    478 		 * ie: the "Grammar" section wins.  The text is just
    479 		 * a rough guide (introduction to the common case.)
    480 		 */
    481 		while (lasttoken != TESAC) {
    482 			*cpp = cp = stalloc(sizeof(struct nclist));
    483 			cp->type = NCLIST;
    484 			app = &cp->nclist.pattern;
    485 			if (lasttoken == TLP)
    486 				readtoken();
    487 			for (;;) {
    488 				if (lasttoken < TWORD)
    489 					synexpect(TWORD, 0);
    490 				*app = ap = makename(startlinno);
    491 				checkkwd = 2;
    492 				if (readtoken() != TPIPE)
    493 					break;
    494 				app = &ap->narg.next;
    495 				readtoken();
    496 			}
    497 			noalias = 0;
    498 			if (lasttoken != TRP)
    499 				synexpect(TRP, 0);
    500 			cp->nclist.lineno = startlinno;
    501 			cp->nclist.body = list(0);
    502 
    503 			checkkwd = 2;
    504 			if ((t = readtoken()) != TESAC) {
    505 				if (t != TENDCASE && t != TCASEFALL) {
    506 					noalias = 0;
    507 					synexpect(TENDCASE, 0);
    508 				} else {
    509 					if (t == TCASEFALL)
    510 						cp->type = NCLISTCONT;
    511 					noalias = 1;
    512 					checkkwd = 2;
    513 					readtoken();
    514 				}
    515 			}
    516 			cpp = &cp->nclist.next;
    517 		}
    518 		noalias = 0;
    519 		*cpp = NULL;
    520 		checkkwd = 1;
    521 		break;
    522 	case TLP:
    523 		n1 = stalloc(sizeof(struct nredir));
    524 		n1->type = NSUBSHELL;
    525 		n1->nredir.n = list(0);
    526 		n1->nredir.redirect = NULL;
    527 		if (n1->nredir.n == NULL)
    528 			synexpect(-1, 0);
    529 		consumetoken(TRP);
    530 		checkkwd = 1;
    531 		break;
    532 	case TBEGIN:
    533 		n1 = list(0);
    534 		if (posix && n1 == NULL)
    535 			synexpect(-1, 0);
    536 		consumetoken(TEND);
    537 		checkkwd = 1;
    538 		break;
    539 
    540 	case TBACKGND:
    541 	case TSEMI:
    542 	case TAND:
    543 	case TOR:
    544 	case TPIPE:
    545 	case TNL:
    546 	case TEOF:
    547 	case TRP:
    548 	case TENDCASE:
    549 	case TCASEFALL:
    550 		/*
    551 		 * simple commands must have something in them,
    552 		 * either a word (which at this point includes a=b)
    553 		 * or a redirection.  If we reached the end of the
    554 		 * command (which one of these tokens indicates)
    555 		 * when we are just starting, and have not had a
    556 		 * redirect, then ...
    557 		 *
    558 		 * nb: it is still possible to end up with empty
    559 		 * simple commands, if the "command" is a var
    560 		 * expansion that produces nothing:
    561 		 *	X= ; $X && $X
    562 		 * -->          &&
    563 		 * That is OK and is handled after word expansions.
    564 		 */
    565 		if (!redir)
    566 			synexpect(-1, 0);
    567 		/*
    568 		 * continue to build a node containing the redirect.
    569 		 * the tokpushback means that our ending token will be
    570 		 * read again in simplecmd, causing it to terminate,
    571 		 * so only the redirect(s) will be contained in the
    572 		 * returned n1
    573 		 */
    574 		/* FALLTHROUGH */
    575 	case TWORD:
    576 		tokpushback++;
    577 		n1 = simplecmd(rpp, redir);
    578 		goto checkneg;
    579 	default:
    580 		synexpect(-1, 0);
    581 		/* NOTREACHED */
    582 	}
    583 
    584 	/* Now check for redirection which may follow command */
    585 	while (readtoken() == TREDIR) {
    586 		*rpp = n2 = redirnode;
    587 		rpp = &n2->nfile.next;
    588 		parsefname();
    589 	}
    590 	tokpushback++;
    591 	*rpp = NULL;
    592 	if (redir) {
    593 		if (n1 == NULL || n1->type != NSUBSHELL) {
    594 			n2 = stalloc(sizeof(struct nredir));
    595 			n2->type = NREDIR;
    596 			n2->nredir.n = n1;
    597 			n1 = n2;
    598 		}
    599 		n1->nredir.redirect = redir;
    600 	}
    601 
    602  checkneg:
    603 #ifdef BOGUS_NOT_COMMAND
    604 	if (negate) {
    605 		VTRACE(DBG_PARSE, ("bogus %snegate command\n",
    606 		    (negate&1) ? "" : "double "));
    607 		n2 = stalloc(sizeof(struct nnot));
    608 		n2->type = (negate & 1) ? NNOT : NDNOT;
    609 		n2->nnot.com = n1;
    610 		return n2;
    611 	}
    612 	else
    613 #endif
    614 		return n1;
    615 }
    616 
    617 
    618 STATIC union node *
    619 simplecmd(union node **rpp, union node *redir)
    620 {
    621 	union node *args, **app;
    622 	union node *n = NULL;
    623 	int line = 0;
    624 #ifdef BOGUS_NOT_COMMAND
    625 	union node *n2;
    626 	int negate = 0;
    627 #endif
    628 
    629 	CTRACE(DBG_PARSE, ("simple command with%s redir already @%d\n",
    630 	    redir ? "" : "out", plinno));
    631 
    632 	/* If we don't have any redirections already, then we must reset */
    633 	/* rpp to be the address of the local redir variable.  */
    634 	if (redir == 0)
    635 		rpp = &redir;
    636 
    637 	args = NULL;
    638 	app = &args;
    639 
    640 #ifdef BOGUS_NOT_COMMAND	/* pipelines get negated, commands do not */
    641 	while (readtoken() == TNOT) {
    642 		VTRACE(DBG_PARSE, ("simplcmd: bogus TNOT recognized\n"));
    643 		negate++;
    644 	}
    645 	tokpushback++;
    646 #endif
    647 
    648 	for (;;) {
    649 		if (readtoken() == TWORD) {
    650 			if (line == 0)
    651 				line = startlinno;
    652 			n = makename(startlinno);
    653 			*app = n;
    654 			app = &n->narg.next;
    655 		} else if (lasttoken == TREDIR) {
    656 			if (line == 0)
    657 				line = startlinno;
    658 			*rpp = n = redirnode;
    659 			rpp = &n->nfile.next;
    660 			parsefname();	/* read name of redirection file */
    661 		} else if (lasttoken == TLP && app == &args->narg.next
    662 					    && redir == 0) {
    663 			/* We have a function */
    664 			consumetoken(TRP);
    665 			funclinno = plinno;
    666 			rmescapes(n->narg.text);
    667 			if (strchr(n->narg.text, '/'))
    668 				synerror("Bad function name");
    669 			VTRACE(DBG_PARSE, ("Function '%s' seen @%d\n",
    670 			    n->narg.text, plinno));
    671 			n->type = NDEFUN;
    672 			n->narg.lineno = plinno - elided_nl;
    673 			n->narg.next = command();
    674 			funclinno = 0;
    675 			goto checkneg;
    676 		} else {
    677 			tokpushback++;
    678 			break;
    679 		}
    680 	}
    681 
    682 	if (args == NULL && redir == NULL)
    683 		synexpect(-1, 0);
    684 	*app = NULL;
    685 	*rpp = NULL;
    686 	n = stalloc(sizeof(struct ncmd));
    687 	n->type = NCMD;
    688 	n->ncmd.lineno = line - elided_nl;
    689 	n->ncmd.backgnd = 0;
    690 	n->ncmd.args = args;
    691 	n->ncmd.redirect = redir;
    692 	n->ncmd.lineno = startlinno;
    693 
    694  checkneg:
    695 #ifdef BOGUS_NOT_COMMAND
    696 	if (negate) {
    697 		VTRACE(DBG_PARSE, ("bogus %snegate simplecmd\n",
    698 		    (negate&1) ? "" : "double "));
    699 		n2 = stalloc(sizeof(struct nnot));
    700 		n2->type = (negate & 1) ? NNOT : NDNOT;
    701 		n2->nnot.com = n;
    702 		return n2;
    703 	}
    704 	else
    705 #endif
    706 		return n;
    707 }
    708 
    709 STATIC union node *
    710 makename(int lno)
    711 {
    712 	union node *n;
    713 
    714 	n = stalloc(sizeof(struct narg));
    715 	n->type = NARG;
    716 	n->narg.next = NULL;
    717 	n->narg.text = wordtext;
    718 	n->narg.backquote = backquotelist;
    719 	n->narg.lineno = lno;
    720 	return n;
    721 }
    722 
    723 void
    724 fixredir(union node *n, const char *text, int err)
    725 {
    726 
    727 	VTRACE(DBG_PARSE, ("Fix redir %s %d\n", text, err));
    728 	if (!err)
    729 		n->ndup.vname = NULL;
    730 
    731 	if (is_number(text))
    732 		n->ndup.dupfd = number(text);
    733 	else if (text[0] == '-' && text[1] == '\0')
    734 		n->ndup.dupfd = -1;
    735 	else {
    736 
    737 		if (err)
    738 			synerror("Bad fd number");
    739 		else
    740 			n->ndup.vname = makename(startlinno - elided_nl);
    741 	}
    742 }
    743 
    744 
    745 STATIC void
    746 parsefname(void)
    747 {
    748 	union node *n = redirnode;
    749 
    750 	if (readtoken() != TWORD)
    751 		synexpect(-1, 0);
    752 	if (n->type == NHERE) {
    753 		struct HereDoc *here = heredoc;
    754 		struct HereDoc *p;
    755 
    756 		if (quoteflag == 0)
    757 			n->type = NXHERE;
    758 		VTRACE(DBG_PARSE, ("Here document %d @%d\n", n->type, plinno));
    759 		if (here->striptabs) {
    760 			while (*wordtext == '\t')
    761 				wordtext++;
    762 		}
    763 
    764 		/*
    765 		 * this test is not really necessary, we are not
    766 		 * required to expand wordtext, but there's no reason
    767 		 * it cannot be $$ or something like that - that would
    768 		 * not mean the pid, but literally two '$' characters.
    769 		 * There is no need for limits on what the word can be.
    770 		 * However, it needs to stay literal as entered, not
    771 		 * have $ converted to CTLVAR or something, which as
    772 		 * the parser is, at the minute, is impossible to prevent.
    773 		 * So, leave it like this until the rest of the parser is fixed.
    774 		 */
    775 		if (!noexpand(wordtext))
    776 			synerror("Illegal eof marker for << redirection");
    777 
    778 		rmescapes(wordtext);
    779 		here->eofmark = wordtext;
    780 		here->next = NULL;
    781 		if (heredoclist == NULL)
    782 			heredoclist = here;
    783 		else {
    784 			for (p = heredoclist ; p->next ; p = p->next)
    785 				continue;
    786 			p->next = here;
    787 		}
    788 	} else if (n->type == NTOFD || n->type == NFROMFD) {
    789 		fixredir(n, wordtext, 0);
    790 	} else {
    791 		n->nfile.fname = makename(startlinno - elided_nl);
    792 	}
    793 }
    794 
    795 /*
    796  * Check to see whether we are at the end of the here document.  When this
    797  * is called, c is set to the first character of the next input line.  If
    798  * we are at the end of the here document, this routine sets the c to PEOF.
    799  * The new value of c is returned.
    800  */
    801 
    802 static int
    803 checkend(int c, char * const eofmark, const int striptabs)
    804 {
    805 
    806 	if (striptabs) {
    807 		while (c == '\t')
    808 			c = pgetc();
    809 	}
    810 	if (c == PEOF) {
    811 		if (*eofmark == '\0')
    812 			return (c);
    813 		synerror(EOFhere);
    814 	}
    815 	if (c == *eofmark) {
    816 		int c2;
    817 		char *q;
    818 
    819 		for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
    820 			if (c2 == '\n') {
    821 				plinno++;
    822 				needprompt = doprompt;
    823 			}
    824 		if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
    825 			c = PEOF;
    826 			if (c2 == '\n') {
    827 				plinno++;
    828 				needprompt = doprompt;
    829 			}
    830 		} else {
    831 			pungetc();
    832 			pushstring(eofmark + 1, q - (eofmark + 1), NULL);
    833 		}
    834 	} else if (c == '\n' && *eofmark == '\0') {
    835 		c = PEOF;
    836 		plinno++;
    837 		needprompt = doprompt;
    838 	}
    839 	return (c);
    840 }
    841 
    842 
    843 /*
    844  * Input any here documents.
    845  */
    846 
    847 STATIC int
    848 slurp_heredoc(char *const eofmark, const int striptabs, const int sq)
    849 {
    850 	int c;
    851 	char *out;
    852 	int lines = plinno;
    853 
    854 	c = pgetc();
    855 
    856 	/*
    857 	 * If we hit EOF on the input, and the eofmark is a null string ('')
    858 	 * we consider this empty line to be the eofmark, and exit without err.
    859 	 */
    860 	if (c == PEOF && *eofmark != '\0')
    861 		synerror(EOFhere);
    862 
    863 	STARTSTACKSTR(out);
    864 
    865 	while ((c = checkend(c, eofmark, striptabs)) != PEOF) {
    866 		do {
    867 			if (sq) {
    868 				/*
    869 				 * in single quoted mode (eofmark quoted)
    870 				 * all we look for is \n so we can check
    871 				 * for the epfmark - everything saved literally.
    872 				 */
    873 				STPUTC(c, out);
    874 				if (c == '\n') {
    875 					plinno++;
    876 					break;
    877 				}
    878 				continue;
    879 			}
    880 			/*
    881 			 * In double quoted (non-quoted eofmark)
    882 			 * we must handle \ followed by \n here
    883 			 * otherwise we can mismatch the end mark.
    884 			 * All other uses of \ will be handled later
    885 			 * when the here doc is expanded.
    886 			 *
    887 			 * This also makes sure \\ followed by \n does
    888 			 * not suppress the newline (the \ quotes itself)
    889 			 */
    890 			if (c == '\\') {		/* A backslash */
    891 				STPUTC(c, out);
    892 				c = pgetc();		/* followed by */
    893 				if (c == '\n') {	/* a newline?  */
    894 					STPUTC(c, out);
    895 					plinno++;
    896 					continue;	/* don't break */
    897 				}
    898 			}
    899 			STPUTC(c, out);			/* keep the char */
    900 			if (c == '\n') {		/* at end of line */
    901 				plinno++;
    902 				break;			/* look for eofmark */
    903 			}
    904 		} while ((c = pgetc()) != PEOF);
    905 
    906 		/*
    907 		 * If we have read a line, and reached EOF, without
    908 		 * finding the eofmark, whether the EOF comes before
    909 		 * or immediately after the \n, that is an error.
    910 		 */
    911 		if (c == PEOF || (c = pgetc()) == PEOF)
    912 			synerror(EOFhere);
    913 	}
    914 	STPUTC('\0', out);
    915 
    916 	c = out - stackblock();
    917 	out = stackblock();
    918 	grabstackblock(c);
    919 	wordtext = out;
    920 
    921 	VTRACE(DBG_PARSE,
    922 	   ("Slurped a %d line %sheredoc (to '%s')%s: len %d, \"%.*s%s\" @%d\n",
    923 		plinno - lines, sq ? "quoted " : "",  eofmark,
    924 		striptabs ? " tab stripped" : "", c, (c > 16 ? 16 : c),
    925 		wordtext, (c > 16 ? "..." : ""), plinno));
    926 
    927 	return (plinno - lines);
    928 }
    929 
    930 static char *
    931 insert_elided_nl(char *str)
    932 {
    933 	while (elided_nl > 0) {
    934 		STPUTC(CTLNONL, str);
    935 		elided_nl--;
    936 	}
    937 	return str;
    938 }
    939 
    940 STATIC void
    941 readheredocs(void)
    942 {
    943 	struct HereDoc *here;
    944 	union node *n;
    945 	int line, l;
    946 
    947 	line = 0;		/*XXX - gcc!  obviously unneeded */
    948 	if (heredoclist)
    949 		line = heredoclist->startline + 1;
    950 	l = 0;
    951 	while (heredoclist) {
    952 		line += l;
    953 		here = heredoclist;
    954 		heredoclist = here->next;
    955 		if (needprompt) {
    956 			setprompt(2);
    957 			needprompt = 0;
    958 		}
    959 
    960 		l = slurp_heredoc(here->eofmark, here->striptabs,
    961 		    here->here->nhere.type == NHERE);
    962 
    963 		n = stalloc(sizeof(struct narg));
    964 		n->narg.type = NARG;
    965 		n->narg.next = NULL;
    966 		n->narg.text = wordtext;
    967 		n->narg.lineno = line;
    968 		n->narg.backquote = backquotelist;
    969 		here->here->nhere.doc = n;
    970 
    971 		if (here->here->nhere.type == NHERE)
    972 			continue;
    973 
    974 		/*
    975 		 * Now "parse" here docs that have unquoted eofmarkers.
    976 		 */
    977 		setinputstring(wordtext, 1, line);
    978 		VTRACE(DBG_PARSE, ("Reprocessing %d line here doc from %d\n",
    979 			l, line));
    980 		readtoken1(pgetc(), DQSYNTAX, 1);
    981 		n->narg.text = wordtext;
    982 		n->narg.backquote = backquotelist;
    983 		popfile();
    984 	}
    985 }
    986 
    987 STATIC int
    988 peektoken(void)
    989 {
    990 	int t;
    991 
    992 	t = readtoken();
    993 	tokpushback++;
    994 	return (t);
    995 }
    996 
    997 STATIC int
    998 readtoken(void)
    999 {
   1000 	int t;
   1001 	int savecheckkwd = checkkwd;
   1002 #ifdef DEBUG
   1003 	int alreadyseen = tokpushback;
   1004 #endif
   1005 	struct alias *ap;
   1006 
   1007  top:
   1008 	t = xxreadtoken();
   1009 
   1010 	if (checkkwd) {
   1011 		/*
   1012 		 * eat newlines
   1013 		 */
   1014 		if (checkkwd == 2) {
   1015 			checkkwd = 0;
   1016 			while (t == TNL) {
   1017 				readheredocs();
   1018 				t = xxreadtoken();
   1019 			}
   1020 		} else
   1021 			checkkwd = 0;
   1022 		/*
   1023 		 * check for keywords and aliases
   1024 		 */
   1025 		if (t == TWORD && !quoteflag) {
   1026 			const char *const *pp;
   1027 
   1028 			for (pp = parsekwd; *pp; pp++) {
   1029 				if (**pp == *wordtext && equal(*pp, wordtext)) {
   1030 					lasttoken = t = pp -
   1031 					    parsekwd + KWDOFFSET;
   1032 					VTRACE(DBG_PARSE,
   1033 					    ("keyword %s recognized @%d\n",
   1034 					    tokname[t], plinno));
   1035 					goto out;
   1036 				}
   1037 			}
   1038 			if (!noalias &&
   1039 			    (ap = lookupalias(wordtext, 1)) != NULL) {
   1040 				VTRACE(DBG_PARSE,
   1041 				    ("alias '%s' recognized -> <:%s:>\n",
   1042 				    wordtext, ap->val));
   1043 				pushstring(ap->val, strlen(ap->val), ap);
   1044 				checkkwd = savecheckkwd;
   1045 				goto top;
   1046 			}
   1047 		}
   1048  out:
   1049 		checkkwd = (t == TNOT) ? savecheckkwd : 0;
   1050 	}
   1051 	VTRACE(DBG_PARSE, ("%stoken %s %s @%d\n", alreadyseen ? "reread " : "",
   1052 	    tokname[t], t == TWORD ? wordtext : "", plinno));
   1053 	return (t);
   1054 }
   1055 
   1056 
   1057 /*
   1058  * Read the next input token.
   1059  * If the token is a word, we set backquotelist to the list of cmds in
   1060  *	backquotes.  We set quoteflag to true if any part of the word was
   1061  *	quoted.
   1062  * If the token is TREDIR, then we set redirnode to a structure containing
   1063  *	the redirection.
   1064  * In all cases, the variable startlinno is set to the number of the line
   1065  *	on which the token starts.
   1066  *
   1067  * [Change comment:  here documents and internal procedures]
   1068  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
   1069  *  word parsing code into a separate routine.  In this case, readtoken
   1070  *  doesn't need to have any internal procedures, but parseword does.
   1071  *  We could also make parseoperator in essence the main routine, and
   1072  *  have parseword (readtoken1?) handle both words and redirection.]
   1073  */
   1074 
   1075 #define RETURN(token)	return lasttoken = token
   1076 
   1077 STATIC int
   1078 xxreadtoken(void)
   1079 {
   1080 	int c;
   1081 
   1082 	if (tokpushback) {
   1083 		tokpushback = 0;
   1084 		return lasttoken;
   1085 	}
   1086 	if (needprompt) {
   1087 		setprompt(2);
   1088 		needprompt = 0;
   1089 	}
   1090 	elided_nl = 0;
   1091 	startlinno = plinno;
   1092 	for (;;) {	/* until token or start of word found */
   1093 		c = pgetc_macro();
   1094 		switch (c) {
   1095 		case ' ': case '\t':
   1096 			continue;
   1097 		case '#':
   1098 			while ((c = pgetc()) != '\n' && c != PEOF)
   1099 				continue;
   1100 			pungetc();
   1101 			continue;
   1102 
   1103 		case '\n':
   1104 			plinno++;
   1105 			needprompt = doprompt;
   1106 			RETURN(TNL);
   1107 		case PEOF:
   1108 			RETURN(TEOF);
   1109 
   1110 		case '&':
   1111 			if (pgetc_linecont() == '&')
   1112 				RETURN(TAND);
   1113 			pungetc();
   1114 			RETURN(TBACKGND);
   1115 		case '|':
   1116 			if (pgetc_linecont() == '|')
   1117 				RETURN(TOR);
   1118 			pungetc();
   1119 			RETURN(TPIPE);
   1120 		case ';':
   1121 			switch (pgetc_linecont()) {
   1122 			case ';':
   1123 				RETURN(TENDCASE);
   1124 			case '&':
   1125 				RETURN(TCASEFALL);
   1126 			default:
   1127 				pungetc();
   1128 				RETURN(TSEMI);
   1129 			}
   1130 		case '(':
   1131 			RETURN(TLP);
   1132 		case ')':
   1133 			RETURN(TRP);
   1134 
   1135 		case '\\':
   1136 			switch (pgetc()) {
   1137 			case '\n':
   1138 				startlinno = ++plinno;
   1139 				if (doprompt)
   1140 					setprompt(2);
   1141 				else
   1142 					setprompt(0);
   1143 				continue;
   1144 			case PEOF:
   1145 				RETURN(TEOF);
   1146 			default:
   1147 				pungetc();
   1148 				break;
   1149 			}
   1150 			/* FALLTHROUGH */
   1151 		default:
   1152 			return readtoken1(c, BASESYNTAX, 0);
   1153 		}
   1154 	}
   1155 #undef RETURN
   1156 }
   1157 
   1158 
   1159 
   1160 /*
   1161  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
   1162  * is not NULL, read a here document.  In the latter case, eofmark is the
   1163  * word which marks the end of the document and striptabs is true if
   1164  * leading tabs should be stripped from the document.  The argument firstc
   1165  * is the first character of the input token or document.
   1166  *
   1167  * Because C does not have internal subroutines, I have simulated them
   1168  * using goto's to implement the subroutine linkage.  The following macros
   1169  * will run code that appears at the end of readtoken1.
   1170  */
   1171 
   1172 /*
   1173  * We used to remember only the current syntax, variable nesting level,
   1174  * double quote state for each var nesting level, and arith nesting
   1175  * level (unrelated to var nesting) and one prev syntax when in arith
   1176  * syntax.  This worked for simple cases, but can't handle arith inside
   1177  * var expansion inside arith inside var with some quoted and some not.
   1178  *
   1179  * Inspired by FreeBSD's implementation (though it was the obvious way)
   1180  * though implemented differently, we now have a stack that keeps track
   1181  * of what we are doing now, and what we were doing previously.
   1182  * Every time something changes, which will eventually end and should
   1183  * revert to the previous state, we push this stack, and then pop it
   1184  * again later (that is every ${} with an operator (to parse the word
   1185  * or pattern that follows) ${x} and $x are too simple to need it)
   1186  * $(( )) $( ) and "...".   Always.   Really, always!
   1187  *
   1188  * The stack is implemented as one static (on the C stack) base block
   1189  * containing LEVELS_PER_BLOCK (8) stack entries, which should be
   1190  * enough for the vast majority of cases.  For torture tests, we
   1191  * malloc more blocks as needed.  All accesses through the inline
   1192  * functions below.
   1193  */
   1194 
   1195 /*
   1196  * varnest & arinest will typically be 0 or 1
   1197  * (varnest can increment in usages like ${x=${y}} but probably
   1198  *  does not really need to)
   1199  * parenlevel allows balancing parens inside a $(( )), it is reset
   1200  * at each new nesting level ( $(( ( x + 3 ${unset-)} )) does not work.
   1201  * quoted is special - we need to know 2 things ... are we inside "..."
   1202  * (even if inherited from some previous nesting level) and was there
   1203  * an opening '"' at this level (so the next will be closing).
   1204  * "..." can span nesting levels, but cannot be opened in one and
   1205  * closed in a different one.
   1206  * To handle this, "quoted" has two fields, the bottom 4 (really 2)
   1207  * bits are 0, 1, or 2, for un, single, and double quoted (single quoted
   1208  * is really so special that this setting is not very important)
   1209  * and 0x10 that indicates that an opening quote has been seen.
   1210  * The bottom 4 bits are inherited, the 0x10 bit is not.
   1211  */
   1212 struct tokenstate {
   1213 	const char *ts_syntax;
   1214 	unsigned short ts_parenlevel;	/* counters */
   1215 	unsigned short ts_varnest;	/* 64000 levels should be enough! */
   1216 	unsigned short ts_arinest;
   1217 	unsigned short ts_quoted;	/* 1 -> single, 2 -> double */
   1218 };
   1219 
   1220 #define	NQ	0x00	/* Unquoted */
   1221 #define	SQ	0x01	/* Single Quotes */
   1222 #define	DQ	0x02	/* Double Quotes (or equivalent) */
   1223 #define	CQ	0x03	/* C style Single Quotes */
   1224 #define	QF	0x0F		/* Mask to extract previous values */
   1225 #define	QS	0x10	/* Quoting started at this level in stack */
   1226 
   1227 #define	LEVELS_PER_BLOCK	8
   1228 #define	VSS			struct statestack
   1229 
   1230 struct statestack {
   1231 	VSS *prev;		/* previous block in list */
   1232 	int cur;		/* which of our tokenstates is current */
   1233 	struct tokenstate tokenstate[LEVELS_PER_BLOCK];
   1234 };
   1235 
   1236 static inline struct tokenstate *
   1237 currentstate(VSS *stack)
   1238 {
   1239 	return &stack->tokenstate[stack->cur];
   1240 }
   1241 
   1242 static inline struct tokenstate *
   1243 prevstate(VSS *stack)
   1244 {
   1245 	if (stack->cur != 0)
   1246 		return &stack->tokenstate[stack->cur - 1];
   1247 	if (stack->prev == NULL)	/* cannot drop below base */
   1248 		return &stack->tokenstate[0];
   1249 	return &stack->prev->tokenstate[LEVELS_PER_BLOCK - 1];
   1250 }
   1251 
   1252 static inline VSS *
   1253 bump_state_level(VSS *stack)
   1254 {
   1255 	struct tokenstate *os, *ts;
   1256 
   1257 	os = currentstate(stack);
   1258 
   1259 	if (++stack->cur >= LEVELS_PER_BLOCK) {
   1260 		VSS *ss;
   1261 
   1262 		ss = (VSS *)ckmalloc(sizeof (struct statestack));
   1263 		ss->cur = 0;
   1264 		ss->prev = stack;
   1265 		stack = ss;
   1266 	}
   1267 
   1268 	ts = currentstate(stack);
   1269 
   1270 	ts->ts_parenlevel = 0;	/* parens inside never match outside */
   1271 
   1272 	ts->ts_quoted  = os->ts_quoted & QF;	/* these are default settings */
   1273 	ts->ts_varnest = os->ts_varnest;
   1274 	ts->ts_arinest = os->ts_arinest;	/* when appropriate	   */
   1275 	ts->ts_syntax  = os->ts_syntax;		/*    they will be altered */
   1276 
   1277 	return stack;
   1278 }
   1279 
   1280 static inline VSS *
   1281 drop_state_level(VSS *stack)
   1282 {
   1283 	if (stack->cur == 0) {
   1284 		VSS *ss;
   1285 
   1286 		ss = stack;
   1287 		stack = ss->prev;
   1288 		if (stack == NULL)
   1289 			return ss;
   1290 		ckfree(ss);
   1291 	}
   1292 	--stack->cur;
   1293 	return stack;
   1294 }
   1295 
   1296 static inline void
   1297 cleanup_state_stack(VSS *stack)
   1298 {
   1299 	while (stack->prev != NULL) {
   1300 		stack->cur = 0;
   1301 		stack = drop_state_level(stack);
   1302 	}
   1303 }
   1304 
   1305 #define	PARSESUB()	{goto parsesub; parsesub_return:;}
   1306 #define	PARSEARITH()	{goto parsearith; parsearith_return:;}
   1307 
   1308 /*
   1309  * The following macros all assume the existance of a local var "stack"
   1310  * which contains a pointer to the current struct stackstate
   1311  */
   1312 
   1313 /*
   1314  * These are macros rather than inline funcs to avoid code churn as much
   1315  * as possible - they replace macros of the same name used previously.
   1316  */
   1317 #define	ISDBLQUOTE()	(currentstate(stack)->ts_quoted & QS)
   1318 #define	SETDBLQUOTE()	(currentstate(stack)->ts_quoted = QS | DQ)
   1319 #define	CLRDBLQUOTE()	(currentstate(stack)->ts_quoted =		\
   1320 			    stack->cur != 0 || stack->prev ?		\
   1321 				prevstate(stack)->ts_quoted & QF : 0)
   1322 
   1323 /*
   1324  * This set are just to avoid excess typing and line lengths...
   1325  * The ones that "look like" var names must be implemented to be lvalues
   1326  */
   1327 #define	syntax		(currentstate(stack)->ts_syntax)
   1328 #define	parenlevel	(currentstate(stack)->ts_parenlevel)
   1329 #define	varnest		(currentstate(stack)->ts_varnest)
   1330 #define	arinest		(currentstate(stack)->ts_arinest)
   1331 #define	quoted		(currentstate(stack)->ts_quoted)
   1332 #define	TS_PUSH()	(stack = bump_state_level(stack))
   1333 #define	TS_POP()	(stack = drop_state_level(stack))
   1334 
   1335 /*
   1336  * Called to parse command substitutions.  oldstyle is true if the command
   1337  * is enclosed inside `` (otherwise it was enclosed in "$( )")
   1338  *
   1339  * Internally nlpp is a pointer to the head of the linked
   1340  * list of commands (passed by reference), and savelen is the number of
   1341  * characters on the top of the stack which must be preserved.
   1342  */
   1343 static char *
   1344 parsebackq(VSS *const stack, char * const in,
   1345     struct nodelist **const pbqlist, const int oldstyle, const int magicq)
   1346 {
   1347 	struct nodelist **nlpp;
   1348 	const int savepbq = parsebackquote;
   1349 	union node *n;
   1350 	char *out;
   1351 	char *str = NULL;
   1352 	char *volatile sstr = str;
   1353 	struct jmploc jmploc;
   1354 	struct jmploc *const savehandler = handler;
   1355 	const int savelen = in - stackblock();
   1356 	int saveprompt;
   1357 	int lno;
   1358 
   1359 	if (setjmp(jmploc.loc)) {
   1360 		if (sstr)
   1361 			ckfree(__UNVOLATILE(sstr));
   1362 		cleanup_state_stack(stack);
   1363 		parsebackquote = 0;
   1364 		handler = savehandler;
   1365 		longjmp(handler->loc, 1);
   1366 	}
   1367 	INTOFF;
   1368 	sstr = str = NULL;
   1369 	if (savelen > 0) {
   1370 		sstr = str = ckmalloc(savelen);
   1371 		memcpy(str, stackblock(), savelen);
   1372 	}
   1373 	handler = &jmploc;
   1374 	INTON;
   1375 	if (oldstyle) {
   1376 		/*
   1377 		 * We must read until the closing backquote, giving special
   1378 		 * treatment to some slashes, and then push the string and
   1379 		 * reread it as input, interpreting it normally.
   1380 		 */
   1381 		int pc;
   1382 		int psavelen;
   1383 		char *pstr;
   1384 		int line1 = plinno;
   1385 
   1386 		VTRACE(DBG_PARSE, ("parsebackq: repackaging `` as $( )"));
   1387 		/*
   1388 		 * Because the entire `...` is read here, we don't
   1389 		 * need to bother the state stack.  That will be used
   1390 		 * (as appropriate) when the processed string is re-read.
   1391 		 */
   1392 		STARTSTACKSTR(out);
   1393 #ifdef DEBUG
   1394 		for (psavelen = 0;;psavelen++) {
   1395 #else
   1396 		for (;;) {
   1397 #endif
   1398 			if (needprompt) {
   1399 				setprompt(2);
   1400 				needprompt = 0;
   1401 			}
   1402 			pc = pgetc();
   1403 			if (pc == '`')
   1404 				break;
   1405 			switch (pc) {
   1406 			case '\\':
   1407 				pc = pgetc();
   1408 #ifdef DEBUG
   1409 				psavelen++;
   1410 #endif
   1411 				if (pc == '\n') {   /* keep \ \n for later */
   1412 					plinno++;
   1413 					needprompt = doprompt;
   1414 				}
   1415 				if (pc != '\\' && pc != '`' && pc != '$'
   1416 				    && (!ISDBLQUOTE() || pc != '"'))
   1417 					STPUTC('\\', out);
   1418 				break;
   1419 
   1420 			case '\n':
   1421 				plinno++;
   1422 				needprompt = doprompt;
   1423 				break;
   1424 
   1425 			case PEOF:
   1426 			        startlinno = line1;
   1427 				synerror("EOF in backquote substitution");
   1428  				break;
   1429 
   1430 			default:
   1431 				break;
   1432 			}
   1433 			STPUTC(pc, out);
   1434 		}
   1435 		STPUTC('\0', out);
   1436 		VTRACE(DBG_PARSE, (" read %d", psavelen));
   1437 		psavelen = out - stackblock();
   1438 		VTRACE(DBG_PARSE, (" produced %d\n", psavelen));
   1439 		if (psavelen > 0) {
   1440 			pstr = grabstackstr(out);
   1441 			setinputstring(pstr, 1, line1);
   1442 		}
   1443 	}
   1444 	nlpp = pbqlist;
   1445 	while (*nlpp)
   1446 		nlpp = &(*nlpp)->next;
   1447 	*nlpp = stalloc(sizeof(struct nodelist));
   1448 	(*nlpp)->next = NULL;
   1449 	parsebackquote = oldstyle;
   1450 
   1451 	if (oldstyle) {
   1452 		saveprompt = doprompt;
   1453 		doprompt = 0;
   1454 	} else
   1455 		saveprompt = 0;
   1456 
   1457 	lno = -plinno;
   1458 	n = list(0);
   1459 	lno += plinno;
   1460 
   1461 	if (oldstyle) {
   1462 		if (peektoken() != TEOF)
   1463 			synexpect(-1, 0);
   1464 		doprompt = saveprompt;
   1465 	} else
   1466 		consumetoken(TRP);
   1467 
   1468 	(*nlpp)->n = n;
   1469 	if (oldstyle) {
   1470 		/*
   1471 		 * Start reading from old file again, ignoring any pushed back
   1472 		 * tokens left from the backquote parsing
   1473 		 */
   1474 		popfile();
   1475 		tokpushback = 0;
   1476 	}
   1477 
   1478 	while (stackblocksize() <= savelen)
   1479 		growstackblock();
   1480 	STARTSTACKSTR(out);
   1481 	if (str) {
   1482 		memcpy(out, str, savelen);
   1483 		STADJUST(savelen, out);
   1484 		INTOFF;
   1485 		ckfree(str);
   1486 		sstr = str = NULL;
   1487 		INTON;
   1488 	}
   1489 	parsebackquote = savepbq;
   1490 	handler = savehandler;
   1491 	if (arinest || ISDBLQUOTE()) {
   1492 		STPUTC(CTLBACKQ | CTLQUOTE, out);
   1493 		while (--lno >= 0)
   1494 			STPUTC(CTLNONL, out);
   1495 	} else
   1496 		STPUTC(CTLBACKQ, out);
   1497 
   1498 	return out;
   1499 }
   1500 
   1501 /*
   1502  * Parse a redirection operator.  The parameter "out" points to a string
   1503  * specifying the fd to be redirected.  It is guaranteed to be either ""
   1504  * or a numeric string (for now anyway).  The parameter "c" contains the
   1505  * first character of the redirection operator.
   1506  *
   1507  * Note the string "out" is on the stack, which we are about to clobber,
   1508  * so process it first...
   1509  */
   1510 
   1511 static void
   1512 parseredir(const char *out,  int c)
   1513 {
   1514 	union node *np;
   1515 	int fd;
   1516 
   1517 	fd = (*out == '\0') ? -1 : number(out);
   1518 
   1519 	np = stalloc(sizeof(struct nfile));
   1520 	if (c == '>') {
   1521 		if (fd < 0)
   1522 			fd = 1;
   1523 		c = pgetc_linecont();
   1524 		if (c == '>')
   1525 			np->type = NAPPEND;
   1526 		else if (c == '|')
   1527 			np->type = NCLOBBER;
   1528 		else if (c == '&')
   1529 			np->type = NTOFD;
   1530 		else {
   1531 			np->type = NTO;
   1532 			pungetc();
   1533 		}
   1534 	} else {	/* c == '<' */
   1535 		if (fd < 0)
   1536 			fd = 0;
   1537 		switch (c = pgetc_linecont()) {
   1538 		case '<':
   1539 			if (sizeof (struct nfile) != sizeof (struct nhere)) {
   1540 				np = stalloc(sizeof(struct nhere));
   1541 				np->nfile.fd = 0;
   1542 			}
   1543 			np->type = NHERE;
   1544 			heredoc = stalloc(sizeof(struct HereDoc));
   1545 			heredoc->here = np;
   1546 			heredoc->startline = plinno;
   1547 			if ((c = pgetc_linecont()) == '-') {
   1548 				heredoc->striptabs = 1;
   1549 			} else {
   1550 				heredoc->striptabs = 0;
   1551 				pungetc();
   1552 			}
   1553 			break;
   1554 
   1555 		case '&':
   1556 			np->type = NFROMFD;
   1557 			break;
   1558 
   1559 		case '>':
   1560 			np->type = NFROMTO;
   1561 			break;
   1562 
   1563 		default:
   1564 			np->type = NFROM;
   1565 			pungetc();
   1566 			break;
   1567 		}
   1568 	}
   1569 	np->nfile.fd = fd;
   1570 
   1571 	redirnode = np;		/* this is the "value" of TRENODE */
   1572 }
   1573 
   1574 /*
   1575  * Called to parse a backslash escape sequence inside $'...'.
   1576  * The backslash has already been read.
   1577  */
   1578 static char *
   1579 readcstyleesc(char *out)
   1580 {
   1581 	int c, vc, i, n;
   1582 	unsigned int v;
   1583 
   1584 	c = pgetc();
   1585 	switch (c) {
   1586 	case '\0':
   1587 	case PEOF:
   1588 		synerror("Unterminated quoted string");
   1589 	case '\n':
   1590 		plinno++;
   1591 		if (doprompt)
   1592 			setprompt(2);
   1593 		else
   1594 			setprompt(0);
   1595 		return out;
   1596 
   1597 	case '\\':
   1598 	case '\'':
   1599 	case '"':
   1600 		v = c;
   1601 		break;
   1602 
   1603 	case 'a': v = '\a'; break;
   1604 	case 'b': v = '\b'; break;
   1605 	case 'e': v = '\033'; break;
   1606 	case 'f': v = '\f'; break;
   1607 	case 'n': v = '\n'; break;
   1608 	case 'r': v = '\r'; break;
   1609 	case 't': v = '\t'; break;
   1610 	case 'v': v = '\v'; break;
   1611 
   1612 	case '0': case '1': case '2': case '3':
   1613 	case '4': case '5': case '6': case '7':
   1614 		v = c - '0';
   1615 		c = pgetc();
   1616 		if (c >= '0' && c <= '7') {
   1617 			v <<= 3;
   1618 			v += c - '0';
   1619 			c = pgetc();
   1620 			if (c >= '0' && c <= '7') {
   1621 				v <<= 3;
   1622 				v += c - '0';
   1623 			} else
   1624 				pungetc();
   1625 		} else
   1626 			pungetc();
   1627 		break;
   1628 
   1629 	case 'c':
   1630 		c = pgetc();
   1631 		if (c < 0x3f || c > 0x7a || c == 0x60)
   1632 			synerror("Bad \\c escape sequence");
   1633 		if (c == '\\' && pgetc() != '\\')
   1634 			synerror("Bad \\c\\ escape sequence");
   1635 		if (c == '?')
   1636 			v = 127;
   1637 		else
   1638 			v = c & 0x1f;
   1639 		break;
   1640 
   1641 	case 'x':
   1642 		n = 2;
   1643 		goto hexval;
   1644 	case 'u':
   1645 		n = 4;
   1646 		goto hexval;
   1647 	case 'U':
   1648 		n = 8;
   1649 	hexval:
   1650 		v = 0;
   1651 		for (i = 0; i < n; i++) {
   1652 			c = pgetc();
   1653 			if (c >= '0' && c <= '9')
   1654 				v = (v << 4) + c - '0';
   1655 			else if (c >= 'A' && c <= 'F')
   1656 				v = (v << 4) + c - 'A' + 10;
   1657 			else if (c >= 'a' && c <= 'f')
   1658 				v = (v << 4) + c - 'a' + 10;
   1659 			else {
   1660 				pungetc();
   1661 				break;
   1662 			}
   1663 		}
   1664 		if (n > 2 && v > 127) {
   1665 			if (v >= 0xd800 && v <= 0xdfff)
   1666 				synerror("Invalid \\u escape sequence");
   1667 
   1668 			/* XXX should we use iconv here. What locale? */
   1669 			CHECKSTRSPACE(4, out);
   1670 
   1671 			if (v <= 0x7ff) {
   1672 				USTPUTC(0xc0 | v >> 6, out);
   1673 				USTPUTC(0x80 | (v & 0x3f), out);
   1674 				return out;
   1675 			} else if (v <= 0xffff) {
   1676 				USTPUTC(0xe0 | v >> 12, out);
   1677 				USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
   1678 				USTPUTC(0x80 | (v & 0x3f), out);
   1679 				return out;
   1680 			} else if (v <= 0x10ffff) {
   1681 				USTPUTC(0xf0 | v >> 18, out);
   1682 				USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
   1683 				USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
   1684 				USTPUTC(0x80 | (v & 0x3f), out);
   1685 				return out;
   1686 			}
   1687 			if (v > 127)
   1688 				v = '?';
   1689 		}
   1690 		break;
   1691 	default:
   1692 		synerror("Unknown $'' escape sequence");
   1693 	}
   1694 	vc = (char)v;
   1695 
   1696 	/*
   1697 	 * If we managed to create a \n from a \ sequence (no matter how)
   1698 	 * then we replace it with the magic CRTCNL control char, which
   1699 	 * will turn into a \n again later, but in the meantime, never
   1700 	 * causes LINENO increments.
   1701 	 */
   1702 	if (vc == '\n') {
   1703 		USTPUTC(CTLCNL, out);
   1704 		return out;
   1705 	}
   1706 
   1707 	/*
   1708 	 * We can't handle NUL bytes.
   1709 	 * POSIX says we should skip till the closing quote.
   1710 	 */
   1711 	if (vc == '\0') {
   1712 		while ((c = pgetc()) != '\'') {
   1713 			if (c == '\\')
   1714 				c = pgetc();
   1715 			if (c == PEOF)
   1716 				synerror("Unterminated quoted string");
   1717 			if (c == '\n') {
   1718 				plinno++;
   1719 				if (doprompt)
   1720 					setprompt(2);
   1721 				else
   1722 					setprompt(0);
   1723 			}
   1724 		}
   1725 		pungetc();
   1726 		return out;
   1727 	}
   1728 	if (NEEDESC(vc))
   1729 		USTPUTC(CTLESC, out);
   1730 	USTPUTC(vc, out);
   1731 	return out;
   1732 }
   1733 
   1734 /*
   1735  * The lowest level basic tokenizer.
   1736  *
   1737  * The next input byte (character) is in firstc, syn says which
   1738  * syntax tables we are to use (basic, single or double quoted, or arith)
   1739  * and magicq (used with sqsyntax and dqsyntax only) indicates that the
   1740  * quote character itself is not special (used parsing here docs and similar)
   1741  *
   1742  * The result is the type of the next token (its value, when there is one,
   1743  * is saved in the relevant global var - must fix that someday!) which is
   1744  * also saved for re-reading ("lasttoken").
   1745  *
   1746  * Overall, this routine does far more parsing than it is supposed to.
   1747  * That will also need fixing, someday...
   1748  */
   1749 STATIC int
   1750 readtoken1(int firstc, char const *syn, int magicq)
   1751 {
   1752 	int c;
   1753 	char * out;
   1754 	int len;
   1755 	struct nodelist *bqlist;
   1756 	int quotef;
   1757 	VSS static_stack;
   1758 	VSS *stack = &static_stack;
   1759 
   1760 	stack->prev = NULL;
   1761 	stack->cur = 0;
   1762 
   1763 	syntax = syn;
   1764 
   1765 	startlinno = plinno;
   1766 	varnest = 0;
   1767 	quoted = 0;
   1768 	if (syntax == DQSYNTAX)
   1769 		SETDBLQUOTE();
   1770 	quotef = 0;
   1771 	bqlist = NULL;
   1772 	arinest = 0;
   1773 	parenlevel = 0;
   1774 	elided_nl = 0;
   1775 
   1776 	STARTSTACKSTR(out);
   1777 
   1778 	for (c = firstc ;; c = pgetc_macro()) {	/* until of token */
   1779 		if (syntax == ARISYNTAX)
   1780 			out = insert_elided_nl(out);
   1781 		CHECKSTRSPACE(6, out);	/* permit 6 calls to USTPUTC */
   1782 		switch (syntax[c]) {
   1783 		case CNL:	/* '\n' */
   1784 			if (syntax == BASESYNTAX && varnest == 0)
   1785 				break;	/* exit loop */
   1786 			USTPUTC(c, out);
   1787 			plinno++;
   1788 			if (doprompt)
   1789 				setprompt(2);
   1790 			else
   1791 				setprompt(0);
   1792 			continue;
   1793 
   1794 		case CSBACK:	/* single quoted backslash */
   1795 			if ((quoted & QF) == CQ) {
   1796 				out = readcstyleesc(out);
   1797 				continue;
   1798 			}
   1799 			USTPUTC(CTLESC, out);
   1800 			/* FALLTHROUGH */
   1801 		case CWORD:
   1802 			USTPUTC(c, out);
   1803 			continue;
   1804 
   1805 		case CCTL:
   1806 			if (!magicq || ISDBLQUOTE())
   1807 				USTPUTC(CTLESC, out);
   1808 			USTPUTC(c, out);
   1809 			continue;
   1810 		case CBACK:	/* backslash */
   1811 			c = pgetc();
   1812 			if (c == PEOF) {
   1813 				USTPUTC('\\', out);
   1814 				pungetc();
   1815 				continue;
   1816 			}
   1817 			if (c == '\n') {
   1818 				plinno++;
   1819 				elided_nl++;
   1820 				if (doprompt)
   1821 					setprompt(2);
   1822 				else
   1823 					setprompt(0);
   1824 				continue;
   1825 			}
   1826 			quotef = 1;	/* current token is quoted */
   1827 			if (ISDBLQUOTE() && c != '\\' && c != '`' &&
   1828 			    c != '$' && (c != '"' || magicq)) {
   1829 				/*
   1830 				 * retain the \ (which we *know* needs CTLESC)
   1831 				 * when in "..." and the following char is
   1832 				 * not one of the magic few.)
   1833 				 * Otherwise the \ has done its work, and
   1834 				 * is dropped.
   1835 				 */
   1836 				USTPUTC(CTLESC, out);
   1837 				USTPUTC('\\', out);
   1838 			}
   1839 			if (NEEDESC(c))
   1840 				USTPUTC(CTLESC, out);
   1841 			else if (!magicq) {
   1842 				USTPUTC(CTLQUOTEMARK, out);
   1843 				USTPUTC(c, out);
   1844 				if (varnest != 0)
   1845 					USTPUTC(CTLQUOTEEND, out);
   1846 				continue;
   1847 			}
   1848 			USTPUTC(c, out);
   1849 			continue;
   1850 		case CSQUOTE:
   1851 			if (syntax != SQSYNTAX) {
   1852 				if (!magicq)
   1853 					USTPUTC(CTLQUOTEMARK, out);
   1854 				quotef = 1;
   1855 				TS_PUSH();
   1856 				syntax = SQSYNTAX;
   1857 				quoted = SQ;
   1858 				continue;
   1859 			}
   1860 			if (magicq && arinest == 0 && varnest == 0) {
   1861 				/* Ignore inside quoted here document */
   1862 				USTPUTC(c, out);
   1863 				continue;
   1864 			}
   1865 			/* End of single quotes... */
   1866 			TS_POP();
   1867 			if (syntax == BASESYNTAX && varnest != 0)
   1868 				USTPUTC(CTLQUOTEEND, out);
   1869 			continue;
   1870 		case CDQUOTE:
   1871 			if (magicq && arinest == 0 && varnest == 0) {
   1872 				/* Ignore inside here document */
   1873 				USTPUTC(c, out);
   1874 				continue;
   1875 			}
   1876 			quotef = 1;
   1877 			if (arinest) {
   1878 				if (ISDBLQUOTE()) {
   1879 					TS_POP();
   1880 				} else {
   1881 					TS_PUSH();
   1882 					syntax = DQSYNTAX;
   1883 					SETDBLQUOTE();
   1884 					USTPUTC(CTLQUOTEMARK, out);
   1885 				}
   1886 				continue;
   1887 			}
   1888 			if (magicq)
   1889 				continue;
   1890 			if (ISDBLQUOTE()) {
   1891 				TS_POP();
   1892 				if (varnest != 0)
   1893 					USTPUTC(CTLQUOTEEND, out);
   1894 			} else {
   1895 				TS_PUSH();
   1896 				syntax = DQSYNTAX;
   1897 				SETDBLQUOTE();
   1898 				USTPUTC(CTLQUOTEMARK, out);
   1899 			}
   1900 			continue;
   1901 		case CVAR:	/* '$' */
   1902 			out = insert_elided_nl(out);
   1903 			PARSESUB();		/* parse substitution */
   1904 			continue;
   1905 		case CENDVAR:	/* CLOSEBRACE */
   1906 			if (varnest > 0 && !ISDBLQUOTE()) {
   1907 				TS_POP();
   1908 				USTPUTC(CTLENDVAR, out);
   1909 			} else {
   1910 				USTPUTC(c, out);
   1911 			}
   1912 			out = insert_elided_nl(out);
   1913 			continue;
   1914 		case CLP:	/* '(' in arithmetic */
   1915 			parenlevel++;
   1916 			USTPUTC(c, out);
   1917 			continue;;
   1918 		case CRP:	/* ')' in arithmetic */
   1919 			if (parenlevel > 0) {
   1920 				USTPUTC(c, out);
   1921 				--parenlevel;
   1922 			} else {
   1923 				if (pgetc_linecont() == /*(*/ ')') {
   1924 					out = insert_elided_nl(out);
   1925 					if (--arinest == 0) {
   1926 						TS_POP();
   1927 						USTPUTC(CTLENDARI, out);
   1928 					} else
   1929 						USTPUTC(/*(*/ ')', out);
   1930 				} else {
   1931 					break;	/* to synerror() just below */
   1932 #if 0	/* the old way, causes weird errors on bad input */
   1933 					/*
   1934 					 * unbalanced parens
   1935 					 *  (don't 2nd guess - no error)
   1936 					 */
   1937 					pungetc();
   1938 					USTPUTC(/*(*/ ')', out);
   1939 #endif
   1940 				}
   1941 			}
   1942 			continue;
   1943 		case CBQUOTE:	/* '`' */
   1944 			out = parsebackq(stack, out, &bqlist, 1, magicq);
   1945 			continue;
   1946 		case CEOF:		/* --> c == PEOF */
   1947 			break;		/* will exit loop */
   1948 		default:
   1949 			if (varnest == 0 && !ISDBLQUOTE())
   1950 				break;	/* exit loop */
   1951 			USTPUTC(c, out);
   1952 			continue;
   1953 		}
   1954 		break;	/* break from switch -> break from for loop too */
   1955 	}
   1956 
   1957 	if (syntax == ARISYNTAX) {
   1958 		cleanup_state_stack(stack);
   1959 		synerror(/*((*/ "Missing '))'");
   1960 	}
   1961 	if (syntax != BASESYNTAX && /* ! parsebackquote && */ !magicq) {
   1962 		cleanup_state_stack(stack);
   1963 		synerror("Unterminated quoted string");
   1964 	}
   1965 	if (varnest != 0) {
   1966 		cleanup_state_stack(stack);
   1967 		startlinno = plinno;
   1968 		/* { */
   1969 		synerror("Missing '}'");
   1970 	}
   1971 
   1972 	STPUTC('\0', out);
   1973 	len = out - stackblock();
   1974 	out = stackblock();
   1975 
   1976 	if (!magicq) {
   1977 		if ((c == '<' || c == '>')
   1978 		 && quotef == 0 && (*out == '\0' || is_number(out))) {
   1979 			parseredir(out, c);
   1980 			cleanup_state_stack(stack);
   1981 			return lasttoken = TREDIR;
   1982 		} else {
   1983 			pungetc();
   1984 		}
   1985 	}
   1986 
   1987 	VTRACE(DBG_PARSE,
   1988 	    ("readtoken1 %sword \"%s\", completed%s (%d) left %d enl\n",
   1989 	    (quotef ? "quoted " : ""), out, (bqlist ? " with cmdsubs" : ""),
   1990 	    len, elided_nl));
   1991 
   1992 	quoteflag = quotef;
   1993 	backquotelist = bqlist;
   1994 	grabstackblock(len);
   1995 	wordtext = out;
   1996 	cleanup_state_stack(stack);
   1997 	return lasttoken = TWORD;
   1998 /* end of readtoken routine */
   1999 
   2000 
   2001 /*
   2002  * Parse a substitution.  At this point, we have read the dollar sign
   2003  * and nothing else.
   2004  */
   2005 
   2006 parsesub: {
   2007 	int subtype;
   2008 	int typeloc;
   2009 	int flags;
   2010 	char *p;
   2011 	static const char types[] = "}-+?=";
   2012 
   2013 	c = pgetc_linecont();
   2014 	if (c == '(' /*)*/) {	/* $(command) or $((arith)) */
   2015 		if (pgetc_linecont() == '(' /*')'*/ ) {
   2016 			out = insert_elided_nl(out);
   2017 			PARSEARITH();
   2018 		} else {
   2019 			out = insert_elided_nl(out);
   2020 			pungetc();
   2021 			out = parsebackq(stack, out, &bqlist, 0, magicq);
   2022 		}
   2023 	} else if (c == OPENBRACE || is_name(c) || is_special(c)) {
   2024 		USTPUTC(CTLVAR, out);
   2025 		typeloc = out - stackblock();
   2026 		USTPUTC(VSNORMAL, out);
   2027 		subtype = VSNORMAL;
   2028 		flags = 0;
   2029 		if (c == OPENBRACE) {
   2030 			c = pgetc_linecont();
   2031 			if (c == '#') {
   2032 				if ((c = pgetc_linecont()) == CLOSEBRACE)
   2033 					c = '#';
   2034 				else if (is_name(c) || isdigit(c))
   2035 					subtype = VSLENGTH;
   2036 				else if (is_special(c)) {
   2037 					/*
   2038 					 * ${#} is $# - the number of sh params
   2039 					 * ${##} is the length of ${#}
   2040 					 * ${###} is ${#} with as much nothing
   2041 					 *        as possible removed from start
   2042 					 * ${##1} is ${#} with leading 1 gone
   2043 					 * ${##\#} is ${#} with leading # gone
   2044 					 *
   2045 					 * this stuff is UGLY!
   2046 					 */
   2047 					if (pgetc_linecont() == CLOSEBRACE) {
   2048 						pungetc();
   2049 						subtype = VSLENGTH;
   2050 					} else {
   2051 						static char cbuf[2];
   2052 
   2053 						pungetc();   /* would like 2 */
   2054 						cbuf[0] = c; /* so ... */
   2055 						cbuf[1] = '\0';
   2056 						pushstring(cbuf, 1, NULL);
   2057 						c = '#';     /* ${#:...} */
   2058 						subtype = 0; /* .. or similar */
   2059 					}
   2060 				} else {
   2061 					pungetc();
   2062 					c = '#';
   2063 					subtype = 0;
   2064 				}
   2065 			}
   2066 			else
   2067 				subtype = 0;
   2068 		}
   2069 		if (is_name(c)) {
   2070 			p = out;
   2071 			do {
   2072 				STPUTC(c, out);
   2073 				c = pgetc_linecont();
   2074 			} while (is_in_name(c));
   2075 #if 0
   2076 			if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
   2077 				int i;
   2078 				int linno;
   2079 				char buf[10];
   2080 
   2081 				/*
   2082 				 * The "LINENO hack"
   2083 				 *
   2084 				 * Replace the variable name with the
   2085 				 * current line number.
   2086 				 */
   2087 				linno = plinno;
   2088 				if (funclinno != 0)
   2089 					linno -= funclinno - 1;
   2090 				snprintf(buf, sizeof(buf), "%d", linno);
   2091 				STADJUST(-6, out);
   2092 				for (i = 0; buf[i] != '\0'; i++)
   2093 					STPUTC(buf[i], out);
   2094 				flags |= VSLINENO;
   2095 			}
   2096 #endif
   2097 		} else if (is_digit(c)) {
   2098 			do {
   2099 				STPUTC(c, out);
   2100 				c = pgetc_linecont();
   2101 			} while (subtype != VSNORMAL && is_digit(c));
   2102 		}
   2103 		else if (is_special(c)) {
   2104 			USTPUTC(c, out);
   2105 			c = pgetc_linecont();
   2106 		}
   2107 		else {
   2108  badsub:
   2109 			cleanup_state_stack(stack);
   2110 			synerror("Bad substitution");
   2111 		}
   2112 
   2113 		STPUTC('=', out);
   2114 		if (subtype == 0) {
   2115 			switch (c) {
   2116 			case ':':
   2117 				flags |= VSNUL;
   2118 				c = pgetc_linecont();
   2119 				/*FALLTHROUGH*/
   2120 			default:
   2121 				p = strchr(types, c);
   2122 				if (p == NULL)
   2123 					goto badsub;
   2124 				subtype = p - types + VSNORMAL;
   2125 				break;
   2126 			case '%':
   2127 			case '#':
   2128 				{
   2129 					int cc = c;
   2130 					subtype = c == '#' ? VSTRIMLEFT :
   2131 							     VSTRIMRIGHT;
   2132 					c = pgetc_linecont();
   2133 					if (c == cc)
   2134 						subtype++;
   2135 					else
   2136 						pungetc();
   2137 					break;
   2138 				}
   2139 			}
   2140 		} else {
   2141 			if (subtype == VSLENGTH && c != /*{*/ '}')
   2142 				synerror("no modifiers allowed with ${#var}");
   2143 			pungetc();
   2144 		}
   2145 		if (ISDBLQUOTE() || arinest)
   2146 			flags |= VSQUOTE;
   2147 		if (subtype >= VSTRIMLEFT && subtype <= VSTRIMRIGHTMAX)
   2148 			flags |= VSPATQ;
   2149 		*(stackblock() + typeloc) = subtype | flags;
   2150 		if (subtype != VSNORMAL) {
   2151 			TS_PUSH();
   2152 			varnest++;
   2153 			arinest = 0;
   2154 			if (subtype > VSASSIGN) {	/* # ## % %% */
   2155 				syntax = BASESYNTAX;
   2156 				CLRDBLQUOTE();
   2157 			}
   2158 		}
   2159 	} else if (c == '\'' && syntax == BASESYNTAX) {
   2160 		USTPUTC(CTLQUOTEMARK, out);
   2161 		quotef = 1;
   2162 		TS_PUSH();
   2163 		syntax = SQSYNTAX;
   2164 		quoted = CQ;
   2165 	} else {
   2166 		USTPUTC('$', out);
   2167 		pungetc();
   2168 	}
   2169 	goto parsesub_return;
   2170 }
   2171 
   2172 
   2173 /*
   2174  * Parse an arithmetic expansion (indicate start of one and set state)
   2175  */
   2176 parsearith: {
   2177 
   2178 #if 0
   2179 	if (syntax == ARISYNTAX) {
   2180 		/*
   2181 		 * we collapse embedded arithmetic expansion to
   2182 		 * parentheses, which should be equivalent
   2183 		 *
   2184 		 *	XXX It isn't, must fix, soonish...
   2185 		 */
   2186 		USTPUTC('(' /*)*/, out);
   2187 		USTPUTC('(' /*)*/, out);
   2188 		/*
   2189 		 * Need 2 of them because there will (should be)
   2190 		 * two closing ))'s to follow later.
   2191 		 */
   2192 		parenlevel += 2;
   2193 	} else
   2194 #endif
   2195 	{
   2196 		USTPUTC(CTLARI, out);
   2197 		if (ISDBLQUOTE())
   2198 			USTPUTC('"',out);
   2199 		else
   2200 			USTPUTC(' ',out);
   2201 
   2202 		TS_PUSH();
   2203 		syntax = ARISYNTAX;
   2204 		arinest = 1;
   2205 		varnest = 0;
   2206 	}
   2207 	goto parsearith_return;
   2208 }
   2209 
   2210 } /* end of readtoken */
   2211 
   2212 
   2213 
   2214 
   2215 #ifdef mkinit
   2216 INCLUDE "parser.h"
   2217 
   2218 RESET {
   2219 	psp.v_current_parser = &parse_state;
   2220 
   2221 	parse_state.ps_tokpushback = 0;
   2222 	parse_state.ps_checkkwd = 0;
   2223 	parse_state.ps_heredoclist = NULL;
   2224 }
   2225 #endif
   2226 
   2227 /*
   2228  * Returns true if the text contains nothing to expand (no dollar signs
   2229  * or backquotes).
   2230  */
   2231 
   2232 STATIC int
   2233 noexpand(char *text)
   2234 {
   2235 	char *p;
   2236 	char c;
   2237 
   2238 	p = text;
   2239 	while ((c = *p++) != '\0') {
   2240 		if (c == CTLQUOTEMARK)
   2241 			continue;
   2242 		if (c == CTLESC)
   2243 			p++;
   2244 		else if (BASESYNTAX[(int)c] == CCTL)
   2245 			return 0;
   2246 	}
   2247 	return 1;
   2248 }
   2249 
   2250 
   2251 /*
   2252  * Return true if the argument is a legal variable name (a letter or
   2253  * underscore followed by zero or more letters, underscores, and digits).
   2254  */
   2255 
   2256 int
   2257 goodname(char *name)
   2258 {
   2259 	char *p;
   2260 
   2261 	p = name;
   2262 	if (! is_name(*p))
   2263 		return 0;
   2264 	while (*++p) {
   2265 		if (! is_in_name(*p))
   2266 			return 0;
   2267 	}
   2268 	return 1;
   2269 }
   2270 
   2271 /*
   2272  * skip past any \n's, and leave lasttoken set to whatever follows
   2273  */
   2274 STATIC void
   2275 linebreak(void)
   2276 {
   2277 	while (readtoken() == TNL)
   2278 		;
   2279 }
   2280 
   2281 /*
   2282  * The next token must be "token" -- check, then move past it
   2283  */
   2284 STATIC void
   2285 consumetoken(int token)
   2286 {
   2287 	if (readtoken() != token) {
   2288 		VTRACE(DBG_PARSE, ("consumetoken(%d): expecting %s got %s",
   2289 		    token, tokname[token], tokname[lasttoken]));
   2290 		CVTRACE(DBG_PARSE, (lasttoken==TWORD), (" \"%s\"", wordtext));
   2291 		VTRACE(DBG_PARSE, ("\n"));
   2292 		synexpect(token, NULL);
   2293 	}
   2294 }
   2295 
   2296 /*
   2297  * Called when an unexpected token is read during the parse.  The argument
   2298  * is the token that is expected, or -1 if more than one type of token can
   2299  * occur at this point.
   2300  */
   2301 
   2302 STATIC void
   2303 synexpect(int token, const char *text)
   2304 {
   2305 	char msg[64];
   2306 	char *p;
   2307 
   2308 	if (lasttoken == TWORD) {
   2309 		size_t len = strlen(wordtext);
   2310 
   2311 		if (len <= 13)
   2312 			fmtstr(msg, 34, "Word \"%.13s\" unexpected", wordtext);
   2313 		else
   2314 			fmtstr(msg, 34,
   2315 			    "Word \"%.10s...\" unexpected", wordtext);
   2316 	} else
   2317 		fmtstr(msg, 34, "%s unexpected", tokname[lasttoken]);
   2318 
   2319 	p = strchr(msg, '\0');
   2320 	if (text)
   2321 		fmtstr(p, 30, " (expecting \"%.10s\")", text);
   2322 	else if (token >= 0)
   2323 		fmtstr(p, 30, " (expecting %s)",  tokname[token]);
   2324 
   2325 	synerror(msg);
   2326 	/* NOTREACHED */
   2327 }
   2328 
   2329 
   2330 STATIC void
   2331 synerror(const char *msg)
   2332 {
   2333 	error("%d: Syntax error: %s", startlinno, msg);
   2334 	/* NOTREACHED */
   2335 }
   2336 
   2337 STATIC void
   2338 setprompt(int which)
   2339 {
   2340 	whichprompt = which;
   2341 
   2342 #ifndef SMALL
   2343 	if (!el)
   2344 #endif
   2345 		out2str(getprompt(NULL));
   2346 }
   2347 
   2348 /*
   2349  * handle getting the next character, while ignoring \ \n
   2350  * (which is a little tricky as we only have one char of pushback
   2351  * and we need that one elsewhere).
   2352  */
   2353 STATIC int
   2354 pgetc_linecont(void)
   2355 {
   2356 	int c;
   2357 
   2358 	while ((c = pgetc_macro()) == '\\') {
   2359 		c = pgetc();
   2360 		if (c == '\n') {
   2361 			plinno++;
   2362 			elided_nl++;
   2363 			if (doprompt)
   2364 				setprompt(2);
   2365 			else
   2366 				setprompt(0);
   2367 		} else {
   2368 			pungetc();
   2369 			/* Allow the backslash to be pushed back. */
   2370 			pushstring("\\", 1, NULL);
   2371 			return (pgetc());
   2372 		}
   2373 	}
   2374 	return (c);
   2375 }
   2376 
   2377 /*
   2378  * called by editline -- any expansions to the prompt
   2379  *    should be added here.
   2380  */
   2381 const char *
   2382 getprompt(void *unused)
   2383 {
   2384 	char *p;
   2385 	const char *cp;
   2386 	int wp;
   2387 
   2388 	if (!doprompt)
   2389 		return "";
   2390 
   2391 	VTRACE(DBG_PARSE|DBG_EXPAND, ("getprompt %d\n", whichprompt));
   2392 
   2393 	switch (wp = whichprompt) {
   2394 	case 0:
   2395 		return "";
   2396 	case 1:
   2397 		p = ps1val();
   2398 		break;
   2399 	case 2:
   2400 		p = ps2val();
   2401 		break;
   2402 	default:
   2403 		return "<internal prompt error>";
   2404 	}
   2405 	if (p == NULL)
   2406 		return "";
   2407 
   2408 	VTRACE(DBG_PARSE|DBG_EXPAND, ("prompt <<%s>>\n", p));
   2409 
   2410 	cp = expandstr(p, plinno);
   2411 	whichprompt = wp;	/* history depends on it not changing */
   2412 
   2413 	VTRACE(DBG_PARSE|DBG_EXPAND, ("prompt -> <<%s>>\n", cp));
   2414 
   2415 	return cp;
   2416 }
   2417 
   2418 /*
   2419  * Expand a string ... used for expanding prompts (PS1...)
   2420  *
   2421  * Never return NULL, always some string (return input string if invalid)
   2422  *
   2423  * The internal routine does the work, leaving the result on the
   2424  * stack (or in a static string, or even the input string) and
   2425  * handles parser recursion, and cleanup after an error while parsing.
   2426  *
   2427  * The visible interface copies the result off the stack (if it is there),
   2428  * and handles stack management, leaving the stack in the exact same
   2429  * state it was when expandstr() was called (so it can be used part way
   2430  * through building a stack data structure - as in when PS2 is being
   2431  * expanded half way through reading a "command line")
   2432  *
   2433  * on error, expandonstack() cleans up the parser state, but then
   2434  * simply jumps out through expandstr() withut doing any stack cleanup,
   2435  * which is OK, as the error handler must deal with that anyway.
   2436  *
   2437  * The split into two funcs is to avoid problems with setjmp/longjmp
   2438  * and local variables which could otherwise be optimised into bizarre
   2439  * behaviour.
   2440  */
   2441 static const char *
   2442 expandonstack(char *ps, int lineno)
   2443 {
   2444 	union node n;
   2445 	struct jmploc jmploc;
   2446 	struct jmploc *const savehandler = handler;
   2447 	struct parsefile *const savetopfile = getcurrentfile();
   2448 	const int save_x = xflag;
   2449 	struct parse_state new_state = init_parse_state;
   2450 	struct parse_state *const saveparser = psp.v_current_parser;
   2451 	const char *result = NULL;
   2452 
   2453 	if (!setjmp(jmploc.loc)) {
   2454 		handler = &jmploc;
   2455 
   2456 		psp.v_current_parser = &new_state;
   2457 		setinputstring(ps, 1, lineno);
   2458 
   2459 		readtoken1(pgetc(), DQSYNTAX, 1);
   2460 		if (backquotelist != NULL && !promptcmds)
   2461 			result = "-o promptcmds not set: ";
   2462 		else {
   2463 			n.narg.type = NARG;
   2464 			n.narg.next = NULL;
   2465 			n.narg.text = wordtext;
   2466 			n.narg.lineno = lineno;
   2467 			n.narg.backquote = backquotelist;
   2468 
   2469 			xflag = 0;	/* we might be expanding PS4 ... */
   2470 			expandarg(&n, NULL, 0);
   2471 			result = stackblock();
   2472 		}
   2473 		INTOFF;
   2474 	}
   2475 	psp.v_current_parser = saveparser;
   2476 	xflag = save_x;
   2477 	popfilesupto(savetopfile);
   2478 	handler = savehandler;
   2479 
   2480 	if (exception == EXEXIT)
   2481 		longjmp(handler->loc, 1);
   2482 
   2483 	if (result != NULL) {
   2484 		INTON;
   2485 	} else {
   2486 		if (exception == EXINT)
   2487 			exraise(SIGINT);
   2488 		result = ps;
   2489 	}
   2490 
   2491 	return result;
   2492 }
   2493 
   2494 const char *
   2495 expandstr(char *ps, int lineno)
   2496 {
   2497 	const char *result = NULL;
   2498 	struct stackmark smark;
   2499 	static char *buffer = NULL;	/* storage for prompt, never freed */
   2500 	static size_t bufferlen = 0;
   2501 
   2502 	setstackmark(&smark);
   2503 	/*
   2504 	 * At this point we anticipate that there may be a string
   2505 	 * growing on the stack, but we have no idea how big it is.
   2506 	 * However we know that it cannot be bigger than the current
   2507 	 * allocated stack block, so simply reserve the whole thing,
   2508 	 * then we can use the stack without barfing all over what
   2509 	 * is there already...   (the stack mark undoes this later.)
   2510 	 */
   2511 	(void) stalloc(stackblocksize());
   2512 
   2513 	result = expandonstack(ps, lineno);
   2514 
   2515 	if (__predict_true(result == stackblock())) {
   2516 		size_t len = strlen(result) + 1;
   2517 
   2518 		/*
   2519 		 * the result (usual case) is on the stack, which we
   2520 		 * are just about to discard (popstackmark()) so we
   2521 		 * need to move it somewhere safe first.
   2522 		 */
   2523 
   2524 		if (__predict_false(len > bufferlen)) {
   2525 			char *new;
   2526 			size_t newlen = bufferlen;
   2527 
   2528 			if (__predict_false(len > (SIZE_MAX >> 4))) {
   2529 				result = "huge prompt: ";
   2530 				goto getout;
   2531 			}
   2532 
   2533 			if (newlen == 0)
   2534 				newlen = 32;
   2535 			while (newlen <= len)
   2536 				newlen <<= 1;
   2537 
   2538 			new = (char *)realloc(buffer, newlen);
   2539 
   2540 			if (__predict_false(new == NULL)) {
   2541 				/*
   2542 				 * this should rarely (if ever) happen
   2543 				 * but we must do something when it does...
   2544 				 */
   2545 				result = "No mem for prompt: ";
   2546 				goto getout;
   2547 			} else {
   2548 				buffer = new;
   2549 				bufferlen = newlen;
   2550 			}
   2551 		}
   2552 		(void)memcpy(buffer, result, len);
   2553 		result = buffer;
   2554 	}
   2555 
   2556   getout:;
   2557 	popstackmark(&smark);
   2558 
   2559 	return result;
   2560 }
   2561