1 /* $OpenBSD: lex.c,v 1.49 2013/12/17 16:37:06 deraadt Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5 * 2011, 2012, 2013, 2014
6 * Thorsten Glaser <tg@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.193 2014/06/29 11:28:28 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 <<,<<-,<<< delimiter */
42 #define SHEREDQUOTE 11 /* parsing " in <<,<<-,<<< 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 s_get(void);
98 static void s_put(int);
99 static char *get_brace_var(XString *, char *);
100 static bool arraysub(char **);
101 static void gethere(bool);
102 static Lex_state *push_state_i(State_info *, Lex_state *);
103 static Lex_state *pop_state_i(State_info *, Lex_state *);
105 static int backslash_skip;
106 static int ignore_backslash_newline;
108 /* optimised getsc_bn() */
109 #define o_getsc() (*source->str != '\0' && *source->str != '\\' && \
110 !backslash_skip ? *source->str++ : getsc_bn())
111 /* optimised getsc_uu() */
112 #define o_getsc_u() ((*source->str != '\0') ? *source->str++ : getsc_uu())
115 #define o_getsc_r(carg) { \
117 struct sretrace_info *rp = retrace_info; \
120 Xcheck(rp->xs, rp->xp); \
128 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
129 static int getsc(void);
134 o_getsc_r(o_getsc());
137 static int getsc_r(int);
145 #define getsc() getsc_r(o_getsc())
148 #define STATE_BSIZE 8
150 #define PUSH_STATE(s) do { \
151 if (++statep == state_info.end) \
152 statep = push_state_i(&state_info, statep); \
153 state = statep->type = (s); \
154 } while (/* CONSTCOND */ 0)
156 #define POP_STATE() do { \
157 if (--statep == state_info.base) \
158 statep = pop_state_i(&state_info, statep); \
159 state = statep->type; \
160 } while (/* CONSTCOND */ 0)
162 #define PUSH_SRETRACE(s) do { \
163 struct sretrace_info *ri; \
166 statep->ls_start = Xsavepos(ws, wp); \
167 ri = alloc(sizeof(struct sretrace_info), ATEMP); \
168 Xinit(ri->xs, ri->xp, 64, ATEMP); \
169 ri->next = retrace_info; \
171 } while (/* CONSTCOND */ 0)
173 #define POP_SRETRACE() do { \
174 wp = Xrestpos(ws, wp, statep->ls_start); \
175 *retrace_info->xp = '\0'; \
176 sp = Xstring(retrace_info->xs, retrace_info->xp); \
177 dp = (void *)retrace_info; \
178 retrace_info = retrace_info->next; \
181 } while (/* CONSTCOND */ 0)
186 * tokens are not regular expressions, they are LL(1).
187 * for example, "${var:-${PWD}}", and "$(size $(whence ksh))".
188 * hence the state stack. Note "$(...)" are now parsed recursively.
194 Lex_state states[STATE_BSIZE], *statep, *s2, *base;
195 State_info state_info;
198 XString ws; /* expandable output word */
199 char *wp; /* output word pointer */
203 states[0].type = SINVALID;
204 states[0].ls_base = NULL;
206 state_info.base = states;
207 state_info.end = &state_info.base[STATE_BSIZE];
209 Xinit(ws, wp, 64, ATEMP);
212 ignore_backslash_newline = 0;
216 else if (cf & LETEXPR) {
217 /* enclose arguments in (double) quotes */
223 state = (cf & HEREDELIM) ? SHEREDELIM : SBASE;
224 while ((c = getsc()) == ' ' || c == '\t')
227 ignore_backslash_newline++;
228 while ((c = getsc()) != '\0' && c != '\n')
230 ignore_backslash_newline--;
234 if (source->flags & SF_ALIAS) {
235 /* trailing ' ' in alias definition */
236 source->flags &= ~SF_ALIAS;
240 /* Initial state: one of SWORD SLETPAREN SHEREDELIM SBASE */
241 statep->type = state;
243 /* check for here string */
244 if (state == SHEREDELIM) {
248 while ((c = getsc()) == ' ' || c == '\t')
257 /* collect non-special or quoted characters to form word */
258 while (!((c = getsc()) == 0 ||
259 ((state == SBASE || state == SHEREDELIM) && ctype(c, C_LEX1)))) {
260 if (state == SBASE &&
261 subshell_nesting_type == /*{*/ '}' &&
263 /* possibly end ${ :;} */
273 else if (statep->nparen == 0 && (c == /*{*/ '}' ||
274 c == (int)statep->ls_adelim.delimiter)) {
277 if (c == /*{*/ '}' || --statep->ls_adelim.num == 0)
285 if (c == '[' && (cf & (VARASN|ARRAYVAR))) {
288 if (is_wdvarname(Xstring(ws, wp), false)) {
291 if (arraysub(&tmp)) {
294 for (p = tmp; *p; ) {
317 Sbase1: /* includes *(...|...) pattern (*+?@!) */
318 if (c == '*' || c == '@' || c == '+' || c == '?' ||
321 if (c2 == '(' /*)*/ ) {
324 PUSH_STATE(SPATTERN);
330 Sbase2: /* doesn't include *(...|...) pattern (*+?@!) */
335 /* trailing \ is lost */
341 open_ssquote_unless_heredoc:
345 ignore_backslash_newline++;
355 * processing of dollar sign belongs into
356 * Subst, except for those which can open
357 * a string: $'…' and $"…"
393 /* trailing \ is lost */
405 if (c == '(') /*)*/ {
407 if (c == '(') /*)*/ {
409 PUSH_SRETRACE(SASPAREN);
411 *retrace_info->xp++ = '(';
424 } else if (c == '{') /*}*/ {
425 if ((c = getsc()) == '|') {
432 } else if (ctype(c, C_IFSWS)) {
435 * "command" substitution
443 wp = get_brace_var(&ws, wp);
445 /* allow :# and :% (ksh88 compat) */
457 statep->ls_adelim.delimiter = ':';
458 statep->ls_adelim.num = 1;
461 } else if (ksh_isdigit(c) ||
462 c == '('/*)*/ || c == ' ' ||
465 /* substring subst. */
473 statep->ls_adelim.delimiter = ':';
474 statep->ls_adelim.num = 2;
478 } else if (c == '/') {
481 if ((c = getsc()) == '/') {
488 statep->ls_adelim.delimiter = '/';
489 statep->ls_adelim.num = 1;
494 * If this is a trim operation,
495 * treat (,|,) specially in STBRACE.
497 if (ctype(c, C_SUBOP2)) {
500 PUSH_STATE(STBRACEBOURNE);
502 PUSH_STATE(STBRACEKORN);
505 if (state == SDQUOTE ||
511 } else if (ksh_isalphx(c)) {
518 } while (ksh_isalnux(c));
523 } else if (ctype(c, C_VAR1 | C_DIGIT)) {
542 * Need to know if we are inside double quotes
543 * since sh/AT&T-ksh translate the \" to " in
545 * This is not done in POSIX mode (section
546 * 3.2.3, Double Quotes: "The backquote shall
547 * retain its special meaning introducing the
548 * other form of command substitution (see
549 * 3.6.3). The portion of the quoted string
550 * from the initial backquote and the
551 * characters up to the next backquote that
552 * is not preceded by a backslash (having
553 * escape characters removed) defines that
554 * command whose output replaces `...` when
555 * the word is expanded."
556 * Section 3.6.3, Command Substitution:
557 * "Within the backquoted style of command
558 * substitution, backslash shall retain its
559 * literal meaning, except when followed by
562 statep->ls_bool = false;
564 base = state_info.base;
565 while (/* CONSTCOND */ 1) {
566 for (; s2 != base; s2--) {
567 if (s2->type == SDQUOTE) {
568 statep->ls_bool = true;
574 if (!(s2 = s2->ls_base))
576 base = s2-- - STATE_BSIZE;
597 ignore_backslash_newline--;
598 } else if (c == '\\') {
599 if ((c2 = unbksl(true, s_get, s_put)) == -1)
602 statep->ls_bool = true;
603 if (!statep->ls_bool) {
606 if ((unsigned int)c2 < 0x100) {
610 cz = utf_wctomb(ts, c2 - 0x100);
612 for (cz = 0; ts[cz]; ++cz) {
618 } else if (!statep->ls_bool) {
627 if ((cf & HEREDOC) || state == SQBRACE)
630 ignore_backslash_newline--;
651 if (statep->nparen == 1) {
655 if ((c2 = getsc()) == /*(*/ ')') {
658 memcpy(wp, sp + 1, cz);
668 * mismatched parenthesis -
669 * assume we were really
670 * parsing a $(...) expression
683 /* reuse existing state machine */
689 * perform POSIX "quote removal" if the back-
690 * slash is "special", i.e. same cases as the
691 * {case '\\':} in Subst: plus closing brace;
692 * in mksh code "quote removal" on '\c' means
693 * write QCHAR+c, otherwise CHAR+\+CHAR+c are
694 * emitted (in heredocquote:)
696 if ((c = getsc()) == '"' || c == '\\' ||
697 c == '$' || c == '`' || c == /*{*/'}')
705 goto open_ssquote_unless_heredoc;
712 goto subst_dollar_ex;
715 else if (c != /*{*/ '}')
722 /* Same as SBASE, except (,|,) treated specially */
730 PUSH_STATE(SPATTERN);
731 } else /* FALLTHROUGH */
733 if (c == /*{*/ '}') {
745 } else if (c == '\\') {
746 switch (c = getsc()) {
748 /* trailing \ is lost */
755 if (statep->ls_bool) {
773 /* LETEXPR: (( ... )) */
775 if (c == /*(*/ ')') {
776 if (statep->nparen > 0)
778 else if ((c2 = getsc()) == /*(*/ ')') {
787 * mismatched parenthesis -
788 * assume we were really
789 * parsing a (...) expression
792 sp = Xstring(ws, wp);
793 dp = wdstrip(sp, WDS_KEEPQ);
794 s = pushs(SREREAD, source->areap);
795 s->start = s->str = s->u.freeme = dp;
802 * parentheses inside quotes and
803 * backslashes are lost, but AT&T ksh
804 * doesn't count them either
809 /* <<, <<-, <<< delimiter */
812 * here delimiters need a special case since
813 * $ and `...` are not to be treated specially
818 /* trailing \ is lost */
824 goto open_ssquote_unless_heredoc;
826 if ((c2 = getsc()) == '\'') {
829 ignore_backslash_newline++;
831 statep->ls_bool = false;
833 } else if (c2 == '"') {
836 PUSH_SRETRACE(SHEREDQUOTE);
847 /* " in <<, <<-, <<< delimiter */
853 /* remove the trailing double quote */
855 /* store the quoted string */
857 XcheckN(ws, wp, (dp - sp));
859 while ((c = *dp++)) {
861 switch ((c = *dp++)) {
878 state = statep->type = SHEREDELIM;
881 /* in *(...|...) pattern (*+?@!) */
883 if (c == /*(*/ ')') {
886 } else if (c == '|') {
888 } else if (c == '(') {
892 PUSH_STATE(SPATTERN);
900 if (statep != &states[1])
901 /* XXX figure out what is missing */
902 yyerror("no closing quote\n");
904 /* This done to avoid tests for SHEREDELIM wherever SBASE tested */
905 if (state == SHEREDELIM)
908 dp = Xstring(ws, wp);
909 if (state == SBASE && (
910 #ifndef MKSH_LEGACY_MODE
911 (c == '&' && !Flag(FSH) && !Flag(FPOSIX)) ||
913 c == '<' || c == '>')) {
914 struct ioword *iop = alloc(sizeof(struct ioword), ATEMP);
916 if (Xlength(ws, wp) == 0)
917 iop->unit = c == '<' ? 0 : 1;
918 else for (iop->unit = 0, c2 = 0; c2 < Xlength(ws, wp); c2 += 2) {
921 if (!ksh_isdigit(dp[c2 + 1]))
923 iop->unit = (iop->unit * 10) + dp[c2 + 1] - '0';
926 if (iop->unit >= FDBASE)
930 if ((c2 = getsc()) != '>') {
940 /* <<, >>, <> are ok, >< is not */
941 if (c == c2 || (c == '<' && c2 == '>')) {
942 iop->flag |= c == c2 ?
943 (c == '>' ? IOCAT : IOHERE) : IORDWR;
944 if (iop->flag == IOHERE) {
945 if ((c2 = getsc()) == '-') {
948 } else if (c2 == '<')
949 iop->flag |= IOHERESTR;
952 iop->flag |= IONDELIM;
954 } else if (c2 == '&')
955 iop->flag |= IODUP | (c == '<' ? IORDUP : 0);
957 iop->flag |= c == '>' ? IOWRITE : IOREAD;
958 if (c == '>' && c2 == '|')
975 if (wp == dp && state == SBASE) {
978 /* no word, process LEX1 character */
979 if ((c == '|') || (c == '&') || (c == ';') || (c == '('/*)*/)) {
980 if ((c2 = getsc()) == c)
981 c = (c == ';') ? BREAK :
983 (c == '&') ? LOGAND :
984 /* c == '(' ) */ MDPAREN;
985 else if (c == '|' && c2 == '&')
987 else if (c == ';' && c2 == '|')
989 else if (c == ';' && c2 == '&')
995 if ((c2 = getsc()) == '&')
1001 } else if (c == '\n') {
1005 } else if (c == '\0')
1006 /* need here strings at EOF */
1011 /* terminate word */
1013 yylval.cp = Xclose(ws, wp);
1014 if (state == SWORD || state == SLETPAREN
1018 /* unget terminator */
1022 * note: the alias-vs-function code below depends on several
1023 * interna: starting from here, source->str is not modified;
1024 * the way getsc() and ungetsc() operate; etc.
1027 /* copy word to unprefixed string ident */
1030 if ((cf & HEREDELIM) && (sp[1] == '<'))
1031 while ((dp - ident) < IDENT) {
1032 if ((c = *sp++) == CHAR)
1034 else if ((c != OQUOTE) && (c != CQUOTE))
1038 while ((dp - ident) < IDENT && (c = *sp++) == CHAR)
1040 /* Make sure the ident array stays '\0' padded */
1041 memset(dp, 0, (ident + IDENT) - dp + 1);
1043 /* word is not unquoted */
1046 if (*ident != '\0' && (cf & (KEYWORD | ALIAS))) {
1048 uint32_t h = hash(ident);
1050 if ((cf & KEYWORD) && (p = ktsearch(&keywords, ident, h)) &&
1051 (!(cf & ESACONLY) || p->val.i == ESAC ||
1052 p->val.i == /*{*/ '}')) {
1053 afree(yylval.cp, ATEMP);
1056 if ((cf & ALIAS) && (p = ktsearch(&aliases, ident, h)) &&
1057 (p->flag & ISSET)) {
1059 * this still points to the same character as the
1060 * ungetsc'd terminator from above
1062 const char *cp = source->str;
1064 /* prefer POSIX but not Korn functions over aliases */
1065 while (*cp == ' ' || *cp == '\t')
1067 * this is like getsc() without skipping
1068 * over Source boundaries (including not
1069 * parsing ungetsc'd characters that got
1070 * pushed into an SREREAD) which is what
1071 * we want here anyway: find out whether
1072 * the alias name is followed by a POSIX
1073 * function definition (only the opening
1074 * parenthesis is checked though)
1077 /* prefer functions over aliases */
1078 if (cp[0] != '(' || cp[1] != ')') {
1081 while (s && (s->flags & SF_HASALIAS))
1086 /* push alias expansion */
1087 s = pushs(SALIAS, source->areap);
1088 s->start = s->str = p->val.s;
1090 s->flags |= SF_HASALIAS;
1092 if (source->type == SEOF) {
1093 /* prevent infinite recursion at EOS */
1095 source->flags |= SF_HASALIAS;
1098 afree(yylval.cp, ATEMP);
1112 for (p = heres; p < herep; p++)
1113 if (iseof && !((*p)->flag & IOHERESTR))
1114 /* only here strings at EOF */
1122 * read "<<word" text into temp file
1126 readhere(struct ioword *iop)
1129 const char *eof, *eofp;
1134 if (iop->flag & IOHERESTR) {
1135 /* process the here string */
1136 iop->heredoc = xp = evalstr(iop->delim, DOBLANK);
1137 xpos = strlen(xp) - 1;
1138 memmove(xp, xp + 1, xpos);
1143 eof = iop->flag & IONDELIM ? "<<" : evalstr(iop->delim, 0);
1145 if (!(iop->flag & IOEVAL))
1146 ignore_backslash_newline++;
1148 Xinit(xs, xp, 256, ATEMP);
1151 /* beginning of line */
1153 xpos = Xsavepos(xs, xp);
1154 if (iop->flag & IOSKIP) {
1155 /* skip over leading tabs */
1156 while ((c = getsc()) == '\t')
1158 goto heredoc_parse_char;
1163 /* compare with here document marker */
1165 /* end of here document marker, what to do? */
1168 if (!subshell_nesting_type)
1170 * not allowed outside $(...) or (...)
1174 /* allow $(...) or (...) to close here */
1179 * Allow EOF here to commands without trailing
1180 * newlines (mksh -c '...') will work as well.
1183 /* Newline terminates here document marker */
1184 goto heredoc_found_terminator;
1186 } else if (c == *eofp++)
1187 /* store; then read and compare next character */
1188 goto heredoc_store_and_loop;
1189 /* nope, mismatch; read until end of line */
1192 /* oops, reached EOF */
1193 yyerror("%s '%s' unclosed\n", "here document", eof);
1194 /* store character */
1197 /* read next character */
1200 /* we read a newline as last character */
1201 heredoc_store_and_loop:
1202 /* store character */
1206 goto heredoc_read_line;
1207 goto heredoc_read_char;
1209 heredoc_found_terminator:
1210 /* jump back to saved beginning of line */
1211 xp = Xrestpos(xs, xp, xpos);
1212 /* terminate, close and store */
1214 iop->heredoc = Xclose(xs, xp);
1216 if (!(iop->flag & IOEVAL))
1217 ignore_backslash_newline--;
1221 yyerror(const char *fmt, ...)
1225 /* pop aliases and re-reads */
1226 while (source->type == SALIAS || source->type == SREREAD)
1227 source = source->next;
1228 /* zap pending input */
1233 shf_vfprintf(shl_out, fmt, va);
1239 * input for yylex with alias expansion
1243 pushs(int type, Area *areap)
1247 s = alloc(sizeof(Source), areap);
1248 memset(s, 0, sizeof(Source));
1252 if (type == SFILE || type == SSTDIN)
1253 XinitN(s->xs, 256, s->areap);
1263 while ((c = *s->str++) == 0) {
1264 /* return 0 for EOF by default */
1280 case SSTRINGCMDLINE:
1284 s->start = s->str = *s->u.strv++;
1289 if (*s->u.strv == NULL) {
1290 s->start = s->str = "\n";
1293 s->start = s->str = " ";
1299 if (s->flags & SF_ALIASEND) {
1300 /* pass on an unused SF_ALIAS flag */
1302 source->flags |= s->flags & SF_ALIAS;
1304 } else if (*s->u.tblp->val.s &&
1305 (c = strnul(s->u.tblp->val.s)[-1], ksh_isspace(c))) {
1306 /* pop source stack */
1307 source = s = s->next;
1309 * Note that this alias ended with a
1310 * space, enabling alias expansion on
1311 * the following word.
1313 s->flags |= SF_ALIAS;
1316 * At this point, we need to keep the current
1317 * alias in the source list so recursive
1318 * aliases can be detected and we also need to
1319 * return the next character. Do this by
1320 * temporarily popping the alias to get the
1321 * next character and then put it back in the
1322 * source list with the SF_ALIASEND flag set.
1324 /* pop source stack */
1326 source->flags |= s->flags & SF_ALIAS;
1329 s->flags |= SF_ALIASEND;
1330 s->ugbuf[0] = c; s->ugbuf[1] = '\0';
1331 s->start = s->str = s->ugbuf;
1336 /* avoid reading EOF twice */
1344 if (s->start != s->ugbuf)
1346 afree(s->u.freeme, ATEMP);
1347 source = s = s->next;
1350 if (s->str == NULL) {
1352 s->start = s->str = null;
1355 if (s->flags & SF_ECHO) {
1356 shf_puts(s->str, shl_out);
1364 getsc_line(Source *s)
1366 char *xp = Xstring(s->xs, xp), *cp;
1367 bool interactive = Flag(FTALKING) && s->type == SSTDIN;
1368 bool have_tty = tobool(interactive && (s->flags & SF_TTY));
1370 /* Done here to ensure nothing odd happens when a timeout occurs */
1371 XcheckN(s->xs, xp, LINE);
1373 s->start = s->str = xp;
1375 if (have_tty && ksh_tmout) {
1376 ksh_tmout_state = TMOUT_READING;
1381 #ifndef MKSH_NO_CMDLINE_EDITING
1386 Flag(FEMACS) || Flag(FGMACS))) {
1403 while (/* CONSTCOND */ 1) {
1404 char *p = shf_getse(xp, Xnleft(s->xs, xp), s->u.shf);
1406 if (!p && shf_error(s->u.shf) &&
1407 shf_errno(s->u.shf) == EINTR) {
1408 shf_clearerr(s->u.shf);
1413 if (!p || (xp = p, xp[-1] == '\n'))
1415 /* double buffer size */
1416 /* move past NUL so doubling works... */
1418 XcheckN(s->xs, xp, Xlength(s->xs, xp));
1419 /* ...and move back again */
1423 * flush any unwanted input so other programs/builtins
1424 * can read it. Not very optimal, but less error prone
1425 * than flushing else where, dealing with redirections,
1427 * TODO: reduce size of shf buffer (~128?) if SSTDIN
1429 if (s->type == SSTDIN)
1430 shf_flush(s->u.shf);
1433 * XXX: temporary kludge to restore source after a
1434 * trap may have been executed.
1437 if (have_tty && ksh_tmout) {
1438 ksh_tmout_state = TMOUT_EXECUTING;
1441 cp = Xstring(s->xs, xp);
1443 s->start = s->str = cp;
1444 strip_nuls(Xstring(s->xs, xp), Xlength(s->xs, xp));
1445 /* Note: if input is all nulls, this is not eof */
1446 if (Xlength(s->xs, xp) == 0) {
1448 if (s->type == SFILE)
1449 shf_fdclose(s->u.shf);
1451 } else if (interactive && *s->str &&
1452 (cur_prompt != PS1 || !ctype(*s->str, C_IFS | C_IFSWS))) {
1453 histsave(&s->line, s->str, true, true);
1454 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
1455 } else if (interactive && cur_prompt == PS1) {
1456 cp = Xstring(s->xs, xp);
1457 while (*cp && ctype(*cp, C_IFSWS))
1464 set_prompt(PS2, NULL);
1468 set_prompt(int to, Source *s)
1476 * Substitute ! and !! here, before substitutions are done
1477 * so ! in expanded variables are not expanded.
1478 * NOTE: this is not what AT&T ksh does (it does it after
1479 * substitutions, POSIX doesn't say which is to be done.
1483 char * volatile ps1;
1486 ps1 = str_val(global("PS1"));
1487 shf = shf_sopen(NULL, strlen(ps1) * 2,
1488 SHF_WR | SHF_DYNAMIC, NULL);
1490 if (*ps1 != '!' || *++ps1 == '!')
1491 shf_putchar(*ps1++, shf);
1493 shf_fprintf(shf, "%d",
1494 s ? s->line + 1 : 0);
1495 ps1 = shf_sclose(shf);
1496 saved_atemp = ATEMP;
1498 if (kshsetjmp(e->jbuf)) {
1499 prompt = safe_prompt;
1501 * Don't print an error - assume it has already
1502 * been printed. Reason is we may have forked
1503 * to run a command and the child may be
1504 * unwinding its stack through this code as it
1508 char *cp = substitute(ps1, 0);
1509 strdupx(prompt, cp, saved_atemp);
1514 /* command continuation */
1516 prompt = str_val(global("PS2"));
1522 pprompt(const char *cp, int ntruncate)
1525 bool doprint = (ntruncate != -1);
1526 bool indelimit = false;
1527 int columns = 0, lines = 0;
1530 * Undocumented AT&T ksh feature:
1531 * If the second char in the prompt string is \r then the first
1532 * char is taken to be a non-printing delimiter and any chars
1533 * between two instances of the delimiter are not considered to
1534 * be part of the prompt length
1536 if (*cp && cp[1] == '\r') {
1541 if (indelimit && *cp != delimiter)
1543 else if (*cp == '\n' || *cp == '\r') {
1544 lines += columns / x_cols + ((*cp == '\n') ? 1 : 0);
1546 } else if (*cp == '\t') {
1547 columns = (columns | 7) + 1;
1548 } else if (*cp == '\b') {
1551 } else if (*cp == delimiter)
1552 indelimit = !indelimit;
1553 else if (UTFMODE && ((unsigned char)*cp > 0x7F)) {
1555 columns += utf_widthadj(cp, &cp2);
1556 if (doprint && (indelimit ||
1557 (ntruncate < (x_cols * lines + columns))))
1558 shf_write(cp, cp2 - cp, shl_out);
1559 cp = cp2 - /* loop increment */ 1;
1563 if (doprint && (*cp != delimiter) &&
1564 (indelimit || (ntruncate < (x_cols * lines + columns))))
1565 shf_putc(*cp, shl_out);
1569 return (x_cols * lines + columns);
1573 * Read the variable part of a ${...} expression (i.e. up to but not
1574 * including the :[-+?=#%] or close-brace).
1577 get_brace_var(XString *wsp, char *wp)
1581 PS_INITIAL, PS_SAW_HASH, PS_IDENT,
1583 } state = PS_INITIAL;
1585 while (/* CONSTCOND */ 1) {
1587 /* State machine to figure out where the variable part ends. */
1590 if (c == '#' || c == '!' || c == '%') {
1591 state = PS_SAW_HASH;
1598 else if (ksh_isdigit(c))
1600 else if (c == '#') {
1601 if (state == PS_SAW_HASH) {
1606 if (c2 != /*{*/ '}') {
1612 } else if (ctype(c, C_VAR1))
1618 if (!ksh_isalnux(c)) {
1622 if (!arraysub(&tmp))
1623 yyerror("missing ]\n");
1625 for (p = tmp; *p; ) {
1637 if (!ksh_isdigit(c))
1647 /* end of variable part */
1654 * Save an array subscript - returns true if matching bracket found, false
1655 * if eof or newline was found.
1656 * (Returned string double null terminated)
1659 arraysub(char **strp)
1663 /* we are just past the initial [ */
1664 unsigned int depth = 1;
1666 Xinit(ws, wp, 32, ATEMP);
1676 } while (depth > 0 && c && c != '\n');
1679 *strp = Xclose(ws, wp);
1681 return (tobool(depth == 0));
1684 /* Unget a char: handles case when we are already at the start of the buffer */
1688 struct sretrace_info *rp = retrace_info;
1692 /* Don't unget EOF... */
1693 if (source->str == null && c == '\0')
1696 if (Xlength(rp->xs, rp->xp))
1705 if (source->str > source->start)
1710 s = pushs(SREREAD, source->areap);
1711 s->ugbuf[0] = c; s->ugbuf[1] = '\0';
1712 s->start = s->str = s->ugbuf;
1719 /* Called to get a char that isn't a \newline sequence. */
1725 if (ignore_backslash_newline)
1726 return (o_getsc_u());
1728 if (backslash_skip == 1) {
1730 return (o_getsc_u());
1735 while (/* CONSTCOND */ 1) {
1738 if ((c2 = o_getsc_u()) == '\n')
1739 /* ignore the \newline; get the next char... */
1753 if ((unsigned char)(c = o_getsc_u()) != 0xEF) {
1757 if ((unsigned char)(c = o_getsc_u()) != 0xBB) {
1762 if ((unsigned char)(c = o_getsc_u()) != 0xBF) {
1772 push_state_i(State_info *si, Lex_state *old_end)
1774 Lex_state *news = alloc2(STATE_BSIZE, sizeof(Lex_state), ATEMP);
1776 news[0].ls_base = old_end;
1777 si->base = &news[0];
1778 si->end = &news[STATE_BSIZE];
1783 pop_state_i(State_info *si, Lex_state *old_end)
1785 Lex_state *old_base = si->base;
1787 si->base = old_end->ls_base - STATE_BSIZE;
1788 si->end = old_end->ls_base;
1790 afree(old_base, ATEMP);
1792 return (si->base + STATE_BSIZE - 1);