Home | History | Annotate | Line # | Download | only in sh
parser.c revision 1.86
      1 /*	$NetBSD: parser.c,v 1.86 2013/12/31 22:53:57 christos 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.86 2013/12/31 22:53:57 christos 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 "redir.h"	/* defines copyfd() */
     54 #include "syntax.h"
     55 #include "options.h"
     56 #include "input.h"
     57 #include "output.h"
     58 #include "var.h"
     59 #include "error.h"
     60 #include "memalloc.h"
     61 #include "mystring.h"
     62 #include "alias.h"
     63 #include "show.h"
     64 #ifndef SMALL
     65 #include "myhistedit.h"
     66 #endif
     67 
     68 /*
     69  * Shell command parser.
     70  */
     71 
     72 #define EOFMARKLEN 79
     73 
     74 /* values returned by readtoken */
     75 #include "token.h"
     76 
     77 #define OPENBRACE '{'
     78 #define CLOSEBRACE '}'
     79 
     80 
     81 struct heredoc {
     82 	struct heredoc *next;	/* next here document in list */
     83 	union node *here;		/* redirection node */
     84 	char *eofmark;		/* string indicating end of input */
     85 	int striptabs;		/* if set, strip leading tabs */
     86 };
     87 
     88 
     89 
     90 static int noalias = 0;		/* when set, don't handle aliases */
     91 struct heredoc *heredoclist;	/* list of here documents to read */
     92 int parsebackquote;		/* nonzero if we are inside backquotes */
     93 int doprompt;			/* if set, prompt the user */
     94 int needprompt;			/* true if interactive and at start of line */
     95 int lasttoken;			/* last token read */
     96 MKINIT int tokpushback;		/* last token pushed back */
     97 char *wordtext;			/* text of last word returned by readtoken */
     98 MKINIT int checkkwd;		/* 1 == check for kwds, 2 == also eat newlines */
     99 struct nodelist *backquotelist;
    100 union node *redirnode;
    101 struct heredoc *heredoc;
    102 int quoteflag;			/* set if (part of) last token was quoted */
    103 int startlinno;			/* line # where last token started */
    104 int funclinno;			/* line # where the current function started */
    105 
    106 
    107 STATIC union node *list(int, int);
    108 STATIC union node *andor(void);
    109 STATIC union node *pipeline(void);
    110 STATIC union node *command(void);
    111 STATIC union node *simplecmd(union node **, union node *);
    112 STATIC union node *makename(void);
    113 STATIC void parsefname(void);
    114 STATIC void parseheredoc(void);
    115 STATIC int peektoken(void);
    116 STATIC int readtoken(void);
    117 STATIC int xxreadtoken(void);
    118 STATIC int readtoken1(int, char const *, char *, int);
    119 STATIC int noexpand(char *);
    120 STATIC void synexpect(int) __dead;
    121 STATIC void synerror(const char *) __dead;
    122 STATIC void setprompt(int);
    123 
    124 
    125 /*
    126  * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
    127  * valid parse tree indicating a blank line.)
    128  */
    129 
    130 union node *
    131 parsecmd(int interact)
    132 {
    133 	int t;
    134 
    135 	tokpushback = 0;
    136 	doprompt = interact;
    137 	if (doprompt)
    138 		setprompt(1);
    139 	else
    140 		setprompt(0);
    141 	needprompt = 0;
    142 	t = readtoken();
    143 	if (t == TEOF)
    144 		return NEOF;
    145 	if (t == TNL)
    146 		return NULL;
    147 	tokpushback++;
    148 	return list(1, 0);
    149 }
    150 
    151 
    152 STATIC union node *
    153 list(int nlflag, int erflag)
    154 {
    155 	union node *n1, *n2, *n3;
    156 	int tok;
    157 	TRACE(("list: entered\n"));
    158 
    159 	checkkwd = 2;
    160 	if (nlflag == 0 && tokendlist[peektoken()])
    161 		return NULL;
    162 	n1 = NULL;
    163 	for (;;) {
    164 		n2 = andor();
    165 		tok = readtoken();
    166 		if (tok == TBACKGND) {
    167 			if (n2->type == NCMD || n2->type == NPIPE) {
    168 				n2->ncmd.backgnd = 1;
    169 			} else if (n2->type == NREDIR) {
    170 				n2->type = NBACKGND;
    171 			} else {
    172 				n3 = (union node *)stalloc(sizeof (struct nredir));
    173 				n3->type = NBACKGND;
    174 				n3->nredir.n = n2;
    175 				n3->nredir.redirect = NULL;
    176 				n2 = n3;
    177 			}
    178 		}
    179 		if (n1 == NULL) {
    180 			n1 = n2;
    181 		}
    182 		else {
    183 			n3 = (union node *)stalloc(sizeof (struct nbinary));
    184 			n3->type = NSEMI;
    185 			n3->nbinary.ch1 = n1;
    186 			n3->nbinary.ch2 = n2;
    187 			n1 = n3;
    188 		}
    189 		switch (tok) {
    190 		case TBACKGND:
    191 		case TSEMI:
    192 			tok = readtoken();
    193 			/* fall through */
    194 		case TNL:
    195 			if (tok == TNL) {
    196 				parseheredoc();
    197 				if (nlflag)
    198 					return n1;
    199 			} else {
    200 				tokpushback++;
    201 			}
    202 			checkkwd = 2;
    203 			if (tokendlist[peektoken()])
    204 				return n1;
    205 			break;
    206 		case TEOF:
    207 			if (heredoclist)
    208 				parseheredoc();
    209 			else
    210 				pungetc();		/* push back EOF on input */
    211 			return n1;
    212 		default:
    213 			if (nlflag || erflag)
    214 				synexpect(-1);
    215 			tokpushback++;
    216 			return n1;
    217 		}
    218 	}
    219 }
    220 
    221 
    222 
    223 STATIC union node *
    224 andor(void)
    225 {
    226 	union node *n1, *n2, *n3;
    227 	int t;
    228 
    229 	TRACE(("andor: entered\n"));
    230 	n1 = pipeline();
    231 	for (;;) {
    232 		if ((t = readtoken()) == TAND) {
    233 			t = NAND;
    234 		} else if (t == TOR) {
    235 			t = NOR;
    236 		} else {
    237 			tokpushback++;
    238 			return n1;
    239 		}
    240 		n2 = pipeline();
    241 		n3 = (union node *)stalloc(sizeof (struct nbinary));
    242 		n3->type = t;
    243 		n3->nbinary.ch1 = n1;
    244 		n3->nbinary.ch2 = n2;
    245 		n1 = n3;
    246 	}
    247 }
    248 
    249 
    250 
    251 STATIC union node *
    252 pipeline(void)
    253 {
    254 	union node *n1, *n2, *pipenode;
    255 	struct nodelist *lp, *prev;
    256 	int negate;
    257 
    258 	TRACE(("pipeline: entered\n"));
    259 
    260 	negate = 0;
    261 	checkkwd = 2;
    262 	while (readtoken() == TNOT) {
    263 		TRACE(("pipeline: TNOT recognized\n"));
    264 		negate = !negate;
    265 	}
    266 	tokpushback++;
    267 	n1 = command();
    268 	if (readtoken() == TPIPE) {
    269 		pipenode = (union node *)stalloc(sizeof (struct npipe));
    270 		pipenode->type = NPIPE;
    271 		pipenode->npipe.backgnd = 0;
    272 		lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
    273 		pipenode->npipe.cmdlist = lp;
    274 		lp->n = n1;
    275 		do {
    276 			prev = lp;
    277 			lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
    278 			lp->n = command();
    279 			prev->next = lp;
    280 		} while (readtoken() == TPIPE);
    281 		lp->next = NULL;
    282 		n1 = pipenode;
    283 	}
    284 	tokpushback++;
    285 	if (negate) {
    286 		TRACE(("negate pipeline\n"));
    287 		n2 = (union node *)stalloc(sizeof (struct nnot));
    288 		n2->type = NNOT;
    289 		n2->nnot.com = n1;
    290 		return n2;
    291 	} else
    292 		return n1;
    293 }
    294 
    295 
    296 
    297 STATIC union node *
    298 command(void)
    299 {
    300 	union node *n1, *n2;
    301 	union node *ap, **app;
    302 	union node *cp, **cpp;
    303 	union node *redir, **rpp;
    304 	int t, negate = 0;
    305 
    306 	TRACE(("command: entered\n"));
    307 
    308 	checkkwd = 2;
    309 	redir = NULL;
    310 	n1 = NULL;
    311 	rpp = &redir;
    312 
    313 	/* Check for redirection which may precede command */
    314 	while (readtoken() == TREDIR) {
    315 		*rpp = n2 = redirnode;
    316 		rpp = &n2->nfile.next;
    317 		parsefname();
    318 	}
    319 	tokpushback++;
    320 
    321 	while (readtoken() == TNOT) {
    322 		TRACE(("command: TNOT recognized\n"));
    323 		negate = !negate;
    324 	}
    325 	tokpushback++;
    326 
    327 	switch (readtoken()) {
    328 	case TIF:
    329 		n1 = (union node *)stalloc(sizeof (struct nif));
    330 		n1->type = NIF;
    331 		n1->nif.test = list(0, 0);
    332 		if (readtoken() != TTHEN)
    333 			synexpect(TTHEN);
    334 		n1->nif.ifpart = list(0, 0);
    335 		n2 = n1;
    336 		while (readtoken() == TELIF) {
    337 			n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
    338 			n2 = n2->nif.elsepart;
    339 			n2->type = NIF;
    340 			n2->nif.test = list(0, 0);
    341 			if (readtoken() != TTHEN)
    342 				synexpect(TTHEN);
    343 			n2->nif.ifpart = list(0, 0);
    344 		}
    345 		if (lasttoken == TELSE)
    346 			n2->nif.elsepart = list(0, 0);
    347 		else {
    348 			n2->nif.elsepart = NULL;
    349 			tokpushback++;
    350 		}
    351 		if (readtoken() != TFI)
    352 			synexpect(TFI);
    353 		checkkwd = 1;
    354 		break;
    355 	case TWHILE:
    356 	case TUNTIL: {
    357 		int got;
    358 		n1 = (union node *)stalloc(sizeof (struct nbinary));
    359 		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
    360 		n1->nbinary.ch1 = list(0, 0);
    361 		if ((got=readtoken()) != TDO) {
    362 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
    363 			synexpect(TDO);
    364 		}
    365 		n1->nbinary.ch2 = list(0, 0);
    366 		if (readtoken() != TDONE)
    367 			synexpect(TDONE);
    368 		checkkwd = 1;
    369 		break;
    370 	}
    371 	case TFOR:
    372 		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
    373 			synerror("Bad for loop variable");
    374 		n1 = (union node *)stalloc(sizeof (struct nfor));
    375 		n1->type = NFOR;
    376 		n1->nfor.var = wordtext;
    377 		if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
    378 			app = &ap;
    379 			while (readtoken() == TWORD) {
    380 				n2 = (union node *)stalloc(sizeof (struct narg));
    381 				n2->type = NARG;
    382 				n2->narg.text = wordtext;
    383 				n2->narg.backquote = backquotelist;
    384 				*app = n2;
    385 				app = &n2->narg.next;
    386 			}
    387 			*app = NULL;
    388 			n1->nfor.args = ap;
    389 			if (lasttoken != TNL && lasttoken != TSEMI)
    390 				synexpect(-1);
    391 		} else {
    392 			static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
    393 								   '@', '=', '\0'};
    394 			n2 = (union node *)stalloc(sizeof (struct narg));
    395 			n2->type = NARG;
    396 			n2->narg.text = argvars;
    397 			n2->narg.backquote = NULL;
    398 			n2->narg.next = NULL;
    399 			n1->nfor.args = n2;
    400 			/*
    401 			 * Newline or semicolon here is optional (but note
    402 			 * that the original Bourne shell only allowed NL).
    403 			 */
    404 			if (lasttoken != TNL && lasttoken != TSEMI)
    405 				tokpushback++;
    406 		}
    407 		checkkwd = 2;
    408 		if ((t = readtoken()) == TDO)
    409 			t = TDONE;
    410 		else if (t == TBEGIN)
    411 			t = TEND;
    412 		else
    413 			synexpect(-1);
    414 		n1->nfor.body = list(0, 0);
    415 		if (readtoken() != t)
    416 			synexpect(t);
    417 		checkkwd = 1;
    418 		break;
    419 	case TCASE:
    420 		n1 = (union node *)stalloc(sizeof (struct ncase));
    421 		n1->type = NCASE;
    422 		if (readtoken() != TWORD)
    423 			synexpect(TWORD);
    424 		n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
    425 		n2->type = NARG;
    426 		n2->narg.text = wordtext;
    427 		n2->narg.backquote = backquotelist;
    428 		n2->narg.next = NULL;
    429 		while (readtoken() == TNL);
    430 		if (lasttoken != TWORD || ! equal(wordtext, "in"))
    431 			synerror("expecting \"in\"");
    432 		cpp = &n1->ncase.cases;
    433 		noalias = 1;
    434 		checkkwd = 2, readtoken();
    435 		while(lasttoken != TESAC) {
    436 			*cpp = cp = (union node *)stalloc(sizeof (struct nclist));
    437 			if (lasttoken == TLP)
    438 				readtoken();
    439 			cp->type = NCLIST;
    440 			app = &cp->nclist.pattern;
    441 			for (;;) {
    442 				*app = ap = (union node *)stalloc(sizeof (struct narg));
    443 				ap->type = NARG;
    444 				ap->narg.text = wordtext;
    445 				ap->narg.backquote = backquotelist;
    446 				if (checkkwd = 2, readtoken() != TPIPE)
    447 					break;
    448 				app = &ap->narg.next;
    449 				readtoken();
    450 			}
    451 			ap->narg.next = NULL;
    452 			noalias = 0;
    453 			if (lasttoken != TRP) {
    454 				synexpect(TRP);
    455 			}
    456 			cp->nclist.body = list(0, 0);
    457 
    458 			checkkwd = 2;
    459 			if ((t = readtoken()) != TESAC) {
    460 				if (t != TENDCASE) {
    461 					noalias = 0;
    462 					synexpect(TENDCASE);
    463 				} else {
    464 					noalias = 1;
    465 					checkkwd = 2;
    466 					readtoken();
    467 				}
    468 			}
    469 			cpp = &cp->nclist.next;
    470 		}
    471 		noalias = 0;
    472 		*cpp = NULL;
    473 		checkkwd = 1;
    474 		break;
    475 	case TLP:
    476 		n1 = (union node *)stalloc(sizeof (struct nredir));
    477 		n1->type = NSUBSHELL;
    478 		n1->nredir.n = list(0, 0);
    479 		n1->nredir.redirect = NULL;
    480 		if (readtoken() != TRP)
    481 			synexpect(TRP);
    482 		checkkwd = 1;
    483 		break;
    484 	case TBEGIN:
    485 		n1 = list(0, 0);
    486 		if (readtoken() != TEND)
    487 			synexpect(TEND);
    488 		checkkwd = 1;
    489 		break;
    490 	/* Handle an empty command like other simple commands.  */
    491 	case TSEMI:
    492 		/*
    493 		 * An empty command before a ; doesn't make much sense, and
    494 		 * should certainly be disallowed in the case of `if ;'.
    495 		 */
    496 		if (!redir)
    497 			synexpect(-1);
    498 	case TAND:
    499 	case TOR:
    500 	case TNL:
    501 	case TEOF:
    502 	case TWORD:
    503 	case TRP:
    504 		tokpushback++;
    505 		n1 = simplecmd(rpp, redir);
    506 		goto checkneg;
    507 	default:
    508 		synexpect(-1);
    509 		/* NOTREACHED */
    510 	}
    511 
    512 	/* Now check for redirection which may follow command */
    513 	while (readtoken() == TREDIR) {
    514 		*rpp = n2 = redirnode;
    515 		rpp = &n2->nfile.next;
    516 		parsefname();
    517 	}
    518 	tokpushback++;
    519 	*rpp = NULL;
    520 	if (redir) {
    521 		if (n1->type != NSUBSHELL) {
    522 			n2 = (union node *)stalloc(sizeof (struct nredir));
    523 			n2->type = NREDIR;
    524 			n2->nredir.n = n1;
    525 			n1 = n2;
    526 		}
    527 		n1->nredir.redirect = redir;
    528 	}
    529 
    530 checkneg:
    531 	if (negate) {
    532 		TRACE(("negate command\n"));
    533 		n2 = (union node *)stalloc(sizeof (struct nnot));
    534 		n2->type = NNOT;
    535 		n2->nnot.com = n1;
    536 		return n2;
    537 	}
    538 	else
    539 		return n1;
    540 }
    541 
    542 
    543 STATIC union node *
    544 simplecmd(union node **rpp, union node *redir)
    545 {
    546 	union node *args, **app;
    547 	union node **orig_rpp = rpp;
    548 	union node *n = NULL, *n2;
    549 	int negate = 0;
    550 
    551 	/* If we don't have any redirections already, then we must reset */
    552 	/* rpp to be the address of the local redir variable.  */
    553 	if (redir == 0)
    554 		rpp = &redir;
    555 
    556 	args = NULL;
    557 	app = &args;
    558 	/*
    559 	 * We save the incoming value, because we need this for shell
    560 	 * functions.  There can not be a redirect or an argument between
    561 	 * the function name and the open parenthesis.
    562 	 */
    563 	orig_rpp = rpp;
    564 
    565 	while (readtoken() == TNOT) {
    566 		TRACE(("simplcmd: TNOT recognized\n"));
    567 		negate = !negate;
    568 	}
    569 	tokpushback++;
    570 
    571 	for (;;) {
    572 		if (readtoken() == TWORD) {
    573 			n = (union node *)stalloc(sizeof (struct narg));
    574 			n->type = NARG;
    575 			n->narg.text = wordtext;
    576 			n->narg.backquote = backquotelist;
    577 			*app = n;
    578 			app = &n->narg.next;
    579 		} else if (lasttoken == TREDIR) {
    580 			*rpp = n = redirnode;
    581 			rpp = &n->nfile.next;
    582 			parsefname();	/* read name of redirection file */
    583 		} else if (lasttoken == TLP && app == &args->narg.next
    584 					    && rpp == orig_rpp) {
    585 			/* We have a function */
    586 			if (readtoken() != TRP)
    587 				synexpect(TRP);
    588 			funclinno = plinno;
    589 			rmescapes(n->narg.text);
    590 			if (!goodname(n->narg.text))
    591 				synerror("Bad function name");
    592 			n->type = NDEFUN;
    593 			n->narg.next = command();
    594 			funclinno = 0;
    595 			goto checkneg;
    596 		} else {
    597 			tokpushback++;
    598 			break;
    599 		}
    600 	}
    601 	*app = NULL;
    602 	*rpp = NULL;
    603 	n = (union node *)stalloc(sizeof (struct ncmd));
    604 	n->type = NCMD;
    605 	n->ncmd.backgnd = 0;
    606 	n->ncmd.args = args;
    607 	n->ncmd.redirect = redir;
    608 
    609 checkneg:
    610 	if (negate) {
    611 		TRACE(("negate simplecmd\n"));
    612 		n2 = (union node *)stalloc(sizeof (struct nnot));
    613 		n2->type = NNOT;
    614 		n2->nnot.com = n;
    615 		return n2;
    616 	}
    617 	else
    618 		return n;
    619 }
    620 
    621 STATIC union node *
    622 makename(void)
    623 {
    624 	union node *n;
    625 
    626 	n = (union node *)stalloc(sizeof (struct narg));
    627 	n->type = NARG;
    628 	n->narg.next = NULL;
    629 	n->narg.text = wordtext;
    630 	n->narg.backquote = backquotelist;
    631 	return n;
    632 }
    633 
    634 void fixredir(union node *n, const char *text, int err)
    635 	{
    636 	TRACE(("Fix redir %s %d\n", text, err));
    637 	if (!err)
    638 		n->ndup.vname = NULL;
    639 
    640 	if (is_digit(text[0]) && text[1] == '\0')
    641 		n->ndup.dupfd = digit_val(text[0]);
    642 	else if (text[0] == '-' && text[1] == '\0')
    643 		n->ndup.dupfd = -1;
    644 	else {
    645 
    646 		if (err)
    647 			synerror("Bad fd number");
    648 		else
    649 			n->ndup.vname = makename();
    650 	}
    651 }
    652 
    653 
    654 STATIC void
    655 parsefname(void)
    656 {
    657 	union node *n = redirnode;
    658 
    659 	if (readtoken() != TWORD)
    660 		synexpect(-1);
    661 	if (n->type == NHERE) {
    662 		struct heredoc *here = heredoc;
    663 		struct heredoc *p;
    664 		int i;
    665 
    666 		if (quoteflag == 0)
    667 			n->type = NXHERE;
    668 		TRACE(("Here document %d\n", n->type));
    669 		if (here->striptabs) {
    670 			while (*wordtext == '\t')
    671 				wordtext++;
    672 		}
    673 		if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
    674 			synerror("Illegal eof marker for << redirection");
    675 		rmescapes(wordtext);
    676 		here->eofmark = wordtext;
    677 		here->next = NULL;
    678 		if (heredoclist == NULL)
    679 			heredoclist = here;
    680 		else {
    681 			for (p = heredoclist ; p->next ; p = p->next);
    682 			p->next = here;
    683 		}
    684 	} else if (n->type == NTOFD || n->type == NFROMFD) {
    685 		fixredir(n, wordtext, 0);
    686 	} else {
    687 		n->nfile.fname = makename();
    688 	}
    689 }
    690 
    691 
    692 /*
    693  * Input any here documents.
    694  */
    695 
    696 STATIC void
    697 parseheredoc(void)
    698 {
    699 	struct heredoc *here;
    700 	union node *n;
    701 
    702 	while (heredoclist) {
    703 		here = heredoclist;
    704 		heredoclist = here->next;
    705 		if (needprompt) {
    706 			setprompt(2);
    707 			needprompt = 0;
    708 		}
    709 		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
    710 				here->eofmark, here->striptabs);
    711 		n = (union node *)stalloc(sizeof (struct narg));
    712 		n->narg.type = NARG;
    713 		n->narg.next = NULL;
    714 		n->narg.text = wordtext;
    715 		n->narg.backquote = backquotelist;
    716 		here->here->nhere.doc = n;
    717 	}
    718 }
    719 
    720 STATIC int
    721 peektoken(void)
    722 {
    723 	int t;
    724 
    725 	t = readtoken();
    726 	tokpushback++;
    727 	return (t);
    728 }
    729 
    730 STATIC int
    731 readtoken(void)
    732 {
    733 	int t;
    734 	int savecheckkwd = checkkwd;
    735 #ifdef DEBUG
    736 	int alreadyseen = tokpushback;
    737 #endif
    738 	struct alias *ap;
    739 
    740 	top:
    741 	t = xxreadtoken();
    742 
    743 	if (checkkwd) {
    744 		/*
    745 		 * eat newlines
    746 		 */
    747 		if (checkkwd == 2) {
    748 			checkkwd = 0;
    749 			while (t == TNL) {
    750 				parseheredoc();
    751 				t = xxreadtoken();
    752 			}
    753 		} else
    754 			checkkwd = 0;
    755 		/*
    756 		 * check for keywords and aliases
    757 		 */
    758 		if (t == TWORD && !quoteflag)
    759 		{
    760 			const char *const *pp;
    761 
    762 			for (pp = parsekwd; *pp; pp++) {
    763 				if (**pp == *wordtext && equal(*pp, wordtext))
    764 				{
    765 					lasttoken = t = pp -
    766 					    parsekwd + KWDOFFSET;
    767 					TRACE(("keyword %s recognized\n", tokname[t]));
    768 					goto out;
    769 				}
    770 			}
    771 			if(!noalias &&
    772 			    (ap = lookupalias(wordtext, 1)) != NULL) {
    773 				pushstring(ap->val, strlen(ap->val), ap);
    774 				checkkwd = savecheckkwd;
    775 				goto top;
    776 			}
    777 		}
    778 out:
    779 		checkkwd = (t == TNOT) ? savecheckkwd : 0;
    780 	}
    781 	TRACE(("%stoken %s %s\n", alreadyseen ? "reread " : "", tokname[t], t == TWORD ? wordtext : ""));
    782 	return (t);
    783 }
    784 
    785 
    786 /*
    787  * Read the next input token.
    788  * If the token is a word, we set backquotelist to the list of cmds in
    789  *	backquotes.  We set quoteflag to true if any part of the word was
    790  *	quoted.
    791  * If the token is TREDIR, then we set redirnode to a structure containing
    792  *	the redirection.
    793  * In all cases, the variable startlinno is set to the number of the line
    794  *	on which the token starts.
    795  *
    796  * [Change comment:  here documents and internal procedures]
    797  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
    798  *  word parsing code into a separate routine.  In this case, readtoken
    799  *  doesn't need to have any internal procedures, but parseword does.
    800  *  We could also make parseoperator in essence the main routine, and
    801  *  have parseword (readtoken1?) handle both words and redirection.]
    802  */
    803 
    804 #define RETURN(token)	return lasttoken = token
    805 
    806 STATIC int
    807 xxreadtoken(void)
    808 {
    809 	int c;
    810 
    811 	if (tokpushback) {
    812 		tokpushback = 0;
    813 		return lasttoken;
    814 	}
    815 	if (needprompt) {
    816 		setprompt(2);
    817 		needprompt = 0;
    818 	}
    819 	startlinno = plinno;
    820 	for (;;) {	/* until token or start of word found */
    821 		c = pgetc_macro();
    822 		switch (c) {
    823 		case ' ': case '\t':
    824 			continue;
    825 		case '#':
    826 			while ((c = pgetc()) != '\n' && c != PEOF);
    827 			pungetc();
    828 			continue;
    829 		case '\\':
    830 			if (pgetc() == '\n') {
    831 				startlinno = ++plinno;
    832 				if (doprompt)
    833 					setprompt(2);
    834 				else
    835 					setprompt(0);
    836 				continue;
    837 			}
    838 			pungetc();
    839 			goto breakloop;
    840 		case '\n':
    841 			plinno++;
    842 			needprompt = doprompt;
    843 			RETURN(TNL);
    844 		case PEOF:
    845 			RETURN(TEOF);
    846 		case '&':
    847 			if (pgetc() == '&')
    848 				RETURN(TAND);
    849 			pungetc();
    850 			RETURN(TBACKGND);
    851 		case '|':
    852 			if (pgetc() == '|')
    853 				RETURN(TOR);
    854 			pungetc();
    855 			RETURN(TPIPE);
    856 		case ';':
    857 			if (pgetc() == ';')
    858 				RETURN(TENDCASE);
    859 			pungetc();
    860 			RETURN(TSEMI);
    861 		case '(':
    862 			RETURN(TLP);
    863 		case ')':
    864 			RETURN(TRP);
    865 		default:
    866 			goto breakloop;
    867 		}
    868 	}
    869 breakloop:
    870 	return readtoken1(c, BASESYNTAX, NULL, 0);
    871 #undef RETURN
    872 }
    873 
    874 
    875 
    876 /*
    877  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
    878  * is not NULL, read a here document.  In the latter case, eofmark is the
    879  * word which marks the end of the document and striptabs is true if
    880  * leading tabs should be stripped from the document.  The argument firstc
    881  * is the first character of the input token or document.
    882  *
    883  * Because C does not have internal subroutines, I have simulated them
    884  * using goto's to implement the subroutine linkage.  The following macros
    885  * will run code that appears at the end of readtoken1.
    886  */
    887 
    888 #define CHECKEND()	{goto checkend; checkend_return:;}
    889 #define PARSEREDIR()	{goto parseredir; parseredir_return:;}
    890 #define PARSESUB()	{goto parsesub; parsesub_return:;}
    891 #define PARSEBACKQOLD()	{oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
    892 #define PARSEBACKQNEW()	{oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
    893 #define	PARSEARITH()	{goto parsearith; parsearith_return:;}
    894 
    895 /*
    896  * Keep track of nested doublequotes in dblquote and doublequotep.
    897  * We use dblquote for the first 32 levels, and we expand to a malloc'ed
    898  * region for levels above that. Usually we never need to malloc.
    899  * This code assumes that an int is 32 bits. We don't use uint32_t,
    900  * because the rest of the code does not.
    901  */
    902 #define ISDBLQUOTE() ((varnest < 32) ? (dblquote & (1 << varnest)) : \
    903     (dblquotep[(varnest / 32) - 1] & (1 << (varnest % 32))))
    904 
    905 #define SETDBLQUOTE() \
    906     if (varnest < 32) \
    907 	dblquote |= (1 << varnest); \
    908     else \
    909 	dblquotep[(varnest / 32) - 1] |= (1 << (varnest % 32))
    910 
    911 #define CLRDBLQUOTE() \
    912     if (varnest < 32) \
    913 	dblquote &= ~(1 << varnest); \
    914     else \
    915 	dblquotep[(varnest / 32) - 1] &= ~(1 << (varnest % 32))
    916 
    917 STATIC int
    918 readtoken1(int firstc, char const *syn, char *eofmark, int striptabs)
    919 {
    920 	char const * volatile syntax = syn;
    921 	int c = firstc;
    922 	char * volatile out;
    923 	int len;
    924 	char line[EOFMARKLEN + 1];
    925 	struct nodelist *bqlist;
    926 	volatile int quotef;
    927 	int * volatile dblquotep = NULL;
    928 	volatile size_t maxnest = 32;
    929 	volatile int dblquote;
    930 	volatile size_t varnest;	/* levels of variables expansion */
    931 	volatile int arinest;	/* levels of arithmetic expansion */
    932 	volatile int parenlevel;	/* levels of parens in arithmetic */
    933 	volatile int oldstyle;
    934 	char const * volatile prevsyntax;	/* syntax before arithmetic */
    935 #ifdef __GNUC__
    936 	prevsyntax = NULL;	/* XXX gcc4 */
    937 #endif
    938 
    939 	startlinno = plinno;
    940 	dblquote = 0;
    941 	varnest = 0;
    942 	if (syntax == DQSYNTAX) {
    943 		SETDBLQUOTE();
    944 	}
    945 	quotef = 0;
    946 	bqlist = NULL;
    947 	arinest = 0;
    948 	parenlevel = 0;
    949 
    950 	STARTSTACKSTR(out);
    951 	loop: {	/* for each line, until end of word */
    952 #if ATTY
    953 		if (c == '\034' && doprompt
    954 		 && attyset() && ! equal(termval(), "emacs")) {
    955 			attyline();
    956 			if (syntax == BASESYNTAX)
    957 				return readtoken();
    958 			c = pgetc();
    959 			goto loop;
    960 		}
    961 #endif
    962 		CHECKEND();	/* set c to PEOF if at end of here document */
    963 		for (;;) {	/* until end of line or end of word */
    964 			CHECKSTRSPACE(4, out);	/* permit 4 calls to USTPUTC */
    965 			switch(syntax[c]) {
    966 			case CNL:	/* '\n' */
    967 				if (syntax == BASESYNTAX)
    968 					goto endword;	/* exit outer loop */
    969 				USTPUTC(c, out);
    970 				plinno++;
    971 				if (doprompt)
    972 					setprompt(2);
    973 				else
    974 					setprompt(0);
    975 				c = pgetc();
    976 				goto loop;		/* continue outer loop */
    977 			case CWORD:
    978 				USTPUTC(c, out);
    979 				break;
    980 			case CCTL:
    981 				if (eofmark == NULL || ISDBLQUOTE())
    982 					USTPUTC(CTLESC, out);
    983 				USTPUTC(c, out);
    984 				break;
    985 			case CBACK:	/* backslash */
    986 				c = pgetc();
    987 				if (c == PEOF) {
    988 					USTPUTC('\\', out);
    989 					pungetc();
    990 					break;
    991 				}
    992 				if (c == '\n') {
    993 					if (doprompt)
    994 						setprompt(2);
    995 					else
    996 						setprompt(0);
    997 					break;
    998 				}
    999 				quotef = 1;
   1000 				if (ISDBLQUOTE() && c != '\\' &&
   1001 				    c != '`' && c != '$' &&
   1002 				    (c != '"' || eofmark != NULL))
   1003 					USTPUTC('\\', out);
   1004 				if (SQSYNTAX[c] == CCTL)
   1005 					USTPUTC(CTLESC, out);
   1006 				else if (eofmark == NULL) {
   1007 					USTPUTC(CTLQUOTEMARK, out);
   1008 					USTPUTC(c, out);
   1009 					if (varnest != 0)
   1010 						USTPUTC(CTLQUOTEEND, out);
   1011 					break;
   1012 				}
   1013 				USTPUTC(c, out);
   1014 				break;
   1015 			case CSQUOTE:
   1016 				if (syntax != SQSYNTAX) {
   1017 					if (eofmark == NULL)
   1018 						USTPUTC(CTLQUOTEMARK, out);
   1019 					quotef = 1;
   1020 					syntax = SQSYNTAX;
   1021 					break;
   1022 				}
   1023 				if (eofmark != NULL && arinest == 0 &&
   1024 				    varnest == 0) {
   1025 					/* Ignore inside quoted here document */
   1026 					USTPUTC(c, out);
   1027 					break;
   1028 				}
   1029 				/* End of single quotes... */
   1030 				if (arinest)
   1031 					syntax = ARISYNTAX;
   1032 				else {
   1033 					syntax = BASESYNTAX;
   1034 					if (varnest != 0)
   1035 						USTPUTC(CTLQUOTEEND, out);
   1036 				}
   1037 				break;
   1038 			case CDQUOTE:
   1039 				if (eofmark != NULL && arinest == 0 &&
   1040 				    varnest == 0) {
   1041 					/* Ignore inside here document */
   1042 					USTPUTC(c, out);
   1043 					break;
   1044 				}
   1045 				quotef = 1;
   1046 				if (arinest) {
   1047 					if (ISDBLQUOTE()) {
   1048 						syntax = ARISYNTAX;
   1049 						CLRDBLQUOTE();
   1050 					} else {
   1051 						syntax = DQSYNTAX;
   1052 						SETDBLQUOTE();
   1053 						USTPUTC(CTLQUOTEMARK, out);
   1054 					}
   1055 					break;
   1056 				}
   1057 				if (eofmark != NULL)
   1058 					break;
   1059 				if (ISDBLQUOTE()) {
   1060 					if (varnest != 0)
   1061 						USTPUTC(CTLQUOTEEND, out);
   1062 					syntax = BASESYNTAX;
   1063 					CLRDBLQUOTE();
   1064 				} else {
   1065 					syntax = DQSYNTAX;
   1066 					SETDBLQUOTE();
   1067 					USTPUTC(CTLQUOTEMARK, out);
   1068 				}
   1069 				break;
   1070 			case CVAR:	/* '$' */
   1071 				PARSESUB();		/* parse substitution */
   1072 				break;
   1073 			case CENDVAR:	/* CLOSEBRACE */
   1074 				if (varnest > 0 && !ISDBLQUOTE()) {
   1075 					varnest--;
   1076 					USTPUTC(CTLENDVAR, out);
   1077 				} else {
   1078 					USTPUTC(c, out);
   1079 				}
   1080 				break;
   1081 			case CLP:	/* '(' in arithmetic */
   1082 				parenlevel++;
   1083 				USTPUTC(c, out);
   1084 				break;
   1085 			case CRP:	/* ')' in arithmetic */
   1086 				if (parenlevel > 0) {
   1087 					USTPUTC(c, out);
   1088 					--parenlevel;
   1089 				} else {
   1090 					if (pgetc() == ')') {
   1091 						if (--arinest == 0) {
   1092 							USTPUTC(CTLENDARI, out);
   1093 							syntax = prevsyntax;
   1094 							if (syntax == DQSYNTAX)
   1095 								SETDBLQUOTE();
   1096 							else
   1097 								CLRDBLQUOTE();
   1098 						} else
   1099 							USTPUTC(')', out);
   1100 					} else {
   1101 						/*
   1102 						 * unbalanced parens
   1103 						 *  (don't 2nd guess - no error)
   1104 						 */
   1105 						pungetc();
   1106 						USTPUTC(')', out);
   1107 					}
   1108 				}
   1109 				break;
   1110 			case CBQUOTE:	/* '`' */
   1111 				PARSEBACKQOLD();
   1112 				break;
   1113 			case CEOF:
   1114 				goto endword;		/* exit outer loop */
   1115 			default:
   1116 				if (varnest == 0 && !ISDBLQUOTE())
   1117 					goto endword;	/* exit outer loop */
   1118 				USTPUTC(c, out);
   1119 			}
   1120 			c = pgetc_macro();
   1121 		}
   1122 	}
   1123 endword:
   1124 	if (syntax == ARISYNTAX)
   1125 		synerror("Missing '))'");
   1126 	if (syntax != BASESYNTAX && /* ! parsebackquote && */ eofmark == NULL)
   1127 		synerror("Unterminated quoted string");
   1128 	if (varnest != 0) {
   1129 		startlinno = plinno;
   1130 		/* { */
   1131 		synerror("Missing '}'");
   1132 	}
   1133 	USTPUTC('\0', out);
   1134 	len = out - stackblock();
   1135 	out = stackblock();
   1136 	if (eofmark == NULL) {
   1137 		if ((c == '>' || c == '<')
   1138 		 && quotef == 0
   1139 		 && len <= 2
   1140 		 && (*out == '\0' || is_digit(*out))) {
   1141 			PARSEREDIR();
   1142 			return lasttoken = TREDIR;
   1143 		} else {
   1144 			pungetc();
   1145 		}
   1146 	}
   1147 	quoteflag = quotef;
   1148 	backquotelist = bqlist;
   1149 	grabstackblock(len);
   1150 	wordtext = out;
   1151 	if (dblquotep != NULL)
   1152 	    ckfree(dblquotep);
   1153 	return lasttoken = TWORD;
   1154 /* end of readtoken routine */
   1155 
   1156 
   1157 
   1158 /*
   1159  * Check to see whether we are at the end of the here document.  When this
   1160  * is called, c is set to the first character of the next input line.  If
   1161  * we are at the end of the here document, this routine sets the c to PEOF.
   1162  */
   1163 
   1164 checkend: {
   1165 	if (eofmark) {
   1166 		if (striptabs) {
   1167 			while (c == '\t')
   1168 				c = pgetc();
   1169 		}
   1170 		if (c == *eofmark) {
   1171 			if (pfgets(line, sizeof line) != NULL) {
   1172 				char *p, *q;
   1173 
   1174 				p = line;
   1175 				for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
   1176 				if ((*p == '\0' || *p == '\n') && *q == '\0') {
   1177 					c = PEOF;
   1178 					plinno++;
   1179 					needprompt = doprompt;
   1180 				} else {
   1181 					pushstring(line, strlen(line), NULL);
   1182 				}
   1183 			}
   1184 		}
   1185 	}
   1186 	goto checkend_return;
   1187 }
   1188 
   1189 
   1190 /*
   1191  * Parse a redirection operator.  The variable "out" points to a string
   1192  * specifying the fd to be redirected.  The variable "c" contains the
   1193  * first character of the redirection operator.
   1194  */
   1195 
   1196 parseredir: {
   1197 	char fd = *out;
   1198 	union node *np;
   1199 
   1200 	np = (union node *)stalloc(sizeof (struct nfile));
   1201 	if (c == '>') {
   1202 		np->nfile.fd = 1;
   1203 		c = pgetc();
   1204 		if (c == '>')
   1205 			np->type = NAPPEND;
   1206 		else if (c == '|')
   1207 			np->type = NCLOBBER;
   1208 		else if (c == '&')
   1209 			np->type = NTOFD;
   1210 		else {
   1211 			np->type = NTO;
   1212 			pungetc();
   1213 		}
   1214 	} else {	/* c == '<' */
   1215 		np->nfile.fd = 0;
   1216 		switch (c = pgetc()) {
   1217 		case '<':
   1218 			if (sizeof (struct nfile) != sizeof (struct nhere)) {
   1219 				np = (union node *)stalloc(sizeof (struct nhere));
   1220 				np->nfile.fd = 0;
   1221 			}
   1222 			np->type = NHERE;
   1223 			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
   1224 			heredoc->here = np;
   1225 			if ((c = pgetc()) == '-') {
   1226 				heredoc->striptabs = 1;
   1227 			} else {
   1228 				heredoc->striptabs = 0;
   1229 				pungetc();
   1230 			}
   1231 			break;
   1232 
   1233 		case '&':
   1234 			np->type = NFROMFD;
   1235 			break;
   1236 
   1237 		case '>':
   1238 			np->type = NFROMTO;
   1239 			break;
   1240 
   1241 		default:
   1242 			np->type = NFROM;
   1243 			pungetc();
   1244 			break;
   1245 		}
   1246 	}
   1247 	if (fd != '\0')
   1248 		np->nfile.fd = digit_val(fd);
   1249 	redirnode = np;
   1250 	goto parseredir_return;
   1251 }
   1252 
   1253 
   1254 /*
   1255  * Parse a substitution.  At this point, we have read the dollar sign
   1256  * and nothing else.
   1257  */
   1258 
   1259 parsesub: {
   1260 	char buf[10];
   1261 	int subtype;
   1262 	int typeloc;
   1263 	int flags;
   1264 	char *p;
   1265 	static const char types[] = "}-+?=";
   1266 	int i;
   1267 	int linno;
   1268 
   1269 	c = pgetc();
   1270 	if (c != '(' && c != OPENBRACE && !is_name(c) && !is_special(c)) {
   1271 		USTPUTC('$', out);
   1272 		pungetc();
   1273 	} else if (c == '(') {	/* $(command) or $((arith)) */
   1274 		if (pgetc() == '(') {
   1275 			PARSEARITH();
   1276 		} else {
   1277 			pungetc();
   1278 			PARSEBACKQNEW();
   1279 		}
   1280 	} else {
   1281 		USTPUTC(CTLVAR, out);
   1282 		typeloc = out - stackblock();
   1283 		USTPUTC(VSNORMAL, out);
   1284 		subtype = VSNORMAL;
   1285 		flags = 0;
   1286 		if (c == OPENBRACE) {
   1287 			c = pgetc();
   1288 			if (c == '#') {
   1289 				if ((c = pgetc()) == CLOSEBRACE)
   1290 					c = '#';
   1291 				else
   1292 					subtype = VSLENGTH;
   1293 			}
   1294 			else
   1295 				subtype = 0;
   1296 		}
   1297 		if (is_name(c)) {
   1298 			p = out;
   1299 			do {
   1300 				STPUTC(c, out);
   1301 				c = pgetc();
   1302 			} while (is_in_name(c));
   1303 			if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
   1304 				/* Replace the variable name with the
   1305 				 * current line number. */
   1306 				linno = plinno;
   1307 				if (funclinno != 0)
   1308 					linno -= funclinno - 1;
   1309 				snprintf(buf, sizeof(buf), "%d", linno);
   1310 				STADJUST(-6, out);
   1311 				for (i = 0; buf[i] != '\0'; i++)
   1312 					STPUTC(buf[i], out);
   1313 				flags |= VSLINENO;
   1314 			}
   1315 		} else if (is_digit(c)) {
   1316 			do {
   1317 				USTPUTC(c, out);
   1318 				c = pgetc();
   1319 			} while (is_digit(c));
   1320 		}
   1321 		else if (is_special(c)) {
   1322 			USTPUTC(c, out);
   1323 			c = pgetc();
   1324 		}
   1325 		else
   1326 badsub:			synerror("Bad substitution");
   1327 
   1328 		STPUTC('=', out);
   1329 		if (subtype == 0) {
   1330 			switch (c) {
   1331 			case ':':
   1332 				flags |= VSNUL;
   1333 				c = pgetc();
   1334 				/*FALLTHROUGH*/
   1335 			default:
   1336 				p = strchr(types, c);
   1337 				if (p == NULL)
   1338 					goto badsub;
   1339 				subtype = p - types + VSNORMAL;
   1340 				break;
   1341 			case '%':
   1342 			case '#':
   1343 				{
   1344 					int cc = c;
   1345 					subtype = c == '#' ? VSTRIMLEFT :
   1346 							     VSTRIMRIGHT;
   1347 					c = pgetc();
   1348 					if (c == cc)
   1349 						subtype++;
   1350 					else
   1351 						pungetc();
   1352 					break;
   1353 				}
   1354 			}
   1355 		} else {
   1356 			pungetc();
   1357 		}
   1358 		if (ISDBLQUOTE() || arinest)
   1359 			flags |= VSQUOTE;
   1360 		*(stackblock() + typeloc) = subtype | flags;
   1361 		if (subtype != VSNORMAL) {
   1362 			varnest++;
   1363 			if (varnest >= maxnest) {
   1364 				dblquotep = ckrealloc(dblquotep, maxnest / 8);
   1365 				dblquotep[(maxnest / 32) - 1] = 0;
   1366 				maxnest += 32;
   1367 			}
   1368 		}
   1369 	}
   1370 	goto parsesub_return;
   1371 }
   1372 
   1373 
   1374 /*
   1375  * Called to parse command substitutions.  Newstyle is set if the command
   1376  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
   1377  * list of commands (passed by reference), and savelen is the number of
   1378  * characters on the top of the stack which must be preserved.
   1379  */
   1380 
   1381 parsebackq: {
   1382 	struct nodelist **nlpp;
   1383 	int savepbq;
   1384 	union node *n;
   1385 	char *volatile str = NULL;
   1386 	struct jmploc jmploc;
   1387 	struct jmploc *volatile savehandler = NULL;
   1388 	int savelen;
   1389 	int saveprompt;
   1390 
   1391 	savepbq = parsebackquote;
   1392 	if (setjmp(jmploc.loc)) {
   1393 		if (str)
   1394 			ckfree(str);
   1395 		parsebackquote = 0;
   1396 		handler = savehandler;
   1397 		longjmp(handler->loc, 1);
   1398 	}
   1399 	INTOFF;
   1400 	str = NULL;
   1401 	savelen = out - stackblock();
   1402 	if (savelen > 0) {
   1403 		str = ckmalloc(savelen);
   1404 		memcpy(str, stackblock(), savelen);
   1405 	}
   1406 	savehandler = handler;
   1407 	handler = &jmploc;
   1408 	INTON;
   1409         if (oldstyle) {
   1410                 /* We must read until the closing backquote, giving special
   1411                    treatment to some slashes, and then push the string and
   1412                    reread it as input, interpreting it normally.  */
   1413                 char *pout;
   1414                 int pc;
   1415                 int psavelen;
   1416                 char *pstr;
   1417 
   1418 
   1419                 STARTSTACKSTR(pout);
   1420 		for (;;) {
   1421 			if (needprompt) {
   1422 				setprompt(2);
   1423 				needprompt = 0;
   1424 			}
   1425 			switch (pc = pgetc()) {
   1426 			case '`':
   1427 				goto done;
   1428 
   1429 			case '\\':
   1430                                 if ((pc = pgetc()) == '\n') {
   1431 					plinno++;
   1432 					if (doprompt)
   1433 						setprompt(2);
   1434 					else
   1435 						setprompt(0);
   1436 					/*
   1437 					 * If eating a newline, avoid putting
   1438 					 * the newline into the new character
   1439 					 * stream (via the STPUTC after the
   1440 					 * switch).
   1441 					 */
   1442 					continue;
   1443 				}
   1444                                 if (pc != '\\' && pc != '`' && pc != '$'
   1445                                     && (!ISDBLQUOTE() || pc != '"'))
   1446                                         STPUTC('\\', pout);
   1447 				break;
   1448 
   1449 			case '\n':
   1450 				plinno++;
   1451 				needprompt = doprompt;
   1452 				break;
   1453 
   1454 			case PEOF:
   1455 			        startlinno = plinno;
   1456 				synerror("EOF in backquote substitution");
   1457  				break;
   1458 
   1459 			default:
   1460 				break;
   1461 			}
   1462 			STPUTC(pc, pout);
   1463                 }
   1464 done:
   1465                 STPUTC('\0', pout);
   1466                 psavelen = pout - stackblock();
   1467                 if (psavelen > 0) {
   1468 			pstr = grabstackstr(pout);
   1469 			setinputstring(pstr, 1);
   1470                 }
   1471         }
   1472 	nlpp = &bqlist;
   1473 	while (*nlpp)
   1474 		nlpp = &(*nlpp)->next;
   1475 	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
   1476 	(*nlpp)->next = NULL;
   1477 	parsebackquote = oldstyle;
   1478 
   1479 	if (oldstyle) {
   1480 		saveprompt = doprompt;
   1481 		doprompt = 0;
   1482 	} else
   1483 		saveprompt = 0;
   1484 
   1485 	n = list(0, oldstyle);
   1486 
   1487 	if (oldstyle)
   1488 		doprompt = saveprompt;
   1489 	else {
   1490 		if (readtoken() != TRP)
   1491 			synexpect(TRP);
   1492 	}
   1493 
   1494 	(*nlpp)->n = n;
   1495         if (oldstyle) {
   1496 		/*
   1497 		 * Start reading from old file again, ignoring any pushed back
   1498 		 * tokens left from the backquote parsing
   1499 		 */
   1500                 popfile();
   1501 		tokpushback = 0;
   1502 	}
   1503 	while (stackblocksize() <= savelen)
   1504 		growstackblock();
   1505 	STARTSTACKSTR(out);
   1506 	if (str) {
   1507 		memcpy(out, str, savelen);
   1508 		STADJUST(savelen, out);
   1509 		INTOFF;
   1510 		ckfree(str);
   1511 		str = NULL;
   1512 		INTON;
   1513 	}
   1514 	parsebackquote = savepbq;
   1515 	handler = savehandler;
   1516 	if (arinest || ISDBLQUOTE())
   1517 		USTPUTC(CTLBACKQ | CTLQUOTE, out);
   1518 	else
   1519 		USTPUTC(CTLBACKQ, out);
   1520 	if (oldstyle)
   1521 		goto parsebackq_oldreturn;
   1522 	else
   1523 		goto parsebackq_newreturn;
   1524 }
   1525 
   1526 /*
   1527  * Parse an arithmetic expansion (indicate start of one and set state)
   1528  */
   1529 parsearith: {
   1530 
   1531 	if (++arinest == 1) {
   1532 		prevsyntax = syntax;
   1533 		syntax = ARISYNTAX;
   1534 		USTPUTC(CTLARI, out);
   1535 		if (ISDBLQUOTE())
   1536 			USTPUTC('"',out);
   1537 		else
   1538 			USTPUTC(' ',out);
   1539 	} else {
   1540 		/*
   1541 		 * we collapse embedded arithmetic expansion to
   1542 		 * parenthesis, which should be equivalent
   1543 		 */
   1544 		USTPUTC('(', out);
   1545 	}
   1546 	goto parsearith_return;
   1547 }
   1548 
   1549 } /* end of readtoken */
   1550 
   1551 
   1552 
   1553 #ifdef mkinit
   1554 RESET {
   1555 	tokpushback = 0;
   1556 	checkkwd = 0;
   1557 }
   1558 #endif
   1559 
   1560 /*
   1561  * Returns true if the text contains nothing to expand (no dollar signs
   1562  * or backquotes).
   1563  */
   1564 
   1565 STATIC int
   1566 noexpand(char *text)
   1567 {
   1568 	char *p;
   1569 	char c;
   1570 
   1571 	p = text;
   1572 	while ((c = *p++) != '\0') {
   1573 		if (c == CTLQUOTEMARK)
   1574 			continue;
   1575 		if (c == CTLESC)
   1576 			p++;
   1577 		else if (BASESYNTAX[(int)c] == CCTL)
   1578 			return 0;
   1579 	}
   1580 	return 1;
   1581 }
   1582 
   1583 
   1584 /*
   1585  * Return true if the argument is a legal variable name (a letter or
   1586  * underscore followed by zero or more letters, underscores, and digits).
   1587  */
   1588 
   1589 int
   1590 goodname(char *name)
   1591 	{
   1592 	char *p;
   1593 
   1594 	p = name;
   1595 	if (! is_name(*p))
   1596 		return 0;
   1597 	while (*++p) {
   1598 		if (! is_in_name(*p))
   1599 			return 0;
   1600 	}
   1601 	return 1;
   1602 }
   1603 
   1604 
   1605 /*
   1606  * Called when an unexpected token is read during the parse.  The argument
   1607  * is the token that is expected, or -1 if more than one type of token can
   1608  * occur at this point.
   1609  */
   1610 
   1611 STATIC void
   1612 synexpect(int token)
   1613 {
   1614 	char msg[64];
   1615 
   1616 	if (token >= 0) {
   1617 		fmtstr(msg, 64, "%s unexpected (expecting %s)",
   1618 			tokname[lasttoken], tokname[token]);
   1619 	} else {
   1620 		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
   1621 	}
   1622 	synerror(msg);
   1623 	/* NOTREACHED */
   1624 }
   1625 
   1626 
   1627 STATIC void
   1628 synerror(const char *msg)
   1629 {
   1630 	if (commandname)
   1631 		outfmt(&errout, "%s: %d: ", commandname, startlinno);
   1632 	else
   1633 		outfmt(&errout, "%s: ", getprogname());
   1634 	outfmt(&errout, "Syntax error: %s\n", msg);
   1635 	error(NULL);
   1636 	/* NOTREACHED */
   1637 }
   1638 
   1639 STATIC void
   1640 setprompt(int which)
   1641 {
   1642 	whichprompt = which;
   1643 
   1644 #ifndef SMALL
   1645 	if (!el)
   1646 #endif
   1647 		out2str(getprompt(NULL));
   1648 }
   1649 
   1650 /*
   1651  * called by editline -- any expansions to the prompt
   1652  *    should be added here.
   1653  */
   1654 const char *
   1655 getprompt(void *unused)
   1656 	{
   1657 	switch (whichprompt) {
   1658 	case 0:
   1659 		return "";
   1660 	case 1:
   1661 		return ps1val();
   1662 	case 2:
   1663 		return ps2val();
   1664 	default:
   1665 		return "<internal prompt error>";
   1666 	}
   1667 }
   1668