2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
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
35 static char sccsid[] = "@(#)parser.c 8.7 (Berkeley) 5/16/95";
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
48 #include "expand.h" /* defines rmescapes() */
60 #include "exec.h" /* to check for special builtins */
62 #include "myhistedit.h"
66 * Shell command parser.
72 /* values of checkkwd variable */
77 /* values returned by readtoken */
83 struct heredoc *next; /* next here document in list */
84 union node *here; /* redirection node */
85 char *eofmark; /* string indicating end of input */
86 int striptabs; /* if set, strip leading tabs */
90 struct parser_temp *next;
95 static struct heredoc *heredoclist; /* list of here documents to read */
96 static int doprompt; /* if set, prompt the user */
97 static int needprompt; /* true if interactive and at start of line */
98 static int lasttoken; /* last token read */
99 MKINIT int tokpushback; /* last token pushed back */
100 static char *wordtext; /* text of last word returned by readtoken */
101 MKINIT int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
102 static struct nodelist *backquotelist;
103 static union node *redirnode;
104 static struct heredoc *heredoc;
105 static int quoteflag; /* set if (part of) last token was quoted */
106 static int startlinno; /* line # where last token started */
107 static int funclinno; /* line # where the current function started */
108 static struct parser_temp *parser_temp;
111 static union node *list(int, int);
112 static union node *andor(void);
113 static union node *pipeline(void);
114 static union node *command(void);
115 static union node *simplecmd(union node **, union node *);
116 static union node *makename(void);
117 static void parsefname(void);
118 static void parseheredoc(void);
119 static int peektoken(void);
120 static int readtoken(void);
121 static int xxreadtoken(void);
122 static int readtoken1(int, char const *, char *, int);
123 static int noexpand(char *);
124 static void synexpect(int) __dead2;
125 static void synerror(const char *) __dead2;
126 static void setprompt(int);
130 parser_temp_alloc(size_t len)
132 struct parser_temp *t;
135 t = ckmalloc(sizeof(*t));
137 t->next = parser_temp;
139 t->data = ckmalloc(len);
146 parser_temp_realloc(void *ptr, size_t len)
148 struct parser_temp *t;
153 error("bug: parser_temp_realloc misused");
154 t->data = ckrealloc(t->data, len);
161 parser_temp_free_upto(void *ptr)
163 struct parser_temp *t;
167 while (parser_temp != NULL && !done) {
169 parser_temp = t->next;
170 done = t->data == ptr;
176 error("bug: parser_temp_free_upto misused");
181 parser_temp_free_all(void)
183 struct parser_temp *t;
186 while (parser_temp != NULL) {
188 parser_temp = t->next;
197 * Read and parse a command. Returns NEOF on end of file. (NULL is a
198 * valid parse tree indicating a blank line.)
202 parsecmd(int interact)
206 /* This assumes the parser is not re-entered,
207 * which could happen if we add command substitution on PS1/PS2.
209 parser_temp_free_all();
230 list(int nlflag, int erflag)
232 union node *ntop, *n1, *n2, *n3;
235 checkkwd = CHKNL | CHKKWD | CHKALIAS;
236 if (!nlflag && !erflag && tokendlist[peektoken()])
242 if (tok == TBACKGND) {
243 if (n2 != NULL && n2->type == NPIPE) {
244 n2->npipe.backgnd = 1;
245 } else if (n2 != NULL && n2->type == NREDIR) {
248 n3 = (union node *)stalloc(sizeof (struct nredir));
251 n3->nredir.redirect = NULL;
257 else if (n1 == NULL) {
258 n1 = (union node *)stalloc(sizeof (struct nbinary));
260 n1->nbinary.ch1 = ntop;
261 n1->nbinary.ch2 = n2;
265 n3 = (union node *)stalloc(sizeof (struct nbinary));
267 n3->nbinary.ch1 = n1->nbinary.ch2;
268 n3->nbinary.ch2 = n2;
269 n1->nbinary.ch2 = n3;
282 } else if (tok == TEOF && nlflag) {
288 checkkwd = CHKNL | CHKKWD | CHKALIAS;
289 if (!nlflag && !erflag && tokendlist[peektoken()])
296 pungetc(); /* push back EOF on input */
299 if (nlflag || erflag)
312 union node *n1, *n2, *n3;
317 if ((t = readtoken()) == TAND) {
319 } else if (t == TOR) {
326 n3 = (union node *)stalloc(sizeof (struct nbinary));
328 n3->nbinary.ch1 = n1;
329 n3->nbinary.ch2 = n2;
339 union node *n1, *n2, *pipenode;
340 struct nodelist *lp, *prev;
344 checkkwd = CHKNL | CHKKWD | CHKALIAS;
345 TRACE(("pipeline: entered\n"));
346 while (readtoken() == TNOT)
350 if (readtoken() == TPIPE) {
351 pipenode = (union node *)stalloc(sizeof (struct npipe));
352 pipenode->type = NPIPE;
353 pipenode->npipe.backgnd = 0;
354 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
355 pipenode->npipe.cmdlist = lp;
359 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
360 checkkwd = CHKNL | CHKKWD | CHKALIAS;
368 } while (readtoken() == TPIPE);
374 n2 = (union node *)stalloc(sizeof (struct nnot));
388 union node *ap, **app;
389 union node *cp, **cpp;
390 union node *redir, **rpp;
394 checkkwd = CHKNL | CHKKWD | CHKALIAS;
400 /* Check for redirection which may precede command */
401 while (readtoken() == TREDIR) {
402 *rpp = n2 = redirnode;
403 rpp = &n2->nfile.next;
408 switch (readtoken()) {
410 n1 = (union node *)stalloc(sizeof (struct nif));
412 if ((n1->nif.test = list(0, 0)) == NULL)
414 if (readtoken() != TTHEN)
416 n1->nif.ifpart = list(0, 0);
418 while (readtoken() == TELIF) {
419 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
420 n2 = n2->nif.elsepart;
422 if ((n2->nif.test = list(0, 0)) == NULL)
424 if (readtoken() != TTHEN)
426 n2->nif.ifpart = list(0, 0);
428 if (lasttoken == TELSE)
429 n2->nif.elsepart = list(0, 0);
431 n2->nif.elsepart = NULL;
434 if (readtoken() != TFI)
436 checkkwd = CHKKWD | CHKALIAS;
441 n1 = (union node *)stalloc(sizeof (struct nbinary));
442 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
443 if ((n1->nbinary.ch1 = list(0, 0)) == NULL)
445 if ((got=readtoken()) != TDO) {
446 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
449 n1->nbinary.ch2 = list(0, 0);
450 if (readtoken() != TDONE)
452 checkkwd = CHKKWD | CHKALIAS;
456 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
457 synerror("Bad for loop variable");
458 n1 = (union node *)stalloc(sizeof (struct nfor));
460 n1->nfor.var = wordtext;
461 while (readtoken() == TNL)
463 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
465 while (readtoken() == TWORD) {
466 n2 = (union node *)stalloc(sizeof (struct narg));
468 n2->narg.text = wordtext;
469 n2->narg.backquote = backquotelist;
471 app = &n2->narg.next;
475 if (lasttoken != TNL && lasttoken != TSEMI)
478 static char argvars[5] = {
479 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
481 n2 = (union node *)stalloc(sizeof (struct narg));
483 n2->narg.text = argvars;
484 n2->narg.backquote = NULL;
485 n2->narg.next = NULL;
488 * Newline or semicolon here is optional (but note
489 * that the original Bourne shell only allowed NL).
491 if (lasttoken != TNL && lasttoken != TSEMI)
494 checkkwd = CHKNL | CHKKWD | CHKALIAS;
495 if ((t = readtoken()) == TDO)
497 else if (t == TBEGIN)
501 n1->nfor.body = list(0, 0);
502 if (readtoken() != t)
504 checkkwd = CHKKWD | CHKALIAS;
507 n1 = (union node *)stalloc(sizeof (struct ncase));
509 if (readtoken() != TWORD)
511 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
513 n2->narg.text = wordtext;
514 n2->narg.backquote = backquotelist;
515 n2->narg.next = NULL;
516 while (readtoken() == TNL);
517 if (lasttoken != TWORD || ! equal(wordtext, "in"))
518 synerror("expecting \"in\"");
519 cpp = &n1->ncase.cases;
520 checkkwd = CHKNL | CHKKWD, readtoken();
521 while (lasttoken != TESAC) {
522 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
524 app = &cp->nclist.pattern;
525 if (lasttoken == TLP)
528 *app = ap = (union node *)stalloc(sizeof (struct narg));
530 ap->narg.text = wordtext;
531 ap->narg.backquote = backquotelist;
532 checkkwd = CHKNL | CHKKWD;
533 if (readtoken() != TPIPE)
535 app = &ap->narg.next;
538 ap->narg.next = NULL;
539 if (lasttoken != TRP)
541 cp->nclist.body = list(0, 0);
543 checkkwd = CHKNL | CHKKWD | CHKALIAS;
544 if ((t = readtoken()) != TESAC) {
547 else if (t == TFALLTHRU)
548 cp->type = NCLISTFALLTHRU;
551 checkkwd = CHKNL | CHKKWD, readtoken();
553 cpp = &cp->nclist.next;
556 checkkwd = CHKKWD | CHKALIAS;
559 n1 = (union node *)stalloc(sizeof (struct nredir));
560 n1->type = NSUBSHELL;
561 n1->nredir.n = list(0, 0);
562 n1->nredir.redirect = NULL;
563 if (readtoken() != TRP)
565 checkkwd = CHKKWD | CHKALIAS;
570 if (readtoken() != TEND)
572 checkkwd = CHKKWD | CHKALIAS;
574 /* Handle an empty command like other simple commands. */
583 * An empty command before a ; doesn't make much sense, and
584 * should certainly be disallowed in the case of `if ;'.
593 n1 = simplecmd(rpp, redir);
599 /* Now check for redirection which may follow command */
600 while (readtoken() == TREDIR) {
601 *rpp = n2 = redirnode;
602 rpp = &n2->nfile.next;
609 n2 = (union node *)stalloc(sizeof (struct nredir));
614 n1->nredir.redirect = redir;
622 simplecmd(union node **rpp, union node *redir)
624 union node *args, **app;
625 union node **orig_rpp = rpp;
626 union node *n = NULL;
630 /* If we don't have any redirections already, then we must reset */
631 /* rpp to be the address of the local redir variable. */
638 * We save the incoming value, because we need this for shell
639 * functions. There can not be a redirect or an argument between
640 * the function name and the open parenthesis.
644 savecheckkwd = CHKALIAS;
647 checkkwd = savecheckkwd;
648 if (readtoken() == TWORD) {
649 n = (union node *)stalloc(sizeof (struct narg));
651 n->narg.text = wordtext;
652 n->narg.backquote = backquotelist;
655 if (savecheckkwd != 0 && !isassignment(wordtext))
657 } else if (lasttoken == TREDIR) {
658 *rpp = n = redirnode;
659 rpp = &n->nfile.next;
660 parsefname(); /* read name of redirection file */
661 } else if (lasttoken == TLP && app == &args->narg.next
662 && rpp == orig_rpp) {
663 /* We have a function */
664 if (readtoken() != TRP)
668 * - Require plain text.
669 * - Functions with '/' cannot be called.
671 * - Reject ksh extended glob patterns.
673 if (!noexpand(n->narg.text) || quoteflag ||
674 strchr(n->narg.text, '/') ||
676 n->narg.text[strlen(n->narg.text) - 1]))
677 synerror("Bad function name");
678 rmescapes(n->narg.text);
679 if (find_builtin(n->narg.text, &special) >= 0 &&
681 synerror("Cannot override a special builtin with a function");
683 n->narg.next = command();
693 n = (union node *)stalloc(sizeof (struct ncmd));
696 n->ncmd.redirect = redir;
705 n = (union node *)stalloc(sizeof (struct narg));
708 n->narg.text = wordtext;
709 n->narg.backquote = backquotelist;
714 fixredir(union node *n, const char *text, int err)
716 TRACE(("Fix redir %s %d\n", text, err));
718 n->ndup.vname = NULL;
720 if (is_digit(text[0]) && text[1] == '\0')
721 n->ndup.dupfd = digit_val(text[0]);
722 else if (text[0] == '-' && text[1] == '\0')
727 synerror("Bad fd number");
729 n->ndup.vname = makename();
737 union node *n = redirnode;
739 if (readtoken() != TWORD)
741 if (n->type == NHERE) {
742 struct heredoc *here = heredoc;
748 TRACE(("Here document %d\n", n->type));
749 if (here->striptabs) {
750 while (*wordtext == '\t')
753 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
754 synerror("Illegal eof marker for << redirection");
756 here->eofmark = wordtext;
758 if (heredoclist == NULL)
761 for (p = heredoclist ; p->next ; p = p->next);
764 } else if (n->type == NTOFD || n->type == NFROMFD) {
765 fixredir(n, wordtext, 0);
767 n->nfile.fname = makename();
773 * Input any here documents.
779 struct heredoc *here;
782 while (heredoclist) {
784 heredoclist = here->next;
789 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
790 here->eofmark, here->striptabs);
791 n = (union node *)stalloc(sizeof (struct narg));
794 n->narg.text = wordtext;
795 n->narg.backquote = backquotelist;
796 here->here->nhere.doc = n;
816 int alreadyseen = tokpushback;
825 if (checkkwd & CHKNL) {
833 * check for keywords and aliases
835 if (t == TWORD && !quoteflag)
837 const char * const *pp;
839 if (checkkwd & CHKKWD)
840 for (pp = parsekwd; *pp; pp++) {
841 if (**pp == *wordtext && equal(*pp, wordtext))
843 lasttoken = t = pp - parsekwd + KWDOFFSET;
844 TRACE(("keyword %s recognized\n", tokname[t]));
848 if (checkkwd & CHKALIAS &&
849 (ap = lookupalias(wordtext, 1)) != NULL) {
850 pushstring(ap->val, strlen(ap->val), ap);
860 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
862 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
869 * Read the next input token.
870 * If the token is a word, we set backquotelist to the list of cmds in
871 * backquotes. We set quoteflag to true if any part of the word was
873 * If the token is TREDIR, then we set redirnode to a structure containing
875 * In all cases, the variable startlinno is set to the number of the line
876 * on which the token starts.
878 * [Change comment: here documents and internal procedures]
879 * [Readtoken shouldn't have any arguments. Perhaps we should make the
880 * word parsing code into a separate routine. In this case, readtoken
881 * doesn't need to have any internal procedures, but parseword does.
882 * We could also make parseoperator in essence the main routine, and
883 * have parseword (readtoken1?) handle both words and redirection.]
886 #define RETURN(token) return lasttoken = token
902 for (;;) { /* until token or start of word found */
908 while ((c = pgetc()) != '\n' && c != PEOF);
912 if (pgetc() == '\n') {
913 startlinno = ++plinno;
924 needprompt = doprompt;
955 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
960 #define MAXNEST_static 8
963 const char *syntax; /* *SYNTAX */
964 int parenlevel; /* levels of parentheses in arithmetic */
965 enum tokenstate_category
968 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
969 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
976 * Called to parse command substitutions.
980 parsebackq(char *out, struct nodelist **pbqlist,
981 int oldstyle, int dblquote, int quoted)
983 struct nodelist **nlpp;
986 struct jmploc jmploc;
987 struct jmploc *const savehandler = handler;
990 const int bq_startlinno = plinno;
991 char *volatile ostr = NULL;
992 struct parsefile *const savetopfile = getcurrentfile();
993 struct heredoc *const saveheredoclist = heredoclist;
994 struct heredoc *here;
997 if (setjmp(jmploc.loc)) {
998 popfilesupto(savetopfile);
1003 heredoclist = saveheredoclist;
1004 handler = savehandler;
1005 if (exception == EXERROR) {
1006 startlinno = bq_startlinno;
1007 synerror("Error in command substitution");
1009 longjmp(handler->loc, 1);
1012 savelen = out - stackblock();
1014 str = ckmalloc(savelen);
1015 memcpy(str, stackblock(), savelen);
1021 /* We must read until the closing backquote, giving special
1022 treatment to some slashes, and then push the string and
1023 reread it as input, interpreting it normally. */
1029 STARTSTACKSTR(oout);
1035 CHECKSTRSPACE(2, oout);
1036 switch (c = pgetc()) {
1041 if ((c = pgetc()) == '\n') {
1048 * If eating a newline, avoid putting
1049 * the newline into the new character
1050 * stream (via the USTPUTC after the
1055 if (c != '\\' && c != '`' && c != '$'
1056 && (!dblquote || c != '"'))
1057 USTPUTC('\\', oout);
1062 needprompt = doprompt;
1066 startlinno = plinno;
1067 synerror("EOF in backquote substitution");
1076 USTPUTC('\0', oout);
1077 olen = oout - stackblock();
1079 ostr = ckmalloc(olen);
1080 memcpy(ostr, stackblock(), olen);
1081 setinputstring(ostr, 1);
1086 nlpp = &(*nlpp)->next;
1087 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1088 (*nlpp)->next = NULL;
1091 saveprompt = doprompt;
1095 n = list(0, oldstyle);
1098 doprompt = saveprompt;
1100 if (readtoken() != TRP)
1107 * Start reading from old file again, ignoring any pushed back
1108 * tokens left from the backquote parsing
1114 CHECKSTRSPACE(savelen + 1, out);
1117 memcpy(out, str, savelen);
1118 STADJUST(savelen, out);
1126 here = saveheredoclist;
1128 while (here->next != NULL)
1130 here->next = heredoclist;
1131 heredoclist = saveheredoclist;
1133 handler = savehandler;
1136 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1138 USTPUTC(CTLBACKQ, out);
1144 * Called to parse a backslash escape sequence inside $'...'.
1145 * The backslash has already been read.
1148 readcstyleesc(char *out)
1155 synerror("Unterminated quoted string");
1168 case 'a': v = '\a'; break;
1169 case 'b': v = '\b'; break;
1170 case 'e': v = '\033'; break;
1171 case 'f': v = '\f'; break;
1172 case 'n': v = '\n'; break;
1173 case 'r': v = '\r'; break;
1174 case 't': v = '\t'; break;
1175 case 'v': v = '\v'; break;
1180 if (c >= '0' && c <= '9')
1181 v = (v << 4) + c - '0';
1182 else if (c >= 'A' && c <= 'F')
1183 v = (v << 4) + c - 'A' + 10;
1184 else if (c >= 'a' && c <= 'f')
1185 v = (v << 4) + c - 'a' + 10;
1191 case '0': case '1': case '2': case '3':
1192 case '4': case '5': case '6': case '7':
1195 if (c >= '0' && c <= '7') {
1199 if (c >= '0' && c <= '7') {
1209 if (c < 0x3f || c > 0x7a || c == 0x60)
1210 synerror("Bad escape sequence");
1211 if (c == '\\' && pgetc() != '\\')
1212 synerror("Bad escape sequence");
1220 n = c == 'U' ? 8 : 4;
1222 for (i = 0; i < n; i++) {
1224 if (c >= '0' && c <= '9')
1225 v = (v << 4) + c - '0';
1226 else if (c >= 'A' && c <= 'F')
1227 v = (v << 4) + c - 'A' + 10;
1228 else if (c >= 'a' && c <= 'f')
1229 v = (v << 4) + c - 'a' + 10;
1231 synerror("Bad escape sequence");
1233 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1234 synerror("Bad escape sequence");
1235 /* We really need iconv here. */
1236 if (initial_localeisutf8 && v > 127) {
1237 CHECKSTRSPACE(4, out);
1239 * We cannot use wctomb() as the locale may have
1243 USTPUTC(0xc0 | v >> 6, out);
1244 USTPUTC(0x80 | (v & 0x3f), out);
1246 } else if (v <= 0xffff) {
1247 USTPUTC(0xe0 | v >> 12, out);
1248 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1249 USTPUTC(0x80 | (v & 0x3f), out);
1251 } else if (v <= 0x10ffff) {
1252 USTPUTC(0xf0 | v >> 18, out);
1253 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1254 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1255 USTPUTC(0x80 | (v & 0x3f), out);
1263 synerror("Bad escape sequence");
1267 * We can't handle NUL bytes.
1268 * POSIX says we should skip till the closing quote.
1271 while ((c = pgetc()) != '\'') {
1275 synerror("Unterminated quoted string");
1280 if (SQSYNTAX[v] == CCTL)
1281 USTPUTC(CTLESC, out);
1288 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1289 * is not NULL, read a here document. In the latter case, eofmark is the
1290 * word which marks the end of the document and striptabs is true if
1291 * leading tabs should be stripped from the document. The argument firstc
1292 * is the first character of the input token or document.
1294 * Because C does not have internal subroutines, I have simulated them
1295 * using goto's to implement the subroutine linkage. The following macros
1296 * will run code that appears at the end of readtoken1.
1299 #define CHECKEND() {goto checkend; checkend_return:;}
1300 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
1301 #define PARSESUB() {goto parsesub; parsesub_return:;}
1302 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1305 readtoken1(int firstc, char const *initialsyntax, char *eofmark, int striptabs)
1310 char line[EOFMARKLEN + 1];
1311 struct nodelist *bqlist;
1316 struct tokenstate state_static[MAXNEST_static];
1317 int maxnest = MAXNEST_static;
1318 struct tokenstate *state = state_static;
1321 startlinno = plinno;
1326 state[level].syntax = initialsyntax;
1327 state[level].parenlevel = 0;
1328 state[level].category = TSTATE_TOP;
1331 loop: { /* for each line, until end of word */
1332 CHECKEND(); /* set c to PEOF if at end of here document */
1333 for (;;) { /* until end of line or end of word */
1334 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1336 synentry = state[level].syntax[c];
1339 case CNL: /* '\n' */
1340 if (state[level].syntax == BASESYNTAX)
1341 goto endword; /* exit outer loop */
1349 goto loop; /* continue outer loop */
1352 out = readcstyleesc(out);
1360 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1361 USTPUTC(CTLESC, out);
1364 case CBACK: /* backslash */
1369 } else if (c == '\n') {
1376 if (state[level].syntax == DQSYNTAX &&
1377 c != '\\' && c != '`' && c != '$' &&
1378 (c != '"' || (eofmark != NULL &&
1379 newvarnest == 0)) &&
1380 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1382 if ((eofmark == NULL ||
1384 state[level].syntax == BASESYNTAX)
1385 USTPUTC(CTLQUOTEMARK, out);
1386 if (SQSYNTAX[c] == CCTL)
1387 USTPUTC(CTLESC, out);
1389 if ((eofmark == NULL ||
1391 state[level].syntax == BASESYNTAX &&
1392 state[level].category == TSTATE_VAR_OLD)
1393 USTPUTC(CTLQUOTEEND, out);
1398 USTPUTC(CTLQUOTEMARK, out);
1399 state[level].syntax = SQSYNTAX;
1403 USTPUTC(CTLQUOTEMARK, out);
1404 state[level].syntax = DQSYNTAX;
1407 if (eofmark != NULL && newvarnest == 0)
1410 if (state[level].category == TSTATE_VAR_OLD)
1411 USTPUTC(CTLQUOTEEND, out);
1412 state[level].syntax = BASESYNTAX;
1416 case CVAR: /* '$' */
1417 PARSESUB(); /* parse substitution */
1419 case CENDVAR: /* '}' */
1421 ((state[level].category == TSTATE_VAR_OLD &&
1422 state[level].syntax ==
1423 state[level - 1].syntax) ||
1424 (state[level].category == TSTATE_VAR_NEW &&
1425 state[level].syntax == BASESYNTAX))) {
1426 if (state[level].category == TSTATE_VAR_NEW)
1429 USTPUTC(CTLENDVAR, out);
1434 case CLP: /* '(' in arithmetic */
1435 state[level].parenlevel++;
1438 case CRP: /* ')' in arithmetic */
1439 if (state[level].parenlevel > 0) {
1441 --state[level].parenlevel;
1443 if (pgetc() == ')') {
1445 state[level].category == TSTATE_ARITH) {
1447 USTPUTC(CTLENDARI, out);
1453 * (don't 2nd guess - no error)
1460 case CBQUOTE: /* '`' */
1461 out = parsebackq(out, &bqlist, 1,
1462 state[level].syntax == DQSYNTAX &&
1463 (eofmark == NULL || newvarnest > 0),
1464 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1467 goto endword; /* exit outer loop */
1472 goto endword; /* exit outer loop */
1479 if (state[level].syntax == ARISYNTAX)
1480 synerror("Missing '))'");
1481 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1482 synerror("Unterminated quoted string");
1483 if (state[level].category == TSTATE_VAR_OLD ||
1484 state[level].category == TSTATE_VAR_NEW) {
1485 startlinno = plinno;
1486 synerror("Missing '}'");
1488 if (state != state_static)
1489 parser_temp_free_upto(state);
1491 len = out - stackblock();
1493 if (eofmark == NULL) {
1494 if ((c == '>' || c == '<')
1497 && (*out == '\0' || is_digit(*out))) {
1499 return lasttoken = TREDIR;
1505 backquotelist = bqlist;
1506 grabstackblock(len);
1508 return lasttoken = TWORD;
1509 /* end of readtoken routine */
1513 * Check to see whether we are at the end of the here document. When this
1514 * is called, c is set to the first character of the next input line. If
1515 * we are at the end of the here document, this routine sets the c to PEOF.
1524 if (c == *eofmark) {
1525 if (pfgets(line, sizeof line) != NULL) {
1529 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1530 if ((*p == '\0' || *p == '\n') && *q == '\0') {
1534 needprompt = doprompt;
1537 pushstring(line, strlen(line), NULL);
1542 goto checkend_return;
1547 * Parse a redirection operator. The variable "out" points to a string
1548 * specifying the fd to be redirected. The variable "c" contains the
1549 * first character of the redirection operator.
1556 np = (union node *)stalloc(sizeof (struct nfile));
1565 np->type = NCLOBBER;
1570 } else { /* c == '<' */
1574 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1575 np = (union node *)stalloc(sizeof (struct nhere));
1579 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1581 if ((c = pgetc()) == '-') {
1582 heredoc->striptabs = 1;
1584 heredoc->striptabs = 0;
1587 } else if (c == '&')
1597 np->nfile.fd = digit_val(fd);
1599 goto parseredir_return;
1604 * Parse a substitution. At this point, we have read the dollar sign
1614 static const char types[] = "}-+?=";
1615 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1621 if (c == '(') { /* $(command) or $((arith)) */
1622 if (pgetc() == '(') {
1626 out = parsebackq(out, &bqlist, 0,
1627 state[level].syntax == DQSYNTAX &&
1628 (eofmark == NULL || newvarnest > 0),
1629 state[level].syntax == DQSYNTAX ||
1630 state[level].syntax == ARISYNTAX);
1632 } else if (c == '{' || is_name(c) || is_special(c)) {
1633 USTPUTC(CTLVAR, out);
1634 typeloc = out - stackblock();
1635 USTPUTC(VSNORMAL, out);
1644 if (!is_eof(c) && is_name(c)) {
1650 } while (!is_eof(c) && is_in_name(c));
1652 strncmp(out - length, "LINENO", length) == 0) {
1653 /* Replace the variable name with the
1654 * current line number. */
1657 linno -= funclinno - 1;
1658 snprintf(buf, sizeof(buf), "%d", linno);
1663 } else if (is_digit(c)) {
1664 if (bracketed_name) {
1668 } while (is_digit(c));
1673 } else if (is_special(c)) {
1676 if (subtype == 0 && c1 == '#') {
1678 if (strchr(types, c) == NULL && c != ':' &&
1679 c != '#' && c != '%')
1683 if (c1 != '}' && c == '}') {
1698 else if (c == '\n' || c == PEOF)
1699 synerror("Unexpected end of line in substitution");
1710 p = strchr(types, c);
1712 if (c == '\n' || c == PEOF)
1713 synerror("Unexpected end of line in substitution");
1719 subtype = p - types + VSNORMAL;
1725 subtype = c == '#' ? VSTRIMLEFT :
1735 } else if (subtype != VSERROR) {
1736 if (subtype == VSLENGTH && c != '}')
1741 if (state[level].syntax == DQSYNTAX ||
1742 state[level].syntax == ARISYNTAX)
1744 *(stackblock() + typeloc) = subtype | flags;
1745 if (subtype != VSNORMAL) {
1746 if (level + 1 >= maxnest) {
1748 if (state == state_static) {
1749 state = parser_temp_alloc(
1750 maxnest * sizeof(*state));
1751 memcpy(state, state_static,
1752 MAXNEST_static * sizeof(*state));
1754 state = parser_temp_realloc(state,
1755 maxnest * sizeof(*state));
1758 state[level].parenlevel = 0;
1759 if (subtype == VSMINUS || subtype == VSPLUS ||
1760 subtype == VSQUESTION || subtype == VSASSIGN) {
1762 * For operators that were in the Bourne shell,
1763 * inherit the double-quote state.
1765 state[level].syntax = state[level - 1].syntax;
1766 state[level].category = TSTATE_VAR_OLD;
1769 * The other operators take a pattern,
1770 * so go to BASESYNTAX.
1771 * Also, ' and " are now special, even
1772 * in here documents.
1774 state[level].syntax = BASESYNTAX;
1775 state[level].category = TSTATE_VAR_NEW;
1779 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1780 /* $'cstylequotes' */
1781 USTPUTC(CTLQUOTEMARK, out);
1782 state[level].syntax = SQSYNTAX;
1788 goto parsesub_return;
1793 * Parse an arithmetic expansion (indicate start of one and set state)
1797 if (level + 1 >= maxnest) {
1799 if (state == state_static) {
1800 state = parser_temp_alloc(
1801 maxnest * sizeof(*state));
1802 memcpy(state, state_static,
1803 MAXNEST_static * sizeof(*state));
1805 state = parser_temp_realloc(state,
1806 maxnest * sizeof(*state));
1809 state[level].syntax = ARISYNTAX;
1810 state[level].parenlevel = 0;
1811 state[level].category = TSTATE_ARITH;
1812 USTPUTC(CTLARI, out);
1813 if (state[level - 1].syntax == DQSYNTAX)
1817 goto parsearith_return;
1820 } /* end of readtoken */
1832 * Returns true if the text contains nothing to expand (no dollar signs
1837 noexpand(char *text)
1843 while ((c = *p++) != '\0') {
1844 if ( c == CTLQUOTEMARK)
1848 else if (BASESYNTAX[(int)c] == CCTL)
1856 * Return true if the argument is a legal variable name (a letter or
1857 * underscore followed by zero or more letters, underscores, and digits).
1861 goodname(const char *name)
1869 if (! is_in_name(*p))
1877 isassignment(const char *p)
1885 else if (!is_in_name(*p))
1893 * Called when an unexpected token is read during the parse. The argument
1894 * is the token that is expected, or -1 if more than one type of token can
1895 * occur at this point.
1899 synexpect(int token)
1904 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1905 tokname[lasttoken], tokname[token]);
1907 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1914 synerror(const char *msg)
1917 outfmt(out2, "%s: %d: ", commandname, startlinno);
1918 outfmt(out2, "Syntax error: %s\n", msg);
1919 error((char *)NULL);
1923 setprompt(int which)
1925 whichprompt = which;
1931 out2str(getprompt(NULL));
1937 * called by editline -- any expansions to the prompt
1938 * should be added here.
1941 getprompt(void *unused __unused)
1943 static char ps[PROMPTLEN];
1947 static char internal_error[] = "??";
1950 * Select prompt format.
1952 switch (whichprompt) {
1963 return internal_error;
1967 * Format prompt string.
1969 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1976 * \h specifies just the local hostname,
1977 * \H specifies fully-qualified hostname.
1982 gethostname(&ps[i], PROMPTLEN - i);
1983 /* Skip to end of hostname. */
1984 trim = (*fmt == 'h') ? '.' : '\0';
1985 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1990 * Working directory.
1992 * \W specifies just the final component,
1993 * \w specifies the entire path.
1997 pwd = lookupvar("PWD");
2001 *pwd == '/' && pwd[1] != '\0')
2002 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
2005 strlcpy(&ps[i], pwd, PROMPTLEN - i);
2006 /* Skip to end of path. */
2007 while (ps[i + 1] != '\0')
2014 * '$' for normal users, '#' for root.
2017 ps[i] = (geteuid() != 0) ? '$' : '#';
2028 * Emit unrecognized formats verbatim.
2046 struct jmploc jmploc;
2047 struct jmploc *const savehandler = handler;
2048 const int saveprompt = doprompt;
2049 struct parsefile *const savetopfile = getcurrentfile();
2050 struct parser_temp *const saveparser_temp = parser_temp;
2051 const char *result = NULL;
2053 if (!setjmp(jmploc.loc)) {
2056 setinputstring(ps, 1);
2058 readtoken1(pgetc(), DQSYNTAX, "\n\n", 0);
2059 if (backquotelist != NULL)
2060 error("Command substitution not allowed here");
2064 n.narg.text = wordtext;
2065 n.narg.backquote = backquotelist;
2067 expandarg(&n, NULL, 0);
2068 result = stackblock();
2071 handler = savehandler;
2072 doprompt = saveprompt;
2073 popfilesupto(savetopfile);
2074 if (parser_temp != saveparser_temp) {
2075 parser_temp_free_all();
2076 parser_temp = saveparser_temp;
2078 if (result != NULL) {
2080 } else if (exception == EXINT)