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 static int tokpushback; /* last token pushed back */
100 static char *wordtext; /* text of last word returned by readtoken */
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);
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 union node *makebinary(int type, union node *n1, union node *n2);
118 static void parsefname(void);
119 static void parseheredoc(void);
120 static int peektoken(void);
121 static int readtoken(void);
122 static int xxreadtoken(void);
123 static int readtoken1(int, const char *, const char *, int);
124 static int noexpand(char *);
125 static void consumetoken(int);
126 static void synexpect(int) __dead2;
127 static void synerror(const char *) __dead2;
128 static void setprompt(int);
132 parser_temp_alloc(size_t len)
134 struct parser_temp *t;
137 t = ckmalloc(sizeof(*t));
139 t->next = parser_temp;
141 t->data = ckmalloc(len);
148 parser_temp_realloc(void *ptr, size_t len)
150 struct parser_temp *t;
155 error("bug: parser_temp_realloc misused");
156 t->data = ckrealloc(t->data, len);
163 parser_temp_free_upto(void *ptr)
165 struct parser_temp *t;
169 while (parser_temp != NULL && !done) {
171 parser_temp = t->next;
172 done = t->data == ptr;
178 error("bug: parser_temp_free_upto misused");
183 parser_temp_free_all(void)
185 struct parser_temp *t;
188 while (parser_temp != NULL) {
190 parser_temp = t->next;
199 * Read and parse a command. Returns NEOF on end of file. (NULL is a
200 * valid parse tree indicating a blank line.)
204 parsecmd(int interact)
208 /* This assumes the parser is not re-entered,
209 * which could happen if we add command substitution on PS1/PS2.
211 parser_temp_free_all();
235 union node *ntop, *n1, *n2, *n3;
238 checkkwd = CHKNL | CHKKWD | CHKALIAS;
239 if (!nlflag && tokendlist[peektoken()])
245 if (tok == TBACKGND) {
246 if (n2 != NULL && n2->type == NPIPE) {
247 n2->npipe.backgnd = 1;
248 } else if (n2 != NULL && n2->type == NREDIR) {
251 n3 = (union node *)stalloc(sizeof (struct nredir));
254 n3->nredir.redirect = NULL;
260 else if (n1 == NULL) {
261 n1 = makebinary(NSEMI, ntop, n2);
265 n3 = makebinary(NSEMI, n1->nbinary.ch2, n2);
266 n1->nbinary.ch2 = n3;
279 } else if (tok == TEOF && nlflag) {
285 checkkwd = CHKNL | CHKKWD | CHKALIAS;
286 if (!nlflag && tokendlist[peektoken()])
293 pungetc(); /* push back EOF on input */
314 if ((t = readtoken()) == TAND) {
316 } else if (t == TOR) {
322 n = makebinary(t, n, pipeline());
331 union node *n1, *n2, *pipenode;
332 struct nodelist *lp, *prev;
336 checkkwd = CHKNL | CHKKWD | CHKALIAS;
337 TRACE(("pipeline: entered\n"));
338 while (readtoken() == TNOT)
342 if (readtoken() == TPIPE) {
343 pipenode = (union node *)stalloc(sizeof (struct npipe));
344 pipenode->type = NPIPE;
345 pipenode->npipe.backgnd = 0;
346 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
347 pipenode->npipe.cmdlist = lp;
351 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
352 checkkwd = CHKNL | CHKKWD | CHKALIAS;
360 } while (readtoken() == TPIPE);
366 n2 = (union node *)stalloc(sizeof (struct nnot));
380 union node *ap, **app;
381 union node *cp, **cpp;
382 union node *redir, **rpp;
386 checkkwd = CHKNL | CHKKWD | CHKALIAS;
392 /* Check for redirection which may precede command */
393 while (readtoken() == TREDIR) {
394 *rpp = n2 = redirnode;
395 rpp = &n2->nfile.next;
400 switch (readtoken()) {
402 n1 = (union node *)stalloc(sizeof (struct nif));
404 if ((n1->nif.test = list(0)) == NULL)
407 n1->nif.ifpart = list(0);
409 while (readtoken() == TELIF) {
410 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
411 n2 = n2->nif.elsepart;
413 if ((n2->nif.test = list(0)) == NULL)
416 n2->nif.ifpart = list(0);
418 if (lasttoken == TELSE)
419 n2->nif.elsepart = list(0);
421 n2->nif.elsepart = NULL;
425 checkkwd = CHKKWD | CHKALIAS;
430 if ((n1 = list(0)) == NULL)
433 n1 = makebinary((t == TWHILE)? NWHILE : NUNTIL, n1, list(0));
435 checkkwd = CHKKWD | CHKALIAS;
438 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
439 synerror("Bad for loop variable");
440 n1 = (union node *)stalloc(sizeof (struct nfor));
442 n1->nfor.var = wordtext;
443 while (readtoken() == TNL)
445 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
447 while (readtoken() == TWORD) {
450 app = &n2->narg.next;
454 if (lasttoken != TNL && lasttoken != TSEMI)
457 static char argvars[5] = {
458 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
460 n2 = (union node *)stalloc(sizeof (struct narg));
462 n2->narg.text = argvars;
463 n2->narg.backquote = NULL;
464 n2->narg.next = NULL;
467 * Newline or semicolon here is optional (but note
468 * that the original Bourne shell only allowed NL).
470 if (lasttoken != TNL && lasttoken != TSEMI)
473 checkkwd = CHKNL | CHKKWD | CHKALIAS;
474 if ((t = readtoken()) == TDO)
476 else if (t == TBEGIN)
480 n1->nfor.body = list(0);
482 checkkwd = CHKKWD | CHKALIAS;
485 n1 = (union node *)stalloc(sizeof (struct ncase));
488 n1->ncase.expr = makename();
489 while (readtoken() == TNL);
490 if (lasttoken != TWORD || ! equal(wordtext, "in"))
491 synerror("expecting \"in\"");
492 cpp = &n1->ncase.cases;
493 checkkwd = CHKNL | CHKKWD, readtoken();
494 while (lasttoken != TESAC) {
495 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
497 app = &cp->nclist.pattern;
498 if (lasttoken == TLP)
501 *app = ap = makename();
502 checkkwd = CHKNL | CHKKWD;
503 if (readtoken() != TPIPE)
505 app = &ap->narg.next;
508 ap->narg.next = NULL;
509 if (lasttoken != TRP)
511 cp->nclist.body = list(0);
513 checkkwd = CHKNL | CHKKWD | CHKALIAS;
514 if ((t = readtoken()) != TESAC) {
517 else if (t == TFALLTHRU)
518 cp->type = NCLISTFALLTHRU;
521 checkkwd = CHKNL | CHKKWD, readtoken();
523 cpp = &cp->nclist.next;
526 checkkwd = CHKKWD | CHKALIAS;
529 n1 = (union node *)stalloc(sizeof (struct nredir));
530 n1->type = NSUBSHELL;
531 n1->nredir.n = list(0);
532 n1->nredir.redirect = NULL;
534 checkkwd = CHKKWD | CHKALIAS;
540 checkkwd = CHKKWD | CHKALIAS;
542 /* A simple command must have at least one redirection or word. */
557 n1 = simplecmd(rpp, redir);
563 /* Now check for redirection which may follow command */
564 while (readtoken() == TREDIR) {
565 *rpp = n2 = redirnode;
566 rpp = &n2->nfile.next;
573 n2 = (union node *)stalloc(sizeof (struct nredir));
578 n1->nredir.redirect = redir;
586 simplecmd(union node **rpp, union node *redir)
588 union node *args, **app;
589 union node **orig_rpp = rpp;
590 union node *n = NULL;
594 /* If we don't have any redirections already, then we must reset */
595 /* rpp to be the address of the local redir variable. */
602 * We save the incoming value, because we need this for shell
603 * functions. There can not be a redirect or an argument between
604 * the function name and the open parenthesis.
608 savecheckkwd = CHKALIAS;
611 checkkwd = savecheckkwd;
612 if (readtoken() == TWORD) {
616 if (savecheckkwd != 0 && !isassignment(wordtext))
618 } else if (lasttoken == TREDIR) {
619 *rpp = n = redirnode;
620 rpp = &n->nfile.next;
621 parsefname(); /* read name of redirection file */
622 } else if (lasttoken == TLP && app == &args->narg.next
623 && rpp == orig_rpp) {
624 /* We have a function */
628 * - Require plain text.
629 * - Functions with '/' cannot be called.
631 * - Reject ksh extended glob patterns.
633 if (!noexpand(n->narg.text) || quoteflag ||
634 strchr(n->narg.text, '/') ||
636 n->narg.text[strlen(n->narg.text) - 1]))
637 synerror("Bad function name");
638 rmescapes(n->narg.text);
639 if (find_builtin(n->narg.text, &special) >= 0 &&
641 synerror("Cannot override a special builtin with a function");
643 n->narg.next = command();
653 n = (union node *)stalloc(sizeof (struct ncmd));
656 n->ncmd.redirect = redir;
665 n = (union node *)stalloc(sizeof (struct narg));
668 n->narg.text = wordtext;
669 n->narg.backquote = backquotelist;
674 makebinary(int type, union node *n1, union node *n2)
678 n = (union node *)stalloc(sizeof (struct nbinary));
688 checkkwd |= CHKALIAS;
692 fixredir(union node *n, const char *text, int err)
694 TRACE(("Fix redir %s %d\n", text, err));
696 n->ndup.vname = NULL;
698 if (is_digit(text[0]) && text[1] == '\0')
699 n->ndup.dupfd = digit_val(text[0]);
700 else if (text[0] == '-' && text[1] == '\0')
705 synerror("Bad fd number");
707 n->ndup.vname = makename();
715 union node *n = redirnode;
718 if (n->type == NHERE) {
719 struct heredoc *here = heredoc;
725 TRACE(("Here document %d\n", n->type));
726 if (here->striptabs) {
727 while (*wordtext == '\t')
730 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
731 synerror("Illegal eof marker for << redirection");
733 here->eofmark = wordtext;
735 if (heredoclist == NULL)
738 for (p = heredoclist ; p->next ; p = p->next);
741 } else if (n->type == NTOFD || n->type == NFROMFD) {
742 fixredir(n, wordtext, 0);
744 n->nfile.fname = makename();
750 * Input any here documents.
756 struct heredoc *here;
759 while (heredoclist) {
761 heredoclist = here->next;
766 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
767 here->eofmark, here->striptabs);
769 here->here->nhere.doc = n;
789 int alreadyseen = tokpushback;
798 if (checkkwd & CHKNL) {
806 * check for keywords and aliases
808 if (t == TWORD && !quoteflag)
810 const char * const *pp;
812 if (checkkwd & CHKKWD)
813 for (pp = parsekwd; *pp; pp++) {
814 if (**pp == *wordtext && equal(*pp, wordtext))
816 lasttoken = t = pp - parsekwd + KWDOFFSET;
817 TRACE(("keyword %s recognized\n", tokname[t]));
821 if (checkkwd & CHKALIAS &&
822 (ap = lookupalias(wordtext, 1)) != NULL) {
823 pushstring(ap->val, strlen(ap->val), ap);
833 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
835 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
842 * Read the next input token.
843 * If the token is a word, we set backquotelist to the list of cmds in
844 * backquotes. We set quoteflag to true if any part of the word was
846 * If the token is TREDIR, then we set redirnode to a structure containing
848 * In all cases, the variable startlinno is set to the number of the line
849 * on which the token starts.
851 * [Change comment: here documents and internal procedures]
852 * [Readtoken shouldn't have any arguments. Perhaps we should make the
853 * word parsing code into a separate routine. In this case, readtoken
854 * doesn't need to have any internal procedures, but parseword does.
855 * We could also make parseoperator in essence the main routine, and
856 * have parseword (readtoken1?) handle both words and redirection.]
859 #define RETURN(token) return lasttoken = token
875 for (;;) { /* until token or start of word found */
881 while ((c = pgetc()) != '\n' && c != PEOF);
885 if (pgetc() == '\n') {
886 startlinno = ++plinno;
897 needprompt = doprompt;
928 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
933 #define MAXNEST_static 8
936 const char *syntax; /* *SYNTAX */
937 int parenlevel; /* levels of parentheses in arithmetic */
938 enum tokenstate_category
941 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
942 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
949 * Called to parse command substitutions.
953 parsebackq(char *out, struct nodelist **pbqlist,
954 int oldstyle, int dblquote, int quoted)
956 struct nodelist **nlpp;
959 struct jmploc jmploc;
960 struct jmploc *const savehandler = handler;
963 const int bq_startlinno = plinno;
964 char *volatile ostr = NULL;
965 struct parsefile *const savetopfile = getcurrentfile();
966 struct heredoc *const saveheredoclist = heredoclist;
967 struct heredoc *here;
970 if (setjmp(jmploc.loc)) {
971 popfilesupto(savetopfile);
976 heredoclist = saveheredoclist;
977 handler = savehandler;
978 if (exception == EXERROR) {
979 startlinno = bq_startlinno;
980 synerror("Error in command substitution");
982 longjmp(handler->loc, 1);
985 savelen = out - stackblock();
987 str = ckmalloc(savelen);
988 memcpy(str, stackblock(), savelen);
994 /* We must read until the closing backquote, giving special
995 treatment to some slashes, and then push the string and
996 reread it as input, interpreting it normally. */
1002 STARTSTACKSTR(oout);
1008 CHECKSTRSPACE(2, oout);
1009 switch (c = pgetc()) {
1014 if ((c = pgetc()) == '\n') {
1021 * If eating a newline, avoid putting
1022 * the newline into the new character
1023 * stream (via the USTPUTC after the
1028 if (c != '\\' && c != '`' && c != '$'
1029 && (!dblquote || c != '"'))
1030 USTPUTC('\\', oout);
1035 needprompt = doprompt;
1039 startlinno = plinno;
1040 synerror("EOF in backquote substitution");
1049 USTPUTC('\0', oout);
1050 olen = oout - stackblock();
1052 ostr = ckmalloc(olen);
1053 memcpy(ostr, stackblock(), olen);
1054 setinputstring(ostr, 1);
1059 nlpp = &(*nlpp)->next;
1060 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1061 (*nlpp)->next = NULL;
1064 saveprompt = doprompt;
1071 if (peektoken() != TEOF)
1073 doprompt = saveprompt;
1080 * Start reading from old file again, ignoring any pushed back
1081 * tokens left from the backquote parsing
1087 CHECKSTRSPACE(savelen + 1, out);
1090 memcpy(out, str, savelen);
1091 STADJUST(savelen, out);
1099 here = saveheredoclist;
1101 while (here->next != NULL)
1103 here->next = heredoclist;
1104 heredoclist = saveheredoclist;
1106 handler = savehandler;
1109 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1111 USTPUTC(CTLBACKQ, out);
1117 * Called to parse a backslash escape sequence inside $'...'.
1118 * The backslash has already been read.
1121 readcstyleesc(char *out)
1128 synerror("Unterminated quoted string");
1141 case 'a': v = '\a'; break;
1142 case 'b': v = '\b'; break;
1143 case 'e': v = '\033'; break;
1144 case 'f': v = '\f'; break;
1145 case 'n': v = '\n'; break;
1146 case 'r': v = '\r'; break;
1147 case 't': v = '\t'; break;
1148 case 'v': v = '\v'; break;
1153 if (c >= '0' && c <= '9')
1154 v = (v << 4) + c - '0';
1155 else if (c >= 'A' && c <= 'F')
1156 v = (v << 4) + c - 'A' + 10;
1157 else if (c >= 'a' && c <= 'f')
1158 v = (v << 4) + c - 'a' + 10;
1164 case '0': case '1': case '2': case '3':
1165 case '4': case '5': case '6': case '7':
1168 if (c >= '0' && c <= '7') {
1172 if (c >= '0' && c <= '7') {
1182 if (c < 0x3f || c > 0x7a || c == 0x60)
1183 synerror("Bad escape sequence");
1184 if (c == '\\' && pgetc() != '\\')
1185 synerror("Bad escape sequence");
1193 n = c == 'U' ? 8 : 4;
1195 for (i = 0; i < n; i++) {
1197 if (c >= '0' && c <= '9')
1198 v = (v << 4) + c - '0';
1199 else if (c >= 'A' && c <= 'F')
1200 v = (v << 4) + c - 'A' + 10;
1201 else if (c >= 'a' && c <= 'f')
1202 v = (v << 4) + c - 'a' + 10;
1204 synerror("Bad escape sequence");
1206 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1207 synerror("Bad escape sequence");
1208 /* We really need iconv here. */
1209 if (initial_localeisutf8 && v > 127) {
1210 CHECKSTRSPACE(4, out);
1212 * We cannot use wctomb() as the locale may have
1216 USTPUTC(0xc0 | v >> 6, out);
1217 USTPUTC(0x80 | (v & 0x3f), out);
1219 } else if (v <= 0xffff) {
1220 USTPUTC(0xe0 | v >> 12, out);
1221 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1222 USTPUTC(0x80 | (v & 0x3f), out);
1224 } else if (v <= 0x10ffff) {
1225 USTPUTC(0xf0 | v >> 18, out);
1226 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1227 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1228 USTPUTC(0x80 | (v & 0x3f), out);
1236 synerror("Bad escape sequence");
1240 * We can't handle NUL bytes.
1241 * POSIX says we should skip till the closing quote.
1244 while ((c = pgetc()) != '\'') {
1248 synerror("Unterminated quoted string");
1253 if (SQSYNTAX[v] == CCTL)
1254 USTPUTC(CTLESC, out);
1261 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1262 * is not NULL, read a here document. In the latter case, eofmark is the
1263 * word which marks the end of the document and striptabs is true if
1264 * leading tabs should be stripped from the document. The argument firstc
1265 * is the first character of the input token or document.
1267 * Because C does not have internal subroutines, I have simulated them
1268 * using goto's to implement the subroutine linkage. The following macros
1269 * will run code that appears at the end of readtoken1.
1272 #define CHECKEND() {goto checkend; checkend_return:;}
1273 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
1274 #define PARSESUB() {goto parsesub; parsesub_return:;}
1275 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1278 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1284 char line[EOFMARKLEN + 1];
1285 struct nodelist *bqlist;
1290 struct tokenstate state_static[MAXNEST_static];
1291 int maxnest = MAXNEST_static;
1292 struct tokenstate *state = state_static;
1295 startlinno = plinno;
1300 state[level].syntax = initialsyntax;
1301 state[level].parenlevel = 0;
1302 state[level].category = TSTATE_TOP;
1305 loop: { /* for each line, until end of word */
1306 CHECKEND(); /* set c to PEOF if at end of here document */
1307 for (;;) { /* until end of line or end of word */
1308 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1310 synentry = state[level].syntax[c];
1313 case CNL: /* '\n' */
1314 if (state[level].syntax == BASESYNTAX)
1315 goto endword; /* exit outer loop */
1323 goto loop; /* continue outer loop */
1326 out = readcstyleesc(out);
1334 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1335 USTPUTC(CTLESC, out);
1338 case CBACK: /* backslash */
1343 } else if (c == '\n') {
1350 if (state[level].syntax == DQSYNTAX &&
1351 c != '\\' && c != '`' && c != '$' &&
1352 (c != '"' || (eofmark != NULL &&
1353 newvarnest == 0)) &&
1354 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1356 if ((eofmark == NULL ||
1358 state[level].syntax == BASESYNTAX)
1359 USTPUTC(CTLQUOTEMARK, out);
1360 if (SQSYNTAX[c] == CCTL)
1361 USTPUTC(CTLESC, out);
1363 if ((eofmark == NULL ||
1365 state[level].syntax == BASESYNTAX &&
1366 state[level].category == TSTATE_VAR_OLD)
1367 USTPUTC(CTLQUOTEEND, out);
1372 USTPUTC(CTLQUOTEMARK, out);
1373 state[level].syntax = SQSYNTAX;
1377 USTPUTC(CTLQUOTEMARK, out);
1378 state[level].syntax = DQSYNTAX;
1381 if (eofmark != NULL && newvarnest == 0)
1384 if (state[level].category == TSTATE_VAR_OLD)
1385 USTPUTC(CTLQUOTEEND, out);
1386 state[level].syntax = BASESYNTAX;
1390 case CVAR: /* '$' */
1391 PARSESUB(); /* parse substitution */
1393 case CENDVAR: /* '}' */
1395 ((state[level].category == TSTATE_VAR_OLD &&
1396 state[level].syntax ==
1397 state[level - 1].syntax) ||
1398 (state[level].category == TSTATE_VAR_NEW &&
1399 state[level].syntax == BASESYNTAX))) {
1400 if (state[level].category == TSTATE_VAR_NEW)
1403 USTPUTC(CTLENDVAR, out);
1408 case CLP: /* '(' in arithmetic */
1409 state[level].parenlevel++;
1412 case CRP: /* ')' in arithmetic */
1413 if (state[level].parenlevel > 0) {
1415 --state[level].parenlevel;
1417 if (pgetc() == ')') {
1419 state[level].category == TSTATE_ARITH) {
1421 USTPUTC(CTLENDARI, out);
1427 * (don't 2nd guess - no error)
1434 case CBQUOTE: /* '`' */
1435 out = parsebackq(out, &bqlist, 1,
1436 state[level].syntax == DQSYNTAX &&
1437 (eofmark == NULL || newvarnest > 0),
1438 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1441 goto endword; /* exit outer loop */
1446 goto endword; /* exit outer loop */
1453 if (state[level].syntax == ARISYNTAX)
1454 synerror("Missing '))'");
1455 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1456 synerror("Unterminated quoted string");
1457 if (state[level].category == TSTATE_VAR_OLD ||
1458 state[level].category == TSTATE_VAR_NEW) {
1459 startlinno = plinno;
1460 synerror("Missing '}'");
1462 if (state != state_static)
1463 parser_temp_free_upto(state);
1465 len = out - stackblock();
1467 if (eofmark == NULL) {
1468 if ((c == '>' || c == '<')
1471 && (*out == '\0' || is_digit(*out))) {
1473 return lasttoken = TREDIR;
1479 backquotelist = bqlist;
1480 grabstackblock(len);
1482 return lasttoken = TWORD;
1483 /* end of readtoken routine */
1487 * Check to see whether we are at the end of the here document. When this
1488 * is called, c is set to the first character of the next input line. If
1489 * we are at the end of the here document, this routine sets the c to PEOF.
1498 if (c == *eofmark) {
1499 if (pfgets(line, sizeof line) != NULL) {
1503 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1504 if ((*p == '\0' || *p == '\n') && *q == '\0') {
1508 needprompt = doprompt;
1511 pushstring(line, strlen(line), NULL);
1516 goto checkend_return;
1521 * Parse a redirection operator. The variable "out" points to a string
1522 * specifying the fd to be redirected. The variable "c" contains the
1523 * first character of the redirection operator.
1530 np = (union node *)stalloc(sizeof (struct nfile));
1539 np->type = NCLOBBER;
1544 } else { /* c == '<' */
1548 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1549 np = (union node *)stalloc(sizeof (struct nhere));
1553 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1555 if ((c = pgetc()) == '-') {
1556 heredoc->striptabs = 1;
1558 heredoc->striptabs = 0;
1561 } else if (c == '&')
1571 np->nfile.fd = digit_val(fd);
1573 goto parseredir_return;
1578 * Parse a substitution. At this point, we have read the dollar sign
1588 static const char types[] = "}-+?=";
1589 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1595 if (c == '(') { /* $(command) or $((arith)) */
1596 if (pgetc() == '(') {
1600 out = parsebackq(out, &bqlist, 0,
1601 state[level].syntax == DQSYNTAX &&
1602 (eofmark == NULL || newvarnest > 0),
1603 state[level].syntax == DQSYNTAX ||
1604 state[level].syntax == ARISYNTAX);
1606 } else if (c == '{' || is_name(c) || is_special(c)) {
1607 USTPUTC(CTLVAR, out);
1608 typeloc = out - stackblock();
1609 USTPUTC(VSNORMAL, out);
1618 if (!is_eof(c) && is_name(c)) {
1624 } while (!is_eof(c) && is_in_name(c));
1626 strncmp(out - length, "LINENO", length) == 0) {
1627 /* Replace the variable name with the
1628 * current line number. */
1631 linno -= funclinno - 1;
1632 snprintf(buf, sizeof(buf), "%d", linno);
1637 } else if (is_digit(c)) {
1638 if (bracketed_name) {
1642 } while (is_digit(c));
1647 } else if (is_special(c)) {
1650 if (subtype == 0 && c1 == '#') {
1652 if (strchr(types, c) == NULL && c != ':' &&
1653 c != '#' && c != '%')
1657 if (c1 != '}' && c == '}') {
1672 else if (c == '\n' || c == PEOF)
1673 synerror("Unexpected end of line in substitution");
1684 p = strchr(types, c);
1686 if (c == '\n' || c == PEOF)
1687 synerror("Unexpected end of line in substitution");
1693 subtype = p - types + VSNORMAL;
1699 subtype = c == '#' ? VSTRIMLEFT :
1709 } else if (subtype != VSERROR) {
1710 if (subtype == VSLENGTH && c != '}')
1715 if (state[level].syntax == DQSYNTAX ||
1716 state[level].syntax == ARISYNTAX)
1718 *(stackblock() + typeloc) = subtype | flags;
1719 if (subtype != VSNORMAL) {
1720 if (level + 1 >= maxnest) {
1722 if (state == state_static) {
1723 state = parser_temp_alloc(
1724 maxnest * sizeof(*state));
1725 memcpy(state, state_static,
1726 MAXNEST_static * sizeof(*state));
1728 state = parser_temp_realloc(state,
1729 maxnest * sizeof(*state));
1732 state[level].parenlevel = 0;
1733 if (subtype == VSMINUS || subtype == VSPLUS ||
1734 subtype == VSQUESTION || subtype == VSASSIGN) {
1736 * For operators that were in the Bourne shell,
1737 * inherit the double-quote state.
1739 state[level].syntax = state[level - 1].syntax;
1740 state[level].category = TSTATE_VAR_OLD;
1743 * The other operators take a pattern,
1744 * so go to BASESYNTAX.
1745 * Also, ' and " are now special, even
1746 * in here documents.
1748 state[level].syntax = BASESYNTAX;
1749 state[level].category = TSTATE_VAR_NEW;
1753 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1754 /* $'cstylequotes' */
1755 USTPUTC(CTLQUOTEMARK, out);
1756 state[level].syntax = SQSYNTAX;
1762 goto parsesub_return;
1767 * Parse an arithmetic expansion (indicate start of one and set state)
1771 if (level + 1 >= maxnest) {
1773 if (state == state_static) {
1774 state = parser_temp_alloc(
1775 maxnest * sizeof(*state));
1776 memcpy(state, state_static,
1777 MAXNEST_static * sizeof(*state));
1779 state = parser_temp_realloc(state,
1780 maxnest * sizeof(*state));
1783 state[level].syntax = ARISYNTAX;
1784 state[level].parenlevel = 0;
1785 state[level].category = TSTATE_ARITH;
1786 USTPUTC(CTLARI, out);
1787 if (state[level - 1].syntax == DQSYNTAX)
1791 goto parsearith_return;
1794 } /* end of readtoken */
1798 * Returns true if the text contains nothing to expand (no dollar signs
1803 noexpand(char *text)
1809 while ((c = *p++) != '\0') {
1810 if ( c == CTLQUOTEMARK)
1814 else if (BASESYNTAX[(int)c] == CCTL)
1822 * Return true if the argument is a legal variable name (a letter or
1823 * underscore followed by zero or more letters, underscores, and digits).
1827 goodname(const char *name)
1835 if (! is_in_name(*p))
1843 isassignment(const char *p)
1851 else if (!is_in_name(*p))
1859 consumetoken(int token)
1861 if (readtoken() != token)
1867 * Called when an unexpected token is read during the parse. The argument
1868 * is the token that is expected, or -1 if more than one type of token can
1869 * occur at this point.
1873 synexpect(int token)
1878 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1879 tokname[lasttoken], tokname[token]);
1881 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1888 synerror(const char *msg)
1891 outfmt(out2, "%s: %d: ", commandname, startlinno);
1892 outfmt(out2, "Syntax error: %s\n", msg);
1893 error((char *)NULL);
1897 setprompt(int which)
1899 whichprompt = which;
1905 out2str(getprompt(NULL));
1911 * called by editline -- any expansions to the prompt
1912 * should be added here.
1915 getprompt(void *unused __unused)
1917 static char ps[PROMPTLEN];
1921 static char internal_error[] = "??";
1924 * Select prompt format.
1926 switch (whichprompt) {
1937 return internal_error;
1941 * Format prompt string.
1943 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1950 * \h specifies just the local hostname,
1951 * \H specifies fully-qualified hostname.
1956 gethostname(&ps[i], PROMPTLEN - i);
1957 /* Skip to end of hostname. */
1958 trim = (*fmt == 'h') ? '.' : '\0';
1959 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1964 * Working directory.
1966 * \W specifies just the final component,
1967 * \w specifies the entire path.
1971 pwd = lookupvar("PWD");
1975 *pwd == '/' && pwd[1] != '\0')
1976 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
1979 strlcpy(&ps[i], pwd, PROMPTLEN - i);
1980 /* Skip to end of path. */
1981 while (ps[i + 1] != '\0')
1988 * '$' for normal users, '#' for root.
1991 ps[i] = (geteuid() != 0) ? '$' : '#';
2002 * Emit unrecognized formats verbatim.
2017 expandstr(const char *ps)
2020 struct jmploc jmploc;
2021 struct jmploc *const savehandler = handler;
2022 const int saveprompt = doprompt;
2023 struct parsefile *const savetopfile = getcurrentfile();
2024 struct parser_temp *const saveparser_temp = parser_temp;
2025 const char *result = NULL;
2027 if (!setjmp(jmploc.loc)) {
2030 setinputstring(ps, 1);
2032 readtoken1(pgetc(), DQSYNTAX, "\n\n", 0);
2033 if (backquotelist != NULL)
2034 error("Command substitution not allowed here");
2038 n.narg.text = wordtext;
2039 n.narg.backquote = backquotelist;
2041 expandarg(&n, NULL, 0);
2042 result = stackblock();
2045 handler = savehandler;
2046 doprompt = saveprompt;
2047 popfilesupto(savetopfile);
2048 if (parser_temp != saveparser_temp) {
2049 parser_temp_free_all();
2050 parser_temp = saveparser_temp;
2052 if (result != NULL) {
2054 } else if (exception == EXINT)