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