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: head/bin/sh/parser.c 343399 2019-01-24 11:59:46Z trasz $");
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. */
598 n1 = simplecmd(rpp, redir);
604 /* Now check for redirection which may follow command */
605 while (readtoken() == TREDIR) {
606 *rpp = n2 = redirnode;
607 rpp = &n2->nfile.next;
614 n2 = (union node *)stalloc(sizeof (struct nredir));
619 n1->nredir.redirect = redir;
627 simplecmd(union node **rpp, union node *redir)
629 union node *args, **app;
630 union node **orig_rpp = rpp;
631 union node *n = NULL;
635 /* If we don't have any redirections already, then we must reset */
636 /* rpp to be the address of the local redir variable. */
643 * We save the incoming value, because we need this for shell
644 * functions. There can not be a redirect or an argument between
645 * the function name and the open parenthesis.
649 savecheckkwd = CHKALIAS;
652 checkkwd = savecheckkwd;
653 if (readtoken() == TWORD) {
657 if (savecheckkwd != 0 && !isassignment(wordtext))
659 } else if (lasttoken == TREDIR) {
660 *rpp = n = redirnode;
661 rpp = &n->nfile.next;
662 parsefname(); /* read name of redirection file */
663 } else if (lasttoken == TLP && app == &args->narg.next
664 && rpp == orig_rpp) {
665 /* We have a function */
669 * - Require plain text.
670 * - Functions with '/' cannot be called.
672 * - Reject ksh extended glob patterns.
674 if (!noexpand(n->narg.text) || quoteflag ||
675 strchr(n->narg.text, '/') ||
677 n->narg.text[strlen(n->narg.text) - 1]))
678 synerror("Bad function name");
679 rmescapes(n->narg.text);
680 if (find_builtin(n->narg.text, &special) >= 0 &&
682 synerror("Cannot override a special builtin with a function");
684 n->narg.next = command();
694 n = (union node *)stalloc(sizeof (struct ncmd));
697 n->ncmd.redirect = redir;
706 n = (union node *)stalloc(sizeof (struct narg));
709 n->narg.text = wordtext;
710 n->narg.backquote = backquotelist;
715 makebinary(int type, union node *n1, union node *n2)
719 n = (union node *)stalloc(sizeof (struct nbinary));
729 checkkwd |= CHKALIAS;
733 fixredir(union node *n, const char *text, int err)
735 TRACE(("Fix redir %s %d\n", text, err));
737 n->ndup.vname = NULL;
739 if (is_digit(text[0]) && text[1] == '\0')
740 n->ndup.dupfd = digit_val(text[0]);
741 else if (text[0] == '-' && text[1] == '\0')
746 synerror("Bad fd number");
748 n->ndup.vname = makename();
756 union node *n = redirnode;
759 if (n->type == NHERE) {
760 struct heredoc *here = heredoc;
765 TRACE(("Here document %d\n", n->type));
766 if (here->striptabs) {
767 while (*wordtext == '\t')
770 if (! noexpand(wordtext))
771 synerror("Illegal eof marker for << redirection");
773 here->eofmark = wordtext;
775 if (heredoclist == NULL)
778 for (p = heredoclist ; p->next ; p = p->next);
781 } else if (n->type == NTOFD || n->type == NFROMFD) {
782 fixredir(n, wordtext, 0);
784 n->nfile.fname = makename();
790 * Input any here documents.
796 struct heredoc *here;
799 while (heredoclist) {
801 heredoclist = here->next;
806 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
807 here->eofmark, here->striptabs);
809 here->here->nhere.doc = n;
829 int alreadyseen = tokpushback;
838 if (checkkwd & CHKNL) {
846 * check for keywords and aliases
848 if (t == TWORD && !quoteflag)
850 const char * const *pp;
852 if (checkkwd & CHKKWD)
853 for (pp = parsekwd; *pp; pp++) {
854 if (**pp == *wordtext && equal(*pp, wordtext))
856 lasttoken = t = pp - parsekwd + KWDOFFSET;
857 TRACE(("keyword %s recognized\n", tokname[t]));
861 if (checkkwd & CHKALIAS &&
862 (ap = lookupalias(wordtext, 1)) != NULL) {
863 pushstring(ap->val, strlen(ap->val), ap);
873 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
875 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
882 * Read the next input token.
883 * If the token is a word, we set backquotelist to the list of cmds in
884 * backquotes. We set quoteflag to true if any part of the word was
886 * If the token is TREDIR, then we set redirnode to a structure containing
888 * In all cases, the variable startlinno is set to the number of the line
889 * on which the token starts.
891 * [Change comment: here documents and internal procedures]
892 * [Readtoken shouldn't have any arguments. Perhaps we should make the
893 * word parsing code into a separate routine. In this case, readtoken
894 * doesn't need to have any internal procedures, but parseword does.
895 * We could also make parseoperator in essence the main routine, and
896 * have parseword (readtoken1?) handle both words and redirection.]
899 #define RETURN(token) return lasttoken = token
915 for (;;) { /* until token or start of word found */
921 while ((c = pgetc()) != '\n' && c != PEOF);
925 if (pgetc() == '\n') {
926 startlinno = ++plinno;
936 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
939 needprompt = doprompt;
944 if (pgetc_linecont() == '&')
949 if (pgetc_linecont() == '|')
954 c = pgetc_linecont();
971 #define MAXNEST_static 8
974 const char *syntax; /* *SYNTAX */
975 int parenlevel; /* levels of parentheses in arithmetic */
976 enum tokenstate_category
979 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
980 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
987 * Check to see whether we are at the end of the here document. When this
988 * is called, c is set to the first character of the next input line. If
989 * we are at the end of the here document, this routine sets the c to PEOF.
990 * The new value of c is returned.
994 checkend(int c, const char *eofmark, int striptabs)
1000 if (c == *eofmark) {
1004 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
1006 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
1010 needprompt = doprompt;
1014 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
1016 } else if (c == '\n' && *eofmark == '\0') {
1019 needprompt = doprompt;
1026 * Parse a redirection operator. The variable "out" points to a string
1027 * specifying the fd to be redirected. The variable "c" contains the
1028 * first character of the redirection operator.
1032 parseredir(char *out, int c)
1037 np = (union node *)stalloc(sizeof (struct nfile));
1040 c = pgetc_linecont();
1046 np->type = NCLOBBER;
1051 } else { /* c == '<' */
1053 c = pgetc_linecont();
1055 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1056 np = (union node *)stalloc(sizeof (struct nhere));
1060 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1062 if ((c = pgetc_linecont()) == '-') {
1063 heredoc->striptabs = 1;
1065 heredoc->striptabs = 0;
1068 } else if (c == '&')
1078 np->nfile.fd = digit_val(fd);
1083 * Called to parse command substitutions.
1087 parsebackq(char *out, struct nodelist **pbqlist,
1088 int oldstyle, int dblquote, int quoted)
1090 struct nodelist **nlpp;
1093 struct jmploc jmploc;
1094 struct jmploc *const savehandler = handler;
1097 const int bq_startlinno = plinno;
1098 char *volatile ostr = NULL;
1099 struct parsefile *const savetopfile = getcurrentfile();
1100 struct heredoc *const saveheredoclist = heredoclist;
1101 struct heredoc *here;
1104 if (setjmp(jmploc.loc)) {
1105 popfilesupto(savetopfile);
1110 heredoclist = saveheredoclist;
1111 handler = savehandler;
1112 if (exception == EXERROR) {
1113 startlinno = bq_startlinno;
1114 synerror("Error in command substitution");
1116 longjmp(handler->loc, 1);
1119 savelen = out - stackblock();
1121 str = ckmalloc(savelen);
1122 memcpy(str, stackblock(), savelen);
1128 /* We must read until the closing backquote, giving special
1129 treatment to some slashes, and then push the string and
1130 reread it as input, interpreting it normally. */
1136 STARTSTACKSTR(oout);
1142 CHECKSTRSPACE(2, oout);
1143 c = pgetc_linecont();
1149 if (c != '\\' && c != '`' && c != '$'
1150 && (!dblquote || c != '"'))
1151 USTPUTC('\\', oout);
1156 needprompt = doprompt;
1160 startlinno = plinno;
1161 synerror("EOF in backquote substitution");
1169 USTPUTC('\0', oout);
1170 olen = oout - stackblock();
1172 ostr = ckmalloc(olen);
1173 memcpy(ostr, stackblock(), olen);
1174 setinputstring(ostr, 1);
1179 nlpp = &(*nlpp)->next;
1180 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1181 (*nlpp)->next = NULL;
1184 saveprompt = doprompt;
1191 if (peektoken() != TEOF)
1193 doprompt = saveprompt;
1200 * Start reading from old file again, ignoring any pushed back
1201 * tokens left from the backquote parsing
1207 CHECKSTRSPACE(savelen + 1, out);
1210 memcpy(out, str, savelen);
1211 STADJUST(savelen, out);
1219 here = saveheredoclist;
1221 while (here->next != NULL)
1223 here->next = heredoclist;
1224 heredoclist = saveheredoclist;
1226 handler = savehandler;
1229 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1231 USTPUTC(CTLBACKQ, out);
1237 * Called to parse a backslash escape sequence inside $'...'.
1238 * The backslash has already been read.
1241 readcstyleesc(char *out)
1249 synerror("Unterminated quoted string");
1262 case 'a': v = '\a'; break;
1263 case 'b': v = '\b'; break;
1264 case 'e': v = '\033'; break;
1265 case 'f': v = '\f'; break;
1266 case 'n': v = '\n'; break;
1267 case 'r': v = '\r'; break;
1268 case 't': v = '\t'; break;
1269 case 'v': v = '\v'; break;
1274 if (c >= '0' && c <= '9')
1275 v = (v << 4) + c - '0';
1276 else if (c >= 'A' && c <= 'F')
1277 v = (v << 4) + c - 'A' + 10;
1278 else if (c >= 'a' && c <= 'f')
1279 v = (v << 4) + c - 'a' + 10;
1285 case '0': case '1': case '2': case '3':
1286 case '4': case '5': case '6': case '7':
1289 if (c >= '0' && c <= '7') {
1293 if (c >= '0' && c <= '7') {
1303 if (c < 0x3f || c > 0x7a || c == 0x60)
1304 synerror("Bad escape sequence");
1305 if (c == '\\' && pgetc() != '\\')
1306 synerror("Bad escape sequence");
1314 n = c == 'U' ? 8 : 4;
1316 for (i = 0; i < n; i++) {
1318 if (c >= '0' && c <= '9')
1319 v = (v << 4) + c - '0';
1320 else if (c >= 'A' && c <= 'F')
1321 v = (v << 4) + c - 'A' + 10;
1322 else if (c >= 'a' && c <= 'f')
1323 v = (v << 4) + c - 'a' + 10;
1325 synerror("Bad escape sequence");
1327 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1328 synerror("Bad escape sequence");
1329 /* We really need iconv here. */
1330 if (initial_localeisutf8 && v > 127) {
1331 CHECKSTRSPACE(4, out);
1333 * We cannot use wctomb() as the locale may have
1337 USTPUTC(0xc0 | v >> 6, out);
1338 USTPUTC(0x80 | (v & 0x3f), out);
1340 } else if (v <= 0xffff) {
1341 USTPUTC(0xe0 | v >> 12, out);
1342 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1343 USTPUTC(0x80 | (v & 0x3f), out);
1345 } else if (v <= 0x10ffff) {
1346 USTPUTC(0xf0 | v >> 18, out);
1347 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1348 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1349 USTPUTC(0x80 | (v & 0x3f), out);
1357 synerror("Bad escape sequence");
1361 * We can't handle NUL bytes.
1362 * POSIX says we should skip till the closing quote.
1365 while ((c = pgetc()) != '\'') {
1369 synerror("Unterminated quoted string");
1381 if (SQSYNTAX[vc] == CCTL)
1382 USTPUTC(CTLESC, out);
1389 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1390 * is not NULL, read a here document. In the latter case, eofmark is the
1391 * word which marks the end of the document and striptabs is true if
1392 * leading tabs should be stripped from the document. The argument firstc
1393 * is the first character of the input token or document.
1395 * Because C does not have internal subroutines, I have simulated them
1396 * using goto's to implement the subroutine linkage. The following macros
1397 * will run code that appears at the end of readtoken1.
1400 #define PARSESUB() {goto parsesub; parsesub_return:;}
1401 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1404 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1410 struct nodelist *bqlist;
1415 struct tokenstate state_static[MAXNEST_static];
1416 int maxnest = MAXNEST_static;
1417 struct tokenstate *state = state_static;
1420 startlinno = plinno;
1425 state[level].syntax = initialsyntax;
1426 state[level].parenlevel = 0;
1427 state[level].category = TSTATE_TOP;
1430 loop: { /* for each line, until end of word */
1431 if (eofmark && eofmark != NOEOFMARK)
1432 /* set c to PEOF if at end of here document */
1433 c = checkend(c, eofmark, striptabs);
1434 for (;;) { /* until end of line or end of word */
1435 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1437 synentry = state[level].syntax[c];
1440 case CNL: /* '\n' */
1442 goto endword; /* exit outer loop */
1452 goto loop; /* continue outer loop */
1455 out = readcstyleesc(out);
1463 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1464 USTPUTC(CTLESC, out);
1467 case CBACK: /* backslash */
1472 } else if (c == '\n') {
1479 if (state[level].syntax == DQSYNTAX &&
1480 c != '\\' && c != '`' && c != '$' &&
1481 (c != '"' || (eofmark != NULL &&
1482 newvarnest == 0)) &&
1483 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1485 if ((eofmark == NULL ||
1487 state[level].syntax == BASESYNTAX)
1488 USTPUTC(CTLQUOTEMARK, out);
1489 if (SQSYNTAX[c] == CCTL)
1490 USTPUTC(CTLESC, out);
1492 if ((eofmark == NULL ||
1494 state[level].syntax == BASESYNTAX &&
1495 state[level].category == TSTATE_VAR_OLD)
1496 USTPUTC(CTLQUOTEEND, out);
1501 USTPUTC(CTLQUOTEMARK, out);
1502 state[level].syntax = SQSYNTAX;
1506 USTPUTC(CTLQUOTEMARK, out);
1507 state[level].syntax = DQSYNTAX;
1510 if (eofmark != NULL && newvarnest == 0)
1513 if (state[level].category == TSTATE_VAR_OLD)
1514 USTPUTC(CTLQUOTEEND, out);
1515 state[level].syntax = BASESYNTAX;
1519 case CVAR: /* '$' */
1520 PARSESUB(); /* parse substitution */
1522 case CENDVAR: /* '}' */
1524 ((state[level].category == TSTATE_VAR_OLD &&
1525 state[level].syntax ==
1526 state[level - 1].syntax) ||
1527 (state[level].category == TSTATE_VAR_NEW &&
1528 state[level].syntax == BASESYNTAX))) {
1529 if (state[level].category == TSTATE_VAR_NEW)
1532 USTPUTC(CTLENDVAR, out);
1537 case CLP: /* '(' in arithmetic */
1538 state[level].parenlevel++;
1541 case CRP: /* ')' in arithmetic */
1542 if (state[level].parenlevel > 0) {
1544 --state[level].parenlevel;
1546 if (pgetc_linecont() == ')') {
1548 state[level].category == TSTATE_ARITH) {
1550 USTPUTC(CTLENDARI, out);
1556 * (don't 2nd guess - no error)
1563 case CBQUOTE: /* '`' */
1564 out = parsebackq(out, &bqlist, 1,
1565 state[level].syntax == DQSYNTAX &&
1566 (eofmark == NULL || newvarnest > 0),
1567 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1570 goto endword; /* exit outer loop */
1575 goto endword; /* exit outer loop */
1582 if (state[level].syntax == ARISYNTAX)
1583 synerror("Missing '))'");
1584 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1585 synerror("Unterminated quoted string");
1586 if (state[level].category == TSTATE_VAR_OLD ||
1587 state[level].category == TSTATE_VAR_NEW) {
1588 startlinno = plinno;
1589 synerror("Missing '}'");
1591 if (state != state_static)
1592 parser_temp_free_upto(state);
1594 len = out - stackblock();
1596 if (eofmark == NULL) {
1597 if ((c == '>' || c == '<')
1600 && (*out == '\0' || is_digit(*out))) {
1602 return lasttoken = TREDIR;
1608 backquotelist = bqlist;
1609 grabstackblock(len);
1611 return lasttoken = TWORD;
1612 /* end of readtoken routine */
1616 * Parse a substitution. At this point, we have read the dollar sign
1625 static const char types[] = "}-+?=";
1630 c = pgetc_linecont();
1631 if (c == '(') { /* $(command) or $((arith)) */
1632 if (pgetc_linecont() == '(') {
1636 out = parsebackq(out, &bqlist, 0,
1637 state[level].syntax == DQSYNTAX &&
1638 (eofmark == NULL || newvarnest > 0),
1639 state[level].syntax == DQSYNTAX ||
1640 state[level].syntax == ARISYNTAX);
1642 } else if (c == '{' || is_name(c) || is_special(c)) {
1643 USTPUTC(CTLVAR, out);
1644 typeloc = out - stackblock();
1645 USTPUTC(VSNORMAL, out);
1649 c = pgetc_linecont();
1653 if (!is_eof(c) && is_name(c)) {
1657 c = pgetc_linecont();
1659 } while (!is_eof(c) && is_in_name(c));
1661 strncmp(out - length, "LINENO", length) == 0) {
1662 /* Replace the variable name with the
1663 * current line number. */
1665 CHECKSTRSPACE(11, out);
1668 linno -= funclinno - 1;
1669 length = snprintf(out, 11, "%d", linno);
1675 } else if (is_digit(c)) {
1676 if (subtype != VSNORMAL) {
1679 c = pgetc_linecont();
1680 } while (is_digit(c));
1683 c = pgetc_linecont();
1685 } else if (is_special(c)) {
1687 c = pgetc_linecont();
1688 if (subtype == 0 && c1 == '#') {
1690 if (strchr(types, c) == NULL && c != ':' &&
1691 c != '#' && c != '%')
1694 c = pgetc_linecont();
1695 if (c1 != '}' && c == '}') {
1710 else if (c == '\n' || c == PEOF)
1711 synerror("Unexpected end of line in substitution");
1712 else if (BASESYNTAX[c] != CCTL)
1719 c = pgetc_linecont();
1722 p = strchr(types, c);
1724 if (c == '\n' || c == PEOF)
1725 synerror("Unexpected end of line in substitution");
1728 if (BASESYNTAX[c] != CCTL)
1732 subtype = p - types + VSNORMAL;
1738 subtype = c == '#' ? VSTRIMLEFT :
1740 c = pgetc_linecont();
1748 } else if (subtype != VSERROR) {
1749 if (subtype == VSLENGTH && c != '}')
1754 if (state[level].syntax == DQSYNTAX ||
1755 state[level].syntax == ARISYNTAX)
1757 *(stackblock() + typeloc) = subtype | flags;
1758 if (subtype != VSNORMAL) {
1759 if (level + 1 >= maxnest) {
1761 if (state == state_static) {
1762 state = parser_temp_alloc(
1763 maxnest * sizeof(*state));
1764 memcpy(state, state_static,
1765 MAXNEST_static * sizeof(*state));
1767 state = parser_temp_realloc(state,
1768 maxnest * sizeof(*state));
1771 state[level].parenlevel = 0;
1772 if (subtype == VSMINUS || subtype == VSPLUS ||
1773 subtype == VSQUESTION || subtype == VSASSIGN) {
1775 * For operators that were in the Bourne shell,
1776 * inherit the double-quote state.
1778 state[level].syntax = state[level - 1].syntax;
1779 state[level].category = TSTATE_VAR_OLD;
1782 * The other operators take a pattern,
1783 * so go to BASESYNTAX.
1784 * Also, ' and " are now special, even
1785 * in here documents.
1787 state[level].syntax = BASESYNTAX;
1788 state[level].category = TSTATE_VAR_NEW;
1792 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1793 /* $'cstylequotes' */
1794 USTPUTC(CTLQUOTEMARK, out);
1795 state[level].syntax = SQSYNTAX;
1801 goto parsesub_return;
1806 * Parse an arithmetic expansion (indicate start of one and set state)
1810 if (level + 1 >= maxnest) {
1812 if (state == state_static) {
1813 state = parser_temp_alloc(
1814 maxnest * sizeof(*state));
1815 memcpy(state, state_static,
1816 MAXNEST_static * sizeof(*state));
1818 state = parser_temp_realloc(state,
1819 maxnest * sizeof(*state));
1822 state[level].syntax = ARISYNTAX;
1823 state[level].parenlevel = 0;
1824 state[level].category = TSTATE_ARITH;
1825 USTPUTC(CTLARI, out);
1826 if (state[level - 1].syntax == DQSYNTAX)
1830 goto parsearith_return;
1833 } /* end of readtoken */
1837 * Returns true if the text contains nothing to expand (no dollar signs
1842 noexpand(char *text)
1848 while ((c = *p++) != '\0') {
1849 if ( c == CTLQUOTEMARK)
1853 else if (BASESYNTAX[(int)c] == CCTL)
1861 * Return true if the argument is a legal variable name (a letter or
1862 * underscore followed by zero or more letters, underscores, and digits).
1866 goodname(const char *name)
1874 if (! is_in_name(*p))
1882 isassignment(const char *p)
1890 else if (!is_in_name(*p))
1898 consumetoken(int token)
1900 if (readtoken() != token)
1906 * Called when an unexpected token is read during the parse. The argument
1907 * is the token that is expected, or -1 if more than one type of token can
1908 * occur at this point.
1912 synexpect(int token)
1917 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1918 tokname[lasttoken], tokname[token]);
1920 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1927 synerror(const char *msg)
1930 outfmt(out2, "%s: %d: ", commandname, startlinno);
1932 outfmt(out2, "%s: ", arg0);
1933 outfmt(out2, "Syntax error: %s\n", msg);
1934 error((char *)NULL);
1938 setprompt(int which)
1940 whichprompt = which;
1948 out2str(getprompt(NULL));
1954 pgetc_linecont(void)
1958 while ((c = pgetc_macro()) == '\\') {
1968 /* Allow the backslash to be pushed back. */
1969 pushstring("\\", 1, NULL);
1977 static struct passwd *
1986 return (getpwnam(login));
1991 getusername(char *name, size_t namelen)
1993 static char cached_name[MAXLOGNAME];
1997 if (cached_name[0] == '\0') {
2001 * Handle the case when there is more than one
2002 * login with the same UID, or when the login
2003 * returned by getlogin(2) does no longer match
2007 if (pw == NULL || pw->pw_uid != euid)
2008 pw = getpwuid(euid);
2011 strlcpy(cached_name, pw->pw_name,
2012 sizeof(cached_name));
2014 snprintf(cached_name, sizeof(cached_name),
2019 strlcpy(name, cached_name, namelen);
2024 * called by editline -- any expansions to the prompt
2025 * should be added here.
2028 getprompt(void *unused __unused)
2030 static char ps[PROMPTLEN];
2036 static char internal_error[] = "??";
2039 * Select prompt format.
2041 switch (whichprompt) {
2052 return internal_error;
2056 * Format prompt string.
2058 for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++)
2065 * \h specifies just the local hostname,
2066 * \H specifies fully-qualified hostname.
2071 gethostname(&ps[i], PROMPTLEN - i - 1);
2072 ps[PROMPTLEN - 1] = '\0';
2073 /* Skip to end of hostname. */
2074 trim = (*fmt == 'h') ? '.' : '\0';
2075 while ((ps[i] != '\0') && (ps[i] != trim))
2085 getusername(&ps[i], PROMPTLEN - i);
2086 /* Skip to end of username. */
2087 while (ps[i + 1] != '\0')
2092 * Working directory.
2094 * \W specifies just the final component,
2095 * \w specifies the entire path.
2099 pwd = lookupvar("PWD");
2100 if (pwd == NULL || *pwd == '\0')
2103 *pwd == '/' && pwd[1] != '\0')
2104 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
2107 home = lookupvar("HOME");
2109 homelen = strlen(home);
2111 strcmp(home, "/") != 0 &&
2112 strncmp(pwd, home, homelen) == 0 &&
2113 (pwd[homelen] == '/' ||
2114 pwd[homelen] == '\0')) {
2115 strlcpy(&ps[i], "~",
2121 strlcpy(&ps[i], pwd, PROMPTLEN - i);
2124 /* Skip to end of path. */
2125 while (ps[i + 1] != '\0')
2132 * '$' for normal users, '#' for root.
2135 ps[i] = (geteuid() != 0) ? '$' : '#';
2146 * Emit unrecognized formats verbatim.
2150 if (i < PROMPTLEN - 2)
2162 expandstr(const char *ps)
2165 struct jmploc jmploc;
2166 struct jmploc *const savehandler = handler;
2167 const int saveprompt = doprompt;
2168 struct parsefile *const savetopfile = getcurrentfile();
2169 struct parser_temp *const saveparser_temp = parser_temp;
2170 const char *result = NULL;
2172 if (!setjmp(jmploc.loc)) {
2175 setinputstring(ps, 1);
2177 readtoken1(pgetc(), DQSYNTAX, NOEOFMARK, 0);
2178 if (backquotelist != NULL)
2179 error("Command substitution not allowed here");
2183 n.narg.text = wordtext;
2184 n.narg.backquote = backquotelist;
2186 expandarg(&n, NULL, 0);
2187 result = stackblock();
2190 handler = savehandler;
2191 doprompt = saveprompt;
2192 popfilesupto(savetopfile);
2193 if (parser_temp != saveparser_temp) {
2194 parser_temp_free_all();
2195 parser_temp = saveparser_temp;
2197 if (result != NULL) {
2199 } else if (exception == EXINT)