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