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