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