1 /* Yacc grammar for bash. */
3 /* Copyright (C) 1989-2002 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
12 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License along
18 with Bash; see the file LICENSE. If not, write to the Free Software
19 Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
24 #include "bashtypes.h"
29 #if defined (HAVE_UNISTD_H)
33 #if defined (HAVE_LOCALE_H)
38 #include "chartypes.h"
43 #define NEED_STRFTIME_DECL /* used in externs.h */
49 #include "mailcheck.h"
51 #include "builtins/common.h"
52 #include "builtins/builtext.h"
56 #if defined (READLINE)
57 # include "bashline.h"
58 # include <readline/readline.h>
62 # include "bashhist.h"
63 # include <readline/history.h>
66 #if defined (JOB_CONTROL)
68 #endif /* JOB_CONTROL */
74 #if defined (PROMPT_STRING_DECODE)
76 # include <sys/param.h>
79 # if defined (TM_IN_SYS_TIME)
80 # include <sys/types.h>
81 # include <sys/time.h>
82 # endif /* TM_IN_SYS_TIME */
84 #endif /* PROMPT_STRING_DECODE */
86 #define RE_READ_TOKEN -99
87 #define NO_EXPANSION -100
95 #if defined (HANDLE_MULTIBYTE)
96 # define last_shell_getc_is_singlebyte \
97 ((shell_input_line_index > 1) \
98 ? shell_input_line_property[shell_input_line_index - 1] \
100 # define MBTEST(x) ((x) && last_shell_getc_is_singlebyte)
102 # define last_shell_getc_is_singlebyte 1
103 # define MBTEST(x) ((x))
106 #if defined (EXTENDED_GLOB)
107 extern int extended_glob;
110 extern int eof_encountered;
111 extern int no_line_editing, running_under_emacs;
112 extern int current_command_number;
113 extern int sourcelevel;
114 extern int posixly_correct;
115 extern int last_command_exit_value;
116 extern int interrupt_immediately;
117 extern char *shell_name, *current_host_name;
118 extern char *dist_version;
119 extern int patch_level;
120 extern int dump_translatable_strings, dump_po_strings;
121 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
122 #if defined (BUFFERED_INPUT)
123 extern int bash_input_fd_changed;
127 /* **************************************************************** */
129 /* "Forward" declarations */
131 /* **************************************************************** */
134 static void debug_parser __P((int));
137 static int yy_getc __P((void));
138 static int yy_ungetc __P((int));
140 #if defined (READLINE)
141 static int yy_readline_get __P((void));
142 static int yy_readline_unget __P((int));
145 static int yy_string_get __P((void));
146 static int yy_string_unget __P((int));
147 static int yy_stream_get __P((void));
148 static int yy_stream_unget __P((int));
150 static int shell_getc __P((int));
151 static void shell_ungetc __P((int));
152 static void discard_until __P((int));
154 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
155 static void push_string __P((char *, int, alias_t *));
156 static void pop_string __P((void));
157 static void free_string_list __P((void));
160 static char *read_a_line __P((int));
162 static int reserved_word_acceptable __P((int));
163 static int yylex __P((void));
164 static int alias_expand_token __P((char *));
165 static int time_command_acceptable __P((void));
166 static int special_case_tokens __P((char *));
167 static int read_token __P((int));
168 static char *parse_matched_pair __P((int, int, int, int *, int));
169 #if defined (ARRAY_VARS)
170 static char *parse_compound_assignment __P((int *));
172 #if defined (DPAREN_ARITHMETIC) || defined (ARITH_FOR_COMMAND)
173 static int parse_dparen __P((int));
174 static int parse_arith_cmd __P((char **));
176 #if defined (COND_COMMAND)
177 static void cond_error __P((void));
178 static COND_COM *cond_expr __P((void));
179 static COND_COM *cond_or __P((void));
180 static COND_COM *cond_and __P((void));
181 static COND_COM *cond_term __P((void));
182 static int cond_skip_newlines __P((void));
183 static COMMAND *parse_cond_command __P((void));
185 #if defined (ARRAY_VARS)
186 static int token_is_assignment __P((char *, int));
187 static int token_is_ident __P((char *, int));
189 static int read_token_word __P((int));
190 static void discard_parser_constructs __P((int));
192 static char *error_token_from_token __P((int));
193 static char *error_token_from_text __P((void));
194 static void print_offending_line __P((void));
195 static void report_syntax_error __P((char *));
197 static void handle_eof_input_unit __P((void));
198 static void prompt_again __P((void));
200 static void reset_readline_prompt __P((void));
202 static void print_prompt __P((void));
204 #if defined (HISTORY)
205 char *history_delimiting_chars __P((void));
208 #if defined (HANDLE_MULTIBYTE)
209 static void set_line_mbstate __P((void));
210 static char *shell_input_line_property = NULL;
212 # define set_line_mbstate()
215 extern int yyerror __P((const char *));
221 /* Default prompt strings */
222 char *primary_prompt = PPROMPT;
223 char *secondary_prompt = SPROMPT;
225 /* PROMPT_STRING_POINTER points to one of these, never to an actual string. */
226 char *ps1_prompt, *ps2_prompt;
228 /* Handle on the current prompt string. Indirectly points through
229 ps1_ or ps2_prompt. */
230 char **prompt_string_pointer = (char **)NULL;
231 char *current_prompt_string;
233 /* Non-zero means we expand aliases in commands. */
234 int expand_aliases = 0;
236 /* If non-zero, the decoded prompt string undergoes parameter and
237 variable substitution, command substitution, arithmetic substitution,
238 string expansion, process substitution, and quote removal in
239 decode_prompt_string. */
242 /* The decoded prompt string. Used if READLINE is not defined or if
243 editing is turned off. Analogous to current_readline_prompt. */
244 static char *current_decoded_prompt;
246 /* The number of lines read from input while creating the current command. */
247 int current_command_line_count;
249 /* Variables to manage the task of reading here documents, because we need to
250 defer the reading until after a complete command has been collected. */
251 static REDIRECT *redir_stack[10];
254 /* Where shell input comes from. History expansion is performed on each
255 line when the shell is interactive. */
256 static char *shell_input_line = (char *)NULL;
257 static int shell_input_line_index;
258 static int shell_input_line_size; /* Amount allocated for shell_input_line. */
259 static int shell_input_line_len; /* strlen (shell_input_line) */
261 /* Either zero or EOF. */
262 static int shell_input_line_terminator;
264 /* The line number in a script on which a function definition starts. */
265 static int function_dstart;
267 /* The line number in a script on which a function body starts. */
268 static int function_bstart;
270 /* The line number in a script at which an arithmetic for command starts. */
271 static int arith_for_lineno;
273 static REDIRECTEE redir;
277 WORD_DESC *word; /* the word that we read. */
278 int number; /* the number that we read. */
279 WORD_LIST *word_list;
283 PATTERN_LIST *pattern;
286 /* Reserved words. Members of the first group are only recognized
287 in the case that they are preceded by a list_terminator. Members
288 of the second group are for [[...]] commands. Members of the
289 third group are recognized only under special circumstances. */
290 %token IF THEN ELSE ELIF FI CASE ESAC FOR SELECT WHILE UNTIL DO DONE FUNCTION
291 %token COND_START COND_END COND_ERROR
292 %token IN BANG TIME TIMEOPT
294 /* More general tokens. yylex () knows how to make these. */
295 %token <word> WORD ASSIGNMENT_WORD
296 %token <number> NUMBER
297 %token <word_list> ARITH_CMD ARITH_FOR_EXPRS
298 %token <command> COND_CMD
299 %token AND_AND OR_OR GREATER_GREATER LESS_LESS LESS_AND LESS_LESS_LESS
300 %token GREATER_AND SEMI_SEMI LESS_LESS_MINUS AND_GREATER LESS_GREATER
303 /* The types that the various syntactical units return. */
305 %type <command> inputunit command pipeline pipeline_command
306 %type <command> list list0 list1 compound_list simple_list simple_list1
307 %type <command> simple_command shell_command
308 %type <command> for_command select_command case_command group_command
309 %type <command> arith_command
310 %type <command> cond_command
311 %type <command> arith_for_command
312 %type <command> function_def function_body if_command elif_clause subshell
313 %type <redirect> redirection redirection_list
314 %type <element> simple_command_element
315 %type <word_list> word_list pattern
316 %type <pattern> pattern_list case_clause_sequence case_clause
317 %type <number> timespec
321 %left '&' ';' '\n' yacc_EOF
326 inputunit: simple_list simple_list_terminator
328 /* Case of regular command. Discard the error
329 safety net,and return the command just parsed. */
332 /* discard_parser_constructs (0); */
337 /* Case of regular command, but not a very
338 interesting one. Return a NULL command. */
339 global_command = (COMMAND *)NULL;
344 /* Error during parsing. Return NULL command. */
345 global_command = (COMMAND *)NULL;
347 /* discard_parser_constructs (1); */
359 /* Case of EOF seen by itself. Do ignoreeof or
361 global_command = (COMMAND *)NULL;
362 handle_eof_input_unit ();
368 { $$ = make_word_list ($1, (WORD_LIST *)NULL); }
370 { $$ = make_word_list ($2, $1); }
373 redirection: '>' WORD
376 $$ = make_redirection (1, r_output_direction, redir);
381 $$ = make_redirection (0, r_input_direction, redir);
386 $$ = make_redirection ($1, r_output_direction, redir);
391 $$ = make_redirection ($1, r_input_direction, redir);
393 | GREATER_GREATER WORD
396 $$ = make_redirection (1, r_appending_to, redir);
398 | NUMBER GREATER_GREATER WORD
401 $$ = make_redirection ($1, r_appending_to, redir);
406 $$ = make_redirection (0, r_reading_until, redir);
407 redir_stack[need_here_doc++] = $$;
409 | NUMBER LESS_LESS WORD
412 $$ = make_redirection ($1, r_reading_until, redir);
413 redir_stack[need_here_doc++] = $$;
415 | LESS_LESS_LESS WORD
418 $$ = make_redirection (0, r_reading_string, redir);
420 | NUMBER LESS_LESS_LESS WORD
423 $$ = make_redirection ($1, r_reading_string, redir);
428 $$ = make_redirection (0, r_duplicating_input, redir);
430 | NUMBER LESS_AND NUMBER
433 $$ = make_redirection ($1, r_duplicating_input, redir);
438 $$ = make_redirection (1, r_duplicating_output, redir);
440 | NUMBER GREATER_AND NUMBER
443 $$ = make_redirection ($1, r_duplicating_output, redir);
448 $$ = make_redirection (0, r_duplicating_input_word, redir);
450 | NUMBER LESS_AND WORD
453 $$ = make_redirection ($1, r_duplicating_input_word, redir);
458 $$ = make_redirection (1, r_duplicating_output_word, redir);
460 | NUMBER GREATER_AND WORD
463 $$ = make_redirection ($1, r_duplicating_output_word, redir);
465 | LESS_LESS_MINUS WORD
468 $$ = make_redirection
469 (0, r_deblank_reading_until, redir);
470 redir_stack[need_here_doc++] = $$;
472 | NUMBER LESS_LESS_MINUS WORD
475 $$ = make_redirection
476 ($1, r_deblank_reading_until, redir);
477 redir_stack[need_here_doc++] = $$;
482 $$ = make_redirection (1, r_close_this, redir);
484 | NUMBER GREATER_AND '-'
487 $$ = make_redirection ($1, r_close_this, redir);
492 $$ = make_redirection (0, r_close_this, redir);
494 | NUMBER LESS_AND '-'
497 $$ = make_redirection ($1, r_close_this, redir);
502 $$ = make_redirection (1, r_err_and_out, redir);
504 | NUMBER LESS_GREATER WORD
507 $$ = make_redirection ($1, r_input_output, redir);
512 $$ = make_redirection (0, r_input_output, redir);
517 $$ = make_redirection (1, r_output_force, redir);
519 | NUMBER GREATER_BAR WORD
522 $$ = make_redirection ($1, r_output_force, redir);
526 simple_command_element: WORD
527 { $$.word = $1; $$.redirect = 0; }
529 { $$.word = $1; $$.redirect = 0; }
531 { $$.redirect = $1; $$.word = 0; }
534 redirection_list: redirection
538 | redirection_list redirection
540 register REDIRECT *t;
542 for (t = $1; t->next; t = t->next)
549 simple_command: simple_command_element
550 { $$ = make_simple_command ($1, (COMMAND *)NULL); }
551 | simple_command simple_command_element
552 { $$ = make_simple_command ($2, $1); }
555 command: simple_command
556 { $$ = clean_simple_command ($1); }
559 | shell_command redirection_list
566 register REDIRECT *t;
567 for (t = tc->redirects; t->next; t = t->next)
579 shell_command: for_command
583 | WHILE compound_list DO compound_list DONE
584 { $$ = make_while_command ($2, $4); }
585 | UNTIL compound_list DO compound_list DONE
586 { $$ = make_until_command ($2, $4); }
603 for_command: FOR WORD newline_list DO compound_list DONE
604 { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5); }
605 | FOR WORD newline_list '{' compound_list '}'
606 { $$ = make_for_command ($2, add_string_to_list ("$@", (WORD_LIST *)NULL), $5); }
607 | FOR WORD ';' newline_list DO compound_list DONE
608 { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6); }
609 | FOR WORD ';' newline_list '{' compound_list '}'
610 { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6); }
611 | FOR WORD newline_list IN word_list list_terminator newline_list DO compound_list DONE
612 { $$ = make_for_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9); }
613 | FOR WORD newline_list IN word_list list_terminator newline_list '{' compound_list '}'
614 { $$ = make_for_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9); }
615 | FOR WORD newline_list IN list_terminator newline_list DO compound_list DONE
616 { $$ = make_for_command ($2, (WORD_LIST *)NULL, $8); }
617 | FOR WORD newline_list IN list_terminator newline_list '{' compound_list '}'
618 { $$ = make_for_command ($2, (WORD_LIST *)NULL, $8); }
621 arith_for_command: FOR ARITH_FOR_EXPRS list_terminator newline_list DO compound_list DONE
622 { $$ = make_arith_for_command ($2, $6, arith_for_lineno); }
623 | FOR ARITH_FOR_EXPRS list_terminator newline_list '{' compound_list '}'
624 { $$ = make_arith_for_command ($2, $6, arith_for_lineno); }
625 | FOR ARITH_FOR_EXPRS DO compound_list DONE
626 { $$ = make_arith_for_command ($2, $4, arith_for_lineno); }
627 | FOR ARITH_FOR_EXPRS '{' compound_list '}'
628 { $$ = make_arith_for_command ($2, $4, arith_for_lineno); }
631 select_command: SELECT WORD newline_list DO list DONE
633 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5);
635 | SELECT WORD newline_list '{' list '}'
637 $$ = make_select_command ($2, add_string_to_list ("$@", (WORD_LIST *)NULL), $5);
639 | SELECT WORD ';' newline_list DO list DONE
641 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6);
643 | SELECT WORD ';' newline_list '{' list '}'
645 $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6);
647 | SELECT WORD newline_list IN word_list list_terminator newline_list DO list DONE
649 $$ = make_select_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9);
651 | SELECT WORD newline_list IN word_list list_terminator newline_list '{' list '}'
653 $$ = make_select_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9);
657 case_command: CASE WORD newline_list IN newline_list ESAC
658 { $$ = make_case_command ($2, (PATTERN_LIST *)NULL); }
659 | CASE WORD newline_list IN case_clause_sequence newline_list ESAC
660 { $$ = make_case_command ($2, $5); }
661 | CASE WORD newline_list IN case_clause ESAC
662 { $$ = make_case_command ($2, $5); }
665 function_def: WORD '(' ')' newline_list function_body
666 { $$ = make_function_def ($1, $5, function_dstart, function_bstart); }
668 | FUNCTION WORD '(' ')' newline_list function_body
669 { $$ = make_function_def ($2, $6, function_dstart, function_bstart); }
671 | FUNCTION WORD newline_list function_body
672 { $$ = make_function_def ($2, $4, function_dstart, function_bstart); }
676 function_body: shell_command
678 | shell_command redirection_list
683 /* According to Posix.2 3.9.5, redirections
684 specified after the body of a function should
685 be attached to the function and performed when
686 the function is executed, not as part of the
687 function definition command. */
688 /* XXX - I don't think it matters, but we might
689 want to change this in the future to avoid
690 problems differentiating between a function
691 definition with a redirection and a function
692 definition containing a single command with a
693 redirection. The two are semantically equivalent,
694 though -- the only difference is in how the
695 command printing code displays the redirections. */
698 register REDIRECT *t;
699 for (t = tc->redirects; t->next; t = t->next)
709 subshell: '(' compound_list ')'
711 $$ = make_subshell_command ($2);
712 $$->flags |= CMD_WANT_SUBSHELL;
716 if_command: IF compound_list THEN compound_list FI
717 { $$ = make_if_command ($2, $4, (COMMAND *)NULL); }
718 | IF compound_list THEN compound_list ELSE compound_list FI
719 { $$ = make_if_command ($2, $4, $6); }
720 | IF compound_list THEN compound_list elif_clause FI
721 { $$ = make_if_command ($2, $4, $5); }
725 group_command: '{' compound_list '}'
726 { $$ = make_group_command ($2); }
729 arith_command: ARITH_CMD
730 { $$ = make_arith_command ($1); }
733 cond_command: COND_START COND_CMD COND_END
737 elif_clause: ELIF compound_list THEN compound_list
738 { $$ = make_if_command ($2, $4, (COMMAND *)NULL); }
739 | ELIF compound_list THEN compound_list ELSE compound_list
740 { $$ = make_if_command ($2, $4, $6); }
741 | ELIF compound_list THEN compound_list elif_clause
742 { $$ = make_if_command ($2, $4, $5); }
745 case_clause: pattern_list
746 | case_clause_sequence pattern_list
747 { $2->next = $1; $$ = $2; }
750 pattern_list: newline_list pattern ')' compound_list
751 { $$ = make_pattern_list ($2, $4); }
752 | newline_list pattern ')' newline_list
753 { $$ = make_pattern_list ($2, (COMMAND *)NULL); }
754 | newline_list '(' pattern ')' compound_list
755 { $$ = make_pattern_list ($3, $5); }
756 | newline_list '(' pattern ')' newline_list
757 { $$ = make_pattern_list ($3, (COMMAND *)NULL); }
760 case_clause_sequence: pattern_list SEMI_SEMI
761 | case_clause_sequence pattern_list SEMI_SEMI
762 { $2->next = $1; $$ = $2; }
766 { $$ = make_word_list ($1, (WORD_LIST *)NULL); }
768 { $$ = make_word_list ($3, $1); }
771 /* A list allows leading or trailing newlines and
772 newlines as operators (equivalent to semicolons).
773 It must end with a newline or semicolon.
774 Lists are used within commands such as if, for, while. */
776 list: newline_list list0
780 gather_here_documents ();
791 list0: list1 '\n' newline_list
792 | list1 '&' newline_list
794 if ($1->type == cm_connection)
795 $$ = connect_async_list ($1, (COMMAND *)NULL, '&');
797 $$ = command_connect ($1, (COMMAND *)NULL, '&');
799 | list1 ';' newline_list
803 list1: list1 AND_AND newline_list list1
804 { $$ = command_connect ($1, $4, AND_AND); }
805 | list1 OR_OR newline_list list1
806 { $$ = command_connect ($1, $4, OR_OR); }
807 | list1 '&' newline_list list1
809 if ($1->type == cm_connection)
810 $$ = connect_async_list ($1, $4, '&');
812 $$ = command_connect ($1, $4, '&');
814 | list1 ';' newline_list list1
815 { $$ = command_connect ($1, $4, ';'); }
816 | list1 '\n' newline_list list1
817 { $$ = command_connect ($1, $4, ';'); }
822 simple_list_terminator: '\n'
835 /* A simple_list is a list that contains no significant newlines
836 and no leading or trailing newlines. Newlines are allowed
837 only following operators, where they are not significant.
839 This is what an inputunit consists of. */
841 simple_list: simple_list1
845 gather_here_documents ();
849 if ($1->type == cm_connection)
850 $$ = connect_async_list ($1, (COMMAND *)NULL, '&');
852 $$ = command_connect ($1, (COMMAND *)NULL, '&');
854 gather_here_documents ();
860 gather_here_documents ();
864 simple_list1: simple_list1 AND_AND newline_list simple_list1
865 { $$ = command_connect ($1, $4, AND_AND); }
866 | simple_list1 OR_OR newline_list simple_list1
867 { $$ = command_connect ($1, $4, OR_OR); }
868 | simple_list1 '&' simple_list1
870 if ($1->type == cm_connection)
871 $$ = connect_async_list ($1, $3, '&');
873 $$ = command_connect ($1, $3, '&');
875 | simple_list1 ';' simple_list1
876 { $$ = command_connect ($1, $3, ';'); }
882 pipeline_command: pipeline
886 $2->flags |= CMD_INVERT_RETURN;
894 | timespec BANG pipeline
896 $3->flags |= $1|CMD_INVERT_RETURN;
899 | BANG timespec pipeline
901 $3->flags |= $2|CMD_INVERT_RETURN;
907 pipeline '|' newline_list pipeline
908 { $$ = command_connect ($1, $4, '|'); }
914 { $$ = CMD_TIME_PIPELINE; }
916 { $$ = CMD_TIME_PIPELINE|CMD_TIME_POSIX; }
920 /* Possible states for the parser that require it to do special things. */
921 #define PST_CASEPAT 0x001 /* in a case pattern list */
922 #define PST_ALEXPNEXT 0x002 /* expand next word for aliases */
923 #define PST_ALLOWOPNBRC 0x004 /* allow open brace for function def */
924 #define PST_NEEDCLOSBRC 0x008 /* need close brace */
925 #define PST_DBLPAREN 0x010 /* double-paren parsing */
926 #define PST_SUBSHELL 0x020 /* ( ... ) subshell */
927 #define PST_CMDSUBST 0x040 /* $( ... ) command substitution */
928 #define PST_CASESTMT 0x080 /* parsing a case statement */
929 #define PST_CONDCMD 0x100 /* parsing a [[...]] command */
930 #define PST_CONDEXPR 0x200 /* parsing the guts of [[...]] */
931 #define PST_ARITHFOR 0x400 /* parsing an arithmetic for command */
933 /* Initial size to allocate for tokens, and the
934 amount to grow them by. */
935 #define TOKEN_DEFAULT_INITIAL_SIZE 496
936 #define TOKEN_DEFAULT_GROW_SIZE 512
938 /* The token currently being read. */
939 static int current_token;
941 /* The last read token, or NULL. read_token () uses this for context
943 static int last_read_token;
945 /* The token read prior to last_read_token. */
946 static int token_before_that;
948 /* The token read prior to token_before_that. */
949 static int two_tokens_ago;
951 /* If non-zero, it is the token that we want read_token to return
952 regardless of what text is (or isn't) present to be read. This
953 is reset by read_token. If token_to_read == WORD or
954 ASSIGNMENT_WORD, yylval.word should be set to word_desc_to_read. */
955 static int token_to_read;
956 static WORD_DESC *word_desc_to_read;
958 /* The current parser state. */
959 static int parser_state;
961 /* Global var is non-zero when end of file has been reached. */
975 /* yy_getc () returns the next available character from input or EOF.
976 yy_ungetc (c) makes `c' the next character to read.
977 init_yy_io (get, unget, type, location) makes the function GET the
978 installed function for getting the next character, makes UNGET the
979 installed function for un-getting a character, sets the type of stream
980 (either string or file) from TYPE, and makes LOCATION point to where
981 the input is coming from. */
983 /* Unconditionally returns end-of-file. */
990 /* Variable containing the current get and unget functions.
991 See ./input.h for a clearer description. */
992 BASH_INPUT bash_input;
994 /* Set all of the fields in BASH_INPUT to NULL. Free bash_input.name if it
995 is non-null, avoiding a memory leak. */
997 initialize_bash_input ()
999 bash_input.type = st_none;
1000 FREE (bash_input.name);
1001 bash_input.name = (char *)NULL;
1002 bash_input.location.file = (FILE *)NULL;
1003 bash_input.location.string = (char *)NULL;
1004 bash_input.getter = (sh_cget_func_t *)NULL;
1005 bash_input.ungetter = (sh_cunget_func_t *)NULL;
1008 /* Set the contents of the current bash input stream from
1009 GET, UNGET, TYPE, NAME, and LOCATION. */
1011 init_yy_io (get, unget, type, name, location)
1012 sh_cget_func_t *get;
1013 sh_cunget_func_t *unget;
1014 enum stream_type type;
1016 INPUT_STREAM location;
1018 bash_input.type = type;
1019 FREE (bash_input.name);
1020 bash_input.name = name ? savestring (name) : (char *)NULL;
1024 memcpy((char *)&bash_input.location.string, (char *)&location.string, sizeof(location));
1026 bash_input.location = location;
1028 bash_input.getter = get;
1029 bash_input.ungetter = unget;
1035 return (bash_input.name ? bash_input.name : "stdin");
1038 /* Call this to get the next character of input. */
1042 return (*(bash_input.getter)) ();
1045 /* Call this to unget C. That is, to make C the next character
1051 return (*(bash_input.ungetter)) (c);
1054 #if defined (BUFFERED_INPUT)
1055 #ifdef INCLUDE_UNUSED
1057 input_file_descriptor ()
1059 switch (bash_input.type)
1062 return (fileno (bash_input.location.file));
1064 return (bash_input.location.buffered_fd);
1067 return (fileno (stdin));
1071 #endif /* BUFFERED_INPUT */
1073 /* **************************************************************** */
1075 /* Let input be read from readline (). */
1077 /* **************************************************************** */
1079 #if defined (READLINE)
1080 char *current_readline_prompt = (char *)NULL;
1081 char *current_readline_line = (char *)NULL;
1082 int current_readline_line_index = 0;
1087 SigHandler *old_sigint;
1091 if (!current_readline_line)
1093 if (!bash_readline_initialized)
1094 initialize_readline ();
1096 #if defined (JOB_CONTROL)
1098 give_terminal_to (shell_pgrp, 0);
1099 #endif /* JOB_CONTROL */
1101 old_sigint = (SigHandler *)NULL;
1102 if (signal_is_ignored (SIGINT) == 0)
1104 old_sigint = (SigHandler *)set_signal_handler (SIGINT, sigint_sighandler);
1105 interrupt_immediately++;
1108 current_readline_line = readline (current_readline_prompt ?
1109 current_readline_prompt : "");
1111 if (signal_is_ignored (SIGINT) == 0 && old_sigint)
1113 interrupt_immediately--;
1114 set_signal_handler (SIGINT, old_sigint);
1118 /* Reset the prompt to the decoded value of prompt_string_pointer. */
1119 reset_readline_prompt ();
1122 if (current_readline_line == 0)
1125 current_readline_line_index = 0;
1126 line_len = strlen (current_readline_line);
1128 current_readline_line = (char *)xrealloc (current_readline_line, 2 + line_len);
1129 current_readline_line[line_len++] = '\n';
1130 current_readline_line[line_len] = '\0';
1133 if (current_readline_line[current_readline_line_index] == 0)
1135 free (current_readline_line);
1136 current_readline_line = (char *)NULL;
1137 return (yy_readline_get ());
1141 c = current_readline_line[current_readline_line_index++];
1147 yy_readline_unget (c)
1150 if (current_readline_line_index && current_readline_line)
1151 current_readline_line[--current_readline_line_index] = c;
1156 with_input_from_stdin ()
1158 INPUT_STREAM location;
1160 if (bash_input.type != st_stdin && stream_on_stack (st_stdin) == 0)
1162 location.string = current_readline_line;
1163 init_yy_io (yy_readline_get, yy_readline_unget,
1164 st_stdin, "readline stdin", location);
1168 #else /* !READLINE */
1171 with_input_from_stdin ()
1173 with_input_from_stream (stdin, "stdin");
1175 #endif /* !READLINE */
1177 /* **************************************************************** */
1179 /* Let input come from STRING. STRING is zero terminated. */
1181 /* **************************************************************** */
1186 register char *string;
1187 register unsigned char c;
1189 string = bash_input.location.string;
1191 /* If the string doesn't exist, or is empty, EOF found. */
1192 if (string && *string)
1195 bash_input.location.string = string;
1206 *(--bash_input.location.string) = c;
1211 with_input_from_string (string, name)
1215 INPUT_STREAM location;
1217 location.string = string;
1218 init_yy_io (yy_string_get, yy_string_unget, st_string, name, location);
1221 /* **************************************************************** */
1223 /* Let input come from STREAM. */
1225 /* **************************************************************** */
1227 /* These two functions used to test the value of the HAVE_RESTARTABLE_SYSCALLS
1228 define, and just use getc/ungetc if it was defined, but since bash
1229 installs its signal handlers without the SA_RESTART flag, some signals
1230 (like SIGCHLD, SIGWINCH, etc.) received during a read(2) will not cause
1231 the read to be restarted. We need to restart it ourselves. */
1239 if (bash_input.location.file)
1240 result = getc_with_restart (bash_input.location.file);
1249 return (ungetc_with_restart (c, bash_input.location.file));
1253 with_input_from_stream (stream, name)
1257 INPUT_STREAM location;
1259 location.file = stream;
1260 init_yy_io (yy_stream_get, yy_stream_unget, st_stream, name, location);
1263 typedef struct stream_saver {
1264 struct stream_saver *next;
1265 BASH_INPUT bash_input;
1267 #if defined (BUFFERED_INPUT)
1268 BUFFERED_STREAM *bstream;
1269 #endif /* BUFFERED_INPUT */
1272 /* The globally known line number. */
1273 int line_number = 0;
1275 #if defined (COND_COMMAND)
1276 static int cond_lineno;
1277 static int cond_token;
1280 STREAM_SAVER *stream_list = (STREAM_SAVER *)NULL;
1283 push_stream (reset_lineno)
1286 STREAM_SAVER *saver = (STREAM_SAVER *)xmalloc (sizeof (STREAM_SAVER));
1288 xbcopy ((char *)&bash_input, (char *)&(saver->bash_input), sizeof (BASH_INPUT));
1290 #if defined (BUFFERED_INPUT)
1291 saver->bstream = (BUFFERED_STREAM *)NULL;
1292 /* If we have a buffered stream, clear out buffers[fd]. */
1293 if (bash_input.type == st_bstream && bash_input.location.buffered_fd >= 0)
1294 saver->bstream = set_buffered_stream (bash_input.location.buffered_fd,
1295 (BUFFERED_STREAM *)NULL);
1296 #endif /* BUFFERED_INPUT */
1298 saver->line = line_number;
1299 bash_input.name = (char *)NULL;
1300 saver->next = stream_list;
1301 stream_list = saver;
1314 STREAM_SAVER *saver = stream_list;
1317 stream_list = stream_list->next;
1319 init_yy_io (saver->bash_input.getter,
1320 saver->bash_input.ungetter,
1321 saver->bash_input.type,
1322 saver->bash_input.name,
1323 saver->bash_input.location);
1325 #if defined (BUFFERED_INPUT)
1326 /* If we have a buffered stream, restore buffers[fd]. */
1327 /* If the input file descriptor was changed while this was on the
1328 save stack, update the buffered fd to the new file descriptor and
1329 re-establish the buffer <-> bash_input fd correspondence. */
1330 if (bash_input.type == st_bstream && bash_input.location.buffered_fd >= 0)
1332 if (bash_input_fd_changed)
1334 bash_input_fd_changed = 0;
1335 if (default_buffered_input >= 0)
1337 bash_input.location.buffered_fd = default_buffered_input;
1338 saver->bstream->b_fd = default_buffered_input;
1339 SET_CLOSE_ON_EXEC (default_buffered_input);
1342 /* XXX could free buffered stream returned as result here. */
1343 set_buffered_stream (bash_input.location.buffered_fd, saver->bstream);
1345 #endif /* BUFFERED_INPUT */
1347 line_number = saver->line;
1349 FREE (saver->bash_input.name);
1354 /* Return 1 if a stream of type TYPE is saved on the stack. */
1356 stream_on_stack (type)
1357 enum stream_type type;
1359 register STREAM_SAVER *s;
1361 for (s = stream_list; s; s = s->next)
1362 if (s->bash_input.type == type)
1367 /* Save the current token state and return it in a malloced array. */
1373 ret = (int *)xmalloc (3 * sizeof (int));
1374 ret[0] = last_read_token;
1375 ret[1] = token_before_that;
1376 ret[2] = two_tokens_ago;
1381 restore_token_state (ts)
1386 last_read_token = ts[0];
1387 token_before_that = ts[1];
1388 two_tokens_ago = ts[2];
1392 * This is used to inhibit alias expansion and reserved word recognition
1393 * inside case statement pattern lists. A `case statement pattern list' is:
1395 * everything between the `in' in a `case word in' and the next ')'
1397 * everything between a `;;' and the next `)' or `esac'
1400 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1402 #if !defined (ALIAS)
1403 typedef void *alias_t;
1406 #define END_OF_ALIAS 0
1409 * Pseudo-global variables used in implementing token-wise alias expansion.
1413 * Pushing and popping strings. This works together with shell_getc to
1414 * implement alias expansion on a per-token basis.
1417 typedef struct string_saver {
1418 struct string_saver *next;
1419 int expand_alias; /* Value to set expand_alias to when string is popped. */
1422 alias_t *expander; /* alias that caused this line to be pushed. */
1424 int saved_line_size, saved_line_index, saved_line_terminator;
1427 STRING_SAVER *pushed_string_list = (STRING_SAVER *)NULL;
1430 * Push the current shell_input_line onto a stack of such lines and make S
1431 * the current input. Used when expanding aliases. EXPAND is used to set
1432 * the value of expand_next_token when the string is popped, so that the
1433 * word after the alias in the original line is handled correctly when the
1434 * alias expands to multiple words. TOKEN is the token that was expanded
1435 * into S; it is saved and used to prevent infinite recursive expansion.
1438 push_string (s, expand, ap)
1443 STRING_SAVER *temp = (STRING_SAVER *)xmalloc (sizeof (STRING_SAVER));
1445 temp->expand_alias = expand;
1446 temp->saved_line = shell_input_line;
1447 temp->saved_line_size = shell_input_line_size;
1448 temp->saved_line_index = shell_input_line_index;
1449 temp->saved_line_terminator = shell_input_line_terminator;
1451 temp->expander = ap;
1453 temp->next = pushed_string_list;
1454 pushed_string_list = temp;
1458 ap->flags |= AL_BEINGEXPANDED;
1461 shell_input_line = s;
1462 shell_input_line_size = strlen (s);
1463 shell_input_line_index = 0;
1464 shell_input_line_terminator = '\0';
1465 parser_state &= ~PST_ALEXPNEXT;
1467 set_line_mbstate ();
1471 * Make the top of the pushed_string stack be the current shell input.
1472 * Only called when there is something on the stack. Called from shell_getc
1473 * when it thinks it has consumed the string generated by an alias expansion
1474 * and needs to return to the original input line.
1481 FREE (shell_input_line);
1482 shell_input_line = pushed_string_list->saved_line;
1483 shell_input_line_index = pushed_string_list->saved_line_index;
1484 shell_input_line_size = pushed_string_list->saved_line_size;
1485 shell_input_line_terminator = pushed_string_list->saved_line_terminator;
1487 if (pushed_string_list->expand_alias)
1488 parser_state |= PST_ALEXPNEXT;
1490 parser_state &= ~PST_ALEXPNEXT;
1492 t = pushed_string_list;
1493 pushed_string_list = pushed_string_list->next;
1497 t->expander->flags &= ~AL_BEINGEXPANDED;
1502 set_line_mbstate ();
1508 register STRING_SAVER *t, *t1;
1510 for (t = pushed_string_list; t; )
1513 FREE (t->saved_line);
1516 t->expander->flags &= ~AL_BEINGEXPANDED;
1521 pushed_string_list = (STRING_SAVER *)NULL;
1524 #endif /* ALIAS || DPAREN_ARITHMETIC */
1526 /* Return a line of text, taken from wherever yylex () reads input.
1527 If there is no more input, then we return NULL. If REMOVE_QUOTED_NEWLINE
1528 is non-zero, we remove unquoted \<newline> pairs. This is used by
1529 read_secondary_line to read here documents. */
1531 read_a_line (remove_quoted_newline)
1532 int remove_quoted_newline;
1534 static char *line_buffer = (char *)NULL;
1535 static int buffer_size = 0;
1536 int indx = 0, c, peekc, pass_next;
1538 #if defined (READLINE)
1539 if (interactive && bash_input.type != st_string && no_line_editing)
1541 if (interactive && bash_input.type != st_string)
1550 /* Allow immediate exit if interrupted during input. */
1553 /* Ignore null bytes in input. */
1557 internal_warning ("read_a_line: ignored null byte in input");
1562 /* If there is no more input, then we return NULL. */
1565 if (interactive && bash_input.type == st_stream)
1568 return ((char *)NULL);
1572 /* `+2' in case the final character in the buffer is a newline. */
1573 RESIZE_MALLOCED_BUFFER (line_buffer, indx, 2, buffer_size, 128);
1575 /* IF REMOVE_QUOTED_NEWLINES is non-zero, we are reading a
1576 here document with an unquoted delimiter. In this case,
1577 the line will be expanded as if it were in double quotes.
1578 We allow a backslash to escape the next character, but we
1579 need to treat the backslash specially only if a backslash
1580 quoting a backslash-newline pair appears in the line. */
1583 line_buffer[indx++] = c;
1586 else if (c == '\\' && remove_quoted_newline)
1590 continue; /* Make the unquoted \<newline> pair disappear. */
1595 line_buffer[indx++] = c; /* Preserve the backslash. */
1599 line_buffer[indx++] = c;
1603 line_buffer[indx] = '\0';
1604 return (line_buffer);
1609 /* Return a line as in read_a_line (), but insure that the prompt is
1610 the secondary prompt. This is used to read the lines of a here
1611 document. REMOVE_QUOTED_NEWLINE is non-zero if we should remove
1612 newlines quoted with backslashes while reading the line. It is
1613 non-zero unless the delimiter of the here document was quoted. */
1615 read_secondary_line (remove_quoted_newline)
1616 int remove_quoted_newline;
1618 prompt_string_pointer = &ps2_prompt;
1620 return (read_a_line (remove_quoted_newline));
1623 /* **************************************************************** */
1627 /* **************************************************************** */
1629 /* Reserved words. These are only recognized as the first word of a
1631 STRING_INT_ALIST word_token_alist[] = {
1640 #if defined (SELECT_COMMAND)
1641 { "select", SELECT },
1648 { "function", FUNCTION },
1649 #if defined (COMMAND_TIMING)
1655 #if defined (COND_COMMAND)
1656 { "[[", COND_START },
1662 /* other tokens that can be returned by read_token() */
1663 STRING_INT_ALIST other_token_alist[] = {
1664 /* Multiple-character tokens with special values */
1668 { ">>", GREATER_GREATER },
1669 { "<<", LESS_LESS },
1671 { ">&", GREATER_AND },
1672 { ";;", SEMI_SEMI },
1673 { "<<-", LESS_LESS_MINUS },
1674 { "<<<", LESS_LESS_LESS },
1675 { "&>", AND_GREATER },
1676 { "<>", LESS_GREATER },
1677 { ">|", GREATER_BAR },
1678 { "EOF", yacc_EOF },
1679 /* Tokens whose value is the character itself */
1690 { "newline", '\n' },
1694 /* others not listed here:
1695 WORD look at yylval.word
1696 ASSIGNMENT_WORD look at yylval.word
1697 NUMBER look at yylval.number
1698 ARITH_CMD look at yylval.word_list
1699 ARITH_FOR_EXPRS look at yylval.word_list
1700 COND_CMD look at yylval.command
1703 /* These are used by read_token_word, but appear up here so that shell_getc
1704 can use them to decide when to add otherwise blank lines to the history. */
1706 /* The primary delimiter stack. */
1707 struct dstack dstack = { (char *)NULL, 0, 0 };
1709 /* A temporary delimiter stack to be used when decoding prompt strings.
1710 This is needed because command substitutions in prompt strings (e.g., PS2)
1711 can screw up the parser's quoting state. */
1712 static struct dstack temp_dstack = { (char *)NULL, 0, 0 };
1714 /* Macro for accessing the top delimiter on the stack. Returns the
1715 delimiter or zero if none. */
1716 #define current_delimiter(ds) \
1717 (ds.delimiter_depth ? ds.delimiters[ds.delimiter_depth - 1] : 0)
1719 #define push_delimiter(ds, character) \
1722 if (ds.delimiter_depth + 2 > ds.delimiter_space) \
1723 ds.delimiters = (char *)xrealloc \
1724 (ds.delimiters, (ds.delimiter_space += 10) * sizeof (char)); \
1725 ds.delimiters[ds.delimiter_depth] = character; \
1726 ds.delimiter_depth++; \
1730 #define pop_delimiter(ds) ds.delimiter_depth--
1732 /* Return the next shell input character. This always reads characters
1733 from shell_input_line; when that line is exhausted, it is time to
1734 read the next line. This is called by read_token when the shell is
1735 processing normal command input. */
1737 /* This implements one-character lookahead/lookbehind across physical input
1738 lines, to avoid something being lost because it's pushed back with
1739 shell_ungetc when we're at the start of a line. */
1740 static int eol_ungetc_lookahead = 0;
1743 shell_getc (remove_quoted_newline)
1744 int remove_quoted_newline;
1749 static int mustpop = 0;
1753 if (eol_ungetc_lookahead)
1755 c = eol_ungetc_lookahead;
1756 eol_ungetc_lookahead = 0;
1760 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1761 /* If shell_input_line[shell_input_line_index] == 0, but there is
1762 something on the pushed list of strings, then we don't want to go
1763 off and get another line. We let the code down below handle it. */
1765 if (!shell_input_line || ((!shell_input_line[shell_input_line_index]) &&
1766 (pushed_string_list == (STRING_SAVER *)NULL)))
1767 #else /* !ALIAS && !DPAREN_ARITHMETIC */
1768 if (!shell_input_line || !shell_input_line[shell_input_line_index])
1769 #endif /* !ALIAS && !DPAREN_ARITHMETIC */
1775 /* Allow immediate exit if interrupted during input. */
1779 shell_input_line_terminator = 0;
1781 #if defined (JOB_CONTROL)
1782 /* This can cause a problem when reading a command as the result
1783 of a trap, when the trap is called from flush_child. This call
1784 had better not cause jobs to disappear from the job table in
1785 that case, or we will have big trouble. */
1786 notify_and_cleanup ();
1787 #else /* !JOB_CONTROL */
1788 cleanup_dead_jobs ();
1789 #endif /* !JOB_CONTROL */
1791 #if defined (READLINE)
1792 if (interactive && bash_input.type != st_string && no_line_editing)
1794 if (interactive && bash_input.type != st_string)
1798 if (bash_input.type == st_stream)
1805 /* Allow immediate exit if interrupted during input. */
1811 internal_warning ("shell_getc: ignored null byte in input");
1816 RESIZE_MALLOCED_BUFFER (shell_input_line, i, 2, shell_input_line_size, 256);
1820 if (bash_input.type == st_stream)
1824 shell_input_line_terminator = EOF;
1826 shell_input_line[i] = '\0';
1830 shell_input_line[i++] = c;
1834 shell_input_line[--i] = '\0';
1835 current_command_line_count++;
1840 shell_input_line_index = 0;
1841 shell_input_line_len = i; /* == strlen (shell_input_line) */
1843 set_line_mbstate ();
1845 #if defined (HISTORY)
1846 if (remember_on_history && shell_input_line && shell_input_line[0])
1849 # if defined (BANG_HISTORY)
1852 /* If the current delimiter is a single quote, we should not be
1853 performing history expansion, even if we're on a different
1854 line from the original single quote. */
1855 old_hist = history_expansion_inhibited;
1856 if (current_delimiter (dstack) == '\'')
1857 history_expansion_inhibited = 1;
1859 expansions = pre_process_line (shell_input_line, 1, 1);
1860 # if defined (BANG_HISTORY)
1861 history_expansion_inhibited = old_hist;
1863 if (expansions != shell_input_line)
1865 free (shell_input_line);
1866 shell_input_line = expansions;
1867 shell_input_line_len = shell_input_line ?
1868 strlen (shell_input_line) : 0;
1869 if (!shell_input_line_len)
1870 current_command_line_count--;
1872 /* We have to force the xrealloc below because we don't know
1873 the true allocated size of shell_input_line anymore. */
1874 shell_input_line_size = shell_input_line_len;
1876 set_line_mbstate ();
1879 /* Try to do something intelligent with blank lines encountered while
1880 entering multi-line commands. XXX - this is grotesque */
1881 else if (remember_on_history && shell_input_line &&
1882 shell_input_line[0] == '\0' &&
1883 current_command_line_count > 1)
1885 if (current_delimiter (dstack))
1886 /* We know shell_input_line[0] == 0 and we're reading some sort of
1887 quoted string. This means we've got a line consisting of only
1888 a newline in a quoted string. We want to make sure this line
1889 gets added to the history. */
1890 maybe_add_history (shell_input_line);
1894 hdcs = history_delimiting_chars ();
1895 if (hdcs && hdcs[0] == ';')
1896 maybe_add_history (shell_input_line);
1900 #endif /* HISTORY */
1902 if (shell_input_line)
1904 /* Lines that signify the end of the shell's input should not be
1906 if (echo_input_at_read && (shell_input_line[0] ||
1907 shell_input_line_terminator != EOF))
1908 fprintf (stderr, "%s\n", shell_input_line);
1912 shell_input_line_size = 0;
1913 prompt_string_pointer = ¤t_prompt_string;
1918 /* Add the newline to the end of this string, iff the string does
1919 not already end in an EOF character. */
1920 if (shell_input_line_terminator != EOF)
1922 if (shell_input_line_len + 3 > shell_input_line_size)
1923 shell_input_line = (char *)xrealloc (shell_input_line,
1924 1 + (shell_input_line_size += 2));
1926 shell_input_line[shell_input_line_len] = '\n';
1927 shell_input_line[shell_input_line_len + 1] = '\0';
1929 set_line_mbstate ();
1933 uc = shell_input_line[shell_input_line_index];
1936 shell_input_line_index++;
1938 if MBTEST(uc == '\\' && remove_quoted_newline && shell_input_line[shell_input_line_index] == '\n')
1945 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1946 /* If UC is NULL, we have reached the end of the current input string. If
1947 pushed_string_list is non-empty, it's time to pop to the previous string
1948 because we have fully consumed the result of the last alias expansion.
1949 Do it transparently; just return the next character of the string popped
1951 if (!uc && (pushed_string_list != (STRING_SAVER *)NULL))
1956 uc = shell_input_line[shell_input_line_index];
1958 shell_input_line_index++;
1967 #endif /* ALIAS || DPAREN_ARITHMETIC */
1969 if (!uc && shell_input_line_terminator == EOF)
1970 return ((shell_input_line_index != 0) ? '\n' : EOF);
1975 /* Put C back into the input for the shell. This might need changes for
1976 HANDLE_MULTIBYTE around EOLs. Since we (currently) never push back a
1977 character different than we read, shell_input_line_property doesn't need
1978 to change when manipulating shell_input_line. The define for
1979 last_shell_getc_is_singlebyte should take care of it, though. */
1984 if (shell_input_line && shell_input_line_index)
1985 shell_input_line[--shell_input_line_index] = c;
1987 eol_ungetc_lookahead = c;
1990 #ifdef INCLUDE_UNUSED
1991 /* Back the input pointer up by one, effectively `ungetting' a character. */
1995 if (shell_input_line && shell_input_line_index)
1996 shell_input_line_index--;
2000 /* Discard input until CHARACTER is seen, then push that character back
2001 onto the input stream. */
2003 discard_until (character)
2008 while ((c = shell_getc (0)) != EOF && c != character)
2016 execute_prompt_command (command)
2019 sh_builtin_func_t *temp_last, *temp_this;
2021 int temp_exit_value, temp_eof_encountered;
2023 temp_last = last_shell_builtin;
2024 temp_this = this_shell_builtin;
2025 temp_exit_value = last_command_exit_value;
2026 temp_eof_encountered = eof_encountered;
2027 last_lastarg = get_string_value ("_");
2029 last_lastarg = savestring (last_lastarg);
2031 parse_and_execute (savestring (command), "PROMPT_COMMAND", SEVAL_NONINT|SEVAL_NOHIST);
2033 last_shell_builtin = temp_last;
2034 this_shell_builtin = temp_this;
2035 last_command_exit_value = temp_exit_value;
2036 eof_encountered = temp_eof_encountered;
2038 bind_variable ("_", last_lastarg);
2039 FREE (last_lastarg);
2041 if (token_to_read == '\n') /* reset_parser was called */
2045 /* Place to remember the token. We try to keep the buffer
2046 at a reasonable size, but it can grow. */
2047 static char *token = (char *)NULL;
2049 /* Current size of the token buffer. */
2050 static int token_buffer_size;
2052 /* Command to read_token () explaining what we want it to do. */
2055 #define prompt_is_ps1 \
2056 (!prompt_string_pointer || prompt_string_pointer == &ps1_prompt)
2058 /* Function for yyparse to call. yylex keeps track of
2059 the last two tokens read, and calls read_token. */
2063 if (interactive && (current_token == 0 || current_token == '\n'))
2065 /* Before we print a prompt, we might have to check mailboxes.
2066 We do this only if it is time to do so. Notice that only here
2067 is the mail alarm reset; nothing takes place in check_mail ()
2068 except the checking of mail. Please don't change this. */
2069 if (prompt_is_ps1 && time_to_check_mail ())
2072 reset_mail_timer ();
2075 /* Avoid printing a prompt if we're not going to read anything, e.g.
2076 after resetting the parser with read_token (RESET). */
2077 if (token_to_read == 0 && interactive)
2081 two_tokens_ago = token_before_that;
2082 token_before_that = last_read_token;
2083 last_read_token = current_token;
2084 current_token = read_token (READ);
2085 return (current_token);
2088 /* When non-zero, we have read the required tokens
2089 which allow ESAC to be the next one read. */
2090 static int esacs_needed_count;
2093 gather_here_documents ()
2096 while (need_here_doc)
2098 make_here_document (redir_stack[r++]);
2103 /* When non-zero, an open-brace used to create a group is awaiting a close
2105 static int open_brace_count;
2107 #define command_token_position(token) \
2108 (((token) == ASSIGNMENT_WORD) || \
2109 ((token) != SEMI_SEMI && reserved_word_acceptable(token)))
2111 #define assignment_acceptable(token) command_token_position(token) && \
2112 ((parser_state & PST_CASEPAT) == 0)
2114 /* Check to see if TOKEN is a reserved word and return the token
2116 #define CHECK_FOR_RESERVED_WORD(tok) \
2118 if (!dollar_present && !quoted && \
2119 reserved_word_acceptable (last_read_token)) \
2122 for (i = 0; word_token_alist[i].word != (char *)NULL; i++) \
2123 if (STREQ (tok, word_token_alist[i].word)) \
2125 if ((parser_state & PST_CASEPAT) && (word_token_alist[i].token != ESAC)) \
2127 if (word_token_alist[i].token == TIME) \
2129 if (word_token_alist[i].token == ESAC) \
2130 parser_state &= ~(PST_CASEPAT|PST_CASESTMT); \
2131 else if (word_token_alist[i].token == CASE) \
2132 parser_state |= PST_CASESTMT; \
2133 else if (word_token_alist[i].token == COND_END) \
2134 parser_state &= ~(PST_CONDCMD|PST_CONDEXPR); \
2135 else if (word_token_alist[i].token == COND_START) \
2136 parser_state |= PST_CONDCMD; \
2137 else if (word_token_alist[i].token == '{') \
2138 open_brace_count++; \
2139 else if (word_token_alist[i].token == '}' && open_brace_count) \
2140 open_brace_count--; \
2141 return (word_token_alist[i].token); \
2148 /* OK, we have a token. Let's try to alias expand it, if (and only if)
2151 It is eligible for expansion if EXPAND_ALIASES is set, and
2152 the token is unquoted and the last token read was a command
2153 separator (or expand_next_token is set), and we are currently
2154 processing an alias (pushed_string_list is non-empty) and this
2155 token is not the same as the current or any previously
2158 Special cases that disqualify:
2159 In a pattern list in a case statement (parser_state & PST_CASEPAT). */
2161 alias_expand_token (tokstr)
2167 if (((parser_state & PST_ALEXPNEXT) || command_token_position (last_read_token)) &&
2168 (parser_state & PST_CASEPAT) == 0)
2170 ap = find_alias (tokstr);
2172 /* Currently expanding this token. */
2173 if (ap && (ap->flags & AL_BEINGEXPANDED))
2174 return (NO_EXPANSION);
2176 expanded = ap ? savestring (ap->value) : (char *)NULL;
2179 push_string (expanded, ap->flags & AL_EXPANDNEXT, ap);
2180 return (RE_READ_TOKEN);
2183 /* This is an eligible token that does not have an expansion. */
2184 return (NO_EXPANSION);
2186 return (NO_EXPANSION);
2191 time_command_acceptable ()
2193 #if defined (COMMAND_TIMING)
2194 switch (last_read_token)
2213 #endif /* COMMAND_TIMING */
2216 /* Handle special cases of token recognition:
2217 IN is recognized if the last token was WORD and the token
2218 before that was FOR or CASE or SELECT.
2220 DO is recognized if the last token was WORD and the token
2221 before that was FOR or SELECT.
2223 ESAC is recognized if the last token caused `esacs_needed_count'
2226 `{' is recognized if the last token as WORD and the token
2227 before that was FUNCTION, or if we just parsed an arithmetic
2230 `}' is recognized if there is an unclosed `{' present.
2232 `-p' is returned as TIMEOPT if the last read token was TIME.
2234 ']]' is returned as COND_END if the parser is currently parsing
2235 a conditional expression ((parser_state & PST_CONDEXPR) != 0)
2237 `time' is returned as TIME if and only if it is immediately
2238 preceded by one of `;', `\n', `||', `&&', or `&'.
2242 special_case_tokens (tokstr)
2245 if ((last_read_token == WORD) &&
2246 #if defined (SELECT_COMMAND)
2247 ((token_before_that == FOR) || (token_before_that == CASE) || (token_before_that == SELECT)) &&
2249 ((token_before_that == FOR) || (token_before_that == CASE)) &&
2251 (tokstr[0] == 'i' && tokstr[1] == 'n' && tokstr[2] == 0))
2253 if (token_before_that == CASE)
2255 parser_state |= PST_CASEPAT;
2256 esacs_needed_count++;
2261 if (last_read_token == WORD &&
2262 #if defined (SELECT_COMMAND)
2263 (token_before_that == FOR || token_before_that == SELECT) &&
2265 (token_before_that == FOR) &&
2267 (tokstr[0] == 'd' && tokstr[1] == 'o' && tokstr[2] == '\0'))
2270 /* Ditto for ESAC in the CASE case.
2271 Specifically, this handles "case word in esac", which is a legal
2272 construct, certainly because someone will pass an empty arg to the
2273 case construct, and we don't want it to barf. Of course, we should
2274 insist that the case construct has at least one pattern in it, but
2275 the designers disagree. */
2276 if (esacs_needed_count)
2278 esacs_needed_count--;
2279 if (STREQ (tokstr, "esac"))
2281 parser_state &= ~PST_CASEPAT;
2286 /* The start of a shell function definition. */
2287 if (parser_state & PST_ALLOWOPNBRC)
2289 parser_state &= ~PST_ALLOWOPNBRC;
2290 if (tokstr[0] == '{' && tokstr[1] == '\0') /* } */
2293 function_bstart = line_number;
2294 return ('{'); /* } */
2298 /* We allow a `do' after a for ((...)) without an intervening
2300 if (last_read_token == ARITH_FOR_EXPRS && tokstr[0] == 'd' && tokstr[1] == 'o' && !tokstr[2])
2302 if (last_read_token == ARITH_FOR_EXPRS && tokstr[0] == '{' && tokstr[1] == '\0') /* } */
2305 return ('{'); /* } */
2308 if (open_brace_count && reserved_word_acceptable (last_read_token) && tokstr[0] == '}' && !tokstr[1])
2310 open_brace_count--; /* { */
2314 #if defined (COMMAND_TIMING)
2315 /* Handle -p after `time'. */
2316 if (last_read_token == TIME && tokstr[0] == '-' && tokstr[1] == 'p' && !tokstr[2])
2320 #if defined (COMMAND_TIMING)
2321 if (STREQ (token, "time") && ((parser_state & PST_CASEPAT) == 0) && time_command_acceptable ())
2323 #endif /* COMMAND_TIMING */
2325 #if defined (COND_COMMAND) /* [[ */
2326 if ((parser_state & PST_CONDEXPR) && tokstr[0] == ']' && tokstr[1] == ']' && tokstr[2] == '\0')
2333 /* Called from shell.c when Control-C is typed at top level. Or
2334 by the error rule at top level. */
2338 dstack.delimiter_depth = 0; /* No delimiters found so far. */
2339 open_brace_count = 0;
2343 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
2344 if (pushed_string_list)
2345 free_string_list ();
2346 #endif /* ALIAS || DPAREN_ARITHMETIC */
2348 if (shell_input_line)
2350 free (shell_input_line);
2351 shell_input_line = (char *)NULL;
2352 shell_input_line_size = shell_input_line_index = 0;
2355 FREE (word_desc_to_read);
2356 word_desc_to_read = (WORD_DESC *)NULL;
2358 last_read_token = '\n';
2359 token_to_read = '\n';
2362 /* Read the next token. Command can be READ (normal operation) or
2363 RESET (to normalize state). */
2365 read_token (command)
2368 int character; /* Current character. */
2369 int peek_char; /* Temporary look-ahead character. */
2370 int result; /* The thing to return. */
2372 if (command == RESET)
2380 result = token_to_read;
2381 if (token_to_read == WORD || token_to_read == ASSIGNMENT_WORD)
2383 yylval.word = word_desc_to_read;
2384 word_desc_to_read = (WORD_DESC *)NULL;
2390 #if defined (COND_COMMAND)
2391 if ((parser_state & (PST_CONDCMD|PST_CONDEXPR)) == PST_CONDCMD)
2393 cond_lineno = line_number;
2394 parser_state |= PST_CONDEXPR;
2395 yylval.command = parse_cond_command ();
2396 if (cond_token != COND_END)
2401 token_to_read = COND_END;
2402 parser_state &= ~(PST_CONDEXPR|PST_CONDCMD);
2408 /* This is a place to jump back to once we have successfully expanded a
2409 token with an alias and pushed the string with push_string () */
2413 /* Read a single word from input. Start by skipping blanks. */
2414 while ((character = shell_getc (1)) != EOF && whitespace (character))
2417 if (character == EOF)
2423 if MBTEST(character == '#' && (!interactive || interactive_comments))
2425 /* A comment. Discard until EOL or EOF, and then return a newline. */
2426 discard_until ('\n');
2428 character = '\n'; /* this will take the next if statement and return. */
2431 if (character == '\n')
2433 /* If we're about to return an unquoted newline, we can go and collect
2434 the text of any pending here document. */
2436 gather_here_documents ();
2439 parser_state &= ~PST_ALEXPNEXT;
2445 /* Shell meta-characters. */
2446 if MBTEST(shellmeta (character) && ((parser_state & PST_DBLPAREN) == 0))
2449 /* Turn off alias tokenization iff this character sequence would
2450 not leave us ready to read a command. */
2451 if (character == '<' || character == '>')
2452 parser_state &= ~PST_ALEXPNEXT;
2455 peek_char = shell_getc (1);
2456 if (character == peek_char)
2461 /* If '<' then we could be at "<<" or at "<<-". We have to
2462 look ahead one more character. */
2463 peek_char = shell_getc (1);
2464 if (peek_char == '-')
2465 return (LESS_LESS_MINUS);
2466 else if (peek_char == '<')
2467 return (LESS_LESS_LESS);
2470 shell_ungetc (peek_char);
2475 return (GREATER_GREATER);
2478 parser_state |= PST_CASEPAT;
2480 parser_state &= ~PST_ALEXPNEXT;
2490 #if defined (DPAREN_ARITHMETIC) || defined (ARITH_FOR_COMMAND)
2492 result = parse_dparen (character);
2500 else if MBTEST(character == '<' && peek_char == '&')
2502 else if MBTEST(character == '>' && peek_char == '&')
2503 return (GREATER_AND);
2504 else if MBTEST(character == '<' && peek_char == '>')
2505 return (LESS_GREATER);
2506 else if MBTEST(character == '>' && peek_char == '|')
2507 return (GREATER_BAR);
2508 else if MBTEST(peek_char == '>' && character == '&')
2509 return (AND_GREATER);
2511 shell_ungetc (peek_char);
2513 /* If we look like we are reading the start of a function
2514 definition, then let the reader know about it so that
2515 we will do the right thing with `{'. */
2516 if MBTEST(character == ')' && last_read_token == '(' && token_before_that == WORD)
2518 parser_state |= PST_ALLOWOPNBRC;
2520 parser_state &= ~PST_ALEXPNEXT;
2522 function_dstart = line_number;
2525 /* case pattern lists may be preceded by an optional left paren. If
2526 we're not trying to parse a case pattern list, the left paren
2527 indicates a subshell. */
2528 if MBTEST(character == '(' && (parser_state & PST_CASEPAT) == 0) /* ) */
2529 parser_state |= PST_SUBSHELL;
2531 else if MBTEST((parser_state & PST_CASEPAT) && character == ')')
2532 parser_state &= ~PST_CASEPAT;
2534 else if MBTEST((parser_state & PST_SUBSHELL) && character == ')')
2535 parser_state &= ~PST_SUBSHELL;
2537 #if defined (PROCESS_SUBSTITUTION)
2538 /* Check for the constructs which introduce process substitution.
2539 Shells running in `posix mode' don't do process substitution. */
2540 if MBTEST(posixly_correct || ((character != '>' && character != '<') || peek_char != '(')) /*)*/
2541 #endif /* PROCESS_SUBSTITUTION */
2545 /* Hack <&- (close stdin) case. Also <&N- (dup and close). */
2546 if MBTEST(character == '-' && (last_read_token == LESS_AND || last_read_token == GREATER_AND))
2549 /* Okay, if we got this far, we have to read a word. Read one,
2550 and then check it against the known ones. */
2551 result = read_token_word (character);
2553 if (result == RE_READ_TOKEN)
2560 * Match a $(...) or other grouping construct. This has to handle embedded
2561 * quoted strings ('', ``, "") and nested constructs. It also must handle
2562 * reprompting the user, if necessary, after reading a newline (unless the
2563 * P_NONL flag is passed), and returning correct error values if it reads
2566 #define P_FIRSTCLOSE 0x01
2567 #define P_ALLOWESC 0x02
2569 static char matched_pair_error;
2571 parse_matched_pair (qc, open, close, lenp, flags)
2572 int qc; /* `"' if this construct is within double quotes */
2576 int count, ch, was_dollar;
2577 int pass_next_character, nestlen, ttranslen, start_lineno;
2578 char *ret, *nestret, *ttrans;
2579 int retind, retsize;
2582 pass_next_character = was_dollar = 0;
2584 ret = (char *)xmalloc (retsize = 64);
2587 start_lineno = line_number;
2590 ch = shell_getc ((qc != '\'' || (flags & P_ALLOWESC)) && pass_next_character == 0);
2594 parser_error (start_lineno, "unexpected EOF while looking for matching `%c'", close);
2595 EOF_Reached = 1; /* XXX */
2596 return (&matched_pair_error);
2599 /* Possible reprompting. */
2600 if (ch == '\n' && interactive &&
2601 (bash_input.type == st_stdin || bash_input.type == st_stream))
2604 if (pass_next_character) /* last char was backslash */
2606 pass_next_character = 0;
2607 if (qc != '\'' && ch == '\n') /* double-quoted \<newline> disappears. */
2609 if (retind > 0) retind--; /* swallow previously-added backslash */
2613 RESIZE_MALLOCED_BUFFER (ret, retind, 2, retsize, 64);
2614 if MBTEST(ch == CTLESC || ch == CTLNUL)
2615 ret[retind++] = CTLESC;
2619 else if MBTEST(ch == CTLESC || ch == CTLNUL) /* special shell escapes */
2621 RESIZE_MALLOCED_BUFFER (ret, retind, 2, retsize, 64);
2622 ret[retind++] = CTLESC;
2626 else if MBTEST(ch == close) /* ending delimiter */
2629 /* handle nested ${...} specially. */
2630 else if MBTEST(open != close && was_dollar && open == '{' && ch == open) /* } */
2633 else if MBTEST(((flags & P_FIRSTCLOSE) == 0) && ch == open) /* nested begin */
2636 /* Add this character. */
2637 RESIZE_MALLOCED_BUFFER (ret, retind, 1, retsize, 64);
2640 if (open == '\'') /* '' inside grouping construct */
2642 if MBTEST((flags & P_ALLOWESC) && ch == '\\')
2643 pass_next_character++;
2647 if MBTEST(ch == '\\') /* backslashes */
2648 pass_next_character++;
2650 if (open != close) /* a grouping construct */
2652 if MBTEST(shellquote (ch))
2654 /* '', ``, or "" inside $(...) or other grouping construct. */
2655 push_delimiter (dstack, ch);
2656 if MBTEST(was_dollar && ch == '\'') /* $'...' inside group */
2657 nestret = parse_matched_pair (ch, ch, ch, &nestlen, P_ALLOWESC);
2659 nestret = parse_matched_pair (ch, ch, ch, &nestlen, 0);
2660 pop_delimiter (dstack);
2661 if (nestret == &matched_pair_error)
2664 return &matched_pair_error;
2666 if MBTEST(was_dollar && ch == '\'')
2668 /* Translate $'...' here. */
2669 ttrans = ansiexpand (nestret, 0, nestlen - 1, &ttranslen);
2671 nestret = sh_single_quote (ttrans);
2673 nestlen = strlen (nestret);
2674 retind -= 2; /* back up before the $' */
2676 else if MBTEST(was_dollar && ch == '"')
2678 /* Locale expand $"..." here. */
2679 ttrans = localeexpand (nestret, 0, nestlen - 1, start_lineno, &ttranslen);
2681 nestret = (char *)xmalloc (ttranslen + 3);
2683 strcpy (nestret + 1, ttrans);
2684 nestret[ttranslen + 1] = '"';
2685 nestret[ttranslen += 2] = '\0';
2687 nestlen = ttranslen;
2688 retind -= 2; /* back up before the $" */
2693 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2694 strcpy (ret + retind, nestret);
2700 /* Parse an old-style command substitution within double quotes as a
2702 /* XXX - sh and ksh93 don't do this - XXX */
2703 else if MBTEST(open == '"' && ch == '`')
2705 nestret = parse_matched_pair (0, '`', '`', &nestlen, 0);
2706 if (nestret == &matched_pair_error)
2709 return &matched_pair_error;
2713 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2714 strcpy (ret + retind, nestret);
2719 else if MBTEST(was_dollar && (ch == '(' || ch == '{' || ch == '[')) /* ) } ] */
2720 /* check for $(), $[], or ${} inside quoted string. */
2722 if (open == ch) /* undo previous increment */
2724 if (ch == '(') /* ) */
2725 nestret = parse_matched_pair (0, '(', ')', &nestlen, 0);
2726 else if (ch == '{') /* } */
2727 nestret = parse_matched_pair (0, '{', '}', &nestlen, P_FIRSTCLOSE);
2728 else if (ch == '[') /* ] */
2729 nestret = parse_matched_pair (0, '[', ']', &nestlen, 0);
2730 if (nestret == &matched_pair_error)
2733 return &matched_pair_error;
2737 RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2738 strcpy (ret + retind, nestret);
2743 was_dollar = MBTEST(ch == '$');
2752 #if defined (DPAREN_ARITHMETIC) || defined (ARITH_FOR_COMMAND)
2753 /* Parse a double-paren construct. It can be either an arithmetic
2754 command, an arithmetic `for' command, or a nested subshell. Returns
2755 the parsed token, -1 on error, or -2 if we didn't do anything and
2756 should just go on. */
2761 int cmdtyp, len, sline;
2765 #if defined (ARITH_FOR_COMMAND)
2766 if (last_read_token == FOR)
2768 arith_for_lineno = line_number;
2769 cmdtyp = parse_arith_cmd (&wval);
2772 /* parse_arith_cmd adds quotes at the beginning and end
2773 of the string it returns; we need to take those out. */
2774 len = strlen (wval);
2775 wv2 = (char *)xmalloc (len);
2776 strncpy (wv2, wval + 1, len - 2);
2777 wv2[len - 2] = '\0';
2778 wd = make_word (wv2);
2779 yylval.word_list = make_word_list (wd, (WORD_LIST *)NULL);
2782 return (ARITH_FOR_EXPRS);
2785 return -1; /* ERROR */
2789 #if defined (DPAREN_ARITHMETIC)
2790 if (reserved_word_acceptable (last_read_token))
2792 sline = line_number;
2793 cmdtyp = parse_arith_cmd (&wval);
2794 if (cmdtyp == 1) /* arithmetic command */
2796 wd = make_word (wval);
2797 wd->flags = W_QUOTED;
2798 yylval.word_list = make_word_list (wd, (WORD_LIST *)NULL);
2799 free (wval); /* make_word copies it */
2802 else if (cmdtyp == 0) /* nested subshell */
2804 push_string (wval, 0, (alias_t *)NULL);
2805 if ((parser_state & PST_CASEPAT) == 0)
2806 parser_state |= PST_SUBSHELL;
2814 return -2; /* XXX */
2817 /* We've seen a `(('. Look for the matching `))'. If we get it, return 1.
2818 If not, assume it's a nested subshell for backwards compatibility and
2819 return 0. In any case, put the characters we've consumed into a locally-
2820 allocated buffer and make *ep point to that buffer. Return -1 on an
2821 error, for example EOF. */
2823 parse_arith_cmd (ep)
2826 int exp_lineno, rval, c;
2827 char *ttok, *tokstr;
2830 exp_lineno = line_number;
2831 ttok = parse_matched_pair (0, '(', ')', &ttoklen, 0);
2833 if (ttok == &matched_pair_error)
2835 /* Check that the next character is the closing right paren. If
2836 not, this is a syntax error. ( */
2841 tokstr = (char *)xmalloc (ttoklen + 4);
2843 /* (( ... )) -> "..." */
2844 tokstr[0] = (rval == 1) ? '"' : '(';
2845 strncpy (tokstr + 1, ttok, ttoklen - 1); /* don't copy the final `)' */
2848 tokstr[ttoklen] = '"';
2849 tokstr[ttoklen+1] = '\0';
2853 tokstr[ttoklen] = ')';
2854 tokstr[ttoklen+1] = c;
2855 tokstr[ttoklen+2] = '\0';
2861 #endif /* DPAREN_ARITHMETIC || ARITH_FOR_COMMAND */
2863 #if defined (COND_COMMAND)
2869 if (EOF_Reached && cond_token != COND_ERROR) /* [[ */
2870 parser_error (cond_lineno, "unexpected EOF while looking for `]]'");
2871 else if (cond_token != COND_ERROR)
2873 if (etext = error_token_from_token (cond_token))
2875 parser_error (cond_lineno, "syntax error in conditional expression: unexpected token `%s'", etext);
2879 parser_error (cond_lineno, "syntax error in conditional expression");
2886 return (cond_or ());
2895 if (cond_token == OR_OR)
2898 l = make_cond_node (COND_OR, (WORD_DESC *)NULL, l, r);
2909 if (cond_token == AND_AND)
2912 l = make_cond_node (COND_AND, (WORD_DESC *)NULL, l, r);
2918 cond_skip_newlines ()
2920 while ((cond_token = read_token (READ)) == '\n')
2922 if (interactive && (bash_input.type == st_stdin || bash_input.type == st_stream))
2925 return (cond_token);
2928 #define COND_RETURN_ERROR() \
2929 do { cond_token = COND_ERROR; return ((COND_COM *)NULL); } while (0)
2935 COND_COM *term, *tleft, *tright;
2939 /* Read a token. It can be a left paren, a `!', a unary operator, or a
2940 word that should be the first argument of a binary operator. Start by
2941 skipping newlines, since this is a compound command. */
2942 tok = cond_skip_newlines ();
2943 lineno = line_number;
2944 if (tok == COND_END)
2946 COND_RETURN_ERROR ();
2948 else if (tok == '(')
2950 term = cond_expr ();
2951 if (cond_token != ')')
2954 dispose_cond_node (term); /* ( */
2955 if (etext = error_token_from_token (cond_token))
2957 parser_error (lineno, "unexpected token `%s', expected `)'", etext);
2961 parser_error (lineno, "expected `)'");
2962 COND_RETURN_ERROR ();
2964 term = make_cond_node (COND_EXPR, (WORD_DESC *)NULL, term, (COND_COM *)NULL);
2965 (void)cond_skip_newlines ();
2967 else if (tok == BANG || (tok == WORD && (yylval.word->word[0] == '!' && yylval.word->word[1] == '\0')))
2970 dispose_word (yylval.word); /* not needed */
2971 term = cond_term ();
2973 term->flags |= CMD_INVERT_RETURN;
2975 else if (tok == WORD && test_unop (yylval.word->word))
2978 tok = read_token (READ);
2981 tleft = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
2982 term = make_cond_node (COND_UNARY, op, tleft, (COND_COM *)NULL);
2987 if (etext = error_token_from_token (tok))
2989 parser_error (line_number, "unexpected argument `%s' to conditional unary operator", etext);
2993 parser_error (line_number, "unexpected argument to conditional unary operator");
2994 COND_RETURN_ERROR ();
2997 (void)cond_skip_newlines ();
2999 else if (tok == WORD) /* left argument to binary operator */
3002 tleft = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
3005 tok = read_token (READ);
3006 if (tok == WORD && test_binop (yylval.word->word))
3008 else if (tok == '<' || tok == '>')
3009 op = make_word_from_token (tok); /* ( */
3010 /* There should be a check before blindly accepting the `)' that we have
3011 seen the opening `('. */
3012 else if (tok == COND_END || tok == AND_AND || tok == OR_OR || tok == ')')
3014 /* Special case. [[ x ]] is equivalent to [[ -n x ]], just like
3015 the test command. Similarly for [[ x && expr ]] or
3016 [[ x || expr ]] or [[ (x) ]]. */
3017 op = make_word ("-n");
3018 term = make_cond_node (COND_UNARY, op, tleft, (COND_COM *)NULL);
3024 if (etext = error_token_from_token (tok))
3026 parser_error (line_number, "unexpected token `%s', conditional binary operator expected", etext);
3030 parser_error (line_number, "conditional binary operator expected");
3031 dispose_cond_node (tleft);
3032 COND_RETURN_ERROR ();
3036 tok = read_token (READ);
3039 tright = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
3040 term = make_cond_node (COND_BINARY, op, tleft, tright);
3044 if (etext = error_token_from_token (tok))
3046 parser_error (line_number, "unexpected argument `%s' to conditional binary operator", etext);
3050 parser_error (line_number, "unexpected argument to conditional binary operator");
3051 dispose_cond_node (tleft);
3053 COND_RETURN_ERROR ();
3056 (void)cond_skip_newlines ();
3061 parser_error (line_number, "unexpected token `%c' in conditional command", tok);
3062 else if (etext = error_token_from_token (tok))
3064 parser_error (line_number, "unexpected token `%s' in conditional command", etext);
3068 parser_error (line_number, "unexpected token %d in conditional command", tok);
3069 COND_RETURN_ERROR ();
3074 /* This is kind of bogus -- we slip a mini recursive-descent parser in
3075 here to handle the conditional statement syntax. */
3077 parse_cond_command ()
3081 cexp = cond_expr ();
3082 return (make_cond_command (cexp));
3086 #if defined (ARRAY_VARS)
3087 /* When this is called, it's guaranteed that we don't care about anything
3088 in t beyond i. We do save and restore the chars, though. */
3090 token_is_assignment (t, i)
3094 unsigned char c, c1;
3097 c = t[i]; c1 = t[i+1];
3098 t[i] = '='; t[i+1] = '\0';
3100 t[i] = c; t[i+1] = c1;
3105 token_is_ident (t, i)
3114 r = legal_identifier (t);
3121 read_token_word (character)
3124 /* The value for YYLVAL when a WORD is read. */
3125 WORD_DESC *the_word;
3127 /* Index into the token that we are building. */
3130 /* ALL_DIGITS becomes zero when we see a non-digit. */
3131 int all_digit_token;
3133 /* DOLLAR_PRESENT becomes non-zero if we see a `$'. */
3136 /* QUOTED becomes non-zero if we see one of ("), ('), (`), or (\). */
3139 /* Non-zero means to ignore the value of the next character, and just
3140 to add it no matter what. */
3141 int pass_next_character;
3143 /* The current delimiting character. */
3145 int result, peek_char;
3146 char *ttok, *ttrans;
3147 int ttoklen, ttranslen;
3150 if (token_buffer_size < TOKEN_DEFAULT_INITIAL_SIZE)
3151 token = (char *)xrealloc (token, token_buffer_size = TOKEN_DEFAULT_INITIAL_SIZE);
3154 all_digit_token = DIGIT (character);
3155 dollar_present = quoted = pass_next_character = 0;
3159 if (character == EOF)
3162 if (pass_next_character)
3164 pass_next_character = 0;
3168 cd = current_delimiter (dstack);
3170 /* Handle backslashes. Quote lots of things when not inside of
3171 double-quotes, quote some things inside of double-quotes. */
3172 if MBTEST(character == '\\')
3174 peek_char = shell_getc (0);
3176 /* Backslash-newline is ignored in all cases except
3177 when quoted with single quotes. */
3178 if (peek_char == '\n')
3181 goto next_character;
3185 shell_ungetc (peek_char);
3187 /* If the next character is to be quoted, note it now. */
3188 if (cd == 0 || cd == '`' ||
3189 (cd == '"' && peek_char >= 0 && (sh_syntaxtab[peek_char] & CBSDQUOTE)))
3190 pass_next_character++;
3197 /* Parse a matched pair of quote characters. */
3198 if MBTEST(shellquote (character))
3200 push_delimiter (dstack, character);
3201 ttok = parse_matched_pair (character, character, character, &ttoklen, 0);
3202 pop_delimiter (dstack);
3203 if (ttok == &matched_pair_error)
3204 return -1; /* Bail immediately. */
3205 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3206 token_buffer_size, TOKEN_DEFAULT_GROW_SIZE);
3207 token[token_index++] = character;
3208 strcpy (token + token_index, ttok);
3209 token_index += ttoklen;
3210 all_digit_token = 0;
3212 dollar_present |= (character == '"' && strchr (ttok, '$') != 0);
3214 goto next_character;
3217 #ifdef EXTENDED_GLOB
3218 /* Parse a ksh-style extended pattern matching specification. */
3219 if (extended_glob && PATTERN_CHAR (character))
3221 peek_char = shell_getc (1);
3222 if MBTEST(peek_char == '(') /* ) */
3224 push_delimiter (dstack, peek_char);
3225 ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
3226 pop_delimiter (dstack);
3227 if (ttok == &matched_pair_error)
3228 return -1; /* Bail immediately. */
3229 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3231 TOKEN_DEFAULT_GROW_SIZE);
3232 token[token_index++] = character;
3233 token[token_index++] = peek_char;
3234 strcpy (token + token_index, ttok);
3235 token_index += ttoklen;
3237 dollar_present = all_digit_token = 0;
3238 goto next_character;
3241 shell_ungetc (peek_char);
3243 #endif /* EXTENDED_GLOB */
3245 /* If the delimiter character is not single quote, parse some of
3246 the shell expansions that must be read as a single word. */
3247 if (shellexp (character))
3249 peek_char = shell_getc (1);
3250 /* $(...), <(...), >(...), $((...)), ${...}, and $[...] constructs */
3251 if MBTEST(peek_char == '(' || \
3252 ((peek_char == '{' || peek_char == '[') && character == '$')) /* ) ] } */
3254 if (peek_char == '{') /* } */
3255 ttok = parse_matched_pair (cd, '{', '}', &ttoklen, P_FIRSTCLOSE);
3256 else if (peek_char == '(') /* ) */
3258 /* XXX - push and pop the `(' as a delimiter for use by
3259 the command-oriented-history code. This way newlines
3260 appearing in the $(...) string get added to the
3261 history literally rather than causing a possibly-
3262 incorrect `;' to be added. ) */
3263 push_delimiter (dstack, peek_char);
3264 ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
3265 pop_delimiter (dstack);
3268 ttok = parse_matched_pair (cd, '[', ']', &ttoklen, 0);
3269 if (ttok == &matched_pair_error)
3270 return -1; /* Bail immediately. */
3271 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3273 TOKEN_DEFAULT_GROW_SIZE);
3274 token[token_index++] = character;
3275 token[token_index++] = peek_char;
3276 strcpy (token + token_index, ttok);
3277 token_index += ttoklen;
3280 all_digit_token = 0;
3281 goto next_character;
3283 /* This handles $'...' and $"..." new-style quoted strings. */
3284 else if MBTEST(character == '$' && (peek_char == '\'' || peek_char == '"'))
3288 first_line = line_number;
3289 push_delimiter (dstack, peek_char);
3290 ttok = parse_matched_pair (peek_char, peek_char, peek_char,
3292 (peek_char == '\'') ? P_ALLOWESC : 0);
3293 pop_delimiter (dstack);
3294 if (ttok == &matched_pair_error)
3296 if (peek_char == '\'')
3298 ttrans = ansiexpand (ttok, 0, ttoklen - 1, &ttranslen);
3300 /* Insert the single quotes and correctly quote any
3301 embedded single quotes (allowed because P_ALLOWESC was
3302 passed to parse_matched_pair). */
3303 ttok = sh_single_quote (ttrans);
3306 ttranslen = strlen (ttrans);
3310 /* Try to locale-expand the converted string. */
3311 ttrans = localeexpand (ttok, 0, ttoklen - 1, first_line, &ttranslen);
3314 /* Add the double quotes back */
3315 ttok = (char *)xmalloc (ttranslen + 3);
3317 strcpy (ttok + 1, ttrans);
3318 ttok[ttranslen + 1] = '"';
3319 ttok[ttranslen += 2] = '\0';
3324 RESIZE_MALLOCED_BUFFER (token, token_index, ttranslen + 2,
3326 TOKEN_DEFAULT_GROW_SIZE);
3327 strcpy (token + token_index, ttrans);
3328 token_index += ttranslen;
3331 all_digit_token = 0;
3332 goto next_character;
3334 /* This could eventually be extended to recognize all of the
3335 shell's single-character parameter expansions, and set flags.*/
3336 else if MBTEST(character == '$' && peek_char == '$')
3338 ttok = (char *)xmalloc (3);
3339 ttok[0] = ttok[1] = '$';
3341 RESIZE_MALLOCED_BUFFER (token, token_index, 3,
3343 TOKEN_DEFAULT_GROW_SIZE);
3344 strcpy (token + token_index, ttok);
3347 all_digit_token = 0;
3349 goto next_character;
3352 shell_ungetc (peek_char);
3355 #if defined (ARRAY_VARS)
3356 /* Identify possible array subscript assignment; match [...] */
3357 else if MBTEST(character == '[' && token_index > 0 && assignment_acceptable (last_read_token) && token_is_ident (token, token_index)) /* ] */
3359 ttok = parse_matched_pair (cd, '[', ']', &ttoklen, 0);
3360 if (ttok == &matched_pair_error)
3361 return -1; /* Bail immediately. */
3362 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3364 TOKEN_DEFAULT_GROW_SIZE);
3365 token[token_index++] = character;
3366 strcpy (token + token_index, ttok);
3367 token_index += ttoklen;
3369 all_digit_token = 0;
3370 goto next_character;
3372 /* Identify possible compound array variable assignment. */
3373 else if MBTEST(character == '=' && token_index > 0 && token_is_assignment (token, token_index))
3375 peek_char = shell_getc (1);
3376 if MBTEST(peek_char == '(') /* ) */
3378 ttok = parse_compound_assignment (&ttoklen);
3380 RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 4,
3382 TOKEN_DEFAULT_GROW_SIZE);
3384 token[token_index++] = '=';
3385 token[token_index++] = '(';
3388 strcpy (token + token_index, ttok);
3389 token_index += ttoklen;
3391 token[token_index++] = ')';
3393 all_digit_token = 0;
3394 goto next_character;
3397 shell_ungetc (peek_char);
3401 /* When not parsing a multi-character word construct, shell meta-
3402 characters break words. */
3403 if MBTEST(shellbreak (character))
3405 shell_ungetc (character);
3411 all_digit_token &= DIGIT (character);
3412 dollar_present |= character == '$';
3414 if (character == CTLESC || character == CTLNUL)
3415 token[token_index++] = CTLESC;
3417 token[token_index++] = character;
3419 RESIZE_MALLOCED_BUFFER (token, token_index, 1, token_buffer_size,
3420 TOKEN_DEFAULT_GROW_SIZE);
3423 if (character == '\n' && interactive &&
3424 (bash_input.type == st_stdin || bash_input.type == st_stream))
3427 /* We want to remove quoted newlines (that is, a \<newline> pair)
3428 unless we are within single quotes or pass_next_character is
3429 set (the shell equivalent of literal-next). */
3430 cd = current_delimiter (dstack);
3431 character = shell_getc (cd != '\'' && pass_next_character == 0);
3432 } /* end for (;;) */
3436 token[token_index] = '\0';
3438 /* Check to see what thing we should return. If the last_read_token
3439 is a `<', or a `&', or the character which ended this token is
3440 a '>' or '<', then, and ONLY then, is this input token a NUMBER.
3441 Otherwise, it is just a word, and should be returned as such. */
3442 if MBTEST(all_digit_token && (character == '<' || character == '>' || \
3443 last_read_token == LESS_AND || \
3444 last_read_token == GREATER_AND))
3446 if (legal_number (token, &lvalue) && (int)lvalue == lvalue)
3447 yylval.number = lvalue;
3453 /* Check for special case tokens. */
3454 result = (last_shell_getc_is_singlebyte) ? special_case_tokens (token) : -1;
3459 /* Posix.2 does not allow reserved words to be aliased, so check for all
3460 of them, including special cases, before expanding the current token
3462 if MBTEST(posixly_correct)
3463 CHECK_FOR_RESERVED_WORD (token);
3465 /* Aliases are expanded iff EXPAND_ALIASES is non-zero, and quoting
3466 inhibits alias expansion. */
3467 if (expand_aliases && quoted == 0)
3469 result = alias_expand_token (token);
3470 if (result == RE_READ_TOKEN)
3471 return (RE_READ_TOKEN);
3472 else if (result == NO_EXPANSION)
3473 parser_state &= ~PST_ALEXPNEXT;
3476 /* If not in Posix.2 mode, check for reserved words after alias
3478 if MBTEST(posixly_correct == 0)
3480 CHECK_FOR_RESERVED_WORD (token);
3482 the_word = (WORD_DESC *)xmalloc (sizeof (WORD_DESC));
3483 the_word->word = (char *)xmalloc (1 + token_index);
3484 the_word->flags = 0;
3485 strcpy (the_word->word, token);
3487 the_word->flags |= W_HASDOLLAR;
3489 the_word->flags |= W_QUOTED;
3490 /* A word is an assignment if it appears at the beginning of a
3491 simple command, or after another assignment word. This is
3492 context-dependent, so it cannot be handled in the grammar. */
3493 if (assignment (token))
3495 the_word->flags |= W_ASSIGNMENT;
3496 /* Don't perform word splitting on assignment statements. */
3497 if (assignment_acceptable (last_read_token))
3498 the_word->flags |= W_NOSPLIT;
3501 yylval.word = the_word;
3503 result = ((the_word->flags & (W_ASSIGNMENT|W_NOSPLIT)) == (W_ASSIGNMENT|W_NOSPLIT))
3504 ? ASSIGNMENT_WORD : WORD;
3506 if (last_read_token == FUNCTION)
3508 parser_state |= PST_ALLOWOPNBRC;
3509 function_dstart = line_number;
3515 /* Return 1 if TOKSYM is a token that after being read would allow
3516 a reserved word to be seen, else 0. */
3518 reserved_word_acceptable (toksym)
3554 /* Return the index of TOKEN in the alist of reserved words, or -1 if
3555 TOKEN is not a shell reserved word. */
3557 find_reserved_word (tokstr)
3561 for (i = 0; word_token_alist[i].word; i++)
3562 if (STREQ (tokstr, word_token_alist[i].word))
3568 #if defined (READLINE)
3569 /* Called after each time readline is called. This insures that whatever
3570 the new prompt string is gets propagated to readline's local prompt
3573 reset_readline_prompt ()
3577 if (prompt_string_pointer)
3579 temp_prompt = (*prompt_string_pointer)
3580 ? decode_prompt_string (*prompt_string_pointer)
3583 if (temp_prompt == 0)
3585 temp_prompt = (char *)xmalloc (1);
3586 temp_prompt[0] = '\0';
3589 FREE (current_readline_prompt);
3590 current_readline_prompt = temp_prompt;
3593 #endif /* READLINE */
3596 #if defined (HISTORY)
3597 /* A list of tokens which can be followed by newlines, but not by
3598 semi-colons. When concatenating multiple lines of history, the
3599 newline separator for such tokens is replaced with a space. */
3600 static int no_semi_successors[] = {
3601 '\n', '{', '(', ')', ';', '&', '|',
3602 CASE, DO, ELSE, IF, SEMI_SEMI, THEN, UNTIL, WHILE, AND_AND, OR_OR, IN,
3606 /* If we are not within a delimited expression, try to be smart
3607 about which separators can be semi-colons and which must be
3608 newlines. Returns the string that should be added into the
3611 history_delimiting_chars ()
3615 if (dstack.delimiter_depth != 0)
3618 /* First, handle some special cases. */
3620 /* If we just read `()', assume it's a function definition, and don't
3621 add a semicolon. If the token before the `)' was not `(', and we're
3622 not in the midst of parsing a case statement, assume it's a
3623 parenthesized command and add the semicolon. */
3625 if (token_before_that == ')')
3627 if (two_tokens_ago == '(') /*)*/ /* function def */
3629 /* This does not work for subshells inside case statement
3630 command lists. It's a suboptimal solution. */
3631 else if (parser_state & PST_CASESTMT) /* case statement pattern */
3634 return "; "; /* (...) subshell */
3636 else if (token_before_that == WORD && two_tokens_ago == FUNCTION)
3637 return " "; /* function def using `function name' without `()' */
3639 else if (token_before_that == WORD && two_tokens_ago == FOR)
3641 /* Tricky. `for i\nin ...' should not have a semicolon, but
3642 `for i\ndo ...' should. We do what we can. */
3643 for (i = shell_input_line_index; whitespace(shell_input_line[i]); i++)
3645 if (shell_input_line[i] && shell_input_line[i] == 'i' && shell_input_line[i+1] == 'n')
3650 for (i = 0; no_semi_successors[i]; i++)
3652 if (token_before_that == no_semi_successors[i])
3658 #endif /* HISTORY */
3660 /* Issue a prompt, or prepare to issue a prompt when the next character
3667 if (!interactive) /* XXX */
3670 ps1_prompt = get_string_value ("PS1");
3671 ps2_prompt = get_string_value ("PS2");
3673 if (!prompt_string_pointer)
3674 prompt_string_pointer = &ps1_prompt;
3676 temp_prompt = *prompt_string_pointer
3677 ? decode_prompt_string (*prompt_string_pointer)
3680 if (temp_prompt == 0)
3682 temp_prompt = (char *)xmalloc (1);
3683 temp_prompt[0] = '\0';
3686 current_prompt_string = *prompt_string_pointer;
3687 prompt_string_pointer = &ps2_prompt;
3689 #if defined (READLINE)
3690 if (!no_line_editing)
3692 FREE (current_readline_prompt);
3693 current_readline_prompt = temp_prompt;
3696 #endif /* READLINE */
3698 FREE (current_decoded_prompt);
3699 current_decoded_prompt = temp_prompt;
3704 get_current_prompt_level ()
3706 return ((current_prompt_string && current_prompt_string == ps2_prompt) ? 2 : 1);
3710 set_current_prompt_level (x)
3713 prompt_string_pointer = (x == 2) ? &ps2_prompt : &ps1_prompt;
3714 current_prompt_string = *prompt_string_pointer;
3720 fprintf (stderr, "%s", current_decoded_prompt);
3724 /* Return a string which will be printed as a prompt. The string
3725 may contain special characters which are decoded as follows:
3728 \d the date in Day Mon Date format
3729 \e escape (ascii 033)
3730 \h the hostname up to the first `.'
3732 \j the number of active jobs
3733 \l the basename of the shell's tty device name
3736 \s the name of the shell
3737 \t the time in 24-hour hh:mm:ss format
3738 \T the time in 12-hour hh:mm:ss format
3739 \@ the time in 12-hour hh:mm am/pm format
3740 \A the time in 24-hour hh:mm format
3741 \D{fmt} the result of passing FMT to strftime(3)
3743 \v the version of bash (e.g., 2.00)
3744 \V the release of bash, version + patchlevel (e.g., 2.00.0)
3745 \w the current working directory
3746 \W the last element of $PWD
3747 \! the history number of this command
3748 \# the command number of this command
3749 \$ a $ or a # if you are root
3750 \nnn character code nnn in octal
3752 \[ begin a sequence of non-printing chars
3753 \] end a sequence of non-printing chars
3755 #define PROMPT_GROWTH 48
3757 decode_prompt_string (string)
3762 struct dstack save_dstack;
3763 int last_exit_value;
3764 #if defined (PROMPT_STRING_DECODE)
3765 int result_size, result_index;
3767 char *temp, octal_string[4];
3773 result = (char *)xmalloc (result_size = PROMPT_GROWTH);
3774 result[result_index = 0] = 0;
3775 temp = (char *)NULL;
3777 while (c = *string++)
3779 if (posixly_correct && c == '!')
3783 temp = savestring ("!");
3788 #if !defined (HISTORY)
3789 temp = savestring ("1");
3791 temp = itos (history_number ());
3792 #endif /* HISTORY */
3793 string--; /* add_string increments string again. */
3811 strncpy (octal_string, string, 3);
3812 octal_string[3] = '\0';
3814 n = read_octal (octal_string);
3815 temp = (char *)xmalloc (3);
3817 if (n == CTLESC || n == CTLNUL)
3834 for (c = 0; n != -1 && c < 3 && ISOCTAL (*string); c++)
3837 c = 0; /* tested at add_string: */
3845 /* Make the current time/date into a string. */
3846 (void) time (&the_time);
3847 tm = localtime (&the_time);
3850 n = strftime (timebuf, sizeof (timebuf), "%a %b %d", tm);
3852 n = strftime (timebuf, sizeof (timebuf), "%H:%M:%S", tm);
3854 n = strftime (timebuf, sizeof (timebuf), "%I:%M:%S", tm);
3856 n = strftime (timebuf, sizeof (timebuf), "%I:%M %p", tm);
3858 n = strftime (timebuf, sizeof (timebuf), "%H:%M", tm);
3860 timebuf[sizeof(timebuf) - 1] = '\0';
3861 temp = savestring (timebuf);
3864 case 'D': /* strftime format */
3865 if (string[1] != '{') /* } */
3868 (void) time (&the_time);
3869 tm = localtime (&the_time);
3870 string += 2; /* skip { */
3871 timefmt = xmalloc (strlen (string) + 3);
3872 for (t = timefmt; *string && *string != '}'; )
3875 c = *string; /* tested at add_string */
3876 if (timefmt[0] == '\0')
3879 timefmt[1] = 'X'; /* locale-specific current time */
3882 n = strftime (timebuf, sizeof (timebuf), timefmt, tm);
3885 timebuf[sizeof(timebuf) - 1] = '\0';
3886 if (promptvars || posixly_correct)
3887 /* Make sure that expand_prompt_string is called with a
3888 second argument of Q_DOUBLE_QUOTES if we use this
3890 temp = sh_backslash_quote_for_double_quotes (timebuf);
3892 temp = savestring (timebuf);
3896 temp = (char *)xmalloc (3);
3897 temp[0] = no_line_editing ? '\n' : '\r';
3898 temp[1] = no_line_editing ? '\0' : '\n';
3903 temp = base_pathname (shell_name);
3904 temp = savestring (temp);
3909 temp = (char *)xmalloc (16);
3911 strcpy (temp, dist_version);
3913 sprintf (temp, "%s.%d", dist_version, patch_level);
3919 /* Use the value of PWD because it is much more efficient. */
3920 char t_string[PATH_MAX];
3923 temp = get_string_value ("PWD");
3927 if (getcwd (t_string, sizeof(t_string)) == 0)
3933 tlen = strlen (t_string);
3937 tlen = sizeof (t_string) - 1;
3938 strncpy (t_string, temp, tlen);
3940 t_string[tlen] = '\0';
3942 #define ROOT_PATH(x) ((x)[0] == '/' && (x)[1] == 0)
3943 #define DOUBLE_SLASH_ROOT(x) ((x)[0] == '/' && (x)[1] == '/' && (x)[2] == 0)
3946 if (ROOT_PATH (t_string) == 0 && DOUBLE_SLASH_ROOT (t_string) == 0)
3948 t = strrchr (t_string, '/');
3950 strcpy (t_string, t + 1);
3954 #undef DOUBLE_SLASH_ROOT
3956 /* polite_directory_format is guaranteed to return a string
3957 no longer than PATH_MAX - 1 characters. */
3958 strcpy (t_string, polite_directory_format (t_string));
3960 /* If we're going to be expanding the prompt string later,
3961 quote the directory name. */
3962 if (promptvars || posixly_correct)
3963 /* Make sure that expand_prompt_string is called with a
3964 second argument of Q_DOUBLE_QUOTES if we use this
3966 temp = sh_backslash_quote_for_double_quotes (t_string);
3968 temp = savestring (t_string);
3974 if (current_user.user_name == 0)
3975 get_current_user_info ();
3976 temp = savestring (current_user.user_name);
3981 temp = savestring (current_host_name);
3982 if (c == 'h' && (t = (char *)strchr (temp, '.')))
3987 temp = itos (current_command_number);
3991 #if !defined (HISTORY)
3992 temp = savestring ("1");
3994 temp = itos (history_number ());
3995 #endif /* HISTORY */
3999 t = temp = (char *)xmalloc (3);
4000 if ((promptvars || posixly_correct) && (current_user.euid != 0))
4002 *t++ = current_user.euid == 0 ? '#' : '$';
4007 temp = itos (count_all_jobs ());
4011 #if defined (HAVE_TTYNAME)
4012 temp = (char *)ttyname (fileno (stdin));
4013 t = temp ? base_pathname (temp) : "tty";
4014 temp = savestring (t);
4016 temp = savestring ("tty");
4017 #endif /* !HAVE_TTYNAME */
4020 #if defined (READLINE)
4023 temp = (char *)xmalloc (3);
4025 temp[1] = (c == '[') ? RL_PROMPT_START_IGNORE : RL_PROMPT_END_IGNORE;
4028 #endif /* READLINE */
4034 temp = (char *)xmalloc (2);
4041 else /* (c == '\\') */
4048 temp = (char *)xmalloc (3);
4057 sub_append_string (temp, result, &result_index, &result_size);
4058 temp = (char *)NULL; /* Freed in sub_append_string (). */
4059 result[result_index] = '\0';
4065 RESIZE_MALLOCED_BUFFER (result, result_index, 3, result_size, PROMPT_GROWTH);
4066 result[result_index++] = c;
4067 result[result_index] = '\0';
4070 #else /* !PROMPT_STRING_DECODE */
4071 result = savestring (string);
4072 #endif /* !PROMPT_STRING_DECODE */
4074 /* Save the delimiter stack and point `dstack' to temp space so any
4075 command substitutions in the prompt string won't result in screwing
4076 up the parser's quoting state. */
4077 save_dstack = dstack;
4078 dstack = temp_dstack;
4079 dstack.delimiter_depth = 0;
4081 /* Perform variable and parameter expansion and command substitution on
4082 the prompt string. */
4083 if (promptvars || posixly_correct)
4085 last_exit_value = last_command_exit_value;
4086 list = expand_prompt_string (result, Q_DOUBLE_QUOTES);
4088 result = string_list (list);
4089 dispose_words (list);
4090 last_command_exit_value = last_exit_value;
4094 t = dequote_string (result);
4099 dstack = save_dstack;
4104 /************************************************
4108 ************************************************/
4110 /* Report a syntax error, and restart the parser. Call here for fatal
4116 report_syntax_error ((char *)NULL);
4122 error_token_from_token (token)
4127 if (t = find_token_in_alist (token, word_token_alist, 0))
4130 if (t = find_token_in_alist (token, other_token_alist, 0))
4134 /* This stuff is dicy and needs closer inspection */
4135 switch (current_token)
4138 case ASSIGNMENT_WORD:
4140 t = savestring (yylval.word->word);
4143 t = itos (yylval.number);
4146 if (yylval.word_list)
4147 t = string_list (yylval.word_list);
4149 case ARITH_FOR_EXPRS:
4150 if (yylval.word_list)
4151 t = string_list_internal (yylval.word_list, " ; ");
4154 t = (char *)NULL; /* punt */
4162 error_token_from_text ()
4167 t = shell_input_line;
4168 i = shell_input_line_index;
4172 if (i && t[i] == '\0')
4175 while (i && (whitespace (t[i]) || t[i] == '\n'))
4181 while (i && (member (t[i], " \n\t;|&") == 0))
4184 while (i != token_end && (whitespace (t[i]) || t[i] == '\n'))
4187 /* Return our idea of the offending token. */
4188 if (token_end || (i == 0 && token_end == 0))
4191 msg = substring (t, i, token_end);
4192 else /* one-character token */
4194 msg = (char *)xmalloc (2);
4204 print_offending_line ()
4209 msg = savestring (shell_input_line);
4210 token_end = strlen (msg);
4211 while (token_end && msg[token_end - 1] == '\n')
4212 msg[--token_end] = '\0';
4214 parser_error (line_number, "`%s'", msg);
4218 /* Report a syntax error with line numbers, etc.
4219 Call here for recoverable errors. If you have a message to print,
4220 then place it in MESSAGE, otherwise pass NULL and this will figure
4221 out an appropriate message for you. */
4223 report_syntax_error (message)
4230 parser_error (line_number, "%s", message);
4231 if (interactive && EOF_Reached)
4233 last_command_exit_value = EX_USAGE;
4237 /* If the line of input we're reading is not null, try to find the
4238 objectionable token. First, try to figure out what token the
4239 parser's complaining about by looking at current_token. */
4240 if (current_token != 0 && EOF_Reached == 0 && (msg = error_token_from_token (current_token)))
4242 parser_error (line_number, "syntax error near unexpected token `%s'", msg);
4245 if (interactive == 0)
4246 print_offending_line ();
4248 last_command_exit_value = EX_USAGE;
4252 /* If looking at the current token doesn't prove fruitful, try to find the
4253 offending token by analyzing the text of the input line near the current
4254 input line index and report what we find. */
4255 if (shell_input_line && *shell_input_line)
4257 msg = error_token_from_text ();
4260 parser_error (line_number, "syntax error near `%s'", msg);
4264 /* If not interactive, print the line containing the error. */
4265 if (interactive == 0)
4266 print_offending_line ();
4270 msg = EOF_Reached ? "syntax error: unexpected end of file" : "syntax error";
4271 parser_error (line_number, "%s", msg);
4272 /* When the shell is interactive, this file uses EOF_Reached
4273 only for error reporting. Other mechanisms are used to
4274 decide whether or not to exit. */
4275 if (interactive && EOF_Reached)
4279 last_command_exit_value = EX_USAGE;
4282 /* ??? Needed function. ??? We have to be able to discard the constructs
4283 created during parsing. In the case of error, we want to return
4284 allocated objects to the memory pool. In the case of no error, we want
4285 to throw away the information about where the allocated objects live.
4286 (dispose_command () will actually free the command.) */
4288 discard_parser_constructs (error_p)
4293 /************************************************
4297 ************************************************/
4299 /* Do that silly `type "bye" to exit' stuff. You know, "ignoreeof". */
4301 /* A flag denoting whether or not ignoreeof is set. */
4304 /* The number of times that we have encountered an EOF character without
4305 another character intervening. When this gets above the limit, the
4306 shell terminates. */
4307 int eof_encountered = 0;
4309 /* The limit for eof_encountered. */
4310 int eof_encountered_limit = 10;
4312 /* If we have EOF as the only input unit, this user wants to leave
4313 the shell. If the shell is not interactive, then just leave.
4314 Otherwise, if ignoreeof is set, and we haven't done this the
4315 required number of times in a row, print a message. */
4317 handle_eof_input_unit ()
4321 /* shell.c may use this to decide whether or not to write out the
4322 history, among other things. We use it only for error reporting
4327 /* If the user wants to "ignore" eof, then let her do so, kind of. */
4330 if (eof_encountered < eof_encountered_limit)
4332 fprintf (stderr, "Use \"%s\" to leave the shell.\n",
4333 login_shell ? "logout" : "exit");
4335 /* Reset the parsing state. */
4336 last_read_token = current_token = '\n';
4337 /* Reset the prompt string to be $PS1. */
4338 prompt_string_pointer = (char **)NULL;
4344 /* In this case EOF should exit the shell. Do it now. */
4346 exit_builtin ((WORD_LIST *)NULL);
4350 /* We don't write history files, etc., for non-interactive shells. */
4355 /************************************************
4357 * STRING PARSING FUNCTIONS *
4359 ************************************************/
4361 /* It's very important that these two functions treat the characters
4362 between ( and ) identically. */
4364 static WORD_LIST parse_string_error;
4366 /* Take a string and run it through the shell parser, returning the
4367 resultant word list. Used by compound array assignment. */
4369 parse_string_to_word_list (s, whom)
4374 int tok, orig_current_token, orig_line_number, orig_input_terminator;
4375 int orig_line_count;
4376 int old_echo_input, old_expand_aliases;
4377 #if defined (HISTORY)
4378 int old_remember_on_history, old_history_expansion_inhibited;
4381 #if defined (HISTORY)
4382 old_remember_on_history = remember_on_history;
4383 # if defined (BANG_HISTORY)
4384 old_history_expansion_inhibited = history_expansion_inhibited;
4386 bash_history_disable ();
4389 orig_line_number = line_number;
4390 orig_line_count = current_command_line_count;
4391 orig_input_terminator = shell_input_line_terminator;
4392 old_echo_input = echo_input_at_read;
4393 old_expand_aliases = expand_aliases;
4396 last_read_token = WORD; /* WORD to allow reserved words here */
4397 current_command_line_count = 0;
4398 echo_input_at_read = expand_aliases = 0;
4400 with_input_from_string (s, whom);
4401 wl = (WORD_LIST *)NULL;
4402 while ((tok = read_token (READ)) != yacc_EOF)
4404 if (tok == '\n' && *bash_input.location.string == '\0')
4406 if (tok == '\n') /* Allow newlines in compound assignments */
4408 if (tok != WORD && tok != ASSIGNMENT_WORD)
4410 line_number = orig_line_number + line_number - 1;
4411 orig_current_token = current_token;
4412 current_token = tok;
4413 yyerror ((char *)NULL); /* does the right thing */
4414 current_token = orig_current_token;
4417 wl = &parse_string_error;
4420 wl = make_word_list (yylval.word, wl);
4423 last_read_token = '\n';
4426 #if defined (HISTORY)
4427 remember_on_history = old_remember_on_history;
4428 # if defined (BANG_HISTORY)
4429 history_expansion_inhibited = old_history_expansion_inhibited;
4430 # endif /* BANG_HISTORY */
4431 #endif /* HISTORY */
4433 echo_input_at_read = old_echo_input;
4434 expand_aliases = old_expand_aliases;
4436 current_command_line_count = orig_line_count;
4437 shell_input_line_terminator = orig_input_terminator;
4439 if (wl == &parse_string_error)
4441 last_command_exit_value = EXECUTION_FAILURE;
4442 if (interactive_shell == 0 && posixly_correct)
4443 jump_to_top_level (FORCE_EOF);
4445 jump_to_top_level (DISCARD);
4448 return (REVERSE_LIST (wl, WORD_LIST *));
4452 parse_compound_assignment (retlenp)
4456 int tok, orig_line_number, orig_token_size;
4457 char *saved_token, *ret;
4459 saved_token = token;
4460 orig_token_size = token_buffer_size;
4461 orig_line_number = line_number;
4463 last_read_token = WORD; /* WORD to allow reserved words here */
4465 token = (char *)NULL;
4466 token_buffer_size = 0;
4468 wl = (WORD_LIST *)NULL; /* ( */
4469 while ((tok = read_token (READ)) != ')')
4471 if (tok == '\n') /* Allow newlines in compound assignments */
4473 if (tok != WORD && tok != ASSIGNMENT_WORD)
4475 current_token = tok; /* for error reporting */
4476 if (tok == yacc_EOF) /* ( */
4477 parser_error (orig_line_number, "unexpected EOF while looking for matching `)'");
4479 yyerror ((char *)NULL); /* does the right thing */
4482 wl = &parse_string_error;
4485 wl = make_word_list (yylval.word, wl);
4489 token = saved_token;
4490 token_buffer_size = orig_token_size;
4492 if (wl == &parse_string_error)
4494 last_command_exit_value = EXECUTION_FAILURE;
4495 last_read_token = '\n'; /* XXX */
4496 if (interactive_shell == 0 && posixly_correct)
4497 jump_to_top_level (FORCE_EOF);
4499 jump_to_top_level (DISCARD);
4502 last_read_token = WORD;
4505 rl = REVERSE_LIST (wl, WORD_LIST *);
4506 ret = string_list (rl);
4513 *retlenp = (ret && *ret) ? strlen (ret) : 0;
4517 /************************************************
4519 * MULTIBYTE CHARACTER HANDLING *
4521 ************************************************/
4523 #if defined (HANDLE_MULTIBYTE)
4528 mbstate_t mbs, prevs;
4531 if (shell_input_line == NULL)
4533 len = strlen (shell_input_line); /* XXX - shell_input_line_len ? */
4534 FREE (shell_input_line_property);
4535 shell_input_line_property = (char *)xmalloc (len + 1);
4537 memset (&prevs, '\0', sizeof (mbstate_t));
4538 for (i = previ = 0; i < len; i++)
4542 if (shell_input_line[i] == EOF)
4545 for (j = i; j < len; j++)
4546 shell_input_line_property[j] = 1;
4550 mbclen = mbrlen (shell_input_line + previ, i - previ + 1, &mbs);
4551 if (mbclen == 1 || mbclen == (size_t)-1)
4556 else if (mbclen == (size_t)-2)
4558 else if (mbclen > 1)
4566 /* mbrlen doesn't return any other values */
4569 shell_input_line_property[i] = mbclen;
4572 #endif /* HANDLE_MULTIBYTE */