2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 static char sccsid[] = "@(#)parser.c 8.7 (Berkeley) 5/16/95";
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
43 #include <sys/param.h>
52 #include "expand.h" /* defines rmescapes() */
64 #include "exec.h" /* to check for special builtins */
66 #include "myhistedit.h"
70 * Shell command parser.
75 /* values of checkkwd variable */
80 /* values returned by readtoken */
86 struct heredoc *next; /* next here document in list */
87 union node *here; /* redirection node */
88 char *eofmark; /* string indicating end of input */
89 int striptabs; /* if set, strip leading tabs */
93 struct parser_temp *next;
98 static struct heredoc *heredoclist; /* list of here documents to read */
99 static int doprompt; /* if set, prompt the user */
100 static int needprompt; /* true if interactive and at start of line */
101 static int lasttoken; /* last token read */
102 static int tokpushback; /* last token pushed back */
103 static char *wordtext; /* text of last word returned by readtoken */
105 static struct nodelist *backquotelist;
106 static union node *redirnode;
107 static struct heredoc *heredoc;
108 static int quoteflag; /* set if (part of) last token was quoted */
109 static int startlinno; /* line # where last token started */
110 static int funclinno; /* line # where the current function started */
111 static struct parser_temp *parser_temp;
113 #define NOEOFMARK ((const char *)&heredoclist)
116 static union node *list(int);
117 static union node *andor(void);
118 static union node *pipeline(void);
119 static union node *command(void);
120 static union node *simplecmd(union node **, union node *);
121 static union node *makename(void);
122 static union node *makebinary(int type, union node *n1, union node *n2);
123 static void parsefname(void);
124 static void parseheredoc(void);
125 static int peektoken(void);
126 static int readtoken(void);
127 static int xxreadtoken(void);
128 static int readtoken1(int, const char *, const char *, int);
129 static int noexpand(char *);
130 static void consumetoken(int);
131 static void synexpect(int) __dead2;
132 static void synerror(const char *) __dead2;
133 static void setprompt(int);
134 static int pgetc_linecont(void);
135 static void getusername(char *, size_t);
139 parser_temp_alloc(size_t len)
141 struct parser_temp *t;
144 t = ckmalloc(sizeof(*t));
146 t->next = parser_temp;
148 t->data = ckmalloc(len);
155 parser_temp_realloc(void *ptr, size_t len)
157 struct parser_temp *t;
162 error("bug: parser_temp_realloc misused");
163 t->data = ckrealloc(t->data, len);
170 parser_temp_free_upto(void *ptr)
172 struct parser_temp *t;
176 while (parser_temp != NULL && !done) {
178 parser_temp = t->next;
179 done = t->data == ptr;
185 error("bug: parser_temp_free_upto misused");
190 parser_temp_free_all(void)
192 struct parser_temp *t;
195 while (parser_temp != NULL) {
197 parser_temp = t->next;
206 * Read and parse a command. Returns NEOF on end of file. (NULL is a
207 * valid parse tree indicating a blank line.)
211 parsecmd(int interact)
215 /* This assumes the parser is not re-entered,
216 * which could happen if we add command substitution on PS1/PS2.
218 parser_temp_free_all();
240 * Read and parse words for wordexp.
241 * Returns a list of NARG nodes; NULL if there are no words.
246 union node *n, *first = NULL, **pnext;
249 /* This assumes the parser is not re-entered,
250 * which could happen if we add command substitution on PS1/PS2.
252 parser_temp_free_all();
261 while ((t = readtoken()) != TEOF) {
266 pnext = &n->narg.next;
275 union node *ntop, *n1, *n2, *n3;
278 checkkwd = CHKNL | CHKKWD | CHKALIAS;
279 if (!nlflag && tokendlist[peektoken()])
285 if (tok == TBACKGND) {
286 if (n2 != NULL && n2->type == NPIPE) {
287 n2->npipe.backgnd = 1;
288 } else if (n2 != NULL && n2->type == NREDIR) {
291 n3 = (union node *)stalloc(sizeof (struct nredir));
294 n3->nredir.redirect = NULL;
300 else if (n1 == NULL) {
301 n1 = makebinary(NSEMI, ntop, n2);
305 n3 = makebinary(NSEMI, n1->nbinary.ch2, n2);
306 n1->nbinary.ch2 = n3;
319 } else if (tok == TEOF && nlflag) {
325 checkkwd = CHKNL | CHKKWD | CHKALIAS;
326 if (!nlflag && tokendlist[peektoken()])
333 pungetc(); /* push back EOF on input */
354 if ((t = readtoken()) == TAND) {
356 } else if (t == TOR) {
362 n = makebinary(t, n, pipeline());
371 union node *n1, *n2, *pipenode;
372 struct nodelist *lp, *prev;
376 checkkwd = CHKNL | CHKKWD | CHKALIAS;
377 TRACE(("pipeline: entered\n"));
378 while (readtoken() == TNOT)
382 if (readtoken() == TPIPE) {
383 pipenode = (union node *)stalloc(sizeof (struct npipe));
384 pipenode->type = NPIPE;
385 pipenode->npipe.backgnd = 0;
386 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
387 pipenode->npipe.cmdlist = lp;
391 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
392 checkkwd = CHKNL | CHKKWD | CHKALIAS;
400 } while (readtoken() == TPIPE);
406 n2 = (union node *)stalloc(sizeof (struct nnot));
420 union node *ap, **app;
421 union node *cp, **cpp;
422 union node *redir, **rpp;
426 checkkwd = CHKNL | CHKKWD | CHKALIAS;
432 /* Check for redirection which may precede command */
433 while (readtoken() == TREDIR) {
434 *rpp = n2 = redirnode;
435 rpp = &n2->nfile.next;
440 switch (readtoken()) {
442 n1 = (union node *)stalloc(sizeof (struct nif));
444 if ((n1->nif.test = list(0)) == NULL)
447 n1->nif.ifpart = list(0);
449 while (readtoken() == TELIF) {
450 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
451 n2 = n2->nif.elsepart;
453 if ((n2->nif.test = list(0)) == NULL)
456 n2->nif.ifpart = list(0);
458 if (lasttoken == TELSE)
459 n2->nif.elsepart = list(0);
461 n2->nif.elsepart = NULL;
465 checkkwd = CHKKWD | CHKALIAS;
470 if ((n1 = list(0)) == NULL)
473 n1 = makebinary((t == TWHILE)? NWHILE : NUNTIL, n1, list(0));
475 checkkwd = CHKKWD | CHKALIAS;
478 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
479 synerror("Bad for loop variable");
480 n1 = (union node *)stalloc(sizeof (struct nfor));
482 n1->nfor.var = wordtext;
483 while (readtoken() == TNL)
485 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
487 while (readtoken() == TWORD) {
490 app = &n2->narg.next;
494 if (lasttoken != TNL && lasttoken != TSEMI)
497 static char argvars[5] = {
498 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
500 n2 = (union node *)stalloc(sizeof (struct narg));
502 n2->narg.text = argvars;
503 n2->narg.backquote = NULL;
504 n2->narg.next = NULL;
507 * Newline or semicolon here is optional (but note
508 * that the original Bourne shell only allowed NL).
510 if (lasttoken != TNL && lasttoken != TSEMI)
513 checkkwd = CHKNL | CHKKWD | CHKALIAS;
514 if ((t = readtoken()) == TDO)
516 else if (t == TBEGIN)
520 n1->nfor.body = list(0);
522 checkkwd = CHKKWD | CHKALIAS;
525 n1 = (union node *)stalloc(sizeof (struct ncase));
528 n1->ncase.expr = makename();
529 while (readtoken() == TNL);
530 if (lasttoken != TWORD || ! equal(wordtext, "in"))
531 synerror("expecting \"in\"");
532 cpp = &n1->ncase.cases;
533 checkkwd = CHKNL | CHKKWD, readtoken();
534 while (lasttoken != TESAC) {
535 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
537 app = &cp->nclist.pattern;
538 if (lasttoken == TLP)
541 *app = ap = makename();
542 checkkwd = CHKNL | CHKKWD;
543 if (readtoken() != TPIPE)
545 app = &ap->narg.next;
548 ap->narg.next = NULL;
549 if (lasttoken != TRP)
551 cp->nclist.body = list(0);
553 checkkwd = CHKNL | CHKKWD | CHKALIAS;
554 if ((t = readtoken()) != TESAC) {
557 else if (t == TFALLTHRU)
558 cp->type = NCLISTFALLTHRU;
561 checkkwd = CHKNL | CHKKWD, readtoken();
563 cpp = &cp->nclist.next;
566 checkkwd = CHKKWD | CHKALIAS;
569 n1 = (union node *)stalloc(sizeof (struct nredir));
570 n1->type = NSUBSHELL;
571 n1->nredir.n = list(0);
572 n1->nredir.redirect = NULL;
574 checkkwd = CHKKWD | CHKALIAS;
580 checkkwd = CHKKWD | CHKALIAS;
582 /* A simple command must have at least one redirection or word. */
597 n1 = simplecmd(rpp, redir);
603 /* Now check for redirection which may follow command */
604 while (readtoken() == TREDIR) {
605 *rpp = n2 = redirnode;
606 rpp = &n2->nfile.next;
613 n2 = (union node *)stalloc(sizeof (struct nredir));
618 n1->nredir.redirect = redir;
626 simplecmd(union node **rpp, union node *redir)
628 union node *args, **app;
629 union node **orig_rpp = rpp;
630 union node *n = NULL;
634 /* If we don't have any redirections already, then we must reset */
635 /* rpp to be the address of the local redir variable. */
642 * We save the incoming value, because we need this for shell
643 * functions. There can not be a redirect or an argument between
644 * the function name and the open parenthesis.
648 savecheckkwd = CHKALIAS;
651 checkkwd = savecheckkwd;
652 if (readtoken() == TWORD) {
656 if (savecheckkwd != 0 && !isassignment(wordtext))
658 } else if (lasttoken == TREDIR) {
659 *rpp = n = redirnode;
660 rpp = &n->nfile.next;
661 parsefname(); /* read name of redirection file */
662 } else if (lasttoken == TLP && app == &args->narg.next
663 && rpp == orig_rpp) {
664 /* We have a function */
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 makebinary(int type, union node *n1, union node *n2)
718 n = (union node *)stalloc(sizeof (struct nbinary));
728 checkkwd |= CHKALIAS;
732 fixredir(union node *n, const char *text, int err)
734 TRACE(("Fix redir %s %d\n", text, err));
736 n->ndup.vname = NULL;
738 if (is_digit(text[0]) && text[1] == '\0')
739 n->ndup.dupfd = digit_val(text[0]);
740 else if (text[0] == '-' && text[1] == '\0')
745 synerror("Bad fd number");
747 n->ndup.vname = makename();
755 union node *n = redirnode;
758 if (n->type == NHERE) {
759 struct heredoc *here = heredoc;
764 TRACE(("Here document %d\n", n->type));
765 if (here->striptabs) {
766 while (*wordtext == '\t')
769 if (! noexpand(wordtext))
770 synerror("Illegal eof marker for << redirection");
772 here->eofmark = wordtext;
774 if (heredoclist == NULL)
777 for (p = heredoclist ; p->next ; p = p->next);
780 } else if (n->type == NTOFD || n->type == NFROMFD) {
781 fixredir(n, wordtext, 0);
783 n->nfile.fname = makename();
789 * Input any here documents.
795 struct heredoc *here;
798 while (heredoclist) {
800 heredoclist = here->next;
805 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
806 here->eofmark, here->striptabs);
808 here->here->nhere.doc = n;
828 int alreadyseen = tokpushback;
837 if (checkkwd & CHKNL) {
845 * check for keywords and aliases
847 if (t == TWORD && !quoteflag)
849 const char * const *pp;
851 if (checkkwd & CHKKWD)
852 for (pp = parsekwd; *pp; pp++) {
853 if (**pp == *wordtext && equal(*pp, wordtext))
855 lasttoken = t = pp - parsekwd + KWDOFFSET;
856 TRACE(("keyword %s recognized\n", tokname[t]));
860 if (checkkwd & CHKALIAS &&
861 (ap = lookupalias(wordtext, 1)) != NULL) {
862 pushstring(ap->val, strlen(ap->val), ap);
872 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
874 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
881 * Read the next input token.
882 * If the token is a word, we set backquotelist to the list of cmds in
883 * backquotes. We set quoteflag to true if any part of the word was
885 * If the token is TREDIR, then we set redirnode to a structure containing
887 * In all cases, the variable startlinno is set to the number of the line
888 * on which the token starts.
890 * [Change comment: here documents and internal procedures]
891 * [Readtoken shouldn't have any arguments. Perhaps we should make the
892 * word parsing code into a separate routine. In this case, readtoken
893 * doesn't need to have any internal procedures, but parseword does.
894 * We could also make parseoperator in essence the main routine, and
895 * have parseword (readtoken1?) handle both words and redirection.]
898 #define RETURN(token) return lasttoken = token
914 for (;;) { /* until token or start of word found */
920 while ((c = pgetc()) != '\n' && c != PEOF);
924 if (pgetc() == '\n') {
925 startlinno = ++plinno;
935 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
938 needprompt = doprompt;
943 if (pgetc_linecont() == '&')
948 if (pgetc_linecont() == '|')
953 c = pgetc_linecont();
970 #define MAXNEST_static 8
973 const char *syntax; /* *SYNTAX */
974 int parenlevel; /* levels of parentheses in arithmetic */
975 enum tokenstate_category
978 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
979 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
986 * Check to see whether we are at the end of the here document. When this
987 * is called, c is set to the first character of the next input line. If
988 * we are at the end of the here document, this routine sets the c to PEOF.
989 * The new value of c is returned.
993 checkend(int c, const char *eofmark, int striptabs)
1003 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
1005 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
1009 needprompt = doprompt;
1013 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
1015 } else if (c == '\n' && *eofmark == '\0') {
1018 needprompt = doprompt;
1025 * Parse a redirection operator. The variable "out" points to a string
1026 * specifying the fd to be redirected. The variable "c" contains the
1027 * first character of the redirection operator.
1031 parseredir(char *out, int c)
1036 np = (union node *)stalloc(sizeof (struct nfile));
1039 c = pgetc_linecont();
1045 np->type = NCLOBBER;
1050 } else { /* c == '<' */
1052 c = pgetc_linecont();
1054 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1055 np = (union node *)stalloc(sizeof (struct nhere));
1059 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1061 if ((c = pgetc_linecont()) == '-') {
1062 heredoc->striptabs = 1;
1064 heredoc->striptabs = 0;
1067 } else if (c == '&')
1077 np->nfile.fd = digit_val(fd);
1082 * Called to parse command substitutions.
1086 parsebackq(char *out, struct nodelist **pbqlist,
1087 int oldstyle, int dblquote, int quoted)
1089 struct nodelist **nlpp;
1092 struct jmploc jmploc;
1093 struct jmploc *const savehandler = handler;
1096 const int bq_startlinno = plinno;
1097 char *volatile ostr = NULL;
1098 struct parsefile *const savetopfile = getcurrentfile();
1099 struct heredoc *const saveheredoclist = heredoclist;
1100 struct heredoc *here;
1103 if (setjmp(jmploc.loc)) {
1104 popfilesupto(savetopfile);
1109 heredoclist = saveheredoclist;
1110 handler = savehandler;
1111 if (exception == EXERROR) {
1112 startlinno = bq_startlinno;
1113 synerror("Error in command substitution");
1115 longjmp(handler->loc, 1);
1118 savelen = out - stackblock();
1120 str = ckmalloc(savelen);
1121 memcpy(str, stackblock(), savelen);
1127 /* We must read until the closing backquote, giving special
1128 treatment to some slashes, and then push the string and
1129 reread it as input, interpreting it normally. */
1135 STARTSTACKSTR(oout);
1141 CHECKSTRSPACE(2, oout);
1142 c = pgetc_linecont();
1148 if (c != '\\' && c != '`' && c != '$'
1149 && (!dblquote || c != '"'))
1150 USTPUTC('\\', oout);
1155 needprompt = doprompt;
1159 startlinno = plinno;
1160 synerror("EOF in backquote substitution");
1168 USTPUTC('\0', oout);
1169 olen = oout - stackblock();
1171 ostr = ckmalloc(olen);
1172 memcpy(ostr, stackblock(), olen);
1173 setinputstring(ostr, 1);
1178 nlpp = &(*nlpp)->next;
1179 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1180 (*nlpp)->next = NULL;
1183 saveprompt = doprompt;
1190 if (peektoken() != TEOF)
1192 doprompt = saveprompt;
1199 * Start reading from old file again, ignoring any pushed back
1200 * tokens left from the backquote parsing
1206 CHECKSTRSPACE(savelen + 1, out);
1209 memcpy(out, str, savelen);
1210 STADJUST(savelen, out);
1218 here = saveheredoclist;
1220 while (here->next != NULL)
1222 here->next = heredoclist;
1223 heredoclist = saveheredoclist;
1225 handler = savehandler;
1228 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1230 USTPUTC(CTLBACKQ, out);
1236 * Called to parse a backslash escape sequence inside $'...'.
1237 * The backslash has already been read.
1240 readcstyleesc(char *out)
1248 synerror("Unterminated quoted string");
1261 case 'a': v = '\a'; break;
1262 case 'b': v = '\b'; break;
1263 case 'e': v = '\033'; break;
1264 case 'f': v = '\f'; break;
1265 case 'n': v = '\n'; break;
1266 case 'r': v = '\r'; break;
1267 case 't': v = '\t'; break;
1268 case 'v': v = '\v'; break;
1273 if (c >= '0' && c <= '9')
1274 v = (v << 4) + c - '0';
1275 else if (c >= 'A' && c <= 'F')
1276 v = (v << 4) + c - 'A' + 10;
1277 else if (c >= 'a' && c <= 'f')
1278 v = (v << 4) + c - 'a' + 10;
1284 case '0': case '1': case '2': case '3':
1285 case '4': case '5': case '6': case '7':
1288 if (c >= '0' && c <= '7') {
1292 if (c >= '0' && c <= '7') {
1302 if (c < 0x3f || c > 0x7a || c == 0x60)
1303 synerror("Bad escape sequence");
1304 if (c == '\\' && pgetc() != '\\')
1305 synerror("Bad escape sequence");
1313 n = c == 'U' ? 8 : 4;
1315 for (i = 0; i < n; i++) {
1317 if (c >= '0' && c <= '9')
1318 v = (v << 4) + c - '0';
1319 else if (c >= 'A' && c <= 'F')
1320 v = (v << 4) + c - 'A' + 10;
1321 else if (c >= 'a' && c <= 'f')
1322 v = (v << 4) + c - 'a' + 10;
1324 synerror("Bad escape sequence");
1326 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1327 synerror("Bad escape sequence");
1328 /* We really need iconv here. */
1329 if (initial_localeisutf8 && v > 127) {
1330 CHECKSTRSPACE(4, out);
1332 * We cannot use wctomb() as the locale may have
1336 USTPUTC(0xc0 | v >> 6, out);
1337 USTPUTC(0x80 | (v & 0x3f), out);
1339 } else if (v <= 0xffff) {
1340 USTPUTC(0xe0 | v >> 12, out);
1341 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1342 USTPUTC(0x80 | (v & 0x3f), out);
1344 } else if (v <= 0x10ffff) {
1345 USTPUTC(0xf0 | v >> 18, out);
1346 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1347 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1348 USTPUTC(0x80 | (v & 0x3f), out);
1356 synerror("Bad escape sequence");
1360 * We can't handle NUL bytes.
1361 * POSIX says we should skip till the closing quote.
1364 while ((c = pgetc()) != '\'') {
1368 synerror("Unterminated quoted string");
1380 if (SQSYNTAX[vc] == CCTL)
1381 USTPUTC(CTLESC, out);
1388 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1389 * is not NULL, read a here document. In the latter case, eofmark is the
1390 * word which marks the end of the document and striptabs is true if
1391 * leading tabs should be stripped from the document. The argument firstc
1392 * is the first character of the input token or document.
1394 * Because C does not have internal subroutines, I have simulated them
1395 * using goto's to implement the subroutine linkage. The following macros
1396 * will run code that appears at the end of readtoken1.
1399 #define PARSESUB() {goto parsesub; parsesub_return:;}
1400 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1403 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1409 struct nodelist *bqlist;
1414 struct tokenstate state_static[MAXNEST_static];
1415 int maxnest = MAXNEST_static;
1416 struct tokenstate *state = state_static;
1419 startlinno = plinno;
1424 state[level].syntax = initialsyntax;
1425 state[level].parenlevel = 0;
1426 state[level].category = TSTATE_TOP;
1429 loop: { /* for each line, until end of word */
1430 if (eofmark && eofmark != NOEOFMARK)
1431 /* set c to PEOF if at end of here document */
1432 c = checkend(c, eofmark, striptabs);
1433 for (;;) { /* until end of line or end of word */
1434 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1436 synentry = state[level].syntax[c];
1439 case CNL: /* '\n' */
1441 goto endword; /* exit outer loop */
1451 goto loop; /* continue outer loop */
1454 out = readcstyleesc(out);
1462 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1463 USTPUTC(CTLESC, out);
1466 case CBACK: /* backslash */
1471 } else if (c == '\n') {
1478 if (state[level].syntax == DQSYNTAX &&
1479 c != '\\' && c != '`' && c != '$' &&
1480 (c != '"' || (eofmark != NULL &&
1481 newvarnest == 0)) &&
1482 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1484 if ((eofmark == NULL ||
1486 state[level].syntax == BASESYNTAX)
1487 USTPUTC(CTLQUOTEMARK, out);
1488 if (SQSYNTAX[c] == CCTL)
1489 USTPUTC(CTLESC, out);
1491 if ((eofmark == NULL ||
1493 state[level].syntax == BASESYNTAX &&
1494 state[level].category == TSTATE_VAR_OLD)
1495 USTPUTC(CTLQUOTEEND, out);
1500 USTPUTC(CTLQUOTEMARK, out);
1501 state[level].syntax = SQSYNTAX;
1505 USTPUTC(CTLQUOTEMARK, out);
1506 state[level].syntax = DQSYNTAX;
1509 if (eofmark != NULL && newvarnest == 0)
1512 if (state[level].category == TSTATE_VAR_OLD)
1513 USTPUTC(CTLQUOTEEND, out);
1514 state[level].syntax = BASESYNTAX;
1518 case CVAR: /* '$' */
1519 PARSESUB(); /* parse substitution */
1521 case CENDVAR: /* '}' */
1523 ((state[level].category == TSTATE_VAR_OLD &&
1524 state[level].syntax ==
1525 state[level - 1].syntax) ||
1526 (state[level].category == TSTATE_VAR_NEW &&
1527 state[level].syntax == BASESYNTAX))) {
1528 if (state[level].category == TSTATE_VAR_NEW)
1531 USTPUTC(CTLENDVAR, out);
1536 case CLP: /* '(' in arithmetic */
1537 state[level].parenlevel++;
1540 case CRP: /* ')' in arithmetic */
1541 if (state[level].parenlevel > 0) {
1543 --state[level].parenlevel;
1545 if (pgetc_linecont() == ')') {
1547 state[level].category == TSTATE_ARITH) {
1549 USTPUTC(CTLENDARI, out);
1555 * (don't 2nd guess - no error)
1562 case CBQUOTE: /* '`' */
1563 out = parsebackq(out, &bqlist, 1,
1564 state[level].syntax == DQSYNTAX &&
1565 (eofmark == NULL || newvarnest > 0),
1566 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1569 goto endword; /* exit outer loop */
1574 goto endword; /* exit outer loop */
1581 if (state[level].syntax == ARISYNTAX)
1582 synerror("Missing '))'");
1583 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1584 synerror("Unterminated quoted string");
1585 if (state[level].category == TSTATE_VAR_OLD ||
1586 state[level].category == TSTATE_VAR_NEW) {
1587 startlinno = plinno;
1588 synerror("Missing '}'");
1590 if (state != state_static)
1591 parser_temp_free_upto(state);
1593 len = out - stackblock();
1595 if (eofmark == NULL) {
1596 if ((c == '>' || c == '<')
1599 && (*out == '\0' || is_digit(*out))) {
1601 return lasttoken = TREDIR;
1607 backquotelist = bqlist;
1608 grabstackblock(len);
1610 return lasttoken = TWORD;
1611 /* end of readtoken routine */
1615 * Parse a substitution. At this point, we have read the dollar sign
1624 static const char types[] = "}-+?=";
1629 c = pgetc_linecont();
1630 if (c == '(') { /* $(command) or $((arith)) */
1631 if (pgetc_linecont() == '(') {
1635 out = parsebackq(out, &bqlist, 0,
1636 state[level].syntax == DQSYNTAX &&
1637 (eofmark == NULL || newvarnest > 0),
1638 state[level].syntax == DQSYNTAX ||
1639 state[level].syntax == ARISYNTAX);
1641 } else if (c == '{' || is_name(c) || is_special(c)) {
1642 USTPUTC(CTLVAR, out);
1643 typeloc = out - stackblock();
1644 USTPUTC(VSNORMAL, out);
1648 c = pgetc_linecont();
1652 if (!is_eof(c) && is_name(c)) {
1656 c = pgetc_linecont();
1658 } while (!is_eof(c) && is_in_name(c));
1660 strncmp(out - length, "LINENO", length) == 0) {
1661 /* Replace the variable name with the
1662 * current line number. */
1664 CHECKSTRSPACE(11, out);
1667 linno -= funclinno - 1;
1668 length = snprintf(out, 11, "%d", linno);
1674 } else if (is_digit(c)) {
1675 if (subtype != VSNORMAL) {
1678 c = pgetc_linecont();
1679 } while (is_digit(c));
1682 c = pgetc_linecont();
1684 } else if (is_special(c)) {
1686 c = pgetc_linecont();
1687 if (subtype == 0 && c1 == '#') {
1689 if (strchr(types, c) == NULL && c != ':' &&
1690 c != '#' && c != '%')
1693 c = pgetc_linecont();
1694 if (c1 != '}' && c == '}') {
1709 else if (c == '\n' || c == PEOF)
1710 synerror("Unexpected end of line in substitution");
1711 else if (BASESYNTAX[c] != CCTL)
1718 c = pgetc_linecont();
1721 p = strchr(types, c);
1723 if (c == '\n' || c == PEOF)
1724 synerror("Unexpected end of line in substitution");
1727 if (BASESYNTAX[c] != CCTL)
1731 subtype = p - types + VSNORMAL;
1737 subtype = c == '#' ? VSTRIMLEFT :
1739 c = pgetc_linecont();
1747 } else if (subtype != VSERROR) {
1748 if (subtype == VSLENGTH && c != '}')
1753 if (state[level].syntax == DQSYNTAX ||
1754 state[level].syntax == ARISYNTAX)
1756 *(stackblock() + typeloc) = subtype | flags;
1757 if (subtype != VSNORMAL) {
1758 if (level + 1 >= maxnest) {
1760 if (state == state_static) {
1761 state = parser_temp_alloc(
1762 maxnest * sizeof(*state));
1763 memcpy(state, state_static,
1764 MAXNEST_static * sizeof(*state));
1766 state = parser_temp_realloc(state,
1767 maxnest * sizeof(*state));
1770 state[level].parenlevel = 0;
1771 if (subtype == VSMINUS || subtype == VSPLUS ||
1772 subtype == VSQUESTION || subtype == VSASSIGN) {
1774 * For operators that were in the Bourne shell,
1775 * inherit the double-quote state.
1777 state[level].syntax = state[level - 1].syntax;
1778 state[level].category = TSTATE_VAR_OLD;
1781 * The other operators take a pattern,
1782 * so go to BASESYNTAX.
1783 * Also, ' and " are now special, even
1784 * in here documents.
1786 state[level].syntax = BASESYNTAX;
1787 state[level].category = TSTATE_VAR_NEW;
1791 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1792 /* $'cstylequotes' */
1793 USTPUTC(CTLQUOTEMARK, out);
1794 state[level].syntax = SQSYNTAX;
1800 goto parsesub_return;
1805 * Parse an arithmetic expansion (indicate start of one and set state)
1809 if (level + 1 >= maxnest) {
1811 if (state == state_static) {
1812 state = parser_temp_alloc(
1813 maxnest * sizeof(*state));
1814 memcpy(state, state_static,
1815 MAXNEST_static * sizeof(*state));
1817 state = parser_temp_realloc(state,
1818 maxnest * sizeof(*state));
1821 state[level].syntax = ARISYNTAX;
1822 state[level].parenlevel = 0;
1823 state[level].category = TSTATE_ARITH;
1824 USTPUTC(CTLARI, out);
1825 if (state[level - 1].syntax == DQSYNTAX)
1829 goto parsearith_return;
1832 } /* end of readtoken */
1836 * Returns true if the text contains nothing to expand (no dollar signs
1841 noexpand(char *text)
1847 while ((c = *p++) != '\0') {
1848 if ( c == CTLQUOTEMARK)
1852 else if (BASESYNTAX[(int)c] == CCTL)
1860 * Return true if the argument is a legal variable name (a letter or
1861 * underscore followed by zero or more letters, underscores, and digits).
1865 goodname(const char *name)
1873 if (! is_in_name(*p))
1881 isassignment(const char *p)
1889 else if (!is_in_name(*p))
1897 consumetoken(int token)
1899 if (readtoken() != token)
1905 * Called when an unexpected token is read during the parse. The argument
1906 * is the token that is expected, or -1 if more than one type of token can
1907 * occur at this point.
1911 synexpect(int token)
1916 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1917 tokname[lasttoken], tokname[token]);
1919 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1926 synerror(const char *msg)
1929 outfmt(out2, "%s: %d: ", commandname, startlinno);
1931 outfmt(out2, "%s: ", arg0);
1932 outfmt(out2, "Syntax error: %s\n", msg);
1933 error((char *)NULL);
1937 setprompt(int which)
1939 whichprompt = which;
1947 out2str(getprompt(NULL));
1953 pgetc_linecont(void)
1957 while ((c = pgetc_macro()) == '\\') {
1967 /* Allow the backslash to be pushed back. */
1968 pushstring("\\", 1, NULL);
1976 static struct passwd *
1985 return (getpwnam(login));
1990 getusername(char *name, size_t namelen)
1992 static char cached_name[MAXLOGNAME];
1996 if (cached_name[0] == '\0') {
2000 * Handle the case when there is more than one
2001 * login with the same UID, or when the login
2002 * returned by getlogin(2) does no longer match
2006 if (pw == NULL || pw->pw_uid != euid)
2007 pw = getpwuid(euid);
2010 strlcpy(cached_name, pw->pw_name,
2011 sizeof(cached_name));
2013 snprintf(cached_name, sizeof(cached_name),
2018 strlcpy(name, cached_name, namelen);
2023 * called by editline -- any expansions to the prompt
2024 * should be added here.
2027 getprompt(void *unused __unused)
2029 static char ps[PROMPTLEN];
2035 static char internal_error[] = "??";
2038 * Select prompt format.
2040 switch (whichprompt) {
2051 return internal_error;
2055 * Format prompt string.
2057 for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++)
2064 * \h specifies just the local hostname,
2065 * \H specifies fully-qualified hostname.
2070 gethostname(&ps[i], PROMPTLEN - i - 1);
2071 ps[PROMPTLEN - 1] = '\0';
2072 /* Skip to end of hostname. */
2073 trim = (*fmt == 'h') ? '.' : '\0';
2074 while ((ps[i] != '\0') && (ps[i] != trim))
2084 getusername(&ps[i], PROMPTLEN - i);
2085 /* Skip to end of username. */
2086 while (ps[i + 1] != '\0')
2091 * Working directory.
2093 * \W specifies just the final component,
2094 * \w specifies the entire path.
2098 pwd = lookupvar("PWD");
2099 if (pwd == NULL || *pwd == '\0')
2102 *pwd == '/' && pwd[1] != '\0')
2103 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
2106 home = lookupvar("HOME");
2108 homelen = strlen(home);
2110 strcmp(home, "/") != 0 &&
2111 strncmp(pwd, home, homelen) == 0 &&
2112 (pwd[homelen] == '/' ||
2113 pwd[homelen] == '\0')) {
2114 strlcpy(&ps[i], "~",
2120 strlcpy(&ps[i], pwd, PROMPTLEN - i);
2123 /* Skip to end of path. */
2124 while (ps[i + 1] != '\0')
2131 * '$' for normal users, '#' for root.
2134 ps[i] = (geteuid() != 0) ? '$' : '#';
2145 * Emit unrecognized formats verbatim.
2149 if (i < PROMPTLEN - 2)
2161 expandstr(const char *ps)
2164 struct jmploc jmploc;
2165 struct jmploc *const savehandler = handler;
2166 const int saveprompt = doprompt;
2167 struct parsefile *const savetopfile = getcurrentfile();
2168 struct parser_temp *const saveparser_temp = parser_temp;
2169 const char *result = NULL;
2171 if (!setjmp(jmploc.loc)) {
2174 setinputstring(ps, 1);
2176 readtoken1(pgetc(), DQSYNTAX, NOEOFMARK, 0);
2177 if (backquotelist != NULL)
2178 error("Command substitution not allowed here");
2182 n.narg.text = wordtext;
2183 n.narg.backquote = backquotelist;
2185 expandarg(&n, NULL, 0);
2186 result = stackblock();
2189 handler = savehandler;
2190 doprompt = saveprompt;
2191 popfilesupto(savetopfile);
2192 if (parser_temp != saveparser_temp) {
2193 parser_temp_free_all();
2194 parser_temp = saveparser_temp;
2196 if (result != NULL) {
2198 } else if (exception == EXINT)