Home | History | Annotate | Line # | Download | only in sh
parser.c revision 1.88
      1 /*	$NetBSD: parser.c,v 1.88 2014/01/01 18:29:39 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.88 2014/01/01 18:29:39 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 		/*
    436 		 * Both ksh and bash accept 'case x in esac'
    437 		 * so configure scripts started taking advantage of this.
    438 		 * The page: http://pubs.opengroup.org/onlinepubs/\
    439 		 * 009695399/utilities/xcu_chap02.html contradicts itself,
    440 		 * as to if this is legal; the "Case Conditional Format"
    441 		 * paragraph shows one case is required, but the "Grammar"
    442 		 * section shows a grammar that explicitly allows the no
    443 		 * case option.
    444 		 */
    445 		while (lasttoken != TESAC) {
    446 			*cpp = cp = (union node *)stalloc(sizeof (struct nclist));
    447 			if (lasttoken == TLP)
    448 				readtoken();
    449 			cp->type = NCLIST;
    450 			app = &cp->nclist.pattern;
    451 			for (;;) {
    452 				*app = ap = (union node *)stalloc(sizeof (struct narg));
    453 				ap->type = NARG;
    454 				ap->narg.text = wordtext;
    455 				ap->narg.backquote = backquotelist;
    456 				if (checkkwd = 2, readtoken() != TPIPE)
    457 					break;
    458 				app = &ap->narg.next;
    459 				readtoken();
    460 			}
    461 			ap->narg.next = NULL;
    462 			noalias = 0;
    463 			if (lasttoken != TRP) {
    464 				synexpect(TRP);
    465 			}
    466 			cp->nclist.body = list(0, 0);
    467 
    468 			checkkwd = 2;
    469 			if ((t = readtoken()) != TESAC) {
    470 				if (t != TENDCASE) {
    471 					noalias = 0;
    472 					synexpect(TENDCASE);
    473 				} else {
    474 					noalias = 1;
    475 					checkkwd = 2;
    476 					readtoken();
    477 				}
    478 			}
    479 			cpp = &cp->nclist.next;
    480 		}
    481 		noalias = 0;
    482 		*cpp = NULL;
    483 		checkkwd = 1;
    484 		break;
    485 	case TLP:
    486 		n1 = (union node *)stalloc(sizeof (struct nredir));
    487 		n1->type = NSUBSHELL;
    488 		n1->nredir.n = list(0, 0);
    489 		n1->nredir.redirect = NULL;
    490 		if (readtoken() != TRP)
    491 			synexpect(TRP);
    492 		checkkwd = 1;
    493 		break;
    494 	case TBEGIN:
    495 		n1 = list(0, 0);
    496 		if (readtoken() != TEND)
    497 			synexpect(TEND);
    498 		checkkwd = 1;
    499 		break;
    500 	/* Handle an empty command like other simple commands.  */
    501 	case TSEMI:
    502 		/*
    503 		 * An empty command before a ; doesn't make much sense, and
    504 		 * should certainly be disallowed in the case of `if ;'.
    505 		 */
    506 		if (!redir)
    507 			synexpect(-1);
    508 	case TAND:
    509 	case TOR:
    510 	case TNL:
    511 	case TEOF:
    512 	case TWORD:
    513 	case TRP:
    514 		tokpushback++;
    515 		n1 = simplecmd(rpp, redir);
    516 		goto checkneg;
    517 	default:
    518 		synexpect(-1);
    519 		/* NOTREACHED */
    520 	}
    521 
    522 	/* Now check for redirection which may follow command */
    523 	while (readtoken() == TREDIR) {
    524 		*rpp = n2 = redirnode;
    525 		rpp = &n2->nfile.next;
    526 		parsefname();
    527 	}
    528 	tokpushback++;
    529 	*rpp = NULL;
    530 	if (redir) {
    531 		if (n1->type != NSUBSHELL) {
    532 			n2 = (union node *)stalloc(sizeof (struct nredir));
    533 			n2->type = NREDIR;
    534 			n2->nredir.n = n1;
    535 			n1 = n2;
    536 		}
    537 		n1->nredir.redirect = redir;
    538 	}
    539 
    540 checkneg:
    541 	if (negate) {
    542 		TRACE(("negate command\n"));
    543 		n2 = (union node *)stalloc(sizeof (struct nnot));
    544 		n2->type = NNOT;
    545 		n2->nnot.com = n1;
    546 		return n2;
    547 	}
    548 	else
    549 		return n1;
    550 }
    551 
    552 
    553 STATIC union node *
    554 simplecmd(union node **rpp, union node *redir)
    555 {
    556 	union node *args, **app;
    557 	union node **orig_rpp = rpp;
    558 	union node *n = NULL, *n2;
    559 	int negate = 0;
    560 
    561 	/* If we don't have any redirections already, then we must reset */
    562 	/* rpp to be the address of the local redir variable.  */
    563 	if (redir == 0)
    564 		rpp = &redir;
    565 
    566 	args = NULL;
    567 	app = &args;
    568 	/*
    569 	 * We save the incoming value, because we need this for shell
    570 	 * functions.  There can not be a redirect or an argument between
    571 	 * the function name and the open parenthesis.
    572 	 */
    573 	orig_rpp = rpp;
    574 
    575 	while (readtoken() == TNOT) {
    576 		TRACE(("simplcmd: TNOT recognized\n"));
    577 		negate = !negate;
    578 	}
    579 	tokpushback++;
    580 
    581 	for (;;) {
    582 		if (readtoken() == TWORD) {
    583 			n = (union node *)stalloc(sizeof (struct narg));
    584 			n->type = NARG;
    585 			n->narg.text = wordtext;
    586 			n->narg.backquote = backquotelist;
    587 			*app = n;
    588 			app = &n->narg.next;
    589 		} else if (lasttoken == TREDIR) {
    590 			*rpp = n = redirnode;
    591 			rpp = &n->nfile.next;
    592 			parsefname();	/* read name of redirection file */
    593 		} else if (lasttoken == TLP && app == &args->narg.next
    594 					    && rpp == orig_rpp) {
    595 			/* We have a function */
    596 			if (readtoken() != TRP)
    597 				synexpect(TRP);
    598 			funclinno = plinno;
    599 			rmescapes(n->narg.text);
    600 			if (!goodname(n->narg.text))
    601 				synerror("Bad function name");
    602 			n->type = NDEFUN;
    603 			n->narg.next = command();
    604 			funclinno = 0;
    605 			goto checkneg;
    606 		} else {
    607 			tokpushback++;
    608 			break;
    609 		}
    610 	}
    611 	*app = NULL;
    612 	*rpp = NULL;
    613 	n = (union node *)stalloc(sizeof (struct ncmd));
    614 	n->type = NCMD;
    615 	n->ncmd.backgnd = 0;
    616 	n->ncmd.args = args;
    617 	n->ncmd.redirect = redir;
    618 
    619 checkneg:
    620 	if (negate) {
    621 		TRACE(("negate simplecmd\n"));
    622 		n2 = (union node *)stalloc(sizeof (struct nnot));
    623 		n2->type = NNOT;
    624 		n2->nnot.com = n;
    625 		return n2;
    626 	}
    627 	else
    628 		return n;
    629 }
    630 
    631 STATIC union node *
    632 makename(void)
    633 {
    634 	union node *n;
    635 
    636 	n = (union node *)stalloc(sizeof (struct narg));
    637 	n->type = NARG;
    638 	n->narg.next = NULL;
    639 	n->narg.text = wordtext;
    640 	n->narg.backquote = backquotelist;
    641 	return n;
    642 }
    643 
    644 void fixredir(union node *n, const char *text, int err)
    645 	{
    646 	TRACE(("Fix redir %s %d\n", text, err));
    647 	if (!err)
    648 		n->ndup.vname = NULL;
    649 
    650 	if (is_digit(text[0]) && text[1] == '\0')
    651 		n->ndup.dupfd = digit_val(text[0]);
    652 	else if (text[0] == '-' && text[1] == '\0')
    653 		n->ndup.dupfd = -1;
    654 	else {
    655 
    656 		if (err)
    657 			synerror("Bad fd number");
    658 		else
    659 			n->ndup.vname = makename();
    660 	}
    661 }
    662 
    663 
    664 STATIC void
    665 parsefname(void)
    666 {
    667 	union node *n = redirnode;
    668 
    669 	if (readtoken() != TWORD)
    670 		synexpect(-1);
    671 	if (n->type == NHERE) {
    672 		struct heredoc *here = heredoc;
    673 		struct heredoc *p;
    674 		int i;
    675 
    676 		if (quoteflag == 0)
    677 			n->type = NXHERE;
    678 		TRACE(("Here document %d\n", n->type));
    679 		if (here->striptabs) {
    680 			while (*wordtext == '\t')
    681 				wordtext++;
    682 		}
    683 		if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
    684 			synerror("Illegal eof marker for << redirection");
    685 		rmescapes(wordtext);
    686 		here->eofmark = wordtext;
    687 		here->next = NULL;
    688 		if (heredoclist == NULL)
    689 			heredoclist = here;
    690 		else {
    691 			for (p = heredoclist ; p->next ; p = p->next);
    692 			p->next = here;
    693 		}
    694 	} else if (n->type == NTOFD || n->type == NFROMFD) {
    695 		fixredir(n, wordtext, 0);
    696 	} else {
    697 		n->nfile.fname = makename();
    698 	}
    699 }
    700 
    701 
    702 /*
    703  * Input any here documents.
    704  */
    705 
    706 STATIC void
    707 parseheredoc(void)
    708 {
    709 	struct heredoc *here;
    710 	union node *n;
    711 
    712 	while (heredoclist) {
    713 		here = heredoclist;
    714 		heredoclist = here->next;
    715 		if (needprompt) {
    716 			setprompt(2);
    717 			needprompt = 0;
    718 		}
    719 		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
    720 				here->eofmark, here->striptabs);
    721 		n = (union node *)stalloc(sizeof (struct narg));
    722 		n->narg.type = NARG;
    723 		n->narg.next = NULL;
    724 		n->narg.text = wordtext;
    725 		n->narg.backquote = backquotelist;
    726 		here->here->nhere.doc = n;
    727 	}
    728 }
    729 
    730 STATIC int
    731 peektoken(void)
    732 {
    733 	int t;
    734 
    735 	t = readtoken();
    736 	tokpushback++;
    737 	return (t);
    738 }
    739 
    740 STATIC int
    741 readtoken(void)
    742 {
    743 	int t;
    744 	int savecheckkwd = checkkwd;
    745 #ifdef DEBUG
    746 	int alreadyseen = tokpushback;
    747 #endif
    748 	struct alias *ap;
    749 
    750 	top:
    751 	t = xxreadtoken();
    752 
    753 	if (checkkwd) {
    754 		/*
    755 		 * eat newlines
    756 		 */
    757 		if (checkkwd == 2) {
    758 			checkkwd = 0;
    759 			while (t == TNL) {
    760 				parseheredoc();
    761 				t = xxreadtoken();
    762 			}
    763 		} else
    764 			checkkwd = 0;
    765 		/*
    766 		 * check for keywords and aliases
    767 		 */
    768 		if (t == TWORD && !quoteflag)
    769 		{
    770 			const char *const *pp;
    771 
    772 			for (pp = parsekwd; *pp; pp++) {
    773 				if (**pp == *wordtext && equal(*pp, wordtext))
    774 				{
    775 					lasttoken = t = pp -
    776 					    parsekwd + KWDOFFSET;
    777 					TRACE(("keyword %s recognized\n", tokname[t]));
    778 					goto out;
    779 				}
    780 			}
    781 			if(!noalias &&
    782 			    (ap = lookupalias(wordtext, 1)) != NULL) {
    783 				pushstring(ap->val, strlen(ap->val), ap);
    784 				checkkwd = savecheckkwd;
    785 				goto top;
    786 			}
    787 		}
    788 out:
    789 		checkkwd = (t == TNOT) ? savecheckkwd : 0;
    790 	}
    791 	TRACE(("%stoken %s %s\n", alreadyseen ? "reread " : "", tokname[t], t == TWORD ? wordtext : ""));
    792 	return (t);
    793 }
    794 
    795 
    796 /*
    797  * Read the next input token.
    798  * If the token is a word, we set backquotelist to the list of cmds in
    799  *	backquotes.  We set quoteflag to true if any part of the word was
    800  *	quoted.
    801  * If the token is TREDIR, then we set redirnode to a structure containing
    802  *	the redirection.
    803  * In all cases, the variable startlinno is set to the number of the line
    804  *	on which the token starts.
    805  *
    806  * [Change comment:  here documents and internal procedures]
    807  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
    808  *  word parsing code into a separate routine.  In this case, readtoken
    809  *  doesn't need to have any internal procedures, but parseword does.
    810  *  We could also make parseoperator in essence the main routine, and
    811  *  have parseword (readtoken1?) handle both words and redirection.]
    812  */
    813 
    814 #define RETURN(token)	return lasttoken = token
    815 
    816 STATIC int
    817 xxreadtoken(void)
    818 {
    819 	int c;
    820 
    821 	if (tokpushback) {
    822 		tokpushback = 0;
    823 		return lasttoken;
    824 	}
    825 	if (needprompt) {
    826 		setprompt(2);
    827 		needprompt = 0;
    828 	}
    829 	startlinno = plinno;
    830 	for (;;) {	/* until token or start of word found */
    831 		c = pgetc_macro();
    832 		switch (c) {
    833 		case ' ': case '\t':
    834 			continue;
    835 		case '#':
    836 			while ((c = pgetc()) != '\n' && c != PEOF);
    837 			pungetc();
    838 			continue;
    839 		case '\\':
    840 			if (pgetc() == '\n') {
    841 				startlinno = ++plinno;
    842 				if (doprompt)
    843 					setprompt(2);
    844 				else
    845 					setprompt(0);
    846 				continue;
    847 			}
    848 			pungetc();
    849 			goto breakloop;
    850 		case '\n':
    851 			plinno++;
    852 			needprompt = doprompt;
    853 			RETURN(TNL);
    854 		case PEOF:
    855 			RETURN(TEOF);
    856 		case '&':
    857 			if (pgetc() == '&')
    858 				RETURN(TAND);
    859 			pungetc();
    860 			RETURN(TBACKGND);
    861 		case '|':
    862 			if (pgetc() == '|')
    863 				RETURN(TOR);
    864 			pungetc();
    865 			RETURN(TPIPE);
    866 		case ';':
    867 			if (pgetc() == ';')
    868 				RETURN(TENDCASE);
    869 			pungetc();
    870 			RETURN(TSEMI);
    871 		case '(':
    872 			RETURN(TLP);
    873 		case ')':
    874 			RETURN(TRP);
    875 		default:
    876 			goto breakloop;
    877 		}
    878 	}
    879 breakloop:
    880 	return readtoken1(c, BASESYNTAX, NULL, 0);
    881 #undef RETURN
    882 }
    883 
    884 
    885 
    886 /*
    887  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
    888  * is not NULL, read a here document.  In the latter case, eofmark is the
    889  * word which marks the end of the document and striptabs is true if
    890  * leading tabs should be stripped from the document.  The argument firstc
    891  * is the first character of the input token or document.
    892  *
    893  * Because C does not have internal subroutines, I have simulated them
    894  * using goto's to implement the subroutine linkage.  The following macros
    895  * will run code that appears at the end of readtoken1.
    896  */
    897 
    898 #define CHECKEND()	{goto checkend; checkend_return:;}
    899 #define PARSEREDIR()	{goto parseredir; parseredir_return:;}
    900 #define PARSESUB()	{goto parsesub; parsesub_return:;}
    901 #define PARSEBACKQOLD()	{oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
    902 #define PARSEBACKQNEW()	{oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
    903 #define	PARSEARITH()	{goto parsearith; parsearith_return:;}
    904 
    905 /*
    906  * Keep track of nested doublequotes in dblquote and doublequotep.
    907  * We use dblquote for the first 32 levels, and we expand to a malloc'ed
    908  * region for levels above that. Usually we never need to malloc.
    909  * This code assumes that an int is 32 bits. We don't use uint32_t,
    910  * because the rest of the code does not.
    911  */
    912 #define ISDBLQUOTE() ((varnest < 32) ? (dblquote & (1 << varnest)) : \
    913     (dblquotep[(varnest / 32) - 1] & (1 << (varnest % 32))))
    914 
    915 #define SETDBLQUOTE() \
    916     if (varnest < 32) \
    917 	dblquote |= (1 << varnest); \
    918     else \
    919 	dblquotep[(varnest / 32) - 1] |= (1 << (varnest % 32))
    920 
    921 #define CLRDBLQUOTE() \
    922     if (varnest < 32) \
    923 	dblquote &= ~(1 << varnest); \
    924     else \
    925 	dblquotep[(varnest / 32) - 1] &= ~(1 << (varnest % 32))
    926 
    927 STATIC int
    928 readtoken1(int firstc, char const *syn, char *eofmark, int striptabs)
    929 {
    930 	char const * volatile syntax = syn;
    931 	int c = firstc;
    932 	char * volatile out;
    933 	int len;
    934 	char line[EOFMARKLEN + 1];
    935 	struct nodelist *bqlist;
    936 	volatile int quotef;
    937 	int * volatile dblquotep = NULL;
    938 	volatile size_t maxnest = 32;
    939 	volatile int dblquote;
    940 	volatile size_t varnest;	/* levels of variables expansion */
    941 	volatile int arinest;	/* levels of arithmetic expansion */
    942 	volatile int parenlevel;	/* levels of parens in arithmetic */
    943 	volatile int oldstyle;
    944 	char const * volatile prevsyntax;	/* syntax before arithmetic */
    945 #ifdef __GNUC__
    946 	prevsyntax = NULL;	/* XXX gcc4 */
    947 #endif
    948 
    949 	startlinno = plinno;
    950 	dblquote = 0;
    951 	varnest = 0;
    952 	if (syntax == DQSYNTAX) {
    953 		SETDBLQUOTE();
    954 	}
    955 	quotef = 0;
    956 	bqlist = NULL;
    957 	arinest = 0;
    958 	parenlevel = 0;
    959 
    960 	STARTSTACKSTR(out);
    961 	loop: {	/* for each line, until end of word */
    962 #if ATTY
    963 		if (c == '\034' && doprompt
    964 		 && attyset() && ! equal(termval(), "emacs")) {
    965 			attyline();
    966 			if (syntax == BASESYNTAX)
    967 				return readtoken();
    968 			c = pgetc();
    969 			goto loop;
    970 		}
    971 #endif
    972 		CHECKEND();	/* set c to PEOF if at end of here document */
    973 		for (;;) {	/* until end of line or end of word */
    974 			CHECKSTRSPACE(4, out);	/* permit 4 calls to USTPUTC */
    975 			switch(syntax[c]) {
    976 			case CNL:	/* '\n' */
    977 				if (syntax == BASESYNTAX)
    978 					goto endword;	/* exit outer loop */
    979 				USTPUTC(c, out);
    980 				plinno++;
    981 				if (doprompt)
    982 					setprompt(2);
    983 				else
    984 					setprompt(0);
    985 				c = pgetc();
    986 				goto loop;		/* continue outer loop */
    987 			case CWORD:
    988 				USTPUTC(c, out);
    989 				break;
    990 			case CCTL:
    991 				if (eofmark == NULL || ISDBLQUOTE())
    992 					USTPUTC(CTLESC, out);
    993 				USTPUTC(c, out);
    994 				break;
    995 			case CBACK:	/* backslash */
    996 				c = pgetc();
    997 				if (c == PEOF) {
    998 					USTPUTC('\\', out);
    999 					pungetc();
   1000 					break;
   1001 				}
   1002 				if (c == '\n') {
   1003 					if (doprompt)
   1004 						setprompt(2);
   1005 					else
   1006 						setprompt(0);
   1007 					break;
   1008 				}
   1009 				quotef = 1;
   1010 				if (ISDBLQUOTE() && c != '\\' &&
   1011 				    c != '`' && c != '$' &&
   1012 				    (c != '"' || eofmark != NULL))
   1013 					USTPUTC('\\', out);
   1014 				if (SQSYNTAX[c] == CCTL)
   1015 					USTPUTC(CTLESC, out);
   1016 				else if (eofmark == NULL) {
   1017 					USTPUTC(CTLQUOTEMARK, out);
   1018 					USTPUTC(c, out);
   1019 					if (varnest != 0)
   1020 						USTPUTC(CTLQUOTEEND, out);
   1021 					break;
   1022 				}
   1023 				USTPUTC(c, out);
   1024 				break;
   1025 			case CSQUOTE:
   1026 				if (syntax != SQSYNTAX) {
   1027 					if (eofmark == NULL)
   1028 						USTPUTC(CTLQUOTEMARK, out);
   1029 					quotef = 1;
   1030 					syntax = SQSYNTAX;
   1031 					break;
   1032 				}
   1033 				if (eofmark != NULL && arinest == 0 &&
   1034 				    varnest == 0) {
   1035 					/* Ignore inside quoted here document */
   1036 					USTPUTC(c, out);
   1037 					break;
   1038 				}
   1039 				/* End of single quotes... */
   1040 				if (arinest)
   1041 					syntax = ARISYNTAX;
   1042 				else {
   1043 					syntax = BASESYNTAX;
   1044 					if (varnest != 0)
   1045 						USTPUTC(CTLQUOTEEND, out);
   1046 				}
   1047 				break;
   1048 			case CDQUOTE:
   1049 				if (eofmark != NULL && arinest == 0 &&
   1050 				    varnest == 0) {
   1051 					/* Ignore inside here document */
   1052 					USTPUTC(c, out);
   1053 					break;
   1054 				}
   1055 				quotef = 1;
   1056 				if (arinest) {
   1057 					if (ISDBLQUOTE()) {
   1058 						syntax = ARISYNTAX;
   1059 						CLRDBLQUOTE();
   1060 					} else {
   1061 						syntax = DQSYNTAX;
   1062 						SETDBLQUOTE();
   1063 						USTPUTC(CTLQUOTEMARK, out);
   1064 					}
   1065 					break;
   1066 				}
   1067 				if (eofmark != NULL)
   1068 					break;
   1069 				if (ISDBLQUOTE()) {
   1070 					if (varnest != 0)
   1071 						USTPUTC(CTLQUOTEEND, out);
   1072 					syntax = BASESYNTAX;
   1073 					CLRDBLQUOTE();
   1074 				} else {
   1075 					syntax = DQSYNTAX;
   1076 					SETDBLQUOTE();
   1077 					USTPUTC(CTLQUOTEMARK, out);
   1078 				}
   1079 				break;
   1080 			case CVAR:	/* '$' */
   1081 				PARSESUB();		/* parse substitution */
   1082 				break;
   1083 			case CENDVAR:	/* CLOSEBRACE */
   1084 				if (varnest > 0 && !ISDBLQUOTE()) {
   1085 					varnest--;
   1086 					USTPUTC(CTLENDVAR, out);
   1087 				} else {
   1088 					USTPUTC(c, out);
   1089 				}
   1090 				break;
   1091 			case CLP:	/* '(' in arithmetic */
   1092 				parenlevel++;
   1093 				USTPUTC(c, out);
   1094 				break;
   1095 			case CRP:	/* ')' in arithmetic */
   1096 				if (parenlevel > 0) {
   1097 					USTPUTC(c, out);
   1098 					--parenlevel;
   1099 				} else {
   1100 					if (pgetc() == ')') {
   1101 						if (--arinest == 0) {
   1102 							USTPUTC(CTLENDARI, out);
   1103 							syntax = prevsyntax;
   1104 							if (syntax == DQSYNTAX)
   1105 								SETDBLQUOTE();
   1106 							else
   1107 								CLRDBLQUOTE();
   1108 						} else
   1109 							USTPUTC(')', out);
   1110 					} else {
   1111 						/*
   1112 						 * unbalanced parens
   1113 						 *  (don't 2nd guess - no error)
   1114 						 */
   1115 						pungetc();
   1116 						USTPUTC(')', out);
   1117 					}
   1118 				}
   1119 				break;
   1120 			case CBQUOTE:	/* '`' */
   1121 				PARSEBACKQOLD();
   1122 				break;
   1123 			case CEOF:
   1124 				goto endword;		/* exit outer loop */
   1125 			default:
   1126 				if (varnest == 0 && !ISDBLQUOTE())
   1127 					goto endword;	/* exit outer loop */
   1128 				USTPUTC(c, out);
   1129 			}
   1130 			c = pgetc_macro();
   1131 		}
   1132 	}
   1133 endword:
   1134 	if (syntax == ARISYNTAX)
   1135 		synerror("Missing '))'");
   1136 	if (syntax != BASESYNTAX && /* ! parsebackquote && */ eofmark == NULL)
   1137 		synerror("Unterminated quoted string");
   1138 	if (varnest != 0) {
   1139 		startlinno = plinno;
   1140 		/* { */
   1141 		synerror("Missing '}'");
   1142 	}
   1143 	USTPUTC('\0', out);
   1144 	len = out - stackblock();
   1145 	out = stackblock();
   1146 	if (eofmark == NULL) {
   1147 		if ((c == '>' || c == '<')
   1148 		 && quotef == 0
   1149 		 && len <= 2
   1150 		 && (*out == '\0' || is_digit(*out))) {
   1151 			PARSEREDIR();
   1152 			return lasttoken = TREDIR;
   1153 		} else {
   1154 			pungetc();
   1155 		}
   1156 	}
   1157 	quoteflag = quotef;
   1158 	backquotelist = bqlist;
   1159 	grabstackblock(len);
   1160 	wordtext = out;
   1161 	if (dblquotep != NULL)
   1162 	    ckfree(dblquotep);
   1163 	return lasttoken = TWORD;
   1164 /* end of readtoken routine */
   1165 
   1166 
   1167 
   1168 /*
   1169  * Check to see whether we are at the end of the here document.  When this
   1170  * is called, c is set to the first character of the next input line.  If
   1171  * we are at the end of the here document, this routine sets the c to PEOF.
   1172  */
   1173 
   1174 checkend: {
   1175 	if (eofmark) {
   1176 		if (striptabs) {
   1177 			while (c == '\t')
   1178 				c = pgetc();
   1179 		}
   1180 		if (c == *eofmark) {
   1181 			if (pfgets(line, sizeof line) != NULL) {
   1182 				char *p, *q;
   1183 
   1184 				p = line;
   1185 				for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
   1186 				if ((*p == '\0' || *p == '\n') && *q == '\0') {
   1187 					c = PEOF;
   1188 					plinno++;
   1189 					needprompt = doprompt;
   1190 				} else {
   1191 					pushstring(line, strlen(line), NULL);
   1192 				}
   1193 			}
   1194 		}
   1195 	}
   1196 	goto checkend_return;
   1197 }
   1198 
   1199 
   1200 /*
   1201  * Parse a redirection operator.  The variable "out" points to a string
   1202  * specifying the fd to be redirected.  The variable "c" contains the
   1203  * first character of the redirection operator.
   1204  */
   1205 
   1206 parseredir: {
   1207 	char fd = *out;
   1208 	union node *np;
   1209 
   1210 	np = (union node *)stalloc(sizeof (struct nfile));
   1211 	if (c == '>') {
   1212 		np->nfile.fd = 1;
   1213 		c = pgetc();
   1214 		if (c == '>')
   1215 			np->type = NAPPEND;
   1216 		else if (c == '|')
   1217 			np->type = NCLOBBER;
   1218 		else if (c == '&')
   1219 			np->type = NTOFD;
   1220 		else {
   1221 			np->type = NTO;
   1222 			pungetc();
   1223 		}
   1224 	} else {	/* c == '<' */
   1225 		np->nfile.fd = 0;
   1226 		switch (c = pgetc()) {
   1227 		case '<':
   1228 			if (sizeof (struct nfile) != sizeof (struct nhere)) {
   1229 				np = (union node *)stalloc(sizeof (struct nhere));
   1230 				np->nfile.fd = 0;
   1231 			}
   1232 			np->type = NHERE;
   1233 			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
   1234 			heredoc->here = np;
   1235 			if ((c = pgetc()) == '-') {
   1236 				heredoc->striptabs = 1;
   1237 			} else {
   1238 				heredoc->striptabs = 0;
   1239 				pungetc();
   1240 			}
   1241 			break;
   1242 
   1243 		case '&':
   1244 			np->type = NFROMFD;
   1245 			break;
   1246 
   1247 		case '>':
   1248 			np->type = NFROMTO;
   1249 			break;
   1250 
   1251 		default:
   1252 			np->type = NFROM;
   1253 			pungetc();
   1254 			break;
   1255 		}
   1256 	}
   1257 	if (fd != '\0')
   1258 		np->nfile.fd = digit_val(fd);
   1259 	redirnode = np;
   1260 	goto parseredir_return;
   1261 }
   1262 
   1263 
   1264 /*
   1265  * Parse a substitution.  At this point, we have read the dollar sign
   1266  * and nothing else.
   1267  */
   1268 
   1269 parsesub: {
   1270 	char buf[10];
   1271 	int subtype;
   1272 	int typeloc;
   1273 	int flags;
   1274 	char *p;
   1275 	static const char types[] = "}-+?=";
   1276 	int i;
   1277 	int linno;
   1278 
   1279 	c = pgetc();
   1280 	if (c != '(' && c != OPENBRACE && !is_name(c) && !is_special(c)) {
   1281 		USTPUTC('$', out);
   1282 		pungetc();
   1283 	} else if (c == '(') {	/* $(command) or $((arith)) */
   1284 		if (pgetc() == '(') {
   1285 			PARSEARITH();
   1286 		} else {
   1287 			pungetc();
   1288 			PARSEBACKQNEW();
   1289 		}
   1290 	} else {
   1291 		USTPUTC(CTLVAR, out);
   1292 		typeloc = out - stackblock();
   1293 		USTPUTC(VSNORMAL, out);
   1294 		subtype = VSNORMAL;
   1295 		flags = 0;
   1296 		if (c == OPENBRACE) {
   1297 			c = pgetc();
   1298 			if (c == '#') {
   1299 				if ((c = pgetc()) == CLOSEBRACE)
   1300 					c = '#';
   1301 				else
   1302 					subtype = VSLENGTH;
   1303 			}
   1304 			else
   1305 				subtype = 0;
   1306 		}
   1307 		if (is_name(c)) {
   1308 			p = out;
   1309 			do {
   1310 				STPUTC(c, out);
   1311 				c = pgetc();
   1312 			} while (is_in_name(c));
   1313 			if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
   1314 				/* Replace the variable name with the
   1315 				 * current line number. */
   1316 				linno = plinno;
   1317 				if (funclinno != 0)
   1318 					linno -= funclinno - 1;
   1319 				snprintf(buf, sizeof(buf), "%d", linno);
   1320 				STADJUST(-6, out);
   1321 				for (i = 0; buf[i] != '\0'; i++)
   1322 					STPUTC(buf[i], out);
   1323 				flags |= VSLINENO;
   1324 			}
   1325 		} else if (is_digit(c)) {
   1326 			do {
   1327 				USTPUTC(c, out);
   1328 				c = pgetc();
   1329 			} while (is_digit(c));
   1330 		}
   1331 		else if (is_special(c)) {
   1332 			USTPUTC(c, out);
   1333 			c = pgetc();
   1334 		}
   1335 		else
   1336 badsub:			synerror("Bad substitution");
   1337 
   1338 		STPUTC('=', out);
   1339 		if (subtype == 0) {
   1340 			switch (c) {
   1341 			case ':':
   1342 				flags |= VSNUL;
   1343 				c = pgetc();
   1344 				/*FALLTHROUGH*/
   1345 			default:
   1346 				p = strchr(types, c);
   1347 				if (p == NULL)
   1348 					goto badsub;
   1349 				subtype = p - types + VSNORMAL;
   1350 				break;
   1351 			case '%':
   1352 			case '#':
   1353 				{
   1354 					int cc = c;
   1355 					subtype = c == '#' ? VSTRIMLEFT :
   1356 							     VSTRIMRIGHT;
   1357 					c = pgetc();
   1358 					if (c == cc)
   1359 						subtype++;
   1360 					else
   1361 						pungetc();
   1362 					break;
   1363 				}
   1364 			}
   1365 		} else {
   1366 			pungetc();
   1367 		}
   1368 		if (ISDBLQUOTE() || arinest)
   1369 			flags |= VSQUOTE;
   1370 		*(stackblock() + typeloc) = subtype | flags;
   1371 		if (subtype != VSNORMAL) {
   1372 			varnest++;
   1373 			if (varnest >= maxnest) {
   1374 				dblquotep = ckrealloc(dblquotep, maxnest / 8);
   1375 				dblquotep[(maxnest / 32) - 1] = 0;
   1376 				maxnest += 32;
   1377 			}
   1378 		}
   1379 	}
   1380 	goto parsesub_return;
   1381 }
   1382 
   1383 
   1384 /*
   1385  * Called to parse command substitutions.  Newstyle is set if the command
   1386  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
   1387  * list of commands (passed by reference), and savelen is the number of
   1388  * characters on the top of the stack which must be preserved.
   1389  */
   1390 
   1391 parsebackq: {
   1392 	struct nodelist **nlpp;
   1393 	int savepbq;
   1394 	union node *n;
   1395 	char *volatile str = NULL;
   1396 	struct jmploc jmploc;
   1397 	struct jmploc *volatile savehandler = NULL;
   1398 	int savelen;
   1399 	int saveprompt;
   1400 
   1401 	savepbq = parsebackquote;
   1402 	if (setjmp(jmploc.loc)) {
   1403 		if (str)
   1404 			ckfree(str);
   1405 		parsebackquote = 0;
   1406 		handler = savehandler;
   1407 		longjmp(handler->loc, 1);
   1408 	}
   1409 	INTOFF;
   1410 	str = NULL;
   1411 	savelen = out - stackblock();
   1412 	if (savelen > 0) {
   1413 		str = ckmalloc(savelen);
   1414 		memcpy(str, stackblock(), savelen);
   1415 	}
   1416 	savehandler = handler;
   1417 	handler = &jmploc;
   1418 	INTON;
   1419         if (oldstyle) {
   1420                 /* We must read until the closing backquote, giving special
   1421                    treatment to some slashes, and then push the string and
   1422                    reread it as input, interpreting it normally.  */
   1423                 char *pout;
   1424                 int pc;
   1425                 int psavelen;
   1426                 char *pstr;
   1427 
   1428 
   1429                 STARTSTACKSTR(pout);
   1430 		for (;;) {
   1431 			if (needprompt) {
   1432 				setprompt(2);
   1433 				needprompt = 0;
   1434 			}
   1435 			switch (pc = pgetc()) {
   1436 			case '`':
   1437 				goto done;
   1438 
   1439 			case '\\':
   1440                                 if ((pc = pgetc()) == '\n') {
   1441 					plinno++;
   1442 					if (doprompt)
   1443 						setprompt(2);
   1444 					else
   1445 						setprompt(0);
   1446 					/*
   1447 					 * If eating a newline, avoid putting
   1448 					 * the newline into the new character
   1449 					 * stream (via the STPUTC after the
   1450 					 * switch).
   1451 					 */
   1452 					continue;
   1453 				}
   1454                                 if (pc != '\\' && pc != '`' && pc != '$'
   1455                                     && (!ISDBLQUOTE() || pc != '"'))
   1456                                         STPUTC('\\', pout);
   1457 				break;
   1458 
   1459 			case '\n':
   1460 				plinno++;
   1461 				needprompt = doprompt;
   1462 				break;
   1463 
   1464 			case PEOF:
   1465 			        startlinno = plinno;
   1466 				synerror("EOF in backquote substitution");
   1467  				break;
   1468 
   1469 			default:
   1470 				break;
   1471 			}
   1472 			STPUTC(pc, pout);
   1473                 }
   1474 done:
   1475                 STPUTC('\0', pout);
   1476                 psavelen = pout - stackblock();
   1477                 if (psavelen > 0) {
   1478 			pstr = grabstackstr(pout);
   1479 			setinputstring(pstr, 1);
   1480                 }
   1481         }
   1482 	nlpp = &bqlist;
   1483 	while (*nlpp)
   1484 		nlpp = &(*nlpp)->next;
   1485 	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
   1486 	(*nlpp)->next = NULL;
   1487 	parsebackquote = oldstyle;
   1488 
   1489 	if (oldstyle) {
   1490 		saveprompt = doprompt;
   1491 		doprompt = 0;
   1492 	} else
   1493 		saveprompt = 0;
   1494 
   1495 	n = list(0, oldstyle);
   1496 
   1497 	if (oldstyle)
   1498 		doprompt = saveprompt;
   1499 	else {
   1500 		if (readtoken() != TRP)
   1501 			synexpect(TRP);
   1502 	}
   1503 
   1504 	(*nlpp)->n = n;
   1505         if (oldstyle) {
   1506 		/*
   1507 		 * Start reading from old file again, ignoring any pushed back
   1508 		 * tokens left from the backquote parsing
   1509 		 */
   1510                 popfile();
   1511 		tokpushback = 0;
   1512 	}
   1513 	while (stackblocksize() <= savelen)
   1514 		growstackblock();
   1515 	STARTSTACKSTR(out);
   1516 	if (str) {
   1517 		memcpy(out, str, savelen);
   1518 		STADJUST(savelen, out);
   1519 		INTOFF;
   1520 		ckfree(str);
   1521 		str = NULL;
   1522 		INTON;
   1523 	}
   1524 	parsebackquote = savepbq;
   1525 	handler = savehandler;
   1526 	if (arinest || ISDBLQUOTE())
   1527 		USTPUTC(CTLBACKQ | CTLQUOTE, out);
   1528 	else
   1529 		USTPUTC(CTLBACKQ, out);
   1530 	if (oldstyle)
   1531 		goto parsebackq_oldreturn;
   1532 	else
   1533 		goto parsebackq_newreturn;
   1534 }
   1535 
   1536 /*
   1537  * Parse an arithmetic expansion (indicate start of one and set state)
   1538  */
   1539 parsearith: {
   1540 
   1541 	if (++arinest == 1) {
   1542 		prevsyntax = syntax;
   1543 		syntax = ARISYNTAX;
   1544 		USTPUTC(CTLARI, out);
   1545 		if (ISDBLQUOTE())
   1546 			USTPUTC('"',out);
   1547 		else
   1548 			USTPUTC(' ',out);
   1549 	} else {
   1550 		/*
   1551 		 * we collapse embedded arithmetic expansion to
   1552 		 * parenthesis, which should be equivalent
   1553 		 */
   1554 		USTPUTC('(', out);
   1555 	}
   1556 	goto parsearith_return;
   1557 }
   1558 
   1559 } /* end of readtoken */
   1560 
   1561 
   1562 
   1563 #ifdef mkinit
   1564 RESET {
   1565 	tokpushback = 0;
   1566 	checkkwd = 0;
   1567 }
   1568 #endif
   1569 
   1570 /*
   1571  * Returns true if the text contains nothing to expand (no dollar signs
   1572  * or backquotes).
   1573  */
   1574 
   1575 STATIC int
   1576 noexpand(char *text)
   1577 {
   1578 	char *p;
   1579 	char c;
   1580 
   1581 	p = text;
   1582 	while ((c = *p++) != '\0') {
   1583 		if (c == CTLQUOTEMARK)
   1584 			continue;
   1585 		if (c == CTLESC)
   1586 			p++;
   1587 		else if (BASESYNTAX[(int)c] == CCTL)
   1588 			return 0;
   1589 	}
   1590 	return 1;
   1591 }
   1592 
   1593 
   1594 /*
   1595  * Return true if the argument is a legal variable name (a letter or
   1596  * underscore followed by zero or more letters, underscores, and digits).
   1597  */
   1598 
   1599 int
   1600 goodname(char *name)
   1601 	{
   1602 	char *p;
   1603 
   1604 	p = name;
   1605 	if (! is_name(*p))
   1606 		return 0;
   1607 	while (*++p) {
   1608 		if (! is_in_name(*p))
   1609 			return 0;
   1610 	}
   1611 	return 1;
   1612 }
   1613 
   1614 
   1615 /*
   1616  * Called when an unexpected token is read during the parse.  The argument
   1617  * is the token that is expected, or -1 if more than one type of token can
   1618  * occur at this point.
   1619  */
   1620 
   1621 STATIC void
   1622 synexpect(int token)
   1623 {
   1624 	char msg[64];
   1625 
   1626 	if (token >= 0) {
   1627 		fmtstr(msg, 64, "%s unexpected (expecting %s)",
   1628 			tokname[lasttoken], tokname[token]);
   1629 	} else {
   1630 		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
   1631 	}
   1632 	synerror(msg);
   1633 	/* NOTREACHED */
   1634 }
   1635 
   1636 
   1637 STATIC void
   1638 synerror(const char *msg)
   1639 {
   1640 	if (commandname)
   1641 		outfmt(&errout, "%s: %d: ", commandname, startlinno);
   1642 	else
   1643 		outfmt(&errout, "%s: ", getprogname());
   1644 	outfmt(&errout, "Syntax error: %s\n", msg);
   1645 	error(NULL);
   1646 	/* NOTREACHED */
   1647 }
   1648 
   1649 STATIC void
   1650 setprompt(int which)
   1651 {
   1652 	whichprompt = which;
   1653 
   1654 #ifndef SMALL
   1655 	if (!el)
   1656 #endif
   1657 		out2str(getprompt(NULL));
   1658 }
   1659 
   1660 /*
   1661  * called by editline -- any expansions to the prompt
   1662  *    should be added here.
   1663  */
   1664 const char *
   1665 getprompt(void *unused)
   1666 	{
   1667 	switch (whichprompt) {
   1668 	case 0:
   1669 		return "";
   1670 	case 1:
   1671 		return ps1val();
   1672 	case 2:
   1673 		return ps2val();
   1674 	default:
   1675 		return "<internal prompt error>";
   1676 	}
   1677 }
   1678