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 * 3. 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.
71 /* values of checkkwd variable */
76 /* values returned by readtoken */
82 struct heredoc *next; /* next here document in list */
83 union node *here; /* redirection node */
84 char *eofmark; /* string indicating end of input */
85 int striptabs; /* if set, strip leading tabs */
89 struct parser_temp *next;
94 static struct heredoc *heredoclist; /* list of here documents to read */
95 static int doprompt; /* if set, prompt the user */
96 static int needprompt; /* true if interactive and at start of line */
97 static int lasttoken; /* last token read */
98 static int tokpushback; /* last token pushed back */
99 static char *wordtext; /* text of last word returned by readtoken */
101 static struct nodelist *backquotelist;
102 static union node *redirnode;
103 static struct heredoc *heredoc;
104 static int quoteflag; /* set if (part of) last token was quoted */
105 static int startlinno; /* line # where last token started */
106 static int funclinno; /* line # where the current function started */
107 static struct parser_temp *parser_temp;
110 static union node *list(int);
111 static union node *andor(void);
112 static union node *pipeline(void);
113 static union node *command(void);
114 static union node *simplecmd(union node **, union node *);
115 static union node *makename(void);
116 static union node *makebinary(int type, union node *n1, union node *n2);
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, const char *, const char *, int);
123 static int noexpand(char *);
124 static void consumetoken(int);
125 static void synexpect(int) __dead2;
126 static void synerror(const char *) __dead2;
127 static void setprompt(int);
128 static int pgetc_linecont(void);
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;
724 TRACE(("Here document %d\n", n->type));
725 if (here->striptabs) {
726 while (*wordtext == '\t')
729 if (! noexpand(wordtext))
730 synerror("Illegal eof marker for << redirection");
732 here->eofmark = wordtext;
734 if (heredoclist == NULL)
737 for (p = heredoclist ; p->next ; p = p->next);
740 } else if (n->type == NTOFD || n->type == NFROMFD) {
741 fixredir(n, wordtext, 0);
743 n->nfile.fname = makename();
749 * Input any here documents.
755 struct heredoc *here;
758 while (heredoclist) {
760 heredoclist = here->next;
765 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
766 here->eofmark, here->striptabs);
768 here->here->nhere.doc = n;
788 int alreadyseen = tokpushback;
797 if (checkkwd & CHKNL) {
805 * check for keywords and aliases
807 if (t == TWORD && !quoteflag)
809 const char * const *pp;
811 if (checkkwd & CHKKWD)
812 for (pp = parsekwd; *pp; pp++) {
813 if (**pp == *wordtext && equal(*pp, wordtext))
815 lasttoken = t = pp - parsekwd + KWDOFFSET;
816 TRACE(("keyword %s recognized\n", tokname[t]));
820 if (checkkwd & CHKALIAS &&
821 (ap = lookupalias(wordtext, 1)) != NULL) {
822 pushstring(ap->val, strlen(ap->val), ap);
832 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
834 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
841 * Read the next input token.
842 * If the token is a word, we set backquotelist to the list of cmds in
843 * backquotes. We set quoteflag to true if any part of the word was
845 * If the token is TREDIR, then we set redirnode to a structure containing
847 * In all cases, the variable startlinno is set to the number of the line
848 * on which the token starts.
850 * [Change comment: here documents and internal procedures]
851 * [Readtoken shouldn't have any arguments. Perhaps we should make the
852 * word parsing code into a separate routine. In this case, readtoken
853 * doesn't need to have any internal procedures, but parseword does.
854 * We could also make parseoperator in essence the main routine, and
855 * have parseword (readtoken1?) handle both words and redirection.]
858 #define RETURN(token) return lasttoken = token
874 for (;;) { /* until token or start of word found */
880 while ((c = pgetc()) != '\n' && c != PEOF);
884 if (pgetc() == '\n') {
885 startlinno = ++plinno;
895 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
898 needprompt = doprompt;
903 if (pgetc_linecont() == '&')
908 if (pgetc_linecont() == '|')
913 c = pgetc_linecont();
930 #define MAXNEST_static 8
933 const char *syntax; /* *SYNTAX */
934 int parenlevel; /* levels of parentheses in arithmetic */
935 enum tokenstate_category
938 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
939 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
946 * Check to see whether we are at the end of the here document. When this
947 * is called, c is set to the first character of the next input line. If
948 * we are at the end of the here document, this routine sets the c to PEOF.
949 * The new value of c is returned.
953 checkend(int c, const char *eofmark, int striptabs)
963 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
965 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
969 needprompt = doprompt;
973 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
981 * Parse a redirection operator. The variable "out" points to a string
982 * specifying the fd to be redirected. The variable "c" contains the
983 * first character of the redirection operator.
987 parseredir(char *out, int c)
992 np = (union node *)stalloc(sizeof (struct nfile));
995 c = pgetc_linecont();
1001 np->type = NCLOBBER;
1006 } else { /* c == '<' */
1008 c = pgetc_linecont();
1010 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1011 np = (union node *)stalloc(sizeof (struct nhere));
1015 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1017 if ((c = pgetc_linecont()) == '-') {
1018 heredoc->striptabs = 1;
1020 heredoc->striptabs = 0;
1023 } else if (c == '&')
1033 np->nfile.fd = digit_val(fd);
1038 * Called to parse command substitutions.
1042 parsebackq(char *out, struct nodelist **pbqlist,
1043 int oldstyle, int dblquote, int quoted)
1045 struct nodelist **nlpp;
1048 struct jmploc jmploc;
1049 struct jmploc *const savehandler = handler;
1052 const int bq_startlinno = plinno;
1053 char *volatile ostr = NULL;
1054 struct parsefile *const savetopfile = getcurrentfile();
1055 struct heredoc *const saveheredoclist = heredoclist;
1056 struct heredoc *here;
1059 if (setjmp(jmploc.loc)) {
1060 popfilesupto(savetopfile);
1065 heredoclist = saveheredoclist;
1066 handler = savehandler;
1067 if (exception == EXERROR) {
1068 startlinno = bq_startlinno;
1069 synerror("Error in command substitution");
1071 longjmp(handler->loc, 1);
1074 savelen = out - stackblock();
1076 str = ckmalloc(savelen);
1077 memcpy(str, stackblock(), savelen);
1083 /* We must read until the closing backquote, giving special
1084 treatment to some slashes, and then push the string and
1085 reread it as input, interpreting it normally. */
1091 STARTSTACKSTR(oout);
1097 CHECKSTRSPACE(2, oout);
1098 c = pgetc_linecont();
1104 if (c != '\\' && c != '`' && c != '$'
1105 && (!dblquote || c != '"'))
1106 USTPUTC('\\', oout);
1111 needprompt = doprompt;
1115 startlinno = plinno;
1116 synerror("EOF in backquote substitution");
1124 USTPUTC('\0', oout);
1125 olen = oout - stackblock();
1127 ostr = ckmalloc(olen);
1128 memcpy(ostr, stackblock(), olen);
1129 setinputstring(ostr, 1);
1134 nlpp = &(*nlpp)->next;
1135 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1136 (*nlpp)->next = NULL;
1139 saveprompt = doprompt;
1146 if (peektoken() != TEOF)
1148 doprompt = saveprompt;
1155 * Start reading from old file again, ignoring any pushed back
1156 * tokens left from the backquote parsing
1162 CHECKSTRSPACE(savelen + 1, out);
1165 memcpy(out, str, savelen);
1166 STADJUST(savelen, out);
1174 here = saveheredoclist;
1176 while (here->next != NULL)
1178 here->next = heredoclist;
1179 heredoclist = saveheredoclist;
1181 handler = savehandler;
1184 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1186 USTPUTC(CTLBACKQ, out);
1192 * Called to parse a backslash escape sequence inside $'...'.
1193 * The backslash has already been read.
1196 readcstyleesc(char *out)
1203 synerror("Unterminated quoted string");
1216 case 'a': v = '\a'; break;
1217 case 'b': v = '\b'; break;
1218 case 'e': v = '\033'; break;
1219 case 'f': v = '\f'; break;
1220 case 'n': v = '\n'; break;
1221 case 'r': v = '\r'; break;
1222 case 't': v = '\t'; break;
1223 case 'v': v = '\v'; break;
1228 if (c >= '0' && c <= '9')
1229 v = (v << 4) + c - '0';
1230 else if (c >= 'A' && c <= 'F')
1231 v = (v << 4) + c - 'A' + 10;
1232 else if (c >= 'a' && c <= 'f')
1233 v = (v << 4) + c - 'a' + 10;
1239 case '0': case '1': case '2': case '3':
1240 case '4': case '5': case '6': case '7':
1243 if (c >= '0' && c <= '7') {
1247 if (c >= '0' && c <= '7') {
1257 if (c < 0x3f || c > 0x7a || c == 0x60)
1258 synerror("Bad escape sequence");
1259 if (c == '\\' && pgetc() != '\\')
1260 synerror("Bad escape sequence");
1268 n = c == 'U' ? 8 : 4;
1270 for (i = 0; i < n; i++) {
1272 if (c >= '0' && c <= '9')
1273 v = (v << 4) + c - '0';
1274 else if (c >= 'A' && c <= 'F')
1275 v = (v << 4) + c - 'A' + 10;
1276 else if (c >= 'a' && c <= 'f')
1277 v = (v << 4) + c - 'a' + 10;
1279 synerror("Bad escape sequence");
1281 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1282 synerror("Bad escape sequence");
1283 /* We really need iconv here. */
1284 if (initial_localeisutf8 && v > 127) {
1285 CHECKSTRSPACE(4, out);
1287 * We cannot use wctomb() as the locale may have
1291 USTPUTC(0xc0 | v >> 6, out);
1292 USTPUTC(0x80 | (v & 0x3f), out);
1294 } else if (v <= 0xffff) {
1295 USTPUTC(0xe0 | v >> 12, out);
1296 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1297 USTPUTC(0x80 | (v & 0x3f), out);
1299 } else if (v <= 0x10ffff) {
1300 USTPUTC(0xf0 | v >> 18, out);
1301 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1302 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1303 USTPUTC(0x80 | (v & 0x3f), out);
1311 synerror("Bad escape sequence");
1315 * We can't handle NUL bytes.
1316 * POSIX says we should skip till the closing quote.
1319 while ((c = pgetc()) != '\'') {
1323 synerror("Unterminated quoted string");
1335 if (SQSYNTAX[v] == CCTL)
1336 USTPUTC(CTLESC, out);
1343 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1344 * is not NULL, read a here document. In the latter case, eofmark is the
1345 * word which marks the end of the document and striptabs is true if
1346 * leading tabs should be stripped from the document. The argument firstc
1347 * is the first character of the input token or document.
1349 * Because C does not have internal subroutines, I have simulated them
1350 * using goto's to implement the subroutine linkage. The following macros
1351 * will run code that appears at the end of readtoken1.
1354 #define PARSESUB() {goto parsesub; parsesub_return:;}
1355 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1358 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1364 struct nodelist *bqlist;
1369 struct tokenstate state_static[MAXNEST_static];
1370 int maxnest = MAXNEST_static;
1371 struct tokenstate *state = state_static;
1374 startlinno = plinno;
1379 state[level].syntax = initialsyntax;
1380 state[level].parenlevel = 0;
1381 state[level].category = TSTATE_TOP;
1384 loop: { /* for each line, until end of word */
1386 /* set c to PEOF if at end of here document */
1387 c = checkend(c, eofmark, striptabs);
1388 for (;;) { /* until end of line or end of word */
1389 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1391 synentry = state[level].syntax[c];
1394 case CNL: /* '\n' */
1395 if (state[level].syntax == BASESYNTAX)
1396 goto endword; /* exit outer loop */
1404 goto loop; /* continue outer loop */
1407 out = readcstyleesc(out);
1415 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1416 USTPUTC(CTLESC, out);
1419 case CBACK: /* backslash */
1424 } else if (c == '\n') {
1431 if (state[level].syntax == DQSYNTAX &&
1432 c != '\\' && c != '`' && c != '$' &&
1433 (c != '"' || (eofmark != NULL &&
1434 newvarnest == 0)) &&
1435 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1437 if ((eofmark == NULL ||
1439 state[level].syntax == BASESYNTAX)
1440 USTPUTC(CTLQUOTEMARK, out);
1441 if (SQSYNTAX[c] == CCTL)
1442 USTPUTC(CTLESC, out);
1444 if ((eofmark == NULL ||
1446 state[level].syntax == BASESYNTAX &&
1447 state[level].category == TSTATE_VAR_OLD)
1448 USTPUTC(CTLQUOTEEND, out);
1453 USTPUTC(CTLQUOTEMARK, out);
1454 state[level].syntax = SQSYNTAX;
1458 USTPUTC(CTLQUOTEMARK, out);
1459 state[level].syntax = DQSYNTAX;
1462 if (eofmark != NULL && newvarnest == 0)
1465 if (state[level].category == TSTATE_VAR_OLD)
1466 USTPUTC(CTLQUOTEEND, out);
1467 state[level].syntax = BASESYNTAX;
1471 case CVAR: /* '$' */
1472 PARSESUB(); /* parse substitution */
1474 case CENDVAR: /* '}' */
1476 ((state[level].category == TSTATE_VAR_OLD &&
1477 state[level].syntax ==
1478 state[level - 1].syntax) ||
1479 (state[level].category == TSTATE_VAR_NEW &&
1480 state[level].syntax == BASESYNTAX))) {
1481 if (state[level].category == TSTATE_VAR_NEW)
1484 USTPUTC(CTLENDVAR, out);
1489 case CLP: /* '(' in arithmetic */
1490 state[level].parenlevel++;
1493 case CRP: /* ')' in arithmetic */
1494 if (state[level].parenlevel > 0) {
1496 --state[level].parenlevel;
1498 if (pgetc_linecont() == ')') {
1500 state[level].category == TSTATE_ARITH) {
1502 USTPUTC(CTLENDARI, out);
1508 * (don't 2nd guess - no error)
1515 case CBQUOTE: /* '`' */
1516 out = parsebackq(out, &bqlist, 1,
1517 state[level].syntax == DQSYNTAX &&
1518 (eofmark == NULL || newvarnest > 0),
1519 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1522 goto endword; /* exit outer loop */
1527 goto endword; /* exit outer loop */
1534 if (state[level].syntax == ARISYNTAX)
1535 synerror("Missing '))'");
1536 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1537 synerror("Unterminated quoted string");
1538 if (state[level].category == TSTATE_VAR_OLD ||
1539 state[level].category == TSTATE_VAR_NEW) {
1540 startlinno = plinno;
1541 synerror("Missing '}'");
1543 if (state != state_static)
1544 parser_temp_free_upto(state);
1546 len = out - stackblock();
1548 if (eofmark == NULL) {
1549 if ((c == '>' || c == '<')
1552 && (*out == '\0' || is_digit(*out))) {
1554 return lasttoken = TREDIR;
1560 backquotelist = bqlist;
1561 grabstackblock(len);
1563 return lasttoken = TWORD;
1564 /* end of readtoken routine */
1568 * Parse a substitution. At this point, we have read the dollar sign
1578 static const char types[] = "}-+?=";
1579 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1584 c = pgetc_linecont();
1585 if (c == '(') { /* $(command) or $((arith)) */
1586 if (pgetc_linecont() == '(') {
1590 out = parsebackq(out, &bqlist, 0,
1591 state[level].syntax == DQSYNTAX &&
1592 (eofmark == NULL || newvarnest > 0),
1593 state[level].syntax == DQSYNTAX ||
1594 state[level].syntax == ARISYNTAX);
1596 } else if (c == '{' || is_name(c) || is_special(c)) {
1597 USTPUTC(CTLVAR, out);
1598 typeloc = out - stackblock();
1599 USTPUTC(VSNORMAL, out);
1604 c = pgetc_linecont();
1608 if (!is_eof(c) && is_name(c)) {
1612 c = pgetc_linecont();
1614 } while (!is_eof(c) && is_in_name(c));
1616 strncmp(out - length, "LINENO", length) == 0) {
1617 /* Replace the variable name with the
1618 * current line number. */
1621 linno -= funclinno - 1;
1622 snprintf(buf, sizeof(buf), "%d", linno);
1627 } else if (is_digit(c)) {
1628 if (bracketed_name) {
1631 c = pgetc_linecont();
1632 } while (is_digit(c));
1635 c = pgetc_linecont();
1637 } else if (is_special(c)) {
1639 c = pgetc_linecont();
1640 if (subtype == 0 && c1 == '#') {
1642 if (strchr(types, c) == NULL && c != ':' &&
1643 c != '#' && c != '%')
1646 c = pgetc_linecont();
1647 if (c1 != '}' && c == '}') {
1662 else if (c == '\n' || c == PEOF)
1663 synerror("Unexpected end of line in substitution");
1671 c = pgetc_linecont();
1674 p = strchr(types, c);
1676 if (c == '\n' || c == PEOF)
1677 synerror("Unexpected end of line in substitution");
1683 subtype = p - types + VSNORMAL;
1689 subtype = c == '#' ? VSTRIMLEFT :
1691 c = pgetc_linecont();
1699 } else if (subtype != VSERROR) {
1700 if (subtype == VSLENGTH && c != '}')
1705 if (state[level].syntax == DQSYNTAX ||
1706 state[level].syntax == ARISYNTAX)
1708 *(stackblock() + typeloc) = subtype | flags;
1709 if (subtype != VSNORMAL) {
1710 if (level + 1 >= maxnest) {
1712 if (state == state_static) {
1713 state = parser_temp_alloc(
1714 maxnest * sizeof(*state));
1715 memcpy(state, state_static,
1716 MAXNEST_static * sizeof(*state));
1718 state = parser_temp_realloc(state,
1719 maxnest * sizeof(*state));
1722 state[level].parenlevel = 0;
1723 if (subtype == VSMINUS || subtype == VSPLUS ||
1724 subtype == VSQUESTION || subtype == VSASSIGN) {
1726 * For operators that were in the Bourne shell,
1727 * inherit the double-quote state.
1729 state[level].syntax = state[level - 1].syntax;
1730 state[level].category = TSTATE_VAR_OLD;
1733 * The other operators take a pattern,
1734 * so go to BASESYNTAX.
1735 * Also, ' and " are now special, even
1736 * in here documents.
1738 state[level].syntax = BASESYNTAX;
1739 state[level].category = TSTATE_VAR_NEW;
1743 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1744 /* $'cstylequotes' */
1745 USTPUTC(CTLQUOTEMARK, out);
1746 state[level].syntax = SQSYNTAX;
1752 goto parsesub_return;
1757 * Parse an arithmetic expansion (indicate start of one and set state)
1761 if (level + 1 >= maxnest) {
1763 if (state == state_static) {
1764 state = parser_temp_alloc(
1765 maxnest * sizeof(*state));
1766 memcpy(state, state_static,
1767 MAXNEST_static * sizeof(*state));
1769 state = parser_temp_realloc(state,
1770 maxnest * sizeof(*state));
1773 state[level].syntax = ARISYNTAX;
1774 state[level].parenlevel = 0;
1775 state[level].category = TSTATE_ARITH;
1776 USTPUTC(CTLARI, out);
1777 if (state[level - 1].syntax == DQSYNTAX)
1781 goto parsearith_return;
1784 } /* end of readtoken */
1788 * Returns true if the text contains nothing to expand (no dollar signs
1793 noexpand(char *text)
1799 while ((c = *p++) != '\0') {
1800 if ( c == CTLQUOTEMARK)
1804 else if (BASESYNTAX[(int)c] == CCTL)
1812 * Return true if the argument is a legal variable name (a letter or
1813 * underscore followed by zero or more letters, underscores, and digits).
1817 goodname(const char *name)
1825 if (! is_in_name(*p))
1833 isassignment(const char *p)
1841 else if (!is_in_name(*p))
1849 consumetoken(int token)
1851 if (readtoken() != token)
1857 * Called when an unexpected token is read during the parse. The argument
1858 * is the token that is expected, or -1 if more than one type of token can
1859 * occur at this point.
1863 synexpect(int token)
1868 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1869 tokname[lasttoken], tokname[token]);
1871 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1878 synerror(const char *msg)
1881 outfmt(out2, "%s: %d: ", commandname, startlinno);
1883 outfmt(out2, "%s: ", arg0);
1884 outfmt(out2, "Syntax error: %s\n", msg);
1885 error((char *)NULL);
1889 setprompt(int which)
1891 whichprompt = which;
1897 out2str(getprompt(NULL));
1903 pgetc_linecont(void)
1907 while ((c = pgetc_macro()) == '\\') {
1917 /* Allow the backslash to be pushed back. */
1918 pushstring("\\", 1, NULL);
1926 * called by editline -- any expansions to the prompt
1927 * should be added here.
1930 getprompt(void *unused __unused)
1932 static char ps[PROMPTLEN];
1936 static char internal_error[] = "??";
1939 * Select prompt format.
1941 switch (whichprompt) {
1952 return internal_error;
1956 * Format prompt string.
1958 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1965 * \h specifies just the local hostname,
1966 * \H specifies fully-qualified hostname.
1971 gethostname(&ps[i], PROMPTLEN - i);
1972 /* Skip to end of hostname. */
1973 trim = (*fmt == 'h') ? '.' : '\0';
1974 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1979 * Working directory.
1981 * \W specifies just the final component,
1982 * \w specifies the entire path.
1986 pwd = lookupvar("PWD");
1990 *pwd == '/' && pwd[1] != '\0')
1991 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
1994 strlcpy(&ps[i], pwd, PROMPTLEN - i);
1995 /* Skip to end of path. */
1996 while (ps[i + 1] != '\0')
2003 * '$' for normal users, '#' for root.
2006 ps[i] = (geteuid() != 0) ? '$' : '#';
2017 * Emit unrecognized formats verbatim.
2032 expandstr(const char *ps)
2035 struct jmploc jmploc;
2036 struct jmploc *const savehandler = handler;
2037 const int saveprompt = doprompt;
2038 struct parsefile *const savetopfile = getcurrentfile();
2039 struct parser_temp *const saveparser_temp = parser_temp;
2040 const char *result = NULL;
2042 if (!setjmp(jmploc.loc)) {
2045 setinputstring(ps, 1);
2047 readtoken1(pgetc(), DQSYNTAX, "", 0);
2048 if (backquotelist != NULL)
2049 error("Command substitution not allowed here");
2053 n.narg.text = wordtext;
2054 n.narg.backquote = backquotelist;
2056 expandarg(&n, NULL, 0);
2057 result = stackblock();
2060 handler = savehandler;
2061 doprompt = saveprompt;
2062 popfilesupto(savetopfile);
2063 if (parser_temp != saveparser_temp) {
2064 parser_temp_free_all();
2065 parser_temp = saveparser_temp;
2067 if (result != NULL) {
2069 } else if (exception == EXINT)