Home | History | Annotate | Line # | Download | only in sh
parser.c revision 1.17
      1 /*-
      2  * Copyright (c) 1991, 1993
      3  *	The Regents of the University of California.  All rights reserved.
      4  *
      5  * This code is derived from software contributed to Berkeley by
      6  * Kenneth Almquist.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. All advertising materials mentioning features or use of this software
     17  *    must display the following acknowledgement:
     18  *	This product includes software developed by the University of
     19  *	California, Berkeley and its contributors.
     20  * 4. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  */
     36 
     37 #ifndef lint
     38 /*static char sccsid[] = "from: @(#)parser.c	8.1 (Berkeley) 5/31/93";*/
     39 static char *rcsid = "$Id: parser.c,v 1.17 1994/06/11 16:12:28 mycroft Exp $";
     40 #endif /* not lint */
     41 
     42 #include "shell.h"
     43 #include "parser.h"
     44 #include "nodes.h"
     45 #include "expand.h"	/* defines rmescapes() */
     46 #include "redir.h"	/* defines copyfd() */
     47 #include "syntax.h"
     48 #include "options.h"
     49 #include "input.h"
     50 #include "output.h"
     51 #include "var.h"
     52 #include "error.h"
     53 #include "memalloc.h"
     54 #include "mystring.h"
     55 #include "alias.h"
     56 #ifndef NO_HISTORY
     57 #include "myhistedit.h"
     58 #endif
     59 
     60 /*
     61  * Shell command parser.
     62  */
     63 
     64 #define EOFMARKLEN 79
     65 
     66 /* values returned by readtoken */
     67 #include "token.def"
     68 
     69 
     70 
     71 struct heredoc {
     72 	struct heredoc *next;	/* next here document in list */
     73 	union node *here;		/* redirection node */
     74 	char *eofmark;		/* string indicating end of input */
     75 	int striptabs;		/* if set, strip leading tabs */
     76 };
     77 
     78 
     79 
     80 struct heredoc *heredoclist;	/* list of here documents to read */
     81 int parsebackquote;		/* nonzero if we are inside backquotes */
     82 int doprompt;			/* if set, prompt the user */
     83 int needprompt;			/* true if interactive and at start of line */
     84 int lasttoken;			/* last token read */
     85 MKINIT int tokpushback;		/* last token pushed back */
     86 char *wordtext;			/* text of last word returned by readtoken */
     87 MKINIT int checkkwd;            /* 1 == check for kwds, 2 == also eat newlines */
     88 struct nodelist *backquotelist;
     89 union node *redirnode;
     90 struct heredoc *heredoc;
     91 int quoteflag;			/* set if (part of) last token was quoted */
     92 int startlinno;			/* line # where last token started */
     93 
     94 
     95 #define GDB_HACK 1 /* avoid local declarations which gdb can't handle */
     96 #ifdef GDB_HACK
     97 static const char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'};
     98 static const char types[] = "}-+?=";
     99 #endif
    100 
    101 
    102 STATIC union node *list __P((int));
    103 STATIC union node *andor __P((void));
    104 STATIC union node *pipeline __P((void));
    105 STATIC union node *command __P((void));
    106 STATIC union node *simplecmd __P((union node **, union node *));
    107 STATIC void parsefname __P((void));
    108 STATIC void parseheredoc __P((void));
    109 STATIC int readtoken __P((void));
    110 STATIC int readtoken1 __P((int, char const *, char *, int));
    111 STATIC void attyline __P((void));
    112 STATIC int noexpand __P((char *));
    113 STATIC void synexpect __P((int));
    114 STATIC void synerror __P((char *));
    115 STATIC void setprompt __P((int));
    116 
    117 /*
    118  * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
    119  * valid parse tree indicating a blank line.)
    120  */
    121 
    122 union node *
    123 parsecmd(interact) {
    124 	int t;
    125 
    126 	doprompt = interact;
    127 	if (doprompt)
    128 		setprompt(1);
    129 	else
    130 		setprompt(0);
    131 	needprompt = 0;
    132 	t = readtoken();
    133 	if (t == TEOF)
    134 		return NEOF;
    135 	if (t == TNL)
    136 		return NULL;
    137 	tokpushback++;
    138 	return list(1);
    139 }
    140 
    141 
    142 STATIC union node *
    143 list(nlflag) {
    144 	union node *n1, *n2, *n3;
    145 	int tok;
    146 
    147 	checkkwd = 2;
    148 	if (nlflag == 0 && tokendlist[peektoken()])
    149 		return NULL;
    150 	n1 = NULL;
    151 	for (;;) {
    152 		n2 = andor();
    153 		tok = readtoken();
    154 		if (tok == TBACKGND) {
    155 			if (n2->type == NCMD || n2->type == NPIPE) {
    156 				n2->ncmd.backgnd = 1;
    157 			} else if (n2->type == NREDIR) {
    158 				n2->type = NBACKGND;
    159 			} else {
    160 				n3 = (union node *)stalloc(sizeof (struct nredir));
    161 				n3->type = NBACKGND;
    162 				n3->nredir.n = n2;
    163 				n3->nredir.redirect = NULL;
    164 				n2 = n3;
    165 			}
    166 		}
    167 		if (n1 == NULL) {
    168 			n1 = n2;
    169 		}
    170 		else {
    171 			n3 = (union node *)stalloc(sizeof (struct nbinary));
    172 			n3->type = NSEMI;
    173 			n3->nbinary.ch1 = n1;
    174 			n3->nbinary.ch2 = n2;
    175 			n1 = n3;
    176 		}
    177 		switch (tok) {
    178 		case TBACKGND:
    179 		case TSEMI:
    180 			tok = readtoken();
    181 			/* fall through */
    182 		case TNL:
    183 			if (tok == TNL) {
    184 				parseheredoc();
    185 				if (nlflag)
    186 					return n1;
    187 			} else {
    188 				tokpushback++;
    189 			}
    190 			checkkwd = 2;
    191 			if (tokendlist[peektoken()])
    192 				return n1;
    193 			break;
    194 		case TEOF:
    195 			if (heredoclist)
    196 				parseheredoc();
    197 			else
    198 				pungetc();		/* push back EOF on input */
    199 			return n1;
    200 		default:
    201 			if (nlflag)
    202 				synexpect(-1);
    203 			tokpushback++;
    204 			return n1;
    205 		}
    206 	}
    207 }
    208 
    209 
    210 
    211 STATIC union node *
    212 andor() {
    213 	union node *n1, *n2, *n3;
    214 	int t;
    215 
    216 	n1 = pipeline();
    217 	for (;;) {
    218 		if ((t = readtoken()) == TAND) {
    219 			t = NAND;
    220 		} else if (t == TOR) {
    221 			t = NOR;
    222 		} else {
    223 			tokpushback++;
    224 			return n1;
    225 		}
    226 		n2 = pipeline();
    227 		n3 = (union node *)stalloc(sizeof (struct nbinary));
    228 		n3->type = t;
    229 		n3->nbinary.ch1 = n1;
    230 		n3->nbinary.ch2 = n2;
    231 		n1 = n3;
    232 	}
    233 }
    234 
    235 
    236 
    237 STATIC union node *
    238 pipeline() {
    239 	union node *n1, *pipenode, *notnode;
    240 	struct nodelist *lp, *prev;
    241 	int negate = 0;
    242 
    243 	TRACE(("pipeline: entered\n"));
    244 	while (readtoken() == TNOT) {
    245 		TRACE(("pipeline: TNOT recognized\n"));
    246 		negate = !negate;
    247 	}
    248 	tokpushback++;
    249 	n1 = command();
    250 	if (readtoken() == TPIPE) {
    251 		pipenode = (union node *)stalloc(sizeof (struct npipe));
    252 		pipenode->type = NPIPE;
    253 		pipenode->npipe.backgnd = 0;
    254 		lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
    255 		pipenode->npipe.cmdlist = lp;
    256 		lp->n = n1;
    257 		do {
    258 			prev = lp;
    259 			lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
    260 			lp->n = command();
    261 			prev->next = lp;
    262 		} while (readtoken() == TPIPE);
    263 		lp->next = NULL;
    264 		n1 = pipenode;
    265 	}
    266 	tokpushback++;
    267 	if (negate) {
    268 		notnode = (union node *)stalloc(sizeof (struct nnot));
    269 		notnode->type = NNOT;
    270 		notnode->nnot.com = n1;
    271 		n1 = notnode;
    272 	}
    273 	return n1;
    274 }
    275 
    276 
    277 
    278 STATIC union node *
    279 command() {
    280 	union node *n1, *n2;
    281 	union node *ap, **app;
    282 	union node *cp, **cpp;
    283 	union node *redir, **rpp;
    284 	int t;
    285 
    286 	checkkwd = 2;
    287 	redir = 0;
    288 	rpp = &redir;
    289 	/* Check for redirection which may precede command */
    290 	while (readtoken() == TREDIR) {
    291 		*rpp = n2 = redirnode;
    292 		rpp = &n2->nfile.next;
    293 		parsefname();
    294 	}
    295 	tokpushback++;
    296 
    297 	switch (readtoken()) {
    298 	case TIF:
    299 		n1 = (union node *)stalloc(sizeof (struct nif));
    300 		n1->type = NIF;
    301 		n1->nif.test = list(0);
    302 		if (readtoken() != TTHEN)
    303 			synexpect(TTHEN);
    304 		n1->nif.ifpart = list(0);
    305 		n2 = n1;
    306 		while (readtoken() == TELIF) {
    307 			n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
    308 			n2 = n2->nif.elsepart;
    309 			n2->type = NIF;
    310 			n2->nif.test = list(0);
    311 			if (readtoken() != TTHEN)
    312 				synexpect(TTHEN);
    313 			n2->nif.ifpart = list(0);
    314 		}
    315 		if (lasttoken == TELSE)
    316 			n2->nif.elsepart = list(0);
    317 		else {
    318 			n2->nif.elsepart = NULL;
    319 			tokpushback++;
    320 		}
    321 		if (readtoken() != TFI)
    322 			synexpect(TFI);
    323 		checkkwd = 1;
    324 		break;
    325 	case TWHILE:
    326 	case TUNTIL: {
    327 		int got;
    328 		n1 = (union node *)stalloc(sizeof (struct nbinary));
    329 		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
    330 		n1->nbinary.ch1 = list(0);
    331 		if ((got=readtoken()) != TDO) {
    332 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
    333 			synexpect(TDO);
    334 		}
    335 		n1->nbinary.ch2 = list(0);
    336 		if (readtoken() != TDONE)
    337 			synexpect(TDONE);
    338 		checkkwd = 1;
    339 		break;
    340 	}
    341 	case TFOR:
    342 		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
    343 			synerror("Bad for loop variable");
    344 		n1 = (union node *)stalloc(sizeof (struct nfor));
    345 		n1->type = NFOR;
    346 		n1->nfor.var = wordtext;
    347 		if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
    348 			app = ≈
    349 			while (readtoken() == TWORD) {
    350 				n2 = (union node *)stalloc(sizeof (struct narg));
    351 				n2->type = NARG;
    352 				n2->narg.text = wordtext;
    353 				n2->narg.backquote = backquotelist;
    354 				*app = n2;
    355 				app = &n2->narg.next;
    356 			}
    357 			*app = NULL;
    358 			n1->nfor.args = ap;
    359 			if (lasttoken != TNL && lasttoken != TSEMI)
    360 				synexpect(-1);
    361 		} else {
    362 #ifndef GDB_HACK
    363 			static const char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
    364 								   '@', '=', '\0'};
    365 #endif
    366 			n2 = (union node *)stalloc(sizeof (struct narg));
    367 			n2->type = NARG;
    368 			n2->narg.text = (char *)argvars;
    369 			n2->narg.backquote = NULL;
    370 			n2->narg.next = NULL;
    371 			n1->nfor.args = n2;
    372 			/*
    373 			 * Newline or semicolon here is optional (but note
    374 			 * that the original Bourne shell only allowed NL).
    375 			 */
    376 			if (lasttoken != TNL && lasttoken != TSEMI)
    377 				tokpushback++;
    378 		}
    379 		checkkwd = 2;
    380 		if ((t = readtoken()) == TDO)
    381 			t = TDONE;
    382 		else if (t == TBEGIN)
    383 			t = TEND;
    384 		else
    385 			synexpect(-1);
    386 		n1->nfor.body = list(0);
    387 		if (readtoken() != t)
    388 			synexpect(t);
    389 		checkkwd = 1;
    390 		break;
    391 	case TCASE:
    392 		n1 = (union node *)stalloc(sizeof (struct ncase));
    393 		n1->type = NCASE;
    394 		if (readtoken() != TWORD)
    395 			synexpect(TWORD);
    396 		n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
    397 		n2->type = NARG;
    398 		n2->narg.text = wordtext;
    399 		n2->narg.backquote = backquotelist;
    400 		n2->narg.next = NULL;
    401 		while (readtoken() == TNL);
    402 		if (lasttoken != TWORD || ! equal(wordtext, "in"))
    403 			synerror("expecting \"in\"");
    404 		cpp = &n1->ncase.cases;
    405 		checkkwd = 2, readtoken();
    406 		do {
    407 			*cpp = cp = (union node *)stalloc(sizeof (struct nclist));
    408 			cp->type = NCLIST;
    409 			app = &cp->nclist.pattern;
    410 			for (;;) {
    411 				*app = ap = (union node *)stalloc(sizeof (struct narg));
    412 				ap->type = NARG;
    413 				ap->narg.text = wordtext;
    414 				ap->narg.backquote = backquotelist;
    415 				if (checkkwd = 2, readtoken() != TPIPE)
    416 					break;
    417 				app = &ap->narg.next;
    418 				readtoken();
    419 			}
    420 			ap->narg.next = NULL;
    421 			if (lasttoken != TRP)
    422 				synexpect(TRP);
    423 			cp->nclist.body = list(0);
    424 
    425 			checkkwd = 2;
    426 			if ((t = readtoken()) != TESAC) {
    427 				if (t != TENDCASE)
    428 					synexpect(TENDCASE);
    429 				else
    430 					checkkwd = 2, readtoken();
    431 			}
    432 			cpp = &cp->nclist.next;
    433 		} while(lasttoken != TESAC);
    434 		*cpp = NULL;
    435 		checkkwd = 1;
    436 		break;
    437 	case TLP:
    438 		n1 = (union node *)stalloc(sizeof (struct nredir));
    439 		n1->type = NSUBSHELL;
    440 		n1->nredir.n = list(0);
    441 		n1->nredir.redirect = NULL;
    442 		if (readtoken() != TRP)
    443 			synexpect(TRP);
    444 		checkkwd = 1;
    445 		break;
    446 	case TBEGIN:
    447 		n1 = list(0);
    448 		if (readtoken() != TEND)
    449 			synexpect(TEND);
    450 		checkkwd = 1;
    451 		break;
    452 	/* Handle an empty command like other simple commands.  */
    453 	case TNL:
    454 	case TWORD:
    455 		tokpushback++;
    456 		return simplecmd(rpp, redir);
    457 	default:
    458 		synexpect(-1);
    459 	}
    460 
    461 	/* Now check for redirection which may follow command */
    462 	while (readtoken() == TREDIR) {
    463 		*rpp = n2 = redirnode;
    464 		rpp = &n2->nfile.next;
    465 		parsefname();
    466 	}
    467 	tokpushback++;
    468 	*rpp = NULL;
    469 	if (redir) {
    470 		if (n1->type != NSUBSHELL) {
    471 			n2 = (union node *)stalloc(sizeof (struct nredir));
    472 			n2->type = NREDIR;
    473 			n2->nredir.n = n1;
    474 			n1 = n2;
    475 		}
    476 		n1->nredir.redirect = redir;
    477 	}
    478 	return n1;
    479 }
    480 
    481 
    482 STATIC union node *
    483 simplecmd(rpp, redir)
    484 	union node **rpp, *redir;
    485 	{
    486 	union node *args, **app;
    487 	union node **orig_rpp = rpp;
    488 	union node *n;
    489 
    490 	/* If we don't have any redirections already, then we must reset */
    491 	/* rpp to be the address of the local redir variable.  */
    492 	if (redir == 0)
    493 		rpp = &redir;
    494 
    495 	args = NULL;
    496 	app = &args;
    497 	/*
    498 	 * We save the incoming value, because we need this for shell
    499 	 * functions.  There can not be a redirect or an argument between
    500 	 * the function name and the open parenthesis.
    501 	 */
    502 	orig_rpp = rpp;
    503 
    504 	for (;;) {
    505 		if (readtoken() == TWORD) {
    506 			n = (union node *)stalloc(sizeof (struct narg));
    507 			n->type = NARG;
    508 			n->narg.text = wordtext;
    509 			n->narg.backquote = backquotelist;
    510 			*app = n;
    511 			app = &n->narg.next;
    512 		} else if (lasttoken == TREDIR) {
    513 			*rpp = n = redirnode;
    514 			rpp = &n->nfile.next;
    515 			parsefname();	/* read name of redirection file */
    516 		} else if (lasttoken == TLP && app == &args->narg.next
    517 					    && rpp == orig_rpp) {
    518 			/* We have a function */
    519 			if (readtoken() != TRP)
    520 				synexpect(TRP);
    521 #ifdef notdef
    522 			if (! goodname(n->narg.text))
    523 				synerror("Bad function name");
    524 #endif
    525 			n->type = NDEFUN;
    526 			n->narg.next = command();
    527 			return n;
    528 		} else {
    529 			tokpushback++;
    530 			break;
    531 		}
    532 	}
    533 	*app = NULL;
    534 	*rpp = NULL;
    535 	n = (union node *)stalloc(sizeof (struct ncmd));
    536 	n->type = NCMD;
    537 	n->ncmd.backgnd = 0;
    538 	n->ncmd.args = args;
    539 	n->ncmd.redirect = redir;
    540 	return n;
    541 }
    542 
    543 
    544 STATIC void
    545 parsefname() {
    546 	union node *n = redirnode;
    547 
    548 	if (readtoken() != TWORD)
    549 		synexpect(-1);
    550 	if (n->type == NHERE) {
    551 		struct heredoc *here = heredoc;
    552 		struct heredoc *p;
    553 		int i;
    554 
    555 		if (quoteflag == 0)
    556 			n->type = NXHERE;
    557 		TRACE(("Here document %d\n", n->type));
    558 		if (here->striptabs) {
    559 			while (*wordtext == '\t')
    560 				wordtext++;
    561 		}
    562 		if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
    563 			synerror("Illegal eof marker for << redirection");
    564 		rmescapes(wordtext);
    565 		here->eofmark = wordtext;
    566 		here->next = NULL;
    567 		if (heredoclist == NULL)
    568 			heredoclist = here;
    569 		else {
    570 			for (p = heredoclist ; p->next ; p = p->next);
    571 			p->next = here;
    572 		}
    573 	} else if (n->type == NTOFD || n->type == NFROMFD) {
    574 		if (is_digit(wordtext[0]))
    575 			n->ndup.dupfd = digit_val(wordtext[0]);
    576 		else if (wordtext[0] == '-')
    577 			n->ndup.dupfd = -1;
    578 		else
    579 			goto bad;
    580 		if (wordtext[1] != '\0') {
    581 bad:
    582 			synerror("Bad fd number");
    583 		}
    584 	} else {
    585 		n->nfile.fname = (union node *)stalloc(sizeof (struct narg));
    586 		n = n->nfile.fname;
    587 		n->type = NARG;
    588 		n->narg.next = NULL;
    589 		n->narg.text = wordtext;
    590 		n->narg.backquote = backquotelist;
    591 	}
    592 }
    593 
    594 
    595 /*
    596  * Input any here documents.
    597  */
    598 
    599 STATIC void
    600 parseheredoc() {
    601 	struct heredoc *here;
    602 	union node *n;
    603 
    604 	while (heredoclist) {
    605 		here = heredoclist;
    606 		heredoclist = here->next;
    607 		if (needprompt) {
    608 			setprompt(2);
    609 			needprompt = 0;
    610 		}
    611 		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
    612 				here->eofmark, here->striptabs);
    613 		n = (union node *)stalloc(sizeof (struct narg));
    614 		n->narg.type = NARG;
    615 		n->narg.next = NULL;
    616 		n->narg.text = wordtext;
    617 		n->narg.backquote = backquotelist;
    618 		here->here->nhere.doc = n;
    619 	}
    620 }
    621 
    622 STATIC int
    623 peektoken() {
    624 	int t;
    625 
    626 	t = readtoken();
    627 	tokpushback++;
    628 	return (t);
    629 }
    630 
    631 STATIC int xxreadtoken();
    632 
    633 STATIC int
    634 readtoken() {
    635 	int t;
    636 	int savecheckkwd = checkkwd;
    637 	struct alias *ap;
    638 #ifdef DEBUG
    639 	int alreadyseen = tokpushback;
    640 #endif
    641 
    642 	top:
    643 	t = xxreadtoken();
    644 
    645 	if (checkkwd) {
    646 		/*
    647 		 * eat newlines
    648 		 */
    649 		if (checkkwd == 2) {
    650 			checkkwd = 0;
    651 			while (t == TNL) {
    652 				parseheredoc();
    653 				t = xxreadtoken();
    654 			}
    655 		} else
    656 			checkkwd = 0;
    657 		/*
    658 		 * check for keywords and aliases
    659 		 */
    660 		if (t == TWORD && !quoteflag) {
    661 			register char * const *pp, *s;
    662 
    663 			for (pp = (char **)parsekwd; *pp; pp++) {
    664 				if (**pp == *wordtext && equal(*pp, wordtext)) {
    665 					lasttoken = t = pp - parsekwd + KWDOFFSET;
    666 					TRACE(("keyword %s recognized\n", tokname[t]));
    667 					goto out;
    668 				}
    669 			}
    670 			if (ap = lookupalias(wordtext, 1)) {
    671 				pushstring(ap->val, strlen(ap->val), ap);
    672 				checkkwd = savecheckkwd;
    673 				goto top;
    674 			}
    675 		}
    676 out:
    677 		checkkwd = 0;
    678 	}
    679 #ifdef DEBUG
    680 	if (!alreadyseen)
    681 	    TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
    682 	else
    683 	    TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
    684 #endif
    685 	return (t);
    686 }
    687 
    688 
    689 /*
    690  * Read the next input token.
    691  * If the token is a word, we set backquotelist to the list of cmds in
    692  *	backquotes.  We set quoteflag to true if any part of the word was
    693  *	quoted.
    694  * If the token is TREDIR, then we set redirnode to a structure containing
    695  *	the redirection.
    696  * In all cases, the variable startlinno is set to the number of the line
    697  *	on which the token starts.
    698  *
    699  * [Change comment:  here documents and internal procedures]
    700  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
    701  *  word parsing code into a separate routine.  In this case, readtoken
    702  *  doesn't need to have any internal procedures, but parseword does.
    703  *  We could also make parseoperator in essence the main routine, and
    704  *  have parseword (readtoken1?) handle both words and redirection.]
    705  */
    706 
    707 #define RETURN(token)	return lasttoken = token
    708 
    709 STATIC int
    710 xxreadtoken() {
    711 	register c;
    712 
    713 	if (tokpushback) {
    714 		tokpushback = 0;
    715 		return lasttoken;
    716 	}
    717 	if (needprompt) {
    718 		setprompt(2);
    719 		needprompt = 0;
    720 	}
    721 	startlinno = plinno;
    722 	for (;;) {	/* until token or start of word found */
    723 		c = pgetc_macro();
    724 		if (c == ' ' || c == '\t')
    725 			continue;		/* quick check for white space first */
    726 		switch (c) {
    727 		case ' ': case '\t':
    728 			continue;
    729 		case '#':
    730 			while ((c = pgetc()) != '\n' && c != PEOF);
    731 			pungetc();
    732 			continue;
    733 		case '\\':
    734 			if (pgetc() == '\n') {
    735 				startlinno = ++plinno;
    736 				if (doprompt)
    737 					setprompt(2);
    738 				else
    739 					setprompt(0);
    740 				continue;
    741 			}
    742 			pungetc();
    743 			goto breakloop;
    744 		case '\n':
    745 			plinno++;
    746 			needprompt = doprompt;
    747 			RETURN(TNL);
    748 		case PEOF:
    749 			RETURN(TEOF);
    750 		case '&':
    751 			if (pgetc() == '&')
    752 				RETURN(TAND);
    753 			pungetc();
    754 			RETURN(TBACKGND);
    755 		case '|':
    756 			if (pgetc() == '|')
    757 				RETURN(TOR);
    758 			pungetc();
    759 			RETURN(TPIPE);
    760 		case ';':
    761 			if (pgetc() == ';')
    762 				RETURN(TENDCASE);
    763 			pungetc();
    764 			RETURN(TSEMI);
    765 		case '(':
    766 			RETURN(TLP);
    767 		case ')':
    768 			RETURN(TRP);
    769 		default:
    770 			goto breakloop;
    771 		}
    772 	}
    773 breakloop:
    774 	return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
    775 #undef RETURN
    776 }
    777 
    778 
    779 
    780 /*
    781  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
    782  * is not NULL, read a here document.  In the latter case, eofmark is the
    783  * word which marks the end of the document and striptabs is true if
    784  * leading tabs should be stripped from the document.  The argument firstc
    785  * is the first character of the input token or document.
    786  *
    787  * Because C does not have internal subroutines, I have simulated them
    788  * using goto's to implement the subroutine linkage.  The following macros
    789  * will run code that appears at the end of readtoken1.
    790  */
    791 
    792 #define CHECKEND()	{goto checkend; checkend_return:;}
    793 #define PARSEREDIR()	{goto parseredir; parseredir_return:;}
    794 #define PARSESUB()	{goto parsesub; parsesub_return:;}
    795 #define PARSEBACKQOLD()	{oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
    796 #define PARSEBACKQNEW()	{oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
    797 #define	PARSEARITH()	{goto parsearith; parsearith_return:;}
    798 
    799 STATIC int
    800 readtoken1(firstc, syntax, eofmark, striptabs)
    801 	int firstc;
    802 	char const *syntax;
    803 	char *eofmark;
    804 	int striptabs;
    805 	{
    806 	register c = firstc;
    807 	register char *out;
    808 	int len;
    809 	char line[EOFMARKLEN + 1];
    810 	struct nodelist *bqlist;
    811 	int quotef;
    812 	int dblquote;
    813 	int varnest;	/* levels of variables expansion */
    814 	int arinest;	/* levels of arithmetic expansion */
    815 	int parenlevel;	/* levels of parens in arithmetic */
    816 	int oldstyle;
    817 	char const *prevsyntax;	/* syntax before arithmetic */
    818 
    819 	startlinno = plinno;
    820 	dblquote = 0;
    821 	if (syntax == DQSYNTAX)
    822 		dblquote = 1;
    823 	quotef = 0;
    824 	bqlist = NULL;
    825 	varnest = 0;
    826 	arinest = 0;
    827 	parenlevel = 0;
    828 
    829 	STARTSTACKSTR(out);
    830 	loop: {	/* for each line, until end of word */
    831 #if ATTY
    832 		if (c == '\034' && doprompt
    833 		 && attyset() && ! equal(termval(), "emacs")) {
    834 			attyline();
    835 			if (syntax == BASESYNTAX)
    836 				return readtoken();
    837 			c = pgetc();
    838 			goto loop;
    839 		}
    840 #endif
    841 		CHECKEND();	/* set c to PEOF if at end of here document */
    842 		for (;;) {	/* until end of line or end of word */
    843 			CHECKSTRSPACE(3, out);	/* permit 3 calls to USTPUTC */
    844 			switch(syntax[c]) {
    845 			case CNL:	/* '\n' */
    846 				if (syntax == BASESYNTAX)
    847 					goto endword;	/* exit outer loop */
    848 				USTPUTC(c, out);
    849 				plinno++;
    850 				if (doprompt)
    851 					setprompt(2);
    852 				else
    853 					setprompt(0);
    854 				c = pgetc();
    855 				goto loop;		/* continue outer loop */
    856 			case CWORD:
    857 				USTPUTC(c, out);
    858 				break;
    859 			case CCTL:
    860 				if (eofmark == NULL || dblquote)
    861 					USTPUTC(CTLESC, out);
    862 				USTPUTC(c, out);
    863 				break;
    864 			case CBACK:	/* backslash */
    865 				c = pgetc();
    866 				if (c == PEOF) {
    867 					USTPUTC('\\', out);
    868 					pungetc();
    869 				} else if (c == '\n') {
    870 					if (doprompt)
    871 						setprompt(2);
    872 					else
    873 						setprompt(0);
    874 				} else {
    875 					if (dblquote && c != '\\' && c != '`' && c != '$'
    876 							 && (c != '"' || eofmark != NULL))
    877 						USTPUTC('\\', out);
    878 					if (SQSYNTAX[c] == CCTL)
    879 						USTPUTC(CTLESC, out);
    880 					USTPUTC(c, out);
    881 					quotef++;
    882 				}
    883 				break;
    884 			case CSQUOTE:
    885 				syntax = SQSYNTAX;
    886 				break;
    887 			case CDQUOTE:
    888 				syntax = DQSYNTAX;
    889 				dblquote = 1;
    890 				break;
    891 			case CENDQUOTE:
    892 				if (eofmark) {
    893 					USTPUTC(c, out);
    894 				} else {
    895 					if (arinest)
    896 						syntax = ARISYNTAX;
    897 					else
    898 						syntax = BASESYNTAX;
    899 					quotef++;
    900 					dblquote = 0;
    901 				}
    902 				break;
    903 			case CVAR:	/* '$' */
    904 				PARSESUB();		/* parse substitution */
    905 				break;
    906 			case CENDVAR:	/* '}' */
    907 				if (varnest > 0) {
    908 					varnest--;
    909 					USTPUTC(CTLENDVAR, out);
    910 				} else {
    911 					USTPUTC(c, out);
    912 				}
    913 				break;
    914 			case CLP:	/* '(' in arithmetic */
    915 				parenlevel++;
    916 				USTPUTC(c, out);
    917 				break;
    918 			case CRP:	/* ')' in arithmetic */
    919 				if (parenlevel > 0) {
    920 					USTPUTC(c, out);
    921 					--parenlevel;
    922 				} else {
    923 					if (pgetc() == ')') {
    924 						if (--arinest == 0) {
    925 							USTPUTC(CTLENDARI, out);
    926 							syntax = prevsyntax;
    927 						} else
    928 							USTPUTC(')', out);
    929 					} else {
    930 						/*
    931 						 * unbalanced parens
    932 						 *  (don't 2nd guess - no error)
    933 						 */
    934 						pungetc();
    935 						USTPUTC(')', out);
    936 					}
    937 				}
    938 				break;
    939 			case CBQUOTE:	/* '`' */
    940 				PARSEBACKQOLD();
    941 				break;
    942 			case CEOF:
    943 				goto endword;		/* exit outer loop */
    944 			default:
    945 				if (varnest == 0)
    946 					goto endword;	/* exit outer loop */
    947 				USTPUTC(c, out);
    948 			}
    949 			c = pgetc_macro();
    950 		}
    951 	}
    952 endword:
    953 	if (syntax == ARISYNTAX)
    954 		synerror("Missing '))'");
    955 	if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
    956 		synerror("Unterminated quoted string");
    957 	if (varnest != 0) {
    958 		startlinno = plinno;
    959 		synerror("Missing '}'");
    960 	}
    961 	USTPUTC('\0', out);
    962 	len = out - stackblock();
    963 	out = stackblock();
    964 	if (eofmark == NULL) {
    965 		if ((c == '>' || c == '<')
    966 		 && quotef == 0
    967 		 && len <= 2
    968 		 && (*out == '\0' || is_digit(*out))) {
    969 			PARSEREDIR();
    970 			return lasttoken = TREDIR;
    971 		} else {
    972 			pungetc();
    973 		}
    974 	}
    975 	quoteflag = quotef;
    976 	backquotelist = bqlist;
    977 	grabstackblock(len);
    978 	wordtext = out;
    979 	return lasttoken = TWORD;
    980 /* end of readtoken routine */
    981 
    982 
    983 
    984 /*
    985  * Check to see whether we are at the end of the here document.  When this
    986  * is called, c is set to the first character of the next input line.  If
    987  * we are at the end of the here document, this routine sets the c to PEOF.
    988  */
    989 
    990 checkend: {
    991 	if (eofmark) {
    992 		if (striptabs) {
    993 			while (c == '\t')
    994 				c = pgetc();
    995 		}
    996 		if (c == *eofmark) {
    997 			if (pfgets(line, sizeof line) != NULL) {
    998 				register char *p, *q;
    999 
   1000 				p = line;
   1001 				for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
   1002 				if (*p == '\n' && *q == '\0') {
   1003 					c = PEOF;
   1004 					plinno++;
   1005 					needprompt = doprompt;
   1006 				} else {
   1007 					pushstring(line, strlen(line), NULL);
   1008 				}
   1009 			}
   1010 		}
   1011 	}
   1012 	goto checkend_return;
   1013 }
   1014 
   1015 
   1016 /*
   1017  * Parse a redirection operator.  The variable "out" points to a string
   1018  * specifying the fd to be redirected.  The variable "c" contains the
   1019  * first character of the redirection operator.
   1020  */
   1021 
   1022 parseredir: {
   1023 	char fd = *out;
   1024 	union node *np;
   1025 
   1026 	np = (union node *)stalloc(sizeof (struct nfile));
   1027 	if (c == '>') {
   1028 		np->nfile.fd = 1;
   1029 		c = pgetc();
   1030 		if (c == '>')
   1031 			np->type = NAPPEND;
   1032 		else if (c == '&')
   1033 			np->type = NTOFD;
   1034 		else {
   1035 			np->type = NTO;
   1036 			pungetc();
   1037 		}
   1038 	} else {	/* c == '<' */
   1039 		np->nfile.fd = 0;
   1040 		c = pgetc();
   1041 		if (c == '<') {
   1042 			if (sizeof (struct nfile) != sizeof (struct nhere)) {
   1043 				np = (union node *)stalloc(sizeof (struct nhere));
   1044 				np->nfile.fd = 0;
   1045 			}
   1046 			np->type = NHERE;
   1047 			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
   1048 			heredoc->here = np;
   1049 			if ((c = pgetc()) == '-') {
   1050 				heredoc->striptabs = 1;
   1051 			} else {
   1052 				heredoc->striptabs = 0;
   1053 				pungetc();
   1054 			}
   1055 		} else if (c == '&')
   1056 			np->type = NFROMFD;
   1057 		else {
   1058 			np->type = NFROM;
   1059 			pungetc();
   1060 		}
   1061 	}
   1062 	if (fd != '\0')
   1063 		np->nfile.fd = digit_val(fd);
   1064 	redirnode = np;
   1065 	goto parseredir_return;
   1066 }
   1067 
   1068 
   1069 /*
   1070  * Parse a substitution.  At this point, we have read the dollar sign
   1071  * and nothing else.
   1072  */
   1073 
   1074 parsesub: {
   1075 	int subtype;
   1076 	int typeloc;
   1077 	int flags;
   1078 	char *p;
   1079 #ifndef GDB_HACK
   1080 	static const char types[] = "}-+?=";
   1081 #endif
   1082 
   1083 	c = pgetc();
   1084 	if (c != '(' && c != '{' && !is_name(c) && !is_special(c)) {
   1085 		USTPUTC('$', out);
   1086 		pungetc();
   1087 	} else if (c == '(') {	/* $(command) or $((arith)) */
   1088 		if (pgetc() == '(') {
   1089 			PARSEARITH();
   1090 		} else {
   1091 			pungetc();
   1092 			PARSEBACKQNEW();
   1093 		}
   1094 	} else {
   1095 		USTPUTC(CTLVAR, out);
   1096 		typeloc = out - stackblock();
   1097 		USTPUTC(VSNORMAL, out);
   1098 		subtype = VSNORMAL;
   1099 		if (c == '{') {
   1100 			c = pgetc();
   1101 			subtype = 0;
   1102 		}
   1103 		if (is_name(c)) {
   1104 			do {
   1105 				STPUTC(c, out);
   1106 				c = pgetc();
   1107 			} while (is_in_name(c));
   1108 		} else {
   1109 			if (! is_special(c))
   1110 badsub:				synerror("Bad substitution");
   1111 			USTPUTC(c, out);
   1112 			c = pgetc();
   1113 		}
   1114 		STPUTC('=', out);
   1115 		flags = 0;
   1116 		if (subtype == 0) {
   1117 			if (c == ':') {
   1118 				flags = VSNUL;
   1119 				c = pgetc();
   1120 			}
   1121 			p = strchr(types, c);
   1122 			if (p == NULL)
   1123 				goto badsub;
   1124 			subtype = p - types + VSNORMAL;
   1125 		} else {
   1126 			pungetc();
   1127 		}
   1128 		if (dblquote || arinest)
   1129 			flags |= VSQUOTE;
   1130 		*(stackblock() + typeloc) = subtype | flags;
   1131 		if (subtype != VSNORMAL)
   1132 			varnest++;
   1133 	}
   1134 	goto parsesub_return;
   1135 }
   1136 
   1137 
   1138 /*
   1139  * Called to parse command substitutions.  Newstyle is set if the command
   1140  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
   1141  * list of commands (passed by reference), and savelen is the number of
   1142  * characters on the top of the stack which must be preserved.
   1143  */
   1144 
   1145 parsebackq: {
   1146 	struct nodelist **nlpp;
   1147 	int savepbq;
   1148 	union node *n;
   1149 	char *volatile str;
   1150 	struct jmploc jmploc;
   1151 	struct jmploc *volatile savehandler;
   1152 	int savelen;
   1153 
   1154 	savepbq = parsebackquote;
   1155 	if (setjmp(jmploc.loc)) {
   1156 		if (str)
   1157 			ckfree(str);
   1158 		parsebackquote = 0;
   1159 		handler = savehandler;
   1160 		longjmp(handler->loc, 1);
   1161 	}
   1162 	INTOFF;
   1163 	str = NULL;
   1164 	savelen = out - stackblock();
   1165 	if (savelen > 0) {
   1166 		str = ckmalloc(savelen);
   1167 		bcopy(stackblock(), str, savelen);
   1168 	}
   1169 	savehandler = handler;
   1170 	handler = &jmploc;
   1171 	INTON;
   1172         if (oldstyle) {
   1173                 /* We must read until the closing backquote, giving special
   1174                    treatment to some slashes, and then push the string and
   1175                    reread it as input, interpreting it normally.  */
   1176                 register char *out;
   1177                 register c;
   1178                 int savelen;
   1179                 char *str;
   1180 
   1181                 STARTSTACKSTR(out);
   1182                 while ((c = pgetc ()) != '`') {
   1183                        if (c == '\\') {
   1184                                 c = pgetc ();
   1185                                 if (c != '\\' && c != '`' && c != '$'
   1186                                     && (!dblquote || c != '"'))
   1187                                         STPUTC('\\', out);
   1188                        }
   1189                        STPUTC(c, out);
   1190                 }
   1191                 STPUTC('\0', out);
   1192                 savelen = out - stackblock();
   1193                 if (savelen > 0) {
   1194                         str = ckmalloc(savelen);
   1195                         bcopy(stackblock(), str, savelen);
   1196                 }
   1197                 setinputstring(str, 1);
   1198         }
   1199 	nlpp = &bqlist;
   1200 	while (*nlpp)
   1201 		nlpp = &(*nlpp)->next;
   1202 	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
   1203 	(*nlpp)->next = NULL;
   1204 	parsebackquote = oldstyle;
   1205 	n = list(0);
   1206         if (!oldstyle && (readtoken() != TRP))
   1207                 synexpect(TRP);
   1208 	(*nlpp)->n = n;
   1209         /* Start reading from old file again.  */
   1210         if (oldstyle)
   1211                 popfile();
   1212 	while (stackblocksize() <= savelen)
   1213 		growstackblock();
   1214 	STARTSTACKSTR(out);
   1215 	if (str) {
   1216 		bcopy(str, out, savelen);
   1217 		STADJUST(savelen, out);
   1218 		INTOFF;
   1219 		ckfree(str);
   1220 		str = NULL;
   1221 		INTON;
   1222 	}
   1223 	parsebackquote = savepbq;
   1224 	handler = savehandler;
   1225 	if (arinest || dblquote)
   1226 		USTPUTC(CTLBACKQ | CTLQUOTE, out);
   1227 	else
   1228 		USTPUTC(CTLBACKQ, out);
   1229 	if (oldstyle)
   1230 		goto parsebackq_oldreturn;
   1231 	else
   1232 		goto parsebackq_newreturn;
   1233 }
   1234 
   1235 /*
   1236  * Parse an arithmetic expansion (indicate start of one and set state)
   1237  */
   1238 parsearith: {
   1239 
   1240 	if (++arinest == 1) {
   1241 		prevsyntax = syntax;
   1242 		syntax = ARISYNTAX;
   1243 		USTPUTC(CTLARI, out);
   1244 	} else {
   1245 		/*
   1246 		 * we collapse embedded arithmetic expansion to
   1247 		 * parenthesis, which should be equivalent
   1248 		 */
   1249 		USTPUTC('(', out);
   1250 	}
   1251 	goto parsearith_return;
   1252 }
   1253 
   1254 } /* end of readtoken */
   1255 
   1256 
   1257 
   1258 #ifdef mkinit
   1259 RESET {
   1260 	tokpushback = 0;
   1261 	checkkwd = 0;
   1262 }
   1263 #endif
   1264 
   1265 /*
   1266  * Returns true if the text contains nothing to expand (no dollar signs
   1267  * or backquotes).
   1268  */
   1269 
   1270 STATIC int
   1271 noexpand(text)
   1272 	char *text;
   1273 	{
   1274 	register char *p;
   1275 	register char c;
   1276 
   1277 	p = text;
   1278 	while ((c = *p++) != '\0') {
   1279 		if (c == CTLESC)
   1280 			p++;
   1281 		else if (BASESYNTAX[c] == CCTL)
   1282 			return 0;
   1283 	}
   1284 	return 1;
   1285 }
   1286 
   1287 
   1288 /*
   1289  * Return true if the argument is a legal variable name (a letter or
   1290  * underscore followed by zero or more letters, underscores, and digits).
   1291  */
   1292 
   1293 int
   1294 goodname(name)
   1295 	char *name;
   1296 	{
   1297 	register char *p;
   1298 
   1299 	p = name;
   1300 	if (! is_name(*p))
   1301 		return 0;
   1302 	while (*++p) {
   1303 		if (! is_in_name(*p))
   1304 			return 0;
   1305 	}
   1306 	return 1;
   1307 }
   1308 
   1309 
   1310 /*
   1311  * Called when an unexpected token is read during the parse.  The argument
   1312  * is the token that is expected, or -1 if more than one type of token can
   1313  * occur at this point.
   1314  */
   1315 
   1316 STATIC void
   1317 synexpect(token) {
   1318 	char msg[64];
   1319 
   1320 	if (token >= 0) {
   1321 		fmtstr(msg, 64, "%s unexpected (expecting %s)",
   1322 			tokname[lasttoken], tokname[token]);
   1323 	} else {
   1324 		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
   1325 	}
   1326 	synerror(msg);
   1327 }
   1328 
   1329 
   1330 STATIC void
   1331 synerror(msg)
   1332 	char *msg;
   1333 	{
   1334 	if (commandname)
   1335 		outfmt(&errout, "%s: %d: ", commandname, startlinno);
   1336 	outfmt(&errout, "Syntax error: %s\n", msg);
   1337 	error((char *)NULL);
   1338 }
   1339 
   1340 STATIC void
   1341 setprompt(which)
   1342 	int which;
   1343 	{
   1344 	whichprompt = which;
   1345 
   1346 #ifndef NO_HISTORY
   1347 	if (!el)
   1348 #endif
   1349 		out2str(getprompt(NULL));
   1350 }
   1351 
   1352 /*
   1353  * called by editline -- any expansions to the prompt
   1354  *    should be added here.
   1355  */
   1356 char *
   1357 getprompt(unused)
   1358 	void *unused;
   1359 	{
   1360 	switch (whichprompt) {
   1361 	case 0:
   1362 		return "";
   1363 	case 1:
   1364 		return ps1val();
   1365 	case 2:
   1366 		return ps2val();
   1367 	default:
   1368 		return "<internal prompt error>";
   1369 	}
   1370 }
   1371