1 /* $OpenBSD: lex.c,v 1.51 2015/09/10 22:48:58 nicm Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5 * 2011, 2012, 2013, 2014, 2015, 2016
6 * mirabilos <m@mirbsd.org>
8 * Provided that these terms and disclaimer and all copyright notices
9 * are retained or reproduced in an accompanying document, permission
10 * is granted to deal in this work without restriction, including un-
11 * limited rights to use, publicly perform, distribute, sell, modify,
12 * merge, give away, or sublicence.
14 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 * the utmost extent permitted by applicable law, neither express nor
16 * implied; without malicious intent or gross negligence. In no event
17 * may a licensor, author or contributor be held liable for indirect,
18 * direct, other damage, loss, or other issues arising in any way out
19 * of dealing in the work, even if advised of the possibility of such
20 * damage or existence of a defect, except proven that it results out
21 * of said person's immediate fault when using the work as intended.
26 __RCSID("$MirOS: src/bin/mksh/lex.c,v 1.218 2016/01/20 21:34:12 tg Exp $");
29 * states while lexing word
31 #define SBASE 0 /* outside any lexical constructs */
32 #define SWORD 1 /* implicit quoting for substitute() */
33 #define SLETPAREN 2 /* inside (( )), implicit quoting */
34 #define SSQUOTE 3 /* inside '' */
35 #define SDQUOTE 4 /* inside "" */
36 #define SEQUOTE 5 /* inside $'' */
37 #define SBRACE 6 /* inside ${} */
38 #define SQBRACE 7 /* inside "${}" */
39 #define SBQUOTE 8 /* inside `` */
40 #define SASPAREN 9 /* inside $(( )) */
41 #define SHEREDELIM 10 /* parsing << or <<- delimiter */
42 #define SHEREDQUOTE 11 /* parsing " in << or <<- delimiter */
43 #define SPATTERN 12 /* parsing *(...|...) pattern (*+?@!) */
44 #define SADELIM 13 /* like SBASE, looking for delimiter */
45 #define STBRACEKORN 14 /* parsing ${...[#%]...} !FSH */
46 #define STBRACEBOURNE 15 /* parsing ${...[#%]...} FSH */
47 #define SINVALID 255 /* invalid state */
49 struct sretrace_info {
50 struct sretrace_info *next;
56 * Structure to keep track of the lexing state and the various pieces of info
57 * needed for each particular state.
59 typedef struct lex_state {
61 /* point to the next state block */
62 struct lex_state *base;
63 /* marks start of state output in output string */
65 /* SBQUOTE: true if in double quotes: "`...`" */
66 /* SEQUOTE: got NUL, ignore rest of string */
68 /* SADELIM information */
70 /* character to search for */
71 unsigned char delimiter;
72 /* max. number of delimiters */
76 /* count open parentheses */
78 /* type of this state */
81 #define ls_base u.base
82 #define ls_start u.start
83 #define ls_bool u.abool
84 #define ls_adelim u.adelim
91 static void readhere(struct ioword *);
92 static void ungetsc(int);
93 static void ungetsc_i(int);
94 static int getsc_uu(void);
95 static void getsc_line(Source *);
96 static int getsc_bn(void);
97 static int getsc_i(void);
98 static char *get_brace_var(XString *, char *);
99 static bool arraysub(char **);
100 static void gethere(void);
101 static Lex_state *push_state_i(State_info *, Lex_state *);
102 static Lex_state *pop_state_i(State_info *, Lex_state *);
104 static int backslash_skip;
105 static int ignore_backslash_newline;
107 /* optimised getsc_bn() */
108 #define o_getsc() (*source->str != '\0' && *source->str != '\\' && \
109 !backslash_skip ? *source->str++ : getsc_bn())
110 /* optimised getsc_uu() */
111 #define o_getsc_u() ((*source->str != '\0') ? *source->str++ : getsc_uu())
114 #define o_getsc_r(carg) \
116 struct sretrace_info *rp = retrace_info; \
119 Xcheck(rp->xs, rp->xp); \
130 o_getsc_r(o_getsc());
133 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
134 #define getsc getsc_i
136 static int getsc_r(int);
144 #define getsc() getsc_r(o_getsc())
147 #define STATE_BSIZE 8
149 #define PUSH_STATE(s) do { \
150 if (++statep == state_info.end) \
151 statep = push_state_i(&state_info, statep); \
152 state = statep->type = (s); \
153 } while (/* CONSTCOND */ 0)
155 #define POP_STATE() do { \
156 if (--statep == state_info.base) \
157 statep = pop_state_i(&state_info, statep); \
158 state = statep->type; \
159 } while (/* CONSTCOND */ 0)
161 #define PUSH_SRETRACE(s) do { \
162 struct sretrace_info *ri; \
165 statep->ls_start = Xsavepos(ws, wp); \
166 ri = alloc(sizeof(struct sretrace_info), ATEMP); \
167 Xinit(ri->xs, ri->xp, 64, ATEMP); \
168 ri->next = retrace_info; \
170 } while (/* CONSTCOND */ 0)
172 #define POP_SRETRACE() do { \
173 wp = Xrestpos(ws, wp, statep->ls_start); \
174 *retrace_info->xp = '\0'; \
175 sp = Xstring(retrace_info->xs, retrace_info->xp); \
176 dp = (void *)retrace_info; \
177 retrace_info = retrace_info->next; \
180 } while (/* CONSTCOND */ 0)
185 * tokens are not regular expressions, they are LL(1).
186 * for example, "${var:-${PWD}}", and "$(size $(whence ksh))".
187 * hence the state stack. Note "$(...)" are now parsed recursively.
193 Lex_state states[STATE_BSIZE], *statep, *s2, *base;
194 State_info state_info;
197 XString ws; /* expandable output word */
198 char *wp; /* output word pointer */
202 states[0].type = SINVALID;
203 states[0].ls_base = NULL;
205 state_info.base = states;
206 state_info.end = &state_info.base[STATE_BSIZE];
208 Xinit(ws, wp, 64, ATEMP);
211 ignore_backslash_newline = 0;
215 else if (cf & LETEXPR) {
216 /* enclose arguments in (double) quotes */
222 state = (cf & HEREDELIM) ? SHEREDELIM : SBASE;
223 while ((c = getsc()) == ' ' || c == '\t')
226 ignore_backslash_newline++;
227 while ((c = getsc()) != '\0' && c != '\n')
229 ignore_backslash_newline--;
233 if (source->flags & SF_ALIAS) {
234 /* trailing ' ' in alias definition */
235 source->flags &= ~SF_ALIAS;
236 /* POSIX: trailing space only counts if parsing simple cmd */
237 if (!Flag(FPOSIX) || (cf & CMDWORD))
241 /* Initial state: one of SWORD SLETPAREN SHEREDELIM SBASE */
242 statep->type = state;
244 /* collect non-special or quoted characters to form word */
245 while (!((c = getsc()) == 0 ||
246 ((state == SBASE || state == SHEREDELIM) && ctype(c, C_LEX1)))) {
247 if (state == SBASE &&
248 subshell_nesting_type == /*{*/ '}' &&
250 /* possibly end ${ :;} */
259 else if (statep->nparen == 0 && (c == /*{*/ '}' ||
260 c == (int)statep->ls_adelim.delimiter)) {
263 if (c == /*{*/ '}' || --statep->ls_adelim.num == 0)
271 if (c == '[' && (cf & CMDASN)) {
274 if (is_wdvarname(Xstring(ws, wp), false)) {
277 if (arraysub(&tmp)) {
280 for (p = tmp; *p; ) {
303 Sbase1: /* includes *(...|...) pattern (*+?@!) */
304 if (c == '*' || c == '@' || c == '+' || c == '?' ||
307 if (c2 == '(' /*)*/ ) {
310 PUSH_STATE(SPATTERN);
316 Sbase2: /* doesn't include *(...|...) pattern (*+?@!) */
321 /* trailing \ is lost */
327 open_ssquote_unless_heredoc:
331 ignore_backslash_newline++;
341 * processing of dollar sign belongs into
342 * Subst, except for those which can open
343 * a string: $'…' and $"…"
379 /* trailing \ is lost */
391 if (c == '(') /*)*/ {
393 if (c == '(') /*)*/ {
395 PUSH_SRETRACE(SASPAREN);
397 *retrace_info->xp++ = '(';
410 } else if (c == '{') /*}*/ {
411 if ((c = getsc()) == '|') {
418 } else if (ctype(c, C_IFSWS)) {
421 * "command" substitution
429 wp = get_brace_var(&ws, wp);
431 /* allow :# and :% (ksh88 compat) */
443 statep->ls_adelim.delimiter = ':';
444 statep->ls_adelim.num = 1;
447 } else if (ksh_isdigit(c) ||
448 c == '('/*)*/ || c == ' ' ||
451 /* substring subst. */
459 statep->ls_adelim.delimiter = ':';
460 statep->ls_adelim.num = 2;
464 } else if (c == '/') {
467 if ((c = getsc()) == '/') {
474 statep->ls_adelim.delimiter = '/';
475 statep->ls_adelim.num = 1;
480 * If this is a trim operation,
481 * treat (,|,) specially in STBRACE.
483 if (ctype(c, C_SUBOP2)) {
486 PUSH_STATE(STBRACEBOURNE);
488 PUSH_STATE(STBRACEKORN);
491 if (state == SDQUOTE ||
497 } else if (ksh_isalphx(c)) {
504 } while (ksh_isalnux(c));
509 } else if (ctype(c, C_VAR1 | C_DIGIT)) {
528 * We need to know whether we are within double
529 * quotes, since most shells translate \" to "
530 * within "…`…\"…`…". This is not done in POSIX
531 * mode (§2.2.3 Double-Quotes: “The backquote
532 * shall retain its special meaning introducing
533 * the other form of command substitution (see
534 * Command Substitution). The portion of the
535 * quoted string from the initial backquote and
536 * the characters up to the next backquote that
537 * is not preceded by a <backslash>, having
538 * escape characters removed, defines that
539 * command whose output replaces "`...`" when
540 * the word is expanded.”; §2.6.3 Command
541 * Substitution: “Within the backquoted style
542 * of command substitution, <backslash> shall
543 * retain its literal meaning, except when
544 * followed by: '$', '`', or <backslash>. The
545 * search for the matching backquote shall be
546 * satisfied by the first unquoted non-escaped
547 * backquote; during this search, if a
548 * non-escaped backquote is encountered[…],
549 * undefined results occur.”).
551 statep->ls_bool = false;
552 #ifdef austingroupbugs1015_is_still_not_resolved
557 base = state_info.base;
558 while (/* CONSTCOND */ 1) {
559 for (; s2 != base; s2--) {
560 if (s2->type == SDQUOTE) {
561 statep->ls_bool = true;
567 if (!(s2 = s2->ls_base))
569 base = s2-- - STATE_BSIZE;
590 ignore_backslash_newline--;
591 } else if (c == '\\') {
592 if ((c2 = unbksl(true, getsc_i, ungetsc)) == -1)
595 statep->ls_bool = true;
596 if (!statep->ls_bool) {
599 if ((unsigned int)c2 < 0x100) {
603 cz = utf_wctomb(ts, c2 - 0x100);
612 } else if (!statep->ls_bool) {
621 if ((cf & HEREDOC) || state == SQBRACE)
624 ignore_backslash_newline--;
645 if (statep->nparen == 1) {
649 if ((c2 = getsc()) == /*(*/ ')') {
652 memcpy(wp, sp + 1, cz);
662 * mismatched parenthesis -
663 * assume we were really
664 * parsing a $(...) expression
677 /* reuse existing state machine */
683 * perform POSIX "quote removal" if the back-
684 * slash is "special", i.e. same cases as the
685 * {case '\\':} in Subst: plus closing brace;
686 * in mksh code "quote removal" on '\c' means
687 * write QCHAR+c, otherwise CHAR+\+CHAR+c are
688 * emitted (in heredocquote:)
690 if ((c = getsc()) == '"' || c == '\\' ||
691 c == '$' || c == '`' || c == /*{*/'}')
699 goto open_ssquote_unless_heredoc;
706 goto subst_dollar_ex;
709 else if (c != /*{*/ '}')
716 /* Same as SBASE, except (,|,) treated specially */
724 PUSH_STATE(SPATTERN);
725 } else /* FALLTHROUGH */
727 if (c == /*{*/ '}') {
739 } else if (c == '\\') {
740 switch (c = getsc()) {
742 /* trailing \ is lost */
750 if (statep->ls_bool) {
768 /* LETEXPR: (( ... )) */
770 if (c == /*(*/ ')') {
771 if (statep->nparen > 0)
773 else if ((c2 = getsc()) == /*(*/ ')') {
783 * mismatched parenthesis -
784 * assume we were really
785 * parsing a (...) expression
788 sp = Xstring(ws, wp);
789 dp = wdstrip(sp + 1, WDS_TPUTS);
790 s = pushs(SREREAD, source->areap);
791 s->start = s->str = s->u.freeme = dp;
799 * parentheses inside quotes and
800 * backslashes are lost, but AT&T ksh
801 * doesn't count them either
806 /* << or <<- delimiter */
809 * here delimiters need a special case since
810 * $ and `...` are not to be treated specially
815 /* trailing \ is lost */
821 goto open_ssquote_unless_heredoc;
823 if ((c2 = getsc()) == '\'') {
826 ignore_backslash_newline++;
828 statep->ls_bool = false;
830 } else if (c2 == '"') {
833 PUSH_SRETRACE(SHEREDQUOTE);
844 /* " in << or <<- delimiter */
850 /* remove the trailing double quote */
852 /* store the quoted string */
854 XcheckN(ws, wp, (dp - sp) * 2);
856 while ((c = *dp++)) {
858 switch ((c = *dp++)) {
875 state = statep->type = SHEREDELIM;
878 /* in *(...|...) pattern (*+?@!) */
880 if (c == /*(*/ ')') {
883 } else if (c == '|') {
885 } else if (c == '(') {
889 PUSH_STATE(SPATTERN);
897 if (statep != &states[1])
898 /* XXX figure out what is missing */
899 yyerror("no closing quote\n");
901 /* This done to avoid tests for SHEREDELIM wherever SBASE tested */
902 if (state == SHEREDELIM)
905 dp = Xstring(ws, wp);
906 if (state == SBASE && (
907 #ifndef MKSH_LEGACY_MODE
908 (c == '&' && !Flag(FSH) && !Flag(FPOSIX)) ||
910 c == '<' || c == '>')) {
911 struct ioword *iop = alloc(sizeof(struct ioword), ATEMP);
913 if (Xlength(ws, wp) == 0)
914 iop->unit = c == '<' ? 0 : 1;
915 else for (iop->unit = 0, c2 = 0; c2 < Xlength(ws, wp); c2 += 2) {
918 if (!ksh_isdigit(dp[c2 + 1]))
920 iop->unit = iop->unit * 10 + ksh_numdig(dp[c2 + 1]);
921 if (iop->unit >= FDBASE)
926 if ((c2 = getsc()) != '>') {
931 iop->ioflag = IOBASH;
936 /* <<, >>, <> are ok, >< is not */
937 if (c == c2 || (c == '<' && c2 == '>')) {
938 iop->ioflag |= c == c2 ?
939 (c == '>' ? IOCAT : IOHERE) : IORDWR;
940 if (iop->ioflag == IOHERE) {
941 if ((c2 = getsc()) == '-')
942 iop->ioflag |= IOSKIP;
944 iop->ioflag |= IOHERESTR;
948 } else if (c2 == '&')
949 iop->ioflag |= IODUP | (c == '<' ? IORDUP : 0);
951 iop->ioflag |= c == '>' ? IOWRITE : IOREAD;
952 if (c == '>' && c2 == '|')
953 iop->ioflag |= IOCLOB;
969 if (wp == dp && state == SBASE) {
972 /* no word, process LEX1 character */
973 if ((c == '|') || (c == '&') || (c == ';') || (c == '('/*)*/)) {
974 if ((c2 = getsc()) == c)
975 c = (c == ';') ? BREAK :
977 (c == '&') ? LOGAND :
978 /* c == '(' ) */ MDPAREN;
979 else if (c == '|' && c2 == '&')
981 else if (c == ';' && c2 == '|')
983 else if (c == ';' && c2 == '&')
989 if ((c2 = getsc()) == '&')
995 } else if (c == '\n') {
1007 /* terminate word */
1009 yylval.cp = Xclose(ws, wp);
1010 if (state == SWORD || state == SLETPAREN
1014 /* unget terminator */
1018 * note: the alias-vs-function code below depends on several
1019 * interna: starting from here, source->str is not modified;
1020 * the way getsc() and ungetsc() operate; etc.
1023 /* copy word to unprefixed string ident */
1026 while ((dp - ident) < IDENT && (c = *sp++) == CHAR)
1029 /* word is not unquoted */
1031 /* make sure the ident array stays NUL padded */
1032 memset(dp, 0, (ident + IDENT) - dp + 1);
1034 if (!(cf & (KEYWORD | ALIAS)))
1037 if (*ident != '\0') {
1039 uint32_t h = hash(ident);
1041 if ((cf & KEYWORD) && (p = ktsearch(&keywords, ident, h)) &&
1042 (!(cf & ESACONLY) || p->val.i == ESAC ||
1043 p->val.i == /*{*/ '}')) {
1044 afree(yylval.cp, ATEMP);
1047 if ((cf & ALIAS) && (p = ktsearch(&aliases, ident, h)) &&
1048 (p->flag & ISSET)) {
1050 * this still points to the same character as the
1051 * ungetsc'd terminator from above
1053 const char *cp = source->str;
1055 /* prefer POSIX but not Korn functions over aliases */
1056 while (*cp == ' ' || *cp == '\t')
1058 * this is like getsc() without skipping
1059 * over Source boundaries (including not
1060 * parsing ungetsc'd characters that got
1061 * pushed into an SREREAD) which is what
1062 * we want here anyway: find out whether
1063 * the alias name is followed by a POSIX
1064 * function definition
1067 /* prefer functions over aliases */
1068 if (cp[0] != '(' || cp[1] != ')') {
1071 while (s && (s->flags & SF_HASALIAS))
1076 /* push alias expansion */
1077 s = pushs(SALIAS, source->areap);
1078 s->start = s->str = p->val.s;
1080 s->flags |= SF_HASALIAS;
1082 if (source->type == SEOF) {
1083 /* prevent infinite recursion at EOS */
1085 source->flags |= SF_HASALIAS;
1088 afree(yylval.cp, ATEMP);
1092 } else if (cf & ALIAS) {
1093 /* retain typeset et al. even when quoted */
1094 if (assign_command((dp = wdstrip(yylval.cp, 0)), true))
1095 strlcpy(ident, dp, sizeof(ident));
1107 for (p = heres; p < herep; p++)
1108 if (!((*p)->ioflag & IOHERESTR))
1114 * read "<<word" text into temp file
1118 readhere(struct ioword *iop)
1121 const char *eof, *eofp;
1126 eof = evalstr(iop->delim, 0);
1128 if (!(iop->ioflag & IOEVAL))
1129 ignore_backslash_newline++;
1131 Xinit(xs, xp, 256, ATEMP);
1134 /* beginning of line */
1136 xpos = Xsavepos(xs, xp);
1137 if (iop->ioflag & IOSKIP) {
1138 /* skip over leading tabs */
1139 while ((c = getsc()) == '\t')
1141 goto heredoc_parse_char;
1146 /* compare with here document marker */
1148 /* end of here document marker, what to do? */
1151 if (!subshell_nesting_type)
1153 * not allowed outside $(...) or (...)
1157 /* allow $(...) or (...) to close here */
1162 * Allow EOF here to commands without trailing
1163 * newlines (mksh -c '...') will work as well.
1166 /* Newline terminates here document marker */
1167 goto heredoc_found_terminator;
1169 } else if (c == *eofp++)
1170 /* store; then read and compare next character */
1171 goto heredoc_store_and_loop;
1172 /* nope, mismatch; read until end of line */
1175 /* oops, reached EOF */
1176 yyerror("%s '%s' unclosed\n", "here document", eof);
1177 /* store character */
1180 /* read next character */
1183 /* we read a newline as last character */
1184 heredoc_store_and_loop:
1185 /* store character */
1189 goto heredoc_read_line;
1190 goto heredoc_read_char;
1192 heredoc_found_terminator:
1193 /* jump back to saved beginning of line */
1194 xp = Xrestpos(xs, xp, xpos);
1195 /* terminate, close and store */
1197 iop->heredoc = Xclose(xs, xp);
1199 if (!(iop->ioflag & IOEVAL))
1200 ignore_backslash_newline--;
1204 yyerror(const char *fmt, ...)
1208 /* pop aliases and re-reads */
1209 while (source->type == SALIAS || source->type == SREREAD)
1210 source = source->next;
1211 /* zap pending input */
1216 shf_vfprintf(shl_out, fmt, va);
1222 * input for yylex with alias expansion
1226 pushs(int type, Area *areap)
1230 s = alloc(sizeof(Source), areap);
1231 memset(s, 0, sizeof(Source));
1235 if (type == SFILE || type == SSTDIN)
1236 XinitN(s->xs, 256, s->areap);
1246 while ((c = *s->str++) == 0) {
1247 /* return 0 for EOF by default */
1263 case SSTRINGCMDLINE:
1267 s->start = s->str = *s->u.strv++;
1272 if (*s->u.strv == NULL) {
1273 s->start = s->str = "\n";
1276 s->start = s->str = " ";
1282 if (s->flags & SF_ALIASEND) {
1283 /* pass on an unused SF_ALIAS flag */
1285 source->flags |= s->flags & SF_ALIAS;
1287 } else if (*s->u.tblp->val.s &&
1288 (c = strnul(s->u.tblp->val.s)[-1], ksh_isspace(c))) {
1289 /* pop source stack */
1290 source = s = s->next;
1292 * Note that this alias ended with a
1293 * space, enabling alias expansion on
1294 * the following word.
1296 s->flags |= SF_ALIAS;
1299 * At this point, we need to keep the current
1300 * alias in the source list so recursive
1301 * aliases can be detected and we also need to
1302 * return the next character. Do this by
1303 * temporarily popping the alias to get the
1304 * next character and then put it back in the
1305 * source list with the SF_ALIASEND flag set.
1307 /* pop source stack */
1309 source->flags |= s->flags & SF_ALIAS;
1312 s->flags |= SF_ALIASEND;
1313 s->ugbuf[0] = c; s->ugbuf[1] = '\0';
1314 s->start = s->str = s->ugbuf;
1319 /* avoid reading EOF twice */
1327 if (s->start != s->ugbuf)
1329 afree(s->u.freeme, ATEMP);
1330 source = s = s->next;
1333 if (s->str == NULL) {
1335 s->start = s->str = null;
1338 if (s->flags & SF_ECHO) {
1339 shf_puts(s->str, shl_out);
1347 getsc_line(Source *s)
1349 char *xp = Xstring(s->xs, xp), *cp;
1350 bool interactive = Flag(FTALKING) && s->type == SSTDIN;
1351 bool have_tty = tobool(interactive && (s->flags & SF_TTY));
1353 /* Done here to ensure nothing odd happens when a timeout occurs */
1354 XcheckN(s->xs, xp, LINE);
1356 s->start = s->str = xp;
1358 if (have_tty && ksh_tmout) {
1359 ksh_tmout_state = TMOUT_READING;
1364 #ifndef MKSH_NO_CMDLINE_EDITING
1369 Flag(FEMACS) || Flag(FGMACS))) {
1386 while (/* CONSTCOND */ 1) {
1387 char *p = shf_getse(xp, Xnleft(s->xs, xp), s->u.shf);
1389 if (!p && shf_error(s->u.shf) &&
1390 shf_errno(s->u.shf) == EINTR) {
1391 shf_clearerr(s->u.shf);
1396 if (!p || (xp = p, xp[-1] == '\n'))
1398 /* double buffer size */
1399 /* move past NUL so doubling works... */
1401 XcheckN(s->xs, xp, Xlength(s->xs, xp));
1402 /* ...and move back again */
1406 * flush any unwanted input so other programs/builtins
1407 * can read it. Not very optimal, but less error prone
1408 * than flushing else where, dealing with redirections,
1410 * TODO: reduce size of shf buffer (~128?) if SSTDIN
1412 if (s->type == SSTDIN)
1413 shf_flush(s->u.shf);
1416 * XXX: temporary kludge to restore source after a
1417 * trap may have been executed.
1420 if (have_tty && ksh_tmout) {
1421 ksh_tmout_state = TMOUT_EXECUTING;
1424 cp = Xstring(s->xs, xp);
1426 s->start = s->str = cp;
1427 strip_nuls(Xstring(s->xs, xp), Xlength(s->xs, xp));
1428 /* Note: if input is all nulls, this is not eof */
1429 if (Xlength(s->xs, xp) == 0) {
1431 if (s->type == SFILE)
1432 shf_fdclose(s->u.shf);
1434 } else if (interactive && *s->str) {
1435 if (cur_prompt != PS1)
1436 histsave(&s->line, s->str, HIST_APPEND, true);
1437 else if (!ctype(*s->str, C_IFS | C_IFSWS))
1438 histsave(&s->line, s->str, HIST_QUEUE, true);
1439 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
1441 goto check_for_sole_return;
1442 } else if (interactive && cur_prompt == PS1) {
1443 check_for_sole_return:
1444 cp = Xstring(s->xs, xp);
1445 while (*cp && ctype(*cp, C_IFSWS))
1448 histsave(&s->line, NULL, HIST_FLUSH, true);
1454 set_prompt(PS2, NULL);
1458 set_prompt(int to, Source *s)
1460 cur_prompt = (uint8_t)to;
1466 * Substitute ! and !! here, before substitutions are done
1467 * so ! in expanded variables are not expanded.
1468 * NOTE: this is not what AT&T ksh does (it does it after
1469 * substitutions, POSIX doesn't say which is to be done.
1473 char * volatile ps1;
1477 ps1 = str_val(global("PS1"));
1478 shf = shf_sopen(NULL, strlen(ps1) * 2,
1479 SHF_WR | SHF_DYNAMIC, NULL);
1481 if (*ps1 != '!' || *++ps1 == '!')
1482 shf_putchar(*ps1++, shf);
1484 shf_fprintf(shf, "%lu", s ?
1485 (unsigned long)s->line + 1 : 0UL);
1486 ps1 = shf_sclose(shf);
1487 saved_lineno = current_lineno;
1489 current_lineno = s->line + 1;
1490 saved_atemp = ATEMP;
1492 if (kshsetjmp(e->jbuf)) {
1493 prompt = safe_prompt;
1495 * Don't print an error - assume it has already
1496 * been printed. Reason is we may have forked
1497 * to run a command and the child may be
1498 * unwinding its stack through this code as it
1502 char *cp = substitute(ps1, 0);
1503 strdupx(prompt, cp, saved_atemp);
1505 current_lineno = saved_lineno;
1509 /* command continuation */
1511 prompt = str_val(global("PS2"));
1517 pprompt(const char *cp, int ntruncate)
1520 bool doprint = (ntruncate != -1);
1521 bool indelimit = false;
1522 int columns = 0, lines = 0;
1525 * Undocumented AT&T ksh feature:
1526 * If the second char in the prompt string is \r then the first
1527 * char is taken to be a non-printing delimiter and any chars
1528 * between two instances of the delimiter are not considered to
1529 * be part of the prompt length
1531 if (*cp && cp[1] == '\r') {
1536 if (indelimit && *cp != delimiter)
1538 else if (*cp == '\n' || *cp == '\r') {
1539 lines += columns / x_cols + ((*cp == '\n') ? 1 : 0);
1541 } else if (*cp == '\t') {
1542 columns = (columns | 7) + 1;
1543 } else if (*cp == '\b') {
1546 } else if (*cp == delimiter)
1547 indelimit = !indelimit;
1548 else if (UTFMODE && ((unsigned char)*cp > 0x7F)) {
1550 columns += utf_widthadj(cp, &cp2);
1551 if (doprint && (indelimit ||
1552 (ntruncate < (x_cols * lines + columns))))
1553 shf_write(cp, cp2 - cp, shl_out);
1554 cp = cp2 - /* loop increment */ 1;
1558 if (doprint && (*cp != delimiter) &&
1559 (indelimit || (ntruncate < (x_cols * lines + columns))))
1560 shf_putc(*cp, shl_out);
1564 return (x_cols * lines + columns);
1568 * Read the variable part of a ${...} expression (i.e. up to but not
1569 * including the :[-+?=#%] or close-brace).
1572 get_brace_var(XString *wsp, char *wp)
1576 PS_INITIAL, PS_SAW_HASH, PS_IDENT,
1578 } state = PS_INITIAL;
1580 while (/* CONSTCOND */ 1) {
1582 /* State machine to figure out where the variable part ends. */
1585 if (c == '#' || c == '!' || c == '%') {
1586 state = PS_SAW_HASH;
1593 else if (ksh_isdigit(c))
1595 else if (c == '#') {
1596 if (state == PS_SAW_HASH) {
1601 if (c2 != /*{*/ '}') {
1607 } else if (ctype(c, C_VAR1))
1613 if (!ksh_isalnux(c)) {
1617 if (!arraysub(&tmp))
1618 yyerror("missing ]\n");
1620 for (p = tmp; *p; ) {
1632 if (!ksh_isdigit(c))
1642 /* end of variable part */
1649 * Save an array subscript - returns true if matching bracket found, false
1650 * if eof or newline was found.
1651 * (Returned string double null terminated)
1654 arraysub(char **strp)
1658 /* we are just past the initial [ */
1659 unsigned int depth = 1;
1661 Xinit(ws, wp, 32, ATEMP);
1671 } while (depth > 0 && c && c != '\n');
1674 *strp = Xclose(ws, wp);
1676 return (tobool(depth == 0));
1679 /* Unget a char: handles case when we are already at the start of the buffer */
1683 struct sretrace_info *rp = retrace_info;
1687 /* Don't unget EOF... */
1688 if (source->str == null && c == '\0')
1691 if (Xlength(rp->xs, rp->xp))
1700 if (source->str > source->start)
1705 s = pushs(SREREAD, source->areap);
1706 s->ugbuf[0] = c; s->ugbuf[1] = '\0';
1707 s->start = s->str = s->ugbuf;
1714 /* Called to get a char that isn't a \newline sequence. */
1720 if (ignore_backslash_newline)
1721 return (o_getsc_u());
1723 if (backslash_skip == 1) {
1725 return (o_getsc_u());
1730 while (/* CONSTCOND */ 1) {
1733 if ((c2 = o_getsc_u()) == '\n')
1734 /* ignore the \newline; get the next char... */
1748 if ((unsigned char)(c = o_getsc_u()) != 0xEF) {
1752 if ((unsigned char)(c = o_getsc_u()) != 0xBB) {
1757 if ((unsigned char)(c = o_getsc_u()) != 0xBF) {
1767 push_state_i(State_info *si, Lex_state *old_end)
1769 Lex_state *news = alloc2(STATE_BSIZE, sizeof(Lex_state), ATEMP);
1771 news[0].ls_base = old_end;
1772 si->base = &news[0];
1773 si->end = &news[STATE_BSIZE];
1778 pop_state_i(State_info *si, Lex_state *old_end)
1780 Lex_state *old_base = si->base;
1782 si->base = old_end->ls_base - STATE_BSIZE;
1783 si->end = old_end->ls_base;
1785 afree(old_base, ATEMP);
1787 return (si->base + STATE_BSIZE - 1);