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